Three.js 797 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219
  1. /**
  2. * @author mr.doob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '49dev' };
  5. if ( ! self.Int32Array ) {
  6. self.Int32Array = Array;
  7. self.Float32Array = Array;
  8. }
  9. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  10. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  11. // requestAnimationFrame polyfill by Erik Möller
  12. // fixes from Paul Irish and Tino Zijdel
  13. (function() {
  14. var lastTime = 0;
  15. var vendors = ['ms', 'moz', 'webkit', 'o'];
  16. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  17. window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
  18. window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
  19. || window[vendors[x]+'CancelRequestAnimationFrame'];
  20. }
  21. if (!window.requestAnimationFrame)
  22. window.requestAnimationFrame = function(callback, element) {
  23. var currTime = new Date().getTime();
  24. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  25. var id = window.setTimeout(function() { callback(currTime + timeToCall); },
  26. timeToCall);
  27. lastTime = currTime + timeToCall;
  28. return id;
  29. };
  30. if (!window.cancelAnimationFrame)
  31. window.cancelAnimationFrame = function(id) {
  32. clearTimeout(id);
  33. };
  34. }());
  35. /**
  36. * @author alteredq / http://alteredqualia.com/
  37. */
  38. THREE.Clock = function ( autoStart ) {
  39. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  40. this.startTime = 0;
  41. this.oldTime = 0;
  42. this.elapsedTime = 0;
  43. this.running = false;
  44. };
  45. THREE.Clock.prototype.start = function () {
  46. this.startTime = Date.now();
  47. this.oldTime = this.startTime;
  48. this.running = true;
  49. };
  50. THREE.Clock.prototype.stop = function () {
  51. this.getElapsedTime();
  52. this.running = false;
  53. };
  54. THREE.Clock.prototype.getElapsedTime = function () {
  55. this.elapsedTime += this.getDelta();
  56. return this.elapsedTime;
  57. };
  58. THREE.Clock.prototype.getDelta = function () {
  59. var diff = 0;
  60. if ( this.autoStart && ! this.running ) {
  61. this.start();
  62. }
  63. if ( this.running ) {
  64. var newTime = Date.now();
  65. diff = 0.001 * ( newTime - this.oldTime );
  66. this.oldTime = newTime;
  67. this.elapsedTime += diff;
  68. }
  69. return diff;
  70. };/**
  71. * @author mr.doob / http://mrdoob.com/
  72. */
  73. THREE.Color = function ( hex ) {
  74. if ( hex !== undefined ) this.setHex( hex );
  75. return this;
  76. };
  77. THREE.Color.prototype = {
  78. constructor: THREE.Color,
  79. r: 1, g: 1, b: 1,
  80. copy: function ( color ) {
  81. this.r = color.r;
  82. this.g = color.g;
  83. this.b = color.b;
  84. return this;
  85. },
  86. copyGammaToLinear: function ( color ) {
  87. this.r = color.r * color.r;
  88. this.g = color.g * color.g;
  89. this.b = color.b * color.b;
  90. return this;
  91. },
  92. copyLinearToGamma: function ( color ) {
  93. this.r = Math.sqrt( color.r );
  94. this.g = Math.sqrt( color.g );
  95. this.b = Math.sqrt( color.b );
  96. return this;
  97. },
  98. convertGammaToLinear: function () {
  99. var r = this.r, g = this.g, b = this.b;
  100. this.r = r * r;
  101. this.g = g * g;
  102. this.b = b * b;
  103. return this;
  104. },
  105. convertLinearToGamma: function () {
  106. this.r = Math.sqrt( this.r );
  107. this.g = Math.sqrt( this.g );
  108. this.b = Math.sqrt( this.b );
  109. return this;
  110. },
  111. setRGB: function ( r, g, b ) {
  112. this.r = r;
  113. this.g = g;
  114. this.b = b;
  115. return this;
  116. },
  117. setHSV: function ( h, s, v ) {
  118. // based on MochiKit implementation by Bob Ippolito
  119. // h,s,v ranges are < 0.0 - 1.0 >
  120. var i, f, p, q, t;
  121. if ( v === 0 ) {
  122. this.r = this.g = this.b = 0;
  123. } else {
  124. i = Math.floor( h * 6 );
  125. f = ( h * 6 ) - i;
  126. p = v * ( 1 - s );
  127. q = v * ( 1 - ( s * f ) );
  128. t = v * ( 1 - ( s * ( 1 - f ) ) );
  129. switch ( i ) {
  130. case 1: this.r = q; this.g = v; this.b = p; break;
  131. case 2: this.r = p; this.g = v; this.b = t; break;
  132. case 3: this.r = p; this.g = q; this.b = v; break;
  133. case 4: this.r = t; this.g = p; this.b = v; break;
  134. case 5: this.r = v; this.g = p; this.b = q; break;
  135. case 6: // fall through
  136. case 0: this.r = v; this.g = t; this.b = p; break;
  137. }
  138. }
  139. return this;
  140. },
  141. setHex: function ( hex ) {
  142. hex = Math.floor( hex );
  143. this.r = ( hex >> 16 & 255 ) / 255;
  144. this.g = ( hex >> 8 & 255 ) / 255;
  145. this.b = ( hex & 255 ) / 255;
  146. return this;
  147. },
  148. lerpSelf: function ( color, alpha ) {
  149. this.r += ( color.r - this.r ) * alpha;
  150. this.g += ( color.g - this.g ) * alpha;
  151. this.b += ( color.b - this.b ) * alpha;
  152. return this;
  153. },
  154. getHex: function () {
  155. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  156. },
  157. getContextStyle: function () {
  158. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  159. },
  160. clone: function () {
  161. return new THREE.Color().setRGB( this.r, this.g, this.b );
  162. }
  163. };
  164. /**
  165. * @author mr.doob / http://mrdoob.com/
  166. * @author philogb / http://blog.thejit.org/
  167. * @author egraether / http://egraether.com/
  168. * @author zz85 / http://www.lab4games.net/zz85/blog
  169. */
  170. THREE.Vector2 = function ( x, y ) {
  171. this.x = x || 0;
  172. this.y = y || 0;
  173. };
  174. THREE.Vector2.prototype = {
  175. constructor: THREE.Vector2,
  176. set: function ( x, y ) {
  177. this.x = x;
  178. this.y = y;
  179. return this;
  180. },
  181. copy: function ( v ) {
  182. this.x = v.x;
  183. this.y = v.y;
  184. return this;
  185. },
  186. add: function ( a, b ) {
  187. this.x = a.x + b.x;
  188. this.y = a.y + b.y;
  189. return this;
  190. },
  191. addSelf: function ( v ) {
  192. this.x += v.x;
  193. this.y += v.y;
  194. return this;
  195. },
  196. sub: function ( a, b ) {
  197. this.x = a.x - b.x;
  198. this.y = a.y - b.y;
  199. return this;
  200. },
  201. subSelf: function ( v ) {
  202. this.x -= v.x;
  203. this.y -= v.y;
  204. return this;
  205. },
  206. multiplyScalar: function ( s ) {
  207. this.x *= s;
  208. this.y *= s;
  209. return this;
  210. },
  211. divideScalar: function ( s ) {
  212. if ( s ) {
  213. this.x /= s;
  214. this.y /= s;
  215. } else {
  216. this.set( 0, 0 );
  217. }
  218. return this;
  219. },
  220. negate: function() {
  221. return this.multiplyScalar( - 1 );
  222. },
  223. dot: function ( v ) {
  224. return this.x * v.x + this.y * v.y;
  225. },
  226. lengthSq: function () {
  227. return this.x * this.x + this.y * this.y;
  228. },
  229. length: function () {
  230. return Math.sqrt( this.lengthSq() );
  231. },
  232. normalize: function () {
  233. return this.divideScalar( this.length() );
  234. },
  235. distanceTo: function ( v ) {
  236. return Math.sqrt( this.distanceToSquared( v ) );
  237. },
  238. distanceToSquared: function ( v ) {
  239. var dx = this.x - v.x, dy = this.y - v.y;
  240. return dx * dx + dy * dy;
  241. },
  242. setLength: function ( l ) {
  243. return this.normalize().multiplyScalar( l );
  244. },
  245. lerpSelf: function ( v, alpha ) {
  246. this.x += ( v.x - this.x ) * alpha;
  247. this.y += ( v.y - this.y ) * alpha;
  248. return this;
  249. },
  250. equals: function( v ) {
  251. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  252. },
  253. isZero: function () {
  254. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  255. },
  256. clone: function () {
  257. return new THREE.Vector2( this.x, this.y );
  258. }
  259. };
  260. /**
  261. * @author mr.doob / http://mrdoob.com/
  262. * @author kile / http://kile.stravaganza.org/
  263. * @author philogb / http://blog.thejit.org/
  264. * @author mikael emtinger / http://gomo.se/
  265. * @author egraether / http://egraether.com/
  266. */
  267. THREE.Vector3 = function ( x, y, z ) {
  268. this.x = x || 0;
  269. this.y = y || 0;
  270. this.z = z || 0;
  271. };
  272. THREE.Vector3.prototype = {
  273. constructor: THREE.Vector3,
  274. set: function ( x, y, z ) {
  275. this.x = x;
  276. this.y = y;
  277. this.z = z;
  278. return this;
  279. },
  280. setX: function ( x ) {
  281. this.x = x;
  282. return this;
  283. },
  284. setY: function ( y ) {
  285. this.y = y;
  286. return this;
  287. },
  288. setZ: function ( z ) {
  289. this.z = z;
  290. return this;
  291. },
  292. copy: function ( v ) {
  293. this.x = v.x;
  294. this.y = v.y;
  295. this.z = v.z;
  296. return this;
  297. },
  298. add: function ( a, b ) {
  299. this.x = a.x + b.x;
  300. this.y = a.y + b.y;
  301. this.z = a.z + b.z;
  302. return this;
  303. },
  304. addSelf: function ( v ) {
  305. this.x += v.x;
  306. this.y += v.y;
  307. this.z += v.z;
  308. return this;
  309. },
  310. addScalar: function ( s ) {
  311. this.x += s;
  312. this.y += s;
  313. this.z += s;
  314. return this;
  315. },
  316. sub: function ( a, b ) {
  317. this.x = a.x - b.x;
  318. this.y = a.y - b.y;
  319. this.z = a.z - b.z;
  320. return this;
  321. },
  322. subSelf: function ( v ) {
  323. this.x -= v.x;
  324. this.y -= v.y;
  325. this.z -= v.z;
  326. return this;
  327. },
  328. multiply: function ( a, b ) {
  329. this.x = a.x * b.x;
  330. this.y = a.y * b.y;
  331. this.z = a.z * b.z;
  332. return this;
  333. },
  334. multiplySelf: function ( v ) {
  335. this.x *= v.x;
  336. this.y *= v.y;
  337. this.z *= v.z;
  338. return this;
  339. },
  340. multiplyScalar: function ( s ) {
  341. this.x *= s;
  342. this.y *= s;
  343. this.z *= s;
  344. return this;
  345. },
  346. divideSelf: function ( v ) {
  347. this.x /= v.x;
  348. this.y /= v.y;
  349. this.z /= v.z;
  350. return this;
  351. },
  352. divideScalar: function ( s ) {
  353. if ( s ) {
  354. this.x /= s;
  355. this.y /= s;
  356. this.z /= s;
  357. } else {
  358. this.x = 0;
  359. this.y = 0;
  360. this.z = 0;
  361. }
  362. return this;
  363. },
  364. negate: function() {
  365. return this.multiplyScalar( - 1 );
  366. },
  367. dot: function ( v ) {
  368. return this.x * v.x + this.y * v.y + this.z * v.z;
  369. },
  370. lengthSq: function () {
  371. return this.x * this.x + this.y * this.y + this.z * this.z;
  372. },
  373. length: function () {
  374. return Math.sqrt( this.lengthSq() );
  375. },
  376. lengthManhattan: function () {
  377. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  378. },
  379. normalize: function () {
  380. return this.divideScalar( this.length() );
  381. },
  382. setLength: function ( l ) {
  383. return this.normalize().multiplyScalar( l );
  384. },
  385. lerpSelf: function ( v, alpha ) {
  386. this.x += ( v.x - this.x ) * alpha;
  387. this.y += ( v.y - this.y ) * alpha;
  388. this.z += ( v.z - this.z ) * alpha;
  389. return this;
  390. },
  391. cross: function ( a, b ) {
  392. this.x = a.y * b.z - a.z * b.y;
  393. this.y = a.z * b.x - a.x * b.z;
  394. this.z = a.x * b.y - a.y * b.x;
  395. return this;
  396. },
  397. crossSelf: function ( v ) {
  398. var x = this.x, y = this.y, z = this.z;
  399. this.x = y * v.z - z * v.y;
  400. this.y = z * v.x - x * v.z;
  401. this.z = x * v.y - y * v.x;
  402. return this;
  403. },
  404. distanceTo: function ( v ) {
  405. return Math.sqrt( this.distanceToSquared( v ) );
  406. },
  407. distanceToSquared: function ( v ) {
  408. return new THREE.Vector3().sub( this, v ).lengthSq();
  409. },
  410. getPositionFromMatrix: function ( m ) {
  411. this.x = m.elements[12];
  412. this.y = m.elements[13];
  413. this.z = m.elements[14];
  414. return this;
  415. },
  416. getRotationFromMatrix: function ( m, scale ) {
  417. var sx = scale ? scale.x : 1;
  418. var sy = scale ? scale.y : 1;
  419. var sz = scale ? scale.z : 1;
  420. var m11 = m.elements[0] / sx, m12 = m.elements[4] / sy, m13 = m.elements[8] / sz;
  421. var m21 = m.elements[1] / sx, m22 = m.elements[5] / sy, m23 = m.elements[9] / sz;
  422. var m33 = m.elements[10] / sz;
  423. this.y = Math.asin( m13 );
  424. var cosY = Math.cos( this.y );
  425. if ( Math.abs( cosY ) > 0.00001 ) {
  426. this.x = Math.atan2( - m23 / cosY, m33 / cosY );
  427. this.z = Math.atan2( - m12 / cosY, m11 / cosY );
  428. } else {
  429. this.x = 0;
  430. this.z = Math.atan2( m21, m22 );
  431. }
  432. return this;
  433. },
  434. /*
  435. // from http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  436. // order XYZ
  437. getEulerXYZFromQuaternion: function ( q ) {
  438. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z ) );
  439. this.y = Math.asin( 2 * ( q.x * q.z + q.y * q.w ) );
  440. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z ) );
  441. },
  442. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm
  443. // order YZX (assuming heading == y, attitude == z, bank == x)
  444. getEulerYZXFromQuaternion: function ( q ) {
  445. var sqw = q.w * q.w;
  446. var sqx = q.x * q.x;
  447. var sqy = q.y * q.y;
  448. var sqz = q.z * q.z;
  449. var unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
  450. var test = q.x * q.y + q.z * q.w;
  451. if ( test > 0.499 * unit ) { // singularity at north pole
  452. this.y = 2 * Math.atan2( q.x, q.w );
  453. this.z = Math.PI / 2;
  454. this.x = 0;
  455. return;
  456. }
  457. if ( test < -0.499 * unit ) { // singularity at south pole
  458. this.y = -2 * Math.atan2( q.x, q.w );
  459. this.z = -Math.PI / 2;
  460. this.x = 0;
  461. return;
  462. }
  463. this.y = Math.atan2( 2 * q.y * q.w - 2 * q.x * q.z, sqx - sqy - sqz + sqw );
  464. this.z = Math.asin( 2 * test / unit );
  465. this.x = Math.atan2( 2 * q.x * q.w - 2 * q.y * q.z, -sqx + sqy - sqz + sqw );
  466. },
  467. */
  468. getScaleFromMatrix: function ( m ) {
  469. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  470. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  471. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  472. this.x = sx;
  473. this.y = sy;
  474. this.z = sz;
  475. },
  476. equals: function ( v ) {
  477. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  478. },
  479. isZero: function () {
  480. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  481. },
  482. clone: function () {
  483. return new THREE.Vector3( this.x, this.y, this.z );
  484. }
  485. };
  486. /**
  487. * @author supereggbert / http://www.paulbrunt.co.uk/
  488. * @author philogb / http://blog.thejit.org/
  489. * @author mikael emtinger / http://gomo.se/
  490. * @author egraether / http://egraether.com/
  491. */
  492. THREE.Vector4 = function ( x, y, z, w ) {
  493. this.x = x || 0;
  494. this.y = y || 0;
  495. this.z = z || 0;
  496. this.w = ( w !== undefined ) ? w : 1;
  497. };
  498. THREE.Vector4.prototype = {
  499. constructor: THREE.Vector4,
  500. set: function ( x, y, z, w ) {
  501. this.x = x;
  502. this.y = y;
  503. this.z = z;
  504. this.w = w;
  505. return this;
  506. },
  507. copy: function ( v ) {
  508. this.x = v.x;
  509. this.y = v.y;
  510. this.z = v.z;
  511. this.w = ( v.w !== undefined ) ? v.w : 1;
  512. return this;
  513. },
  514. add: function ( a, b ) {
  515. this.x = a.x + b.x;
  516. this.y = a.y + b.y;
  517. this.z = a.z + b.z;
  518. this.w = a.w + b.w;
  519. return this;
  520. },
  521. addSelf: function ( v ) {
  522. this.x += v.x;
  523. this.y += v.y;
  524. this.z += v.z;
  525. this.w += v.w;
  526. return this;
  527. },
  528. sub: function ( a, b ) {
  529. this.x = a.x - b.x;
  530. this.y = a.y - b.y;
  531. this.z = a.z - b.z;
  532. this.w = a.w - b.w;
  533. return this;
  534. },
  535. subSelf: function ( v ) {
  536. this.x -= v.x;
  537. this.y -= v.y;
  538. this.z -= v.z;
  539. this.w -= v.w;
  540. return this;
  541. },
  542. multiplyScalar: function ( s ) {
  543. this.x *= s;
  544. this.y *= s;
  545. this.z *= s;
  546. this.w *= s;
  547. return this;
  548. },
  549. divideScalar: function ( s ) {
  550. if ( s ) {
  551. this.x /= s;
  552. this.y /= s;
  553. this.z /= s;
  554. this.w /= s;
  555. } else {
  556. this.x = 0;
  557. this.y = 0;
  558. this.z = 0;
  559. this.w = 1;
  560. }
  561. return this;
  562. },
  563. negate: function() {
  564. return this.multiplyScalar( -1 );
  565. },
  566. dot: function ( v ) {
  567. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  568. },
  569. lengthSq: function () {
  570. return this.dot( this );
  571. },
  572. length: function () {
  573. return Math.sqrt( this.lengthSq() );
  574. },
  575. normalize: function () {
  576. return this.divideScalar( this.length() );
  577. },
  578. setLength: function ( l ) {
  579. return this.normalize().multiplyScalar( l );
  580. },
  581. lerpSelf: function ( v, alpha ) {
  582. this.x += ( v.x - this.x ) * alpha;
  583. this.y += ( v.y - this.y ) * alpha;
  584. this.z += ( v.z - this.z ) * alpha;
  585. this.w += ( v.w - this.w ) * alpha;
  586. return this;
  587. },
  588. clone: function () {
  589. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  590. }
  591. };
  592. /**
  593. * @author mrdoob / http://mrdoob.com/
  594. * @author alteredq / http://alteredqualia.com/
  595. */
  596. THREE.Frustum = function ( ) {
  597. this.planes = [
  598. new THREE.Vector4(),
  599. new THREE.Vector4(),
  600. new THREE.Vector4(),
  601. new THREE.Vector4(),
  602. new THREE.Vector4(),
  603. new THREE.Vector4()
  604. ];
  605. };
  606. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  607. var i, plane,
  608. planes = this.planes;
  609. var me = m.elements;
  610. planes[ 0 ].set( me[3] - me[0], me[7] - me[4], me[11] - me[8], me[15] - me[12] );
  611. planes[ 1 ].set( me[3] + me[0], me[7] + me[4], me[11] + me[8], me[15] + me[12] );
  612. planes[ 2 ].set( me[3] + me[1], me[7] + me[5], me[11] + me[9], me[15] + me[13] );
  613. planes[ 3 ].set( me[3] - me[1], me[7] - me[5], me[11] - me[9], me[15] - me[13] );
  614. planes[ 4 ].set( me[3] - me[2], me[7] - me[6], me[11] - me[10], me[15] - me[14] );
  615. planes[ 5 ].set( me[3] + me[2], me[7] + me[6], me[11] + me[10], me[15] + me[14] );
  616. for ( i = 0; i < 6; i ++ ) {
  617. plane = planes[ i ];
  618. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  619. }
  620. };
  621. THREE.Frustum.prototype.contains = function ( object ) {
  622. var distance,
  623. planes = this.planes,
  624. matrix = object.matrixWorld,
  625. me = matrix.elements,
  626. scale = THREE.Frustum.__v1.set( matrix.getColumnX().length(), matrix.getColumnY().length(), matrix.getColumnZ().length() ),
  627. radius = - object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) );
  628. for ( var i = 0; i < 6; i ++ ) {
  629. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  630. if ( distance <= radius ) return false;
  631. }
  632. return true;
  633. };
  634. THREE.Frustum.__v1 = new THREE.Vector3();
  635. /**
  636. * @author mr.doob / http://mrdoob.com/
  637. */
  638. THREE.Ray = function ( origin, direction ) {
  639. this.origin = origin || new THREE.Vector3();
  640. this.direction = direction || new THREE.Vector3();
  641. var precision = 0.0001;
  642. this.setPrecision = function ( value ) {
  643. precision = value;
  644. };
  645. var a = new THREE.Vector3();
  646. var b = new THREE.Vector3();
  647. var c = new THREE.Vector3();
  648. var d = new THREE.Vector3();
  649. var originCopy = new THREE.Vector3();
  650. var directionCopy = new THREE.Vector3();
  651. var vector = new THREE.Vector3();
  652. var normal = new THREE.Vector3();
  653. var intersectPoint = new THREE.Vector3()
  654. this.intersectObject = function ( object ) {
  655. var intersect, intersects = [];
  656. if ( object instanceof THREE.Particle ) {
  657. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  658. if ( distance > object.scale.x ) {
  659. return [];
  660. }
  661. intersect = {
  662. distance: distance,
  663. point: object.position,
  664. face: null,
  665. object: object
  666. };
  667. intersects.push( intersect );
  668. } else if ( object instanceof THREE.Mesh ) {
  669. // Checking boundingSphere
  670. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  671. var scale = THREE.Frustum.__v1.set( object.matrixWorld.getColumnX().length(), object.matrixWorld.getColumnY().length(), object.matrixWorld.getColumnZ().length() );
  672. if ( distance > object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) ) ) {
  673. return intersects;
  674. }
  675. // Checking faces
  676. var f, fl, face, dot, scalar,
  677. geometry = object.geometry,
  678. vertices = geometry.vertices,
  679. objMatrix;
  680. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  681. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  682. face = geometry.faces[ f ];
  683. originCopy.copy( this.origin );
  684. directionCopy.copy( this.direction );
  685. objMatrix = object.matrixWorld;
  686. // determine if ray intersects the plane of the face
  687. // note: this works regardless of the direction of the face normal
  688. vector = objMatrix.multiplyVector3( vector.copy( face.centroid ) ).subSelf( originCopy );
  689. normal = object.matrixRotationWorld.multiplyVector3( normal.copy( face.normal ) );
  690. dot = directionCopy.dot( normal );
  691. // bail if ray and plane are parallel
  692. if ( Math.abs( dot ) < precision ) continue;
  693. // calc distance to plane
  694. scalar = normal.dot( vector ) / dot;
  695. // if negative distance, then plane is behind ray
  696. if ( scalar < 0 ) continue;
  697. if ( object.doubleSided || ( object.flipSided ? dot > 0 : dot < 0 ) ) {
  698. intersectPoint.add( originCopy, directionCopy.multiplyScalar( scalar ) );
  699. if ( face instanceof THREE.Face3 ) {
  700. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ].position ) );
  701. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ].position ) );
  702. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ].position ) );
  703. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  704. intersect = {
  705. distance: originCopy.distanceTo( intersectPoint ),
  706. point: intersectPoint.clone(),
  707. face: face,
  708. object: object
  709. };
  710. intersects.push( intersect );
  711. }
  712. } else if ( face instanceof THREE.Face4 ) {
  713. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ].position ) );
  714. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ].position ) );
  715. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ].position ) );
  716. d = objMatrix.multiplyVector3( d.copy( vertices[ face.d ].position ) );
  717. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  718. intersect = {
  719. distance: originCopy.distanceTo( intersectPoint ),
  720. point: intersectPoint.clone(),
  721. face: face,
  722. object: object
  723. };
  724. intersects.push( intersect );
  725. }
  726. }
  727. }
  728. }
  729. }
  730. return intersects;
  731. }
  732. this.intersectObjects = function ( objects ) {
  733. var intersects = [];
  734. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  735. Array.prototype.push.apply( intersects, this.intersectObject( objects[ i ] ) );
  736. }
  737. intersects.sort( function ( a, b ) { return a.distance - b.distance; } );
  738. return intersects;
  739. };
  740. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  741. var dot, intersect, distance;
  742. function distanceFromIntersection( origin, direction, position ) {
  743. v0.sub( position, origin );
  744. dot = v0.dot( direction );
  745. intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  746. distance = position.distanceTo( intersect );
  747. return distance;
  748. }
  749. // http://www.blackpawn.com/texts/pointinpoly/default.html
  750. var dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
  751. function pointInFace3( p, a, b, c ) {
  752. v0.sub( c, a );
  753. v1.sub( b, a );
  754. v2.sub( p, a );
  755. dot00 = v0.dot( v0 );
  756. dot01 = v0.dot( v1 );
  757. dot02 = v0.dot( v2 );
  758. dot11 = v1.dot( v1 );
  759. dot12 = v1.dot( v2 );
  760. invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  761. u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  762. v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  763. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  764. }
  765. };/**
  766. * @author mr.doob / http://mrdoob.com/
  767. */
  768. THREE.Rectangle = function () {
  769. var _left, _top, _right, _bottom,
  770. _width, _height, _isEmpty = true;
  771. function resize() {
  772. _width = _right - _left;
  773. _height = _bottom - _top;
  774. }
  775. this.getX = function () {
  776. return _left;
  777. };
  778. this.getY = function () {
  779. return _top;
  780. };
  781. this.getWidth = function () {
  782. return _width;
  783. };
  784. this.getHeight = function () {
  785. return _height;
  786. };
  787. this.getLeft = function() {
  788. return _left;
  789. };
  790. this.getTop = function() {
  791. return _top;
  792. };
  793. this.getRight = function() {
  794. return _right;
  795. };
  796. this.getBottom = function() {
  797. return _bottom;
  798. };
  799. this.set = function ( left, top, right, bottom ) {
  800. _isEmpty = false;
  801. _left = left; _top = top;
  802. _right = right; _bottom = bottom;
  803. resize();
  804. };
  805. this.addPoint = function ( x, y ) {
  806. if ( _isEmpty ) {
  807. _isEmpty = false;
  808. _left = x; _top = y;
  809. _right = x; _bottom = y;
  810. resize();
  811. } else {
  812. _left = _left < x ? _left : x; // Math.min( _left, x );
  813. _top = _top < y ? _top : y; // Math.min( _top, y );
  814. _right = _right > x ? _right : x; // Math.max( _right, x );
  815. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  816. resize();
  817. }
  818. };
  819. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  820. if (_isEmpty) {
  821. _isEmpty = false;
  822. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  823. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  824. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  825. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  826. resize();
  827. } else {
  828. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  829. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  830. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  831. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  832. resize();
  833. };
  834. };
  835. this.addRectangle = function ( r ) {
  836. if ( _isEmpty ) {
  837. _isEmpty = false;
  838. _left = r.getLeft(); _top = r.getTop();
  839. _right = r.getRight(); _bottom = r.getBottom();
  840. resize();
  841. } else {
  842. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  843. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  844. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  845. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  846. resize();
  847. }
  848. };
  849. this.inflate = function ( v ) {
  850. _left -= v; _top -= v;
  851. _right += v; _bottom += v;
  852. resize();
  853. };
  854. this.minSelf = function ( r ) {
  855. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  856. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  857. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  858. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  859. resize();
  860. };
  861. this.intersects = function ( r ) {
  862. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  863. if ( _right < r.getLeft() ) return false;
  864. if ( _left > r.getRight() ) return false;
  865. if ( _bottom < r.getTop() ) return false;
  866. if ( _top > r.getBottom() ) return false;
  867. return true;
  868. };
  869. this.empty = function () {
  870. _isEmpty = true;
  871. _left = 0; _top = 0;
  872. _right = 0; _bottom = 0;
  873. resize();
  874. };
  875. this.isEmpty = function () {
  876. return _isEmpty;
  877. };
  878. };
  879. /**
  880. * @author alteredq / http://alteredqualia.com/
  881. */
  882. THREE.Math = {
  883. // Clamp value to range <a, b>
  884. clamp: function ( x, a, b ) {
  885. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  886. },
  887. // Clamp value to range <a, inf)
  888. clampBottom: function ( x, a ) {
  889. return x < a ? a : x;
  890. },
  891. // Linear mapping from range <a1, a2> to range <b1, b2>
  892. mapLinear: function ( x, a1, a2, b1, b2 ) {
  893. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  894. },
  895. // Random float from <0, 1> with 16 bits of randomness
  896. // (standard Math.random() creates repetitive patterns when applied over larger space)
  897. random16: function () {
  898. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  899. },
  900. // Random integer from <low, high> interval
  901. randInt: function ( low, high ) {
  902. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  903. },
  904. // Random float from <low, high> interval
  905. randFloat: function ( low, high ) {
  906. return low + Math.random() * ( high - low );
  907. },
  908. // Random float from <-range/2, range/2> interval
  909. randFloatSpread: function ( range ) {
  910. return range * ( 0.5 - Math.random() );
  911. },
  912. sign: function ( x ) {
  913. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  914. }
  915. };
  916. /**
  917. * @author alteredq / http://alteredqualia.com/
  918. */
  919. THREE.Matrix3 = function () {
  920. this.m = [];
  921. };
  922. THREE.Matrix3.prototype = {
  923. constructor: THREE.Matrix3,
  924. getInverse: function ( matrix ) {
  925. // input: THREE.Matrix4
  926. // ( based on http://code.google.com/p/webgl-mjs/ )
  927. var a11 = matrix.elements[10] * matrix.elements[5] - matrix.elements[6] * matrix.elements[9];
  928. var a21 = - matrix.elements[10] * matrix.elements[1] + matrix.elements[2] * matrix.elements[9];
  929. var a31 = matrix.elements[6] * matrix.elements[1] - matrix.elements[2] * matrix.elements[5];
  930. var a12 = - matrix.elements[10] * matrix.elements[4] + matrix.elements[6] * matrix.elements[8];
  931. var a22 = matrix.elements[10] * matrix.elements[0] - matrix.elements[2] * matrix.elements[8];
  932. var a32 = - matrix.elements[6] * matrix.elements[0] + matrix.elements[2] * matrix.elements[4];
  933. var a13 = matrix.elements[9] * matrix.elements[4] - matrix.elements[5] * matrix.elements[8];
  934. var a23 = - matrix.elements[9] * matrix.elements[0] + matrix.elements[1] * matrix.elements[8];
  935. var a33 = matrix.elements[5] * matrix.elements[0] - matrix.elements[1] * matrix.elements[4];
  936. var det = matrix.elements[0] * a11 + matrix.elements[1] * a12 + matrix.elements[2] * a13;
  937. // no inverse
  938. if ( det === 0 ) {
  939. console.warn( "Matrix3.getInverse(): determinant == 0" );
  940. }
  941. var idet = 1.0 / det;
  942. var m = this.m;
  943. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  944. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  945. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  946. return this;
  947. },
  948. /*
  949. transpose: function () {
  950. var tmp, m = this.m;
  951. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  952. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  953. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  954. return this;
  955. },
  956. */
  957. transposeIntoArray: function ( r ) {
  958. var m = this.m;
  959. r[ 0 ] = m[ 0 ];
  960. r[ 1 ] = m[ 3 ];
  961. r[ 2 ] = m[ 6 ];
  962. r[ 3 ] = m[ 1 ];
  963. r[ 4 ] = m[ 4 ];
  964. r[ 5 ] = m[ 7 ];
  965. r[ 6 ] = m[ 2 ];
  966. r[ 7 ] = m[ 5 ];
  967. r[ 8 ] = m[ 8 ];
  968. return this;
  969. }
  970. };
  971. /**
  972. * @author mr.doob / http://mrdoob.com/
  973. * @author supereggbert / http://www.paulbrunt.co.uk/
  974. * @author philogb / http://blog.thejit.org/
  975. * @author jordi_ros / http://plattsoft.com
  976. * @author D1plo1d / http://github.com/D1plo1d
  977. * @author alteredq / http://alteredqualia.com/
  978. * @author mikael emtinger / http://gomo.se/
  979. * @author timknip / http://www.floorplanner.com/
  980. */
  981. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  982. this.elements = new Float32Array(16);
  983. this.set(
  984. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  985. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  986. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  987. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  988. );
  989. };
  990. THREE.Matrix4.prototype = {
  991. constructor: THREE.Matrix4,
  992. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  993. var te = this.elements;
  994. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  995. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  996. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  997. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  998. return this;
  999. },
  1000. identity: function () {
  1001. this.set(
  1002. 1, 0, 0, 0,
  1003. 0, 1, 0, 0,
  1004. 0, 0, 1, 0,
  1005. 0, 0, 0, 1
  1006. );
  1007. return this;
  1008. },
  1009. copy: function ( m ) {
  1010. var me = m.elements;
  1011. this.set(
  1012. me[0], me[4], me[8], me[12],
  1013. me[1], me[5], me[9], me[13],
  1014. me[2], me[6], me[10], me[14],
  1015. me[3], me[7], me[11], me[15]
  1016. );
  1017. return this;
  1018. },
  1019. lookAt: function ( eye, target, up ) {
  1020. var te = this.elements;
  1021. var x = THREE.Matrix4.__v1;
  1022. var y = THREE.Matrix4.__v2;
  1023. var z = THREE.Matrix4.__v3;
  1024. z.sub( eye, target ).normalize();
  1025. if ( z.length() === 0 ) {
  1026. z.z = 1;
  1027. }
  1028. x.cross( up, z ).normalize();
  1029. if ( x.length() === 0 ) {
  1030. z.x += 0.0001;
  1031. x.cross( up, z ).normalize();
  1032. }
  1033. y.cross( z, x );
  1034. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1035. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1036. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1037. return this;
  1038. },
  1039. multiply: function ( a, b ) {
  1040. var ae = a.elements,
  1041. be = b.elements,
  1042. te = this.elements;
  1043. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1044. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1045. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1046. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1047. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1048. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1049. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1050. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1051. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1052. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1053. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1054. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1055. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1056. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1057. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1058. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1059. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1060. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1061. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1062. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1063. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1064. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1065. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1066. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1067. return this;
  1068. },
  1069. multiplySelf: function ( m ) {
  1070. return this.multiply( this, m );
  1071. },
  1072. multiplyToArray: function ( a, b, r ) {
  1073. var te = this.elements;
  1074. this.multiply( a, b );
  1075. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1076. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1077. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1078. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1079. return this;
  1080. },
  1081. multiplyScalar: function ( s ) {
  1082. var te = this.elements;
  1083. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1084. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1085. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1086. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1087. return this;
  1088. },
  1089. multiplyVector3: function ( v ) {
  1090. var te = this.elements;
  1091. var vx = v.x, vy = v.y, vz = v.z;
  1092. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1093. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1094. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1095. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1096. return v;
  1097. },
  1098. multiplyVector4: function ( v ) {
  1099. var te = this.elements;
  1100. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1101. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1102. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1103. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1104. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1105. return v;
  1106. },
  1107. rotateAxis: function ( v ) {
  1108. var te = this.elements;
  1109. var vx = v.x, vy = v.y, vz = v.z;
  1110. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1111. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1112. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1113. v.normalize();
  1114. return v;
  1115. },
  1116. crossVector: function ( a ) {
  1117. var te = this.elements;
  1118. var v = new THREE.Vector4();
  1119. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1120. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1121. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1122. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1123. return v;
  1124. },
  1125. determinant: function () {
  1126. var te = this.elements;
  1127. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1128. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1129. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1130. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1131. //TODO: make this more efficient
  1132. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1133. return (
  1134. n14 * n23 * n32 * n41-
  1135. n13 * n24 * n32 * n41-
  1136. n14 * n22 * n33 * n41+
  1137. n12 * n24 * n33 * n41+
  1138. n13 * n22 * n34 * n41-
  1139. n12 * n23 * n34 * n41-
  1140. n14 * n23 * n31 * n42+
  1141. n13 * n24 * n31 * n42+
  1142. n14 * n21 * n33 * n42-
  1143. n11 * n24 * n33 * n42-
  1144. n13 * n21 * n34 * n42+
  1145. n11 * n23 * n34 * n42+
  1146. n14 * n22 * n31 * n43-
  1147. n12 * n24 * n31 * n43-
  1148. n14 * n21 * n32 * n43+
  1149. n11 * n24 * n32 * n43+
  1150. n12 * n21 * n34 * n43-
  1151. n11 * n22 * n34 * n43-
  1152. n13 * n22 * n31 * n44+
  1153. n12 * n23 * n31 * n44+
  1154. n13 * n21 * n32 * n44-
  1155. n11 * n23 * n32 * n44-
  1156. n12 * n21 * n33 * n44+
  1157. n11 * n22 * n33 * n44
  1158. );
  1159. },
  1160. transpose: function () {
  1161. var te = this.elements;
  1162. var tmp;
  1163. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1164. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1165. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1166. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1167. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1168. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1169. return this;
  1170. },
  1171. flattenToArray: function ( flat ) {
  1172. var te = this.elements;
  1173. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1174. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1175. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1176. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1177. return flat;
  1178. },
  1179. flattenToArrayOffset: function( flat, offset ) {
  1180. var te = this.elements;
  1181. flat[ offset ] = te[0];
  1182. flat[ offset + 1 ] = te[1];
  1183. flat[ offset + 2 ] = te[2];
  1184. flat[ offset + 3 ] = te[3];
  1185. flat[ offset + 4 ] = te[4];
  1186. flat[ offset + 5 ] = te[5];
  1187. flat[ offset + 6 ] = te[6];
  1188. flat[ offset + 7 ] = te[7];
  1189. flat[ offset + 8 ] = te[8];
  1190. flat[ offset + 9 ] = te[9];
  1191. flat[ offset + 10 ] = te[10];
  1192. flat[ offset + 11 ] = te[11];
  1193. flat[ offset + 12 ] = te[12];
  1194. flat[ offset + 13 ] = te[13];
  1195. flat[ offset + 14 ] = te[14];
  1196. flat[ offset + 15 ] = te[15];
  1197. return flat;
  1198. },
  1199. getPosition: function () {
  1200. var te = this.elements;
  1201. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1202. },
  1203. setPosition: function ( v ) {
  1204. var te = this.elements;
  1205. te[12] = v.x;
  1206. te[13] = v.y;
  1207. te[14] = v.z;
  1208. return this;
  1209. },
  1210. getColumnX: function () {
  1211. var te = this.elements;
  1212. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1213. },
  1214. getColumnY: function () {
  1215. var te = this.elements;
  1216. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1217. },
  1218. getColumnZ: function() {
  1219. var te = this.elements;
  1220. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1221. },
  1222. getInverse: function ( m ) {
  1223. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1224. var te = this.elements;
  1225. var me = m.elements;
  1226. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1227. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1228. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1229. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1230. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1231. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1232. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1233. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1234. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1235. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1236. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1237. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1238. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1239. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1240. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1241. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1242. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1243. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1244. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1245. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1246. this.multiplyScalar( 1 / m.determinant() );
  1247. return this;
  1248. },
  1249. setRotationFromEuler: function( v, order ) {
  1250. var te = this.elements;
  1251. var x = v.x, y = v.y, z = v.z;
  1252. var a = Math.cos( x ), b = Math.sin( x );
  1253. var c = Math.cos( y ), d = Math.sin( y );
  1254. var e = Math.cos( z ), f = Math.sin( z );
  1255. switch ( order ) {
  1256. case 'YXZ':
  1257. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1258. te[0] = ce + df * b;
  1259. te[4] = de * b - cf;
  1260. te[8] = a * d;
  1261. te[1] = a * f;
  1262. te[5] = a * e;
  1263. te[9] = - b;
  1264. te[2] = cf * b - de;
  1265. te[6] = df + ce * b;
  1266. te[10] = a * c;
  1267. break;
  1268. case 'ZXY':
  1269. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1270. te[0] = ce - df * b;
  1271. te[4] = - a * f;
  1272. te[8] = de + cf * b;
  1273. te[1] = cf + de * b;
  1274. te[5] = a * e;
  1275. te[9] = df - ce * b;
  1276. te[2] = - a * d;
  1277. te[6] = b;
  1278. te[10] = a * c;
  1279. break;
  1280. case 'ZYX':
  1281. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1282. te[0] = c * e;
  1283. te[4] = be * d - af;
  1284. te[8] = ae * d + bf;
  1285. te[1] = c * f;
  1286. te[5] = bf * d + ae;
  1287. te[9] = af * d - be;
  1288. te[2] = - d;
  1289. te[6] = b * c;
  1290. te[10] = a * c;
  1291. break;
  1292. case 'YZX':
  1293. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1294. te[0] = c * e;
  1295. te[4] = bd - ac * f;
  1296. te[8] = bc * f + ad;
  1297. te[1] = f;
  1298. te[5] = a * e;
  1299. te[9] = - b * e;
  1300. te[2] = - d * e;
  1301. te[6] = ad * f + bc;
  1302. te[10] = ac - bd * f;
  1303. break;
  1304. case 'XZY':
  1305. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1306. te[0] = c * e;
  1307. te[4] = - f;
  1308. te[8] = d * e;
  1309. te[1] = ac * f + bd;
  1310. te[5] = a * e;
  1311. te[9] = ad * f - bc;
  1312. te[2] = bc * f - ad;
  1313. te[6] = b * e;
  1314. te[10] = bd * f + ac;
  1315. break;
  1316. default: // 'XYZ'
  1317. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1318. te[0] = c * e;
  1319. te[4] = - c * f;
  1320. te[8] = d;
  1321. te[1] = af + be * d;
  1322. te[5] = ae - bf * d;
  1323. te[9] = - b * c;
  1324. te[2] = bf - ae * d;
  1325. te[6] = be + af * d;
  1326. te[10] = a * c;
  1327. break;
  1328. }
  1329. return this;
  1330. },
  1331. setRotationFromQuaternion: function( q ) {
  1332. var te = this.elements;
  1333. var x = q.x, y = q.y, z = q.z, w = q.w;
  1334. var x2 = x + x, y2 = y + y, z2 = z + z;
  1335. var xx = x * x2, xy = x * y2, xz = x * z2;
  1336. var yy = y * y2, yz = y * z2, zz = z * z2;
  1337. var wx = w * x2, wy = w * y2, wz = w * z2;
  1338. te[0] = 1 - ( yy + zz );
  1339. te[4] = xy - wz;
  1340. te[8] = xz + wy;
  1341. te[1] = xy + wz;
  1342. te[5] = 1 - ( xx + zz );
  1343. te[9] = yz - wx;
  1344. te[2] = xz - wy;
  1345. te[6] = yz + wx;
  1346. te[10] = 1 - ( xx + yy );
  1347. return this;
  1348. },
  1349. compose: function ( translation, rotation, scale ) {
  1350. var te = this.elements;
  1351. var mRotation = THREE.Matrix4.__m1;
  1352. var mScale = THREE.Matrix4.__m2;
  1353. mRotation.identity();
  1354. mRotation.setRotationFromQuaternion( rotation );
  1355. mScale.makeScale( scale.x, scale.y, scale.z );
  1356. this.multiply( mRotation, mScale );
  1357. te[12] = translation.x;
  1358. te[13] = translation.y;
  1359. te[14] = translation.z;
  1360. return this;
  1361. },
  1362. decompose: function ( translation, rotation, scale ) {
  1363. // grab the axis vectors
  1364. var te = this.elements;
  1365. var x = THREE.Matrix4.__v1;
  1366. var y = THREE.Matrix4.__v2;
  1367. var z = THREE.Matrix4.__v3;
  1368. x.set( te[0], te[1], te[2] );
  1369. y.set( te[4], te[5], te[6] );
  1370. z.set( te[8], te[9], te[10] );
  1371. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1372. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1373. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1374. scale.x = x.length();
  1375. scale.y = y.length();
  1376. scale.z = z.length();
  1377. translation.x = te[12];
  1378. translation.y = te[13];
  1379. translation.z = te[14];
  1380. // scale the rotation part
  1381. var matrix = THREE.Matrix4.__m1;
  1382. matrix.copy( this );
  1383. matrix.elements[0] /= scale.x;
  1384. matrix.elements[1] /= scale.x;
  1385. matrix.elements[2] /= scale.x;
  1386. matrix.elements[4] /= scale.y;
  1387. matrix.elements[5] /= scale.y;
  1388. matrix.elements[6] /= scale.y;
  1389. matrix.elements[8] /= scale.z;
  1390. matrix.elements[9] /= scale.z;
  1391. matrix.elements[10] /= scale.z;
  1392. rotation.setFromRotationMatrix( matrix );
  1393. return [ translation, rotation, scale ];
  1394. },
  1395. extractPosition: function ( m ) {
  1396. var te = this.elements;
  1397. var me = m.elements;
  1398. te[12] = me[12];
  1399. te[13] = me[13];
  1400. te[14] = me[14];
  1401. return this;
  1402. },
  1403. extractRotation: function ( m ) {
  1404. var te = this.elements;
  1405. var me = m.elements;
  1406. var vector = THREE.Matrix4.__v1;
  1407. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1408. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1409. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1410. te[0] = me[0] * scaleX;
  1411. te[1] = me[1] * scaleX;
  1412. te[2] = me[2] * scaleX;
  1413. te[4] = me[4] * scaleY;
  1414. te[5] = me[5] * scaleY;
  1415. te[6] = me[6] * scaleY;
  1416. te[8] = me[8] * scaleZ;
  1417. te[9] = me[9] * scaleZ;
  1418. te[10] = me[10] * scaleZ;
  1419. return this;
  1420. },
  1421. //
  1422. translate: function ( v ) {
  1423. var te = this.elements;
  1424. var x = v.x, y = v.y, z = v.z;
  1425. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1426. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1427. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1428. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1429. return this;
  1430. },
  1431. rotateX: function ( angle ) {
  1432. var te = this.elements;
  1433. var m12 = te[4];
  1434. var m22 = te[5];
  1435. var m32 = te[6];
  1436. var m42 = te[7];
  1437. var m13 = te[8];
  1438. var m23 = te[9];
  1439. var m33 = te[10];
  1440. var m43 = te[11];
  1441. var c = Math.cos( angle );
  1442. var s = Math.sin( angle );
  1443. te[4] = c * m12 + s * m13;
  1444. te[5] = c * m22 + s * m23;
  1445. te[6] = c * m32 + s * m33;
  1446. te[7] = c * m42 + s * m43;
  1447. te[8] = c * m13 - s * m12;
  1448. te[9] = c * m23 - s * m22;
  1449. te[10] = c * m33 - s * m32;
  1450. te[11] = c * m43 - s * m42;
  1451. return this;
  1452. },
  1453. rotateY: function ( angle ) {
  1454. var te = this.elements;
  1455. var m11 = te[0];
  1456. var m21 = te[1];
  1457. var m31 = te[2];
  1458. var m41 = te[3];
  1459. var m13 = te[8];
  1460. var m23 = te[9];
  1461. var m33 = te[10];
  1462. var m43 = te[11];
  1463. var c = Math.cos( angle );
  1464. var s = Math.sin( angle );
  1465. te[0] = c * m11 - s * m13;
  1466. te[1] = c * m21 - s * m23;
  1467. te[2] = c * m31 - s * m33;
  1468. te[3] = c * m41 - s * m43;
  1469. te[8] = c * m13 + s * m11;
  1470. te[9] = c * m23 + s * m21;
  1471. te[10] = c * m33 + s * m31;
  1472. te[11] = c * m43 + s * m41;
  1473. return this;
  1474. },
  1475. rotateZ: function ( angle ) {
  1476. var te = this.elements;
  1477. var m11 = te[0];
  1478. var m21 = te[1];
  1479. var m31 = te[2];
  1480. var m41 = te[3];
  1481. var m12 = te[4];
  1482. var m22 = te[5];
  1483. var m32 = te[6];
  1484. var m42 = te[7];
  1485. var c = Math.cos( angle );
  1486. var s = Math.sin( angle );
  1487. te[0] = c * m11 + s * m12;
  1488. te[1] = c * m21 + s * m22;
  1489. te[2] = c * m31 + s * m32;
  1490. te[3] = c * m41 + s * m42;
  1491. te[4] = c * m12 - s * m11;
  1492. te[5] = c * m22 - s * m21;
  1493. te[6] = c * m32 - s * m31;
  1494. te[7] = c * m42 - s * m41;
  1495. return this;
  1496. },
  1497. rotateByAxis: function ( axis, angle ) {
  1498. var te = this.elements;
  1499. // optimize by checking axis
  1500. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1501. return this.rotateX( angle );
  1502. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1503. return this.rotateY( angle );
  1504. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1505. return this.rotateZ( angle );
  1506. }
  1507. var x = axis.x, y = axis.y, z = axis.z;
  1508. var n = Math.sqrt(x * x + y * y + z * z);
  1509. x /= n;
  1510. y /= n;
  1511. z /= n;
  1512. var xx = x * x, yy = y * y, zz = z * z;
  1513. var c = Math.cos( angle );
  1514. var s = Math.sin( angle );
  1515. var oneMinusCosine = 1 - c;
  1516. var xy = x * y * oneMinusCosine;
  1517. var xz = x * z * oneMinusCosine;
  1518. var yz = y * z * oneMinusCosine;
  1519. var xs = x * s;
  1520. var ys = y * s;
  1521. var zs = z * s;
  1522. var r11 = xx + (1 - xx) * c;
  1523. var r21 = xy + zs;
  1524. var r31 = xz - ys;
  1525. var r12 = xy - zs;
  1526. var r22 = yy + (1 - yy) * c;
  1527. var r32 = yz + xs;
  1528. var r13 = xz + ys;
  1529. var r23 = yz - xs;
  1530. var r33 = zz + (1 - zz) * c;
  1531. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1532. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1533. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1534. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1535. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1536. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1537. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1538. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1539. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1540. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1541. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1542. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1543. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1544. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1545. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1546. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1547. return this;
  1548. },
  1549. scale: function ( v ) {
  1550. var te = this.elements;
  1551. var x = v.x, y = v.y, z = v.z;
  1552. te[0] *= x; te[4] *= y; te[8] *= z;
  1553. te[1] *= x; te[5] *= y; te[9] *= z;
  1554. te[2] *= x; te[6] *= y; te[10] *= z;
  1555. te[3] *= x; te[7] *= y; te[11] *= z;
  1556. return this;
  1557. },
  1558. //
  1559. makeTranslation: function ( x, y, z ) {
  1560. this.set(
  1561. 1, 0, 0, x,
  1562. 0, 1, 0, y,
  1563. 0, 0, 1, z,
  1564. 0, 0, 0, 1
  1565. );
  1566. return this;
  1567. },
  1568. makeRotationX: function ( theta ) {
  1569. var c = Math.cos( theta ), s = Math.sin( theta );
  1570. this.set(
  1571. 1, 0, 0, 0,
  1572. 0, c, -s, 0,
  1573. 0, s, c, 0,
  1574. 0, 0, 0, 1
  1575. );
  1576. return this;
  1577. },
  1578. makeRotationY: function ( theta ) {
  1579. var c = Math.cos( theta ), s = Math.sin( theta );
  1580. this.set(
  1581. c, 0, s, 0,
  1582. 0, 1, 0, 0,
  1583. -s, 0, c, 0,
  1584. 0, 0, 0, 1
  1585. );
  1586. return this;
  1587. },
  1588. makeRotationZ: function ( theta ) {
  1589. var c = Math.cos( theta ), s = Math.sin( theta );
  1590. this.set(
  1591. c, -s, 0, 0,
  1592. s, c, 0, 0,
  1593. 0, 0, 1, 0,
  1594. 0, 0, 0, 1
  1595. );
  1596. return this;
  1597. },
  1598. makeRotationAxis: function ( axis, angle ) {
  1599. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1600. var c = Math.cos( angle );
  1601. var s = Math.sin( angle );
  1602. var t = 1 - c;
  1603. var x = axis.x, y = axis.y, z = axis.z;
  1604. var tx = t * x, ty = t * y;
  1605. this.set(
  1606. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1607. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1608. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1609. 0, 0, 0, 1
  1610. );
  1611. return this;
  1612. },
  1613. makeScale: function ( x, y, z ) {
  1614. this.set(
  1615. x, 0, 0, 0,
  1616. 0, y, 0, 0,
  1617. 0, 0, z, 0,
  1618. 0, 0, 0, 1
  1619. );
  1620. return this;
  1621. },
  1622. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1623. var te = this.elements;
  1624. var x = 2 * near / ( right - left );
  1625. var y = 2 * near / ( top - bottom );
  1626. var a = ( right + left ) / ( right - left );
  1627. var b = ( top + bottom ) / ( top - bottom );
  1628. var c = - ( far + near ) / ( far - near );
  1629. var d = - 2 * far * near / ( far - near );
  1630. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1631. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1632. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1633. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1634. return this;
  1635. },
  1636. makePerspective: function ( fov, aspect, near, far ) {
  1637. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1638. var ymin = - ymax;
  1639. var xmin = ymin * aspect;
  1640. var xmax = ymax * aspect;
  1641. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1642. },
  1643. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1644. var te = this.elements;
  1645. var w = right - left;
  1646. var h = top - bottom;
  1647. var p = far - near;
  1648. var x = ( right + left ) / w;
  1649. var y = ( top + bottom ) / h;
  1650. var z = ( far + near ) / p;
  1651. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1652. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1653. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1654. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1655. return this;
  1656. },
  1657. clone: function () {
  1658. var te = this.elements;
  1659. return new THREE.Matrix4(
  1660. te[0], te[4], te[8], te[12],
  1661. te[1], te[5], te[9], te[13],
  1662. te[2], te[6], te[10], te[14],
  1663. te[3], te[7], te[11], te[15]
  1664. );
  1665. }
  1666. };
  1667. THREE.Matrix4.__v1 = new THREE.Vector3();
  1668. THREE.Matrix4.__v2 = new THREE.Vector3();
  1669. THREE.Matrix4.__v3 = new THREE.Vector3();
  1670. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1671. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1672. /**
  1673. * @author mr.doob / http://mrdoob.com/
  1674. * @author mikael emtinger / http://gomo.se/
  1675. * @author alteredq / http://alteredqualia.com/
  1676. */
  1677. THREE.Object3D = function () {
  1678. this.id = THREE.Object3DCount ++;
  1679. this.name = '';
  1680. this.parent = undefined;
  1681. this.children = [];
  1682. this.up = new THREE.Vector3( 0, 1, 0 );
  1683. this.position = new THREE.Vector3();
  1684. this.rotation = new THREE.Vector3();
  1685. this.eulerOrder = 'XYZ';
  1686. this.scale = new THREE.Vector3( 1, 1, 1 );
  1687. this.doubleSided = false;
  1688. this.flipSided = false;
  1689. this.renderDepth = null;
  1690. this.rotationAutoUpdate = true;
  1691. this.matrix = new THREE.Matrix4();
  1692. this.matrixWorld = new THREE.Matrix4();
  1693. this.matrixRotationWorld = new THREE.Matrix4();
  1694. this.matrixAutoUpdate = true;
  1695. this.matrixWorldNeedsUpdate = true;
  1696. this.quaternion = new THREE.Quaternion();
  1697. this.useQuaternion = false;
  1698. this.boundRadius = 0.0;
  1699. this.boundRadiusScale = 1.0;
  1700. this.visible = true;
  1701. this.castShadow = false;
  1702. this.receiveShadow = false;
  1703. this.frustumCulled = true;
  1704. this._vector = new THREE.Vector3();
  1705. };
  1706. THREE.Object3D.prototype = {
  1707. constructor: THREE.Object3D,
  1708. applyMatrix: function ( matrix ) {
  1709. this.matrix.multiply( matrix, this.matrix );
  1710. this.scale.getScaleFromMatrix( this.matrix );
  1711. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  1712. this.position.getPositionFromMatrix( this.matrix );
  1713. },
  1714. translate: function ( distance, axis ) {
  1715. this.matrix.rotateAxis( axis );
  1716. this.position.addSelf( axis.multiplyScalar( distance ) );
  1717. },
  1718. translateX: function ( distance ) {
  1719. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  1720. },
  1721. translateY: function ( distance ) {
  1722. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  1723. },
  1724. translateZ: function ( distance ) {
  1725. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  1726. },
  1727. lookAt: function ( vector ) {
  1728. // TODO: Add hierarchy support.
  1729. this.matrix.lookAt( vector, this.position, this.up );
  1730. if ( this.rotationAutoUpdate ) {
  1731. this.rotation.getRotationFromMatrix( this.matrix );
  1732. }
  1733. },
  1734. add: function ( object ) {
  1735. if ( object === this ) {
  1736. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  1737. return;
  1738. }
  1739. if ( this.children.indexOf( object ) === - 1 ) {
  1740. if ( object.parent !== undefined ) {
  1741. object.parent.remove( object );
  1742. }
  1743. object.parent = this;
  1744. this.children.push( object );
  1745. // add to scene
  1746. var scene = this;
  1747. while ( scene.parent !== undefined ) {
  1748. scene = scene.parent;
  1749. }
  1750. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1751. scene.__addObject( object );
  1752. }
  1753. }
  1754. },
  1755. remove: function ( object ) {
  1756. var index = this.children.indexOf( object );
  1757. if ( index !== - 1 ) {
  1758. object.parent = undefined;
  1759. this.children.splice( index, 1 );
  1760. // remove from scene
  1761. var scene = this;
  1762. while ( scene.parent !== undefined ) {
  1763. scene = scene.parent;
  1764. }
  1765. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1766. scene.__removeObject( object );
  1767. }
  1768. }
  1769. },
  1770. getChildByName: function ( name, recursive ) {
  1771. var c, cl, child;
  1772. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  1773. child = this.children[ c ];
  1774. if ( child.name === name ) {
  1775. return child;
  1776. }
  1777. if ( recursive ) {
  1778. child = child.getChildByName( name, recursive );
  1779. if ( child !== undefined ) {
  1780. return child;
  1781. }
  1782. }
  1783. }
  1784. return undefined;
  1785. },
  1786. updateMatrix: function () {
  1787. this.matrix.setPosition( this.position );
  1788. if ( this.useQuaternion ) {
  1789. this.matrix.setRotationFromQuaternion( this.quaternion );
  1790. } else {
  1791. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  1792. }
  1793. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  1794. this.matrix.scale( this.scale );
  1795. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  1796. }
  1797. this.matrixWorldNeedsUpdate = true;
  1798. },
  1799. updateMatrixWorld: function ( force ) {
  1800. this.matrixAutoUpdate && this.updateMatrix();
  1801. // update matrixWorld
  1802. if ( this.matrixWorldNeedsUpdate || force ) {
  1803. if ( this.parent ) {
  1804. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  1805. } else {
  1806. this.matrixWorld.copy( this.matrix );
  1807. }
  1808. this.matrixWorldNeedsUpdate = false;
  1809. force = true;
  1810. }
  1811. // update children
  1812. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  1813. this.children[ i ].updateMatrixWorld( force );
  1814. }
  1815. }
  1816. };
  1817. THREE.Object3DCount = 0;
  1818. /**
  1819. * @author mr.doob / http://mrdoob.com/
  1820. * @author supereggbert / http://www.paulbrunt.co.uk/
  1821. * @author julianwa / https://github.com/julianwa
  1822. */
  1823. THREE.Projector = function() {
  1824. var _object, _objectCount, _objectPool = [],
  1825. _vertex, _vertexCount, _vertexPool = [],
  1826. _face, _face3Count, _face3Pool = [], _face4Count, _face4Pool = [],
  1827. _line, _lineCount, _linePool = [],
  1828. _particle, _particleCount, _particlePool = [],
  1829. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  1830. _vector3 = new THREE.Vector3(),
  1831. _vector4 = new THREE.Vector4(),
  1832. _projScreenMatrix = new THREE.Matrix4(),
  1833. _projScreenobjectMatrixWorld = new THREE.Matrix4(),
  1834. _frustum = new THREE.Frustum(),
  1835. _clippedVertex1PositionScreen = new THREE.Vector4(),
  1836. _clippedVertex2PositionScreen = new THREE.Vector4(),
  1837. _face3VertexNormals;
  1838. this.projectVector = function ( vector, camera ) {
  1839. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1840. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1841. _projScreenMatrix.multiplyVector3( vector );
  1842. return vector;
  1843. };
  1844. this.unprojectVector = function ( vector, camera ) {
  1845. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  1846. _projScreenMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  1847. _projScreenMatrix.multiplyVector3( vector );
  1848. return vector;
  1849. };
  1850. this.pickingRay = function ( vector, camera ) {
  1851. var end, ray, t;
  1852. // set two vectors with opposing z values
  1853. vector.z = -1.0;
  1854. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  1855. this.unprojectVector( vector, camera );
  1856. this.unprojectVector( end, camera );
  1857. // find direction from vector to end
  1858. end.subSelf( vector ).normalize();
  1859. return new THREE.Ray( vector, end );
  1860. };
  1861. this.projectGraph = function ( root, sort ) {
  1862. _objectCount = 0;
  1863. _renderData.objects.length = 0;
  1864. _renderData.sprites.length = 0;
  1865. _renderData.lights.length = 0;
  1866. var projectObject = function ( object ) {
  1867. if ( object.visible === false ) return;
  1868. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  1869. ( object.frustumCulled === false || _frustum.contains( object ) ) ) {
  1870. _vector3.copy( object.matrixWorld.getPosition() );
  1871. _projScreenMatrix.multiplyVector3( _vector3 );
  1872. _object = getNextObjectInPool();
  1873. _object.object = object;
  1874. _object.z = _vector3.z;
  1875. _renderData.objects.push( _object );
  1876. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  1877. _vector3.copy( object.matrixWorld.getPosition() );
  1878. _projScreenMatrix.multiplyVector3( _vector3 );
  1879. _object = getNextObjectInPool();
  1880. _object.object = object;
  1881. _object.z = _vector3.z;
  1882. _renderData.sprites.push( _object );
  1883. } else if ( object instanceof THREE.Light ) {
  1884. _renderData.lights.push( object );
  1885. }
  1886. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  1887. projectObject( object.children[ c ] );
  1888. }
  1889. };
  1890. projectObject( root );
  1891. sort && _renderData.objects.sort( painterSort );
  1892. return _renderData;
  1893. };
  1894. this.projectScene = function ( scene, camera, sort ) {
  1895. var near = camera.near, far = camera.far, visible = false,
  1896. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  1897. objectMatrixWorld, objectMatrixWorldRotation,
  1898. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  1899. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  1900. v1, v2, v3, v4;
  1901. _face3Count = 0;
  1902. _face4Count = 0;
  1903. _lineCount = 0;
  1904. _particleCount = 0;
  1905. _renderData.elements.length = 0;
  1906. if ( camera.parent === undefined ) {
  1907. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  1908. scene.add( camera );
  1909. }
  1910. scene.updateMatrixWorld();
  1911. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1912. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1913. _frustum.setFromMatrix( _projScreenMatrix );
  1914. _renderData = this.projectGraph( scene, false );
  1915. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  1916. object = _renderData.objects[ o ].object;
  1917. objectMatrixWorld = object.matrixWorld;
  1918. _vertexCount = 0;
  1919. if ( object instanceof THREE.Mesh ) {
  1920. geometry = object.geometry;
  1921. geometryMaterials = object.geometry.materials;
  1922. vertices = geometry.vertices;
  1923. faces = geometry.faces;
  1924. faceVertexUvs = geometry.faceVertexUvs;
  1925. objectMatrixWorldRotation = object.matrixRotationWorld.extractRotation( objectMatrixWorld );
  1926. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  1927. _vertex = getNextVertexInPool();
  1928. _vertex.positionWorld.copy( vertices[ v ].position );
  1929. objectMatrixWorld.multiplyVector3( _vertex.positionWorld );
  1930. _vertex.positionScreen.copy( _vertex.positionWorld );
  1931. _projScreenMatrix.multiplyVector4( _vertex.positionScreen );
  1932. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  1933. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  1934. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  1935. }
  1936. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  1937. face = faces[ f ];
  1938. if ( face instanceof THREE.Face3 ) {
  1939. v1 = _vertexPool[ face.a ];
  1940. v2 = _vertexPool[ face.b ];
  1941. v3 = _vertexPool[ face.c ];
  1942. if ( v1.visible && v2.visible && v3.visible ) {
  1943. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1944. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  1945. if ( object.doubleSided || visible != object.flipSided ) {
  1946. _face = getNextFace3InPool();
  1947. _face.v1.copy( v1 );
  1948. _face.v2.copy( v2 );
  1949. _face.v3.copy( v3 );
  1950. } else {
  1951. continue;
  1952. }
  1953. } else {
  1954. continue;
  1955. }
  1956. } else if ( face instanceof THREE.Face4 ) {
  1957. v1 = _vertexPool[ face.a ];
  1958. v2 = _vertexPool[ face.b ];
  1959. v3 = _vertexPool[ face.c ];
  1960. v4 = _vertexPool[ face.d ];
  1961. if ( v1.visible && v2.visible && v3.visible && v4.visible ) {
  1962. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1963. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  1964. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  1965. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  1966. if ( object.doubleSided || visible != object.flipSided ) {
  1967. _face = getNextFace4InPool();
  1968. _face.v1.copy( v1 );
  1969. _face.v2.copy( v2 );
  1970. _face.v3.copy( v3 );
  1971. _face.v4.copy( v4 );
  1972. } else {
  1973. continue;
  1974. }
  1975. } else {
  1976. continue;
  1977. }
  1978. }
  1979. _face.normalWorld.copy( face.normal );
  1980. if ( !visible && ( object.flipSided || object.doubleSided ) ) _face.normalWorld.negate();
  1981. objectMatrixWorldRotation.multiplyVector3( _face.normalWorld );
  1982. _face.centroidWorld.copy( face.centroid );
  1983. objectMatrixWorld.multiplyVector3( _face.centroidWorld );
  1984. _face.centroidScreen.copy( _face.centroidWorld );
  1985. _projScreenMatrix.multiplyVector3( _face.centroidScreen );
  1986. faceVertexNormals = face.vertexNormals;
  1987. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  1988. normal = _face.vertexNormalsWorld[ n ];
  1989. normal.copy( faceVertexNormals[ n ] );
  1990. if ( !visible && ( object.flipSided || object.doubleSided ) ) normal.negate();
  1991. objectMatrixWorldRotation.multiplyVector3( normal );
  1992. }
  1993. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  1994. uvs = faceVertexUvs[ c ][ f ];
  1995. if ( !uvs ) continue;
  1996. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  1997. _face.uvs[ c ][ u ] = uvs[ u ];
  1998. }
  1999. }
  2000. _face.material = object.material;
  2001. _face.faceMaterial = face.materialIndex !== null ? geometryMaterials[ face.materialIndex ] : null;
  2002. _face.z = _face.centroidScreen.z;
  2003. _renderData.elements.push( _face );
  2004. }
  2005. } else if ( object instanceof THREE.Line ) {
  2006. _projScreenobjectMatrixWorld.multiply( _projScreenMatrix, objectMatrixWorld );
  2007. vertices = object.geometry.vertices;
  2008. v1 = getNextVertexInPool();
  2009. v1.positionScreen.copy( vertices[ 0 ].position );
  2010. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2011. // Handle LineStrip and LinePieces
  2012. var step = object.type === THREE.LinePieces ? 2 : 1;
  2013. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2014. v1 = getNextVertexInPool();
  2015. v1.positionScreen.copy( vertices[ v ].position );
  2016. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2017. if ( ( v + 1 ) % step > 0 ) continue;
  2018. v2 = _vertexPool[ _vertexCount - 2 ];
  2019. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2020. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2021. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) ) {
  2022. // Perform the perspective divide
  2023. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2024. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2025. _line = getNextLineInPool();
  2026. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2027. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2028. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2029. _line.material = object.material;
  2030. _renderData.elements.push( _line );
  2031. }
  2032. }
  2033. }
  2034. }
  2035. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2036. object = _renderData.sprites[ o ].object;
  2037. objectMatrixWorld = object.matrixWorld;
  2038. if ( object instanceof THREE.Particle ) {
  2039. _vector4.set( objectMatrixWorld.elements[12], objectMatrixWorld.elements[13], objectMatrixWorld.elements[14], 1 );
  2040. _projScreenMatrix.multiplyVector4( _vector4 );
  2041. _vector4.z /= _vector4.w;
  2042. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2043. _particle = getNextParticleInPool();
  2044. _particle.x = _vector4.x / _vector4.w;
  2045. _particle.y = _vector4.y / _vector4.w;
  2046. _particle.z = _vector4.z;
  2047. _particle.rotation = object.rotation.z;
  2048. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2049. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2050. _particle.material = object.material;
  2051. _renderData.elements.push( _particle );
  2052. }
  2053. }
  2054. }
  2055. sort && _renderData.elements.sort( painterSort );
  2056. return _renderData;
  2057. };
  2058. // Pools
  2059. function getNextObjectInPool() {
  2060. var object = _objectPool[ _objectCount ] = _objectPool[ _objectCount ] || new THREE.RenderableObject();
  2061. _objectCount ++;
  2062. return object;
  2063. }
  2064. function getNextVertexInPool() {
  2065. var vertex = _vertexPool[ _vertexCount ] = _vertexPool[ _vertexCount ] || new THREE.RenderableVertex();
  2066. _vertexCount ++;
  2067. return vertex;
  2068. }
  2069. function getNextFace3InPool() {
  2070. var face = _face3Pool[ _face3Count ] = _face3Pool[ _face3Count ] || new THREE.RenderableFace3();
  2071. _face3Count ++;
  2072. return face;
  2073. }
  2074. function getNextFace4InPool() {
  2075. var face = _face4Pool[ _face4Count ] = _face4Pool[ _face4Count ] || new THREE.RenderableFace4();
  2076. _face4Count ++;
  2077. return face;
  2078. }
  2079. function getNextLineInPool() {
  2080. var line = _linePool[ _lineCount ] = _linePool[ _lineCount ] || new THREE.RenderableLine();
  2081. _lineCount ++;
  2082. return line;
  2083. }
  2084. function getNextParticleInPool() {
  2085. var particle = _particlePool[ _particleCount ] = _particlePool[ _particleCount ] || new THREE.RenderableParticle();
  2086. _particleCount ++;
  2087. return particle;
  2088. }
  2089. //
  2090. function painterSort( a, b ) {
  2091. return b.z - a.z;
  2092. }
  2093. function clipLine( s1, s2 ) {
  2094. var alpha1 = 0, alpha2 = 1,
  2095. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2096. // Z = -1 and Z = +1, respectively.
  2097. bc1near = s1.z + s1.w,
  2098. bc2near = s2.z + s2.w,
  2099. bc1far = - s1.z + s1.w,
  2100. bc2far = - s2.z + s2.w;
  2101. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2102. // Both vertices lie entirely within all clip planes.
  2103. return true;
  2104. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2105. // Both vertices lie entirely outside one of the clip planes.
  2106. return false;
  2107. } else {
  2108. // The line segment spans at least one clip plane.
  2109. if ( bc1near < 0 ) {
  2110. // v1 lies outside the near plane, v2 inside
  2111. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2112. } else if ( bc2near < 0 ) {
  2113. // v2 lies outside the near plane, v1 inside
  2114. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2115. }
  2116. if ( bc1far < 0 ) {
  2117. // v1 lies outside the far plane, v2 inside
  2118. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2119. } else if ( bc2far < 0 ) {
  2120. // v2 lies outside the far plane, v2 inside
  2121. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2122. }
  2123. if ( alpha2 < alpha1 ) {
  2124. // The line segment spans two boundaries, but is outside both of them.
  2125. // (This can't happen when we're only clipping against just near/far but good
  2126. // to leave the check here for future usage if other clip planes are added.)
  2127. return false;
  2128. } else {
  2129. // Update the s1 and s2 vertices to match the clipped line segment.
  2130. s1.lerpSelf( s2, alpha1 );
  2131. s2.lerpSelf( s1, 1 - alpha2 );
  2132. return true;
  2133. }
  2134. }
  2135. }
  2136. };
  2137. /**
  2138. * @author mikael emtinger / http://gomo.se/
  2139. * @author alteredq / http://alteredqualia.com/
  2140. */
  2141. THREE.Quaternion = function( x, y, z, w ) {
  2142. this.x = x || 0;
  2143. this.y = y || 0;
  2144. this.z = z || 0;
  2145. this.w = ( w !== undefined ) ? w : 1;
  2146. };
  2147. THREE.Quaternion.prototype = {
  2148. constructor: THREE.Quaternion,
  2149. set: function ( x, y, z, w ) {
  2150. this.x = x;
  2151. this.y = y;
  2152. this.z = z;
  2153. this.w = w;
  2154. return this;
  2155. },
  2156. copy: function ( q ) {
  2157. this.x = q.x;
  2158. this.y = q.y;
  2159. this.z = q.z;
  2160. this.w = q.w;
  2161. return this;
  2162. },
  2163. setFromEuler: function ( vector ) {
  2164. var c = Math.PI / 360, // 0.5 * Math.PI / 360, // 0.5 is an optimization
  2165. x = vector.x * c,
  2166. y = vector.y * c,
  2167. z = vector.z * c,
  2168. c1 = Math.cos( y ),
  2169. s1 = Math.sin( y ),
  2170. c2 = Math.cos( -z ),
  2171. s2 = Math.sin( -z ),
  2172. c3 = Math.cos( x ),
  2173. s3 = Math.sin( x ),
  2174. c1c2 = c1 * c2,
  2175. s1s2 = s1 * s2;
  2176. this.w = c1c2 * c3 - s1s2 * s3;
  2177. this.x = c1c2 * s3 + s1s2 * c3;
  2178. this.y = s1 * c2 * c3 + c1 * s2 * s3;
  2179. this.z = c1 * s2 * c3 - s1 * c2 * s3;
  2180. return this;
  2181. },
  2182. setFromAxisAngle: function ( axis, angle ) {
  2183. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2184. // axis have to be normalized
  2185. var halfAngle = angle / 2,
  2186. s = Math.sin( halfAngle );
  2187. this.x = axis.x * s;
  2188. this.y = axis.y * s;
  2189. this.z = axis.z * s;
  2190. this.w = Math.cos( halfAngle );
  2191. return this;
  2192. },
  2193. setFromRotationMatrix: function ( m ) {
  2194. // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2195. function copySign( a, b ) {
  2196. return b < 0 ? -Math.abs( a ) : Math.abs( a );
  2197. }
  2198. var absQ = Math.pow( m.determinant(), 1.0 / 3.0 );
  2199. this.w = Math.sqrt( Math.max( 0, absQ + m.elements[0] + m.elements[5] + m.elements[10] ) ) / 2;
  2200. this.x = Math.sqrt( Math.max( 0, absQ + m.elements[0] - m.elements[5] - m.elements[10] ) ) / 2;
  2201. this.y = Math.sqrt( Math.max( 0, absQ - m.elements[0] + m.elements[5] - m.elements[10] ) ) / 2;
  2202. this.z = Math.sqrt( Math.max( 0, absQ - m.elements[0] - m.elements[5] + m.elements[10] ) ) / 2;
  2203. this.x = copySign( this.x, ( m.elements[6] - m.elements[9] ) );
  2204. this.y = copySign( this.y, ( m.elements[8] - m.elements[2] ) );
  2205. this.z = copySign( this.z, ( m.elements[1] - m.elements[4] ) );
  2206. this.normalize();
  2207. return this;
  2208. },
  2209. calculateW : function () {
  2210. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2211. return this;
  2212. },
  2213. inverse: function () {
  2214. this.x *= -1;
  2215. this.y *= -1;
  2216. this.z *= -1;
  2217. return this;
  2218. },
  2219. length: function () {
  2220. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2221. },
  2222. normalize: function () {
  2223. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2224. if ( l === 0 ) {
  2225. this.x = 0;
  2226. this.y = 0;
  2227. this.z = 0;
  2228. this.w = 0;
  2229. } else {
  2230. l = 1 / l;
  2231. this.x = this.x * l;
  2232. this.y = this.y * l;
  2233. this.z = this.z * l;
  2234. this.w = this.w * l;
  2235. }
  2236. return this;
  2237. },
  2238. multiply: function ( a, b ) {
  2239. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2240. this.x = a.x * b.w + a.y * b.z - a.z * b.y + a.w * b.x;
  2241. this.y = -a.x * b.z + a.y * b.w + a.z * b.x + a.w * b.y;
  2242. this.z = a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z;
  2243. this.w = -a.x * b.x - a.y * b.y - a.z * b.z + a.w * b.w;
  2244. return this;
  2245. },
  2246. multiplySelf: function ( b ) {
  2247. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2248. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2249. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2250. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2251. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2252. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2253. return this;
  2254. },
  2255. multiplyVector3: function ( vector, dest ) {
  2256. if ( !dest ) { dest = vector; }
  2257. var x = vector.x, y = vector.y, z = vector.z,
  2258. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2259. // calculate quat * vector
  2260. var ix = qw * x + qy * z - qz * y,
  2261. iy = qw * y + qz * x - qx * z,
  2262. iz = qw * z + qx * y - qy * x,
  2263. iw = -qx * x - qy * y - qz * z;
  2264. // calculate result * inverse quat
  2265. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2266. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2267. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2268. return dest;
  2269. },
  2270. clone: function () {
  2271. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2272. }
  2273. }
  2274. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2275. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2276. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2277. if (cosHalfTheta < 0) {
  2278. qm.w = -qb.w; qm.x = -qb.x; qm.y = -qb.y; qm.z = -qb.z;
  2279. cosHalfTheta = -cosHalfTheta;
  2280. } else {
  2281. qm.copy(qb);
  2282. }
  2283. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2284. qm.w = qa.w; qm.x = qa.x; qm.y = qa.y; qm.z = qa.z;
  2285. return qm;
  2286. }
  2287. var halfTheta = Math.acos( cosHalfTheta ),
  2288. sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2289. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2290. qm.w = 0.5 * ( qa.w + qb.w );
  2291. qm.x = 0.5 * ( qa.x + qb.x );
  2292. qm.y = 0.5 * ( qa.y + qb.y );
  2293. qm.z = 0.5 * ( qa.z + qb.z );
  2294. return qm;
  2295. }
  2296. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2297. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2298. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2299. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2300. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2301. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2302. return qm;
  2303. }
  2304. /**
  2305. * @author mr.doob / http://mrdoob.com/
  2306. */
  2307. THREE.Vertex = function ( position ) {
  2308. this.position = position || new THREE.Vector3();
  2309. };
  2310. THREE.Vertex.prototype = {
  2311. constructor: THREE.Vertex,
  2312. clone: function () {
  2313. return new THREE.Vertex( this.position.clone() );
  2314. }
  2315. };
  2316. /**
  2317. * @author mr.doob / http://mrdoob.com/
  2318. * @author alteredq / http://alteredqualia.com/
  2319. */
  2320. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2321. this.a = a;
  2322. this.b = b;
  2323. this.c = c;
  2324. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2325. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2326. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2327. this.vertexColors = color instanceof Array ? color : [];
  2328. this.vertexTangents = [];
  2329. this.materialIndex = materialIndex;
  2330. this.centroid = new THREE.Vector3();
  2331. };
  2332. THREE.Face3.prototype = {
  2333. constructor: THREE.Face3,
  2334. clone: function () {
  2335. var face = new THREE.Face3( this.a, this.b, this.c );
  2336. face.normal.copy( this.normal );
  2337. face.color.copy( this.color );
  2338. face.centroid.copy( this.centroid );
  2339. face.materialIndex = this.materialIndex;
  2340. var i, il;
  2341. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2342. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2343. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2344. return face;
  2345. }
  2346. };
  2347. /**
  2348. * @author mr.doob / http://mrdoob.com/
  2349. * @author alteredq / http://alteredqualia.com/
  2350. */
  2351. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2352. this.a = a;
  2353. this.b = b;
  2354. this.c = c;
  2355. this.d = d;
  2356. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2357. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2358. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2359. this.vertexColors = color instanceof Array ? color : [];
  2360. this.vertexTangents = [];
  2361. this.materialIndex = materialIndex;
  2362. this.centroid = new THREE.Vector3();
  2363. };
  2364. THREE.Face4.prototype = {
  2365. constructor: THREE.Face4,
  2366. clone: function () {
  2367. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2368. face.normal.copy( this.normal );
  2369. face.color.copy( this.color );
  2370. face.centroid.copy( this.centroid );
  2371. face.materialIndex = this.materialIndex;
  2372. var i, il;
  2373. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2374. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2375. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2376. return face;
  2377. }
  2378. };
  2379. /**
  2380. * @author mr.doob / http://mrdoob.com/
  2381. */
  2382. THREE.UV = function ( u, v ) {
  2383. this.u = u || 0;
  2384. this.v = v || 0;
  2385. };
  2386. THREE.UV.prototype = {
  2387. constructor: THREE.UV,
  2388. set: function ( u, v ) {
  2389. this.u = u;
  2390. this.v = v;
  2391. return this;
  2392. },
  2393. copy: function ( uv ) {
  2394. this.u = uv.u;
  2395. this.v = uv.v;
  2396. return this;
  2397. },
  2398. lerpSelf: function ( uv, alpha ) {
  2399. this.u += ( uv.u - this.u ) * alpha;
  2400. this.v += ( uv.v - this.v ) * alpha;
  2401. return this;
  2402. },
  2403. clone: function () {
  2404. return new THREE.UV( this.u, this.v );
  2405. }
  2406. };
  2407. /**
  2408. * @author mr.doob / http://mrdoob.com/
  2409. * @author kile / http://kile.stravaganza.org/
  2410. * @author alteredq / http://alteredqualia.com/
  2411. * @author mikael emtinger / http://gomo.se/
  2412. * @author zz85 / http://www.lab4games.net/zz85/blog
  2413. */
  2414. THREE.Geometry = function () {
  2415. this.id = THREE.GeometryCount ++;
  2416. this.vertices = [];
  2417. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2418. this.materials = [];
  2419. this.faces = [];
  2420. this.faceUvs = [[]];
  2421. this.faceVertexUvs = [[]];
  2422. this.morphTargets = [];
  2423. this.morphColors = [];
  2424. this.morphNormals = [];
  2425. this.skinWeights = [];
  2426. this.skinIndices = [];
  2427. this.boundingBox = null;
  2428. this.boundingSphere = null;
  2429. this.hasTangents = false;
  2430. this.dynamic = false; // unless set to true the *Arrays will be deleted once sent to a buffer.
  2431. };
  2432. THREE.Geometry.prototype = {
  2433. constructor : THREE.Geometry,
  2434. applyMatrix: function ( matrix ) {
  2435. var matrixRotation = new THREE.Matrix4();
  2436. matrixRotation.extractRotation( matrix );
  2437. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2438. var vertex = this.vertices[ i ];
  2439. matrix.multiplyVector3( vertex.position );
  2440. }
  2441. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2442. var face = this.faces[ i ];
  2443. matrixRotation.multiplyVector3( face.normal );
  2444. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2445. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2446. }
  2447. matrix.multiplyVector3( face.centroid );
  2448. }
  2449. },
  2450. computeCentroids: function () {
  2451. var f, fl, face;
  2452. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2453. face = this.faces[ f ];
  2454. face.centroid.set( 0, 0, 0 );
  2455. if ( face instanceof THREE.Face3 ) {
  2456. face.centroid.addSelf( this.vertices[ face.a ].position );
  2457. face.centroid.addSelf( this.vertices[ face.b ].position );
  2458. face.centroid.addSelf( this.vertices[ face.c ].position );
  2459. face.centroid.divideScalar( 3 );
  2460. } else if ( face instanceof THREE.Face4 ) {
  2461. face.centroid.addSelf( this.vertices[ face.a ].position );
  2462. face.centroid.addSelf( this.vertices[ face.b ].position );
  2463. face.centroid.addSelf( this.vertices[ face.c ].position );
  2464. face.centroid.addSelf( this.vertices[ face.d ].position );
  2465. face.centroid.divideScalar( 4 );
  2466. }
  2467. }
  2468. },
  2469. computeFaceNormals: function () {
  2470. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2471. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2472. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2473. face = this.faces[ f ];
  2474. vA = this.vertices[ face.a ];
  2475. vB = this.vertices[ face.b ];
  2476. vC = this.vertices[ face.c ];
  2477. cb.sub( vC.position, vB.position );
  2478. ab.sub( vA.position, vB.position );
  2479. cb.crossSelf( ab );
  2480. if ( !cb.isZero() ) {
  2481. cb.normalize();
  2482. }
  2483. face.normal.copy( cb );
  2484. }
  2485. },
  2486. computeVertexNormals: function () {
  2487. var v, vl, f, fl, face, vertices;
  2488. // create internal buffers for reuse when calling this method repeatedly
  2489. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2490. if ( this.__tmpVertices === undefined ) {
  2491. this.__tmpVertices = new Array( this.vertices.length );
  2492. vertices = this.__tmpVertices;
  2493. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2494. vertices[ v ] = new THREE.Vector3();
  2495. }
  2496. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2497. face = this.faces[ f ];
  2498. if ( face instanceof THREE.Face3 ) {
  2499. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2500. } else if ( face instanceof THREE.Face4 ) {
  2501. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2502. }
  2503. }
  2504. } else {
  2505. vertices = this.__tmpVertices;
  2506. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2507. vertices[ v ].set( 0, 0, 0 );
  2508. }
  2509. }
  2510. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2511. face = this.faces[ f ];
  2512. if ( face instanceof THREE.Face3 ) {
  2513. vertices[ face.a ].addSelf( face.normal );
  2514. vertices[ face.b ].addSelf( face.normal );
  2515. vertices[ face.c ].addSelf( face.normal );
  2516. } else if ( face instanceof THREE.Face4 ) {
  2517. vertices[ face.a ].addSelf( face.normal );
  2518. vertices[ face.b ].addSelf( face.normal );
  2519. vertices[ face.c ].addSelf( face.normal );
  2520. vertices[ face.d ].addSelf( face.normal );
  2521. }
  2522. }
  2523. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2524. vertices[ v ].normalize();
  2525. }
  2526. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2527. face = this.faces[ f ];
  2528. if ( face instanceof THREE.Face3 ) {
  2529. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2530. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2531. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2532. } else if ( face instanceof THREE.Face4 ) {
  2533. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2534. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2535. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2536. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  2537. }
  2538. }
  2539. },
  2540. computeMorphNormals: function () {
  2541. var i, il, f, fl, face;
  2542. // save original normals
  2543. // - create temp variables on first access
  2544. // otherwise just copy (for faster repeated calls)
  2545. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2546. face = this.faces[ f ];
  2547. if ( ! face.__originalFaceNormal ) {
  2548. face.__originalFaceNormal = face.normal.clone();
  2549. } else {
  2550. face.__originalFaceNormal.copy( face.normal );
  2551. }
  2552. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  2553. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  2554. if ( ! face.__originalVertexNormals[ i ] ) {
  2555. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  2556. } else {
  2557. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  2558. }
  2559. }
  2560. }
  2561. // use temp geometry to compute face and vertex normals for each morph
  2562. var tmpGeo = new THREE.Geometry();
  2563. tmpGeo.faces = this.faces;
  2564. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  2565. // create on first access
  2566. if ( ! this.morphNormals[ i ] ) {
  2567. this.morphNormals[ i ] = {};
  2568. this.morphNormals[ i ].faceNormals = [];
  2569. this.morphNormals[ i ].vertexNormals = [];
  2570. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  2571. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  2572. var faceNormal, vertexNormals;
  2573. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2574. face = this.faces[ f ];
  2575. faceNormal = new THREE.Vector3();
  2576. if ( face instanceof THREE.Face3 ) {
  2577. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  2578. } else {
  2579. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  2580. }
  2581. dstNormalsFace.push( faceNormal );
  2582. dstNormalsVertex.push( vertexNormals );
  2583. }
  2584. }
  2585. var morphNormals = this.morphNormals[ i ];
  2586. // set vertices to morph target
  2587. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  2588. // compute morph normals
  2589. tmpGeo.computeFaceNormals();
  2590. tmpGeo.computeVertexNormals();
  2591. // store morph normals
  2592. var faceNormal, vertexNormals;
  2593. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2594. face = this.faces[ f ];
  2595. faceNormal = morphNormals.faceNormals[ f ];
  2596. vertexNormals = morphNormals.vertexNormals[ f ];
  2597. faceNormal.copy( face.normal );
  2598. if ( face instanceof THREE.Face3 ) {
  2599. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2600. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2601. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2602. } else {
  2603. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2604. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2605. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2606. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  2607. }
  2608. }
  2609. }
  2610. // restore original normals
  2611. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2612. face = this.faces[ f ];
  2613. face.normal = face.__originalFaceNormal;
  2614. face.vertexNormals = face.__originalVertexNormals;
  2615. }
  2616. },
  2617. computeTangents: function () {
  2618. // based on http://www.terathon.com/code/tangent.html
  2619. // tangents go to vertices
  2620. var f, fl, v, vl, i, il, vertexIndex,
  2621. face, uv, vA, vB, vC, uvA, uvB, uvC,
  2622. x1, x2, y1, y2, z1, z2,
  2623. s1, s2, t1, t2, r, t, test,
  2624. tan1 = [], tan2 = [],
  2625. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  2626. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  2627. n = new THREE.Vector3(), w;
  2628. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2629. tan1[ v ] = new THREE.Vector3();
  2630. tan2[ v ] = new THREE.Vector3();
  2631. }
  2632. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  2633. vA = context.vertices[ a ].position;
  2634. vB = context.vertices[ b ].position;
  2635. vC = context.vertices[ c ].position;
  2636. uvA = uv[ ua ];
  2637. uvB = uv[ ub ];
  2638. uvC = uv[ uc ];
  2639. x1 = vB.x - vA.x;
  2640. x2 = vC.x - vA.x;
  2641. y1 = vB.y - vA.y;
  2642. y2 = vC.y - vA.y;
  2643. z1 = vB.z - vA.z;
  2644. z2 = vC.z - vA.z;
  2645. s1 = uvB.u - uvA.u;
  2646. s2 = uvC.u - uvA.u;
  2647. t1 = uvB.v - uvA.v;
  2648. t2 = uvC.v - uvA.v;
  2649. r = 1.0 / ( s1 * t2 - s2 * t1 );
  2650. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  2651. ( t2 * y1 - t1 * y2 ) * r,
  2652. ( t2 * z1 - t1 * z2 ) * r );
  2653. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  2654. ( s1 * y2 - s2 * y1 ) * r,
  2655. ( s1 * z2 - s2 * z1 ) * r );
  2656. tan1[ a ].addSelf( sdir );
  2657. tan1[ b ].addSelf( sdir );
  2658. tan1[ c ].addSelf( sdir );
  2659. tan2[ a ].addSelf( tdir );
  2660. tan2[ b ].addSelf( tdir );
  2661. tan2[ c ].addSelf( tdir );
  2662. }
  2663. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2664. face = this.faces[ f ];
  2665. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  2666. if ( face instanceof THREE.Face3 ) {
  2667. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  2668. } else if ( face instanceof THREE.Face4 ) {
  2669. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  2670. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  2671. }
  2672. }
  2673. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  2674. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2675. face = this.faces[ f ];
  2676. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  2677. n.copy( face.vertexNormals[ i ] );
  2678. vertexIndex = face[ faceIndex[ i ] ];
  2679. t = tan1[ vertexIndex ];
  2680. // Gram-Schmidt orthogonalize
  2681. tmp.copy( t );
  2682. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  2683. // Calculate handedness
  2684. tmp2.cross( face.vertexNormals[ i ], t );
  2685. test = tmp2.dot( tan2[ vertexIndex ] );
  2686. w = (test < 0.0) ? -1.0 : 1.0;
  2687. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  2688. }
  2689. }
  2690. this.hasTangents = true;
  2691. },
  2692. computeBoundingBox: function () {
  2693. if ( ! this.boundingBox ) {
  2694. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  2695. }
  2696. if ( this.vertices.length > 0 ) {
  2697. var position, firstPosition = this.vertices[ 0 ].position;
  2698. this.boundingBox.min.copy( firstPosition );
  2699. this.boundingBox.max.copy( firstPosition );
  2700. var min = this.boundingBox.min,
  2701. max = this.boundingBox.max;
  2702. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  2703. position = this.vertices[ v ].position;
  2704. if ( position.x < min.x ) {
  2705. min.x = position.x;
  2706. } else if ( position.x > max.x ) {
  2707. max.x = position.x;
  2708. }
  2709. if ( position.y < min.y ) {
  2710. min.y = position.y;
  2711. } else if ( position.y > max.y ) {
  2712. max.y = position.y;
  2713. }
  2714. if ( position.z < min.z ) {
  2715. min.z = position.z;
  2716. } else if ( position.z > max.z ) {
  2717. max.z = position.z;
  2718. }
  2719. }
  2720. } else {
  2721. this.boundingBox.min.set( 0, 0, 0 );
  2722. this.boundingBox.max.set( 0, 0, 0 );
  2723. }
  2724. },
  2725. computeBoundingSphere: function () {
  2726. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  2727. var radius, maxRadius = 0;
  2728. for ( var v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2729. radius = this.vertices[ v ].position.length();
  2730. if ( radius > maxRadius ) maxRadius = radius;
  2731. }
  2732. this.boundingSphere.radius = maxRadius;
  2733. },
  2734. /*
  2735. * Checks for duplicate vertices with hashmap.
  2736. * Duplicated vertices are removed
  2737. * and faces' vertices are updated.
  2738. */
  2739. mergeVertices: function() {
  2740. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  2741. var unique = [], changes = [];
  2742. var v, key;
  2743. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  2744. var precision = Math.pow( 10, precisionPoints );
  2745. var i,il, face;
  2746. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  2747. v = this.vertices[ i ].position;
  2748. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  2749. if ( verticesMap[ key ] === undefined ) {
  2750. verticesMap[ key ] = i;
  2751. unique.push( this.vertices[ i ] );
  2752. changes[ i ] = unique.length - 1;
  2753. } else {
  2754. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  2755. changes[ i ] = changes[ verticesMap[ key ] ];
  2756. }
  2757. };
  2758. // Start to patch face indices
  2759. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  2760. face = this.faces[ i ];
  2761. if ( face instanceof THREE.Face3 ) {
  2762. face.a = changes[ face.a ];
  2763. face.b = changes[ face.b ];
  2764. face.c = changes[ face.c ];
  2765. } else if ( face instanceof THREE.Face4 ) {
  2766. face.a = changes[ face.a ];
  2767. face.b = changes[ face.b ];
  2768. face.c = changes[ face.c ];
  2769. face.d = changes[ face.d ];
  2770. }
  2771. }
  2772. // Use unique set of vertices
  2773. this.vertices = unique;
  2774. }
  2775. };
  2776. THREE.GeometryCount = 0;
  2777. /**
  2778. * Spline from Tween.js, slightly optimized (and trashed)
  2779. * http://sole.github.com/tween.js/examples/05_spline.html
  2780. *
  2781. * @author mrdoob / http://mrdoob.com/
  2782. * @author alteredq / http://alteredqualia.com/
  2783. */
  2784. THREE.Spline = function ( points ) {
  2785. this.points = points;
  2786. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2787. point, intPoint, weight, w2, w3,
  2788. pa, pb, pc, pd;
  2789. this.initFromArray = function( a ) {
  2790. this.points = [];
  2791. for ( var i = 0; i < a.length; i++ ) {
  2792. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2793. }
  2794. };
  2795. this.getPoint = function ( k ) {
  2796. point = ( this.points.length - 1 ) * k;
  2797. intPoint = Math.floor( point );
  2798. weight = point - intPoint;
  2799. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  2800. c[ 1 ] = intPoint;
  2801. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  2802. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  2803. pa = this.points[ c[ 0 ] ];
  2804. pb = this.points[ c[ 1 ] ];
  2805. pc = this.points[ c[ 2 ] ];
  2806. pd = this.points[ c[ 3 ] ];
  2807. w2 = weight * weight;
  2808. w3 = weight * w2;
  2809. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  2810. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  2811. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  2812. return v3;
  2813. };
  2814. this.getControlPointsArray = function () {
  2815. var i, p, l = this.points.length,
  2816. coords = [];
  2817. for ( i = 0; i < l; i ++ ) {
  2818. p = this.points[ i ];
  2819. coords[ i ] = [ p.x, p.y, p.z ];
  2820. }
  2821. return coords;
  2822. };
  2823. // approximate length by summing linear segments
  2824. this.getLength = function ( nSubDivisions ) {
  2825. var i, index, nSamples, position,
  2826. point = 0, intPoint = 0, oldIntPoint = 0,
  2827. oldPosition = new THREE.Vector3(),
  2828. tmpVec = new THREE.Vector3(),
  2829. chunkLengths = [],
  2830. totalLength = 0;
  2831. // first point has 0 length
  2832. chunkLengths[ 0 ] = 0;
  2833. if ( !nSubDivisions ) nSubDivisions = 100;
  2834. nSamples = this.points.length * nSubDivisions;
  2835. oldPosition.copy( this.points[ 0 ] );
  2836. for ( i = 1; i < nSamples; i ++ ) {
  2837. index = i / nSamples;
  2838. position = this.getPoint( index );
  2839. tmpVec.copy( position );
  2840. totalLength += tmpVec.distanceTo( oldPosition );
  2841. oldPosition.copy( position );
  2842. point = ( this.points.length - 1 ) * index;
  2843. intPoint = Math.floor( point );
  2844. if ( intPoint != oldIntPoint ) {
  2845. chunkLengths[ intPoint ] = totalLength;
  2846. oldIntPoint = intPoint;
  2847. }
  2848. }
  2849. // last point ends with total length
  2850. chunkLengths[ chunkLengths.length ] = totalLength;
  2851. return { chunks: chunkLengths, total: totalLength };
  2852. };
  2853. this.reparametrizeByArcLength = function ( samplingCoef ) {
  2854. var i, j,
  2855. index, indexCurrent, indexNext,
  2856. linearDistance, realDistance,
  2857. sampling, position,
  2858. newpoints = [],
  2859. tmpVec = new THREE.Vector3(),
  2860. sl = this.getLength();
  2861. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  2862. for ( i = 1; i < this.points.length; i++ ) {
  2863. //tmpVec.copy( this.points[ i - 1 ] );
  2864. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  2865. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  2866. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  2867. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  2868. indexNext = i / ( this.points.length - 1 );
  2869. for ( j = 1; j < sampling - 1; j++ ) {
  2870. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  2871. position = this.getPoint( index );
  2872. newpoints.push( tmpVec.copy( position ).clone() );
  2873. }
  2874. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  2875. }
  2876. this.points = newpoints;
  2877. };
  2878. // Catmull-Rom
  2879. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  2880. var v0 = ( p2 - p0 ) * 0.5,
  2881. v1 = ( p3 - p1 ) * 0.5;
  2882. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2883. };
  2884. };
  2885. /**
  2886. * @author mr.doob / http://mrdoob.com/
  2887. * @author mikael emtinger / http://gomo.se/
  2888. */
  2889. THREE.Camera = function () {
  2890. THREE.Object3D.call( this );
  2891. this.matrixWorldInverse = new THREE.Matrix4();
  2892. this.projectionMatrix = new THREE.Matrix4();
  2893. this.projectionMatrixInverse = new THREE.Matrix4();
  2894. };
  2895. THREE.Camera.prototype = new THREE.Object3D();
  2896. THREE.Camera.prototype.constructor = THREE.Camera;
  2897. THREE.Camera.prototype.lookAt = function ( vector ) {
  2898. // TODO: Add hierarchy support.
  2899. this.matrix.lookAt( this.position, vector, this.up );
  2900. if ( this.rotationAutoUpdate ) {
  2901. this.rotation.getRotationFromMatrix( this.matrix );
  2902. }
  2903. };
  2904. /**
  2905. * @author alteredq / http://alteredqualia.com/
  2906. */
  2907. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  2908. THREE.Camera.call( this );
  2909. this.left = left;
  2910. this.right = right;
  2911. this.top = top;
  2912. this.bottom = bottom;
  2913. this.near = ( near !== undefined ) ? near : 0.1;
  2914. this.far = ( far !== undefined ) ? far : 2000;
  2915. this.updateProjectionMatrix();
  2916. };
  2917. THREE.OrthographicCamera.prototype = new THREE.Camera();
  2918. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  2919. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  2920. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  2921. };
  2922. /**
  2923. * @author mr.doob / http://mrdoob.com/
  2924. * @author greggman / http://games.greggman.com/
  2925. * @author zz85 / http://www.lab4games.net/zz85/blog
  2926. */
  2927. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  2928. THREE.Camera.call( this );
  2929. this.fov = fov !== undefined ? fov : 50;
  2930. this.aspect = aspect !== undefined ? aspect : 1;
  2931. this.near = near !== undefined ? near : 0.1;
  2932. this.far = far !== undefined ? far : 2000;
  2933. this.updateProjectionMatrix();
  2934. };
  2935. THREE.PerspectiveCamera.prototype = new THREE.Camera();
  2936. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  2937. /**
  2938. * Uses Focal Length (in mm) to estimate and set FOV
  2939. * 35mm (fullframe) camera is used if frame size is not specified;
  2940. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  2941. */
  2942. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  2943. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  2944. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  2945. this.updateProjectionMatrix();
  2946. }
  2947. /**
  2948. * Sets an offset in a larger frustum. This is useful for multi-window or
  2949. * multi-monitor/multi-machine setups.
  2950. *
  2951. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  2952. * the monitors are in grid like this
  2953. *
  2954. * +---+---+---+
  2955. * | A | B | C |
  2956. * +---+---+---+
  2957. * | D | E | F |
  2958. * +---+---+---+
  2959. *
  2960. * then for each monitor you would call it like this
  2961. *
  2962. * var w = 1920;
  2963. * var h = 1080;
  2964. * var fullWidth = w * 3;
  2965. * var fullHeight = h * 2;
  2966. *
  2967. * --A--
  2968. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  2969. * --B--
  2970. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  2971. * --C--
  2972. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  2973. * --D--
  2974. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  2975. * --E--
  2976. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  2977. * --F--
  2978. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  2979. *
  2980. * Note there is no reason monitors have to be the same size or in a grid.
  2981. */
  2982. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  2983. this.fullWidth = fullWidth;
  2984. this.fullHeight = fullHeight;
  2985. this.x = x;
  2986. this.y = y;
  2987. this.width = width;
  2988. this.height = height;
  2989. this.updateProjectionMatrix();
  2990. };
  2991. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  2992. if ( this.fullWidth ) {
  2993. var aspect = this.fullWidth / this.fullHeight;
  2994. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  2995. var bottom = -top;
  2996. var left = aspect * bottom;
  2997. var right = aspect * top;
  2998. var width = Math.abs( right - left );
  2999. var height = Math.abs( top - bottom );
  3000. this.projectionMatrix.makeFrustum(
  3001. left + this.x * width / this.fullWidth,
  3002. left + ( this.x + this.width ) * width / this.fullWidth,
  3003. top - ( this.y + this.height ) * height / this.fullHeight,
  3004. top - this.y * height / this.fullHeight,
  3005. this.near,
  3006. this.far
  3007. );
  3008. } else {
  3009. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3010. }
  3011. };
  3012. /**
  3013. * @author mr.doob / http://mrdoob.com/
  3014. * @author alteredq / http://alteredqualia.com/
  3015. */
  3016. THREE.Light = function ( hex ) {
  3017. THREE.Object3D.call( this );
  3018. this.color = new THREE.Color( hex );
  3019. };
  3020. THREE.Light.prototype = new THREE.Object3D();
  3021. THREE.Light.prototype.constructor = THREE.Light;
  3022. THREE.Light.prototype.supr = THREE.Object3D.prototype;
  3023. /**
  3024. * @author mr.doob / http://mrdoob.com/
  3025. */
  3026. THREE.AmbientLight = function ( hex ) {
  3027. THREE.Light.call( this, hex );
  3028. };
  3029. THREE.AmbientLight.prototype = new THREE.Light();
  3030. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  3031. /**
  3032. * @author mr.doob / http://mrdoob.com/
  3033. * @author alteredq / http://alteredqualia.com/
  3034. */
  3035. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3036. THREE.Light.call( this, hex );
  3037. this.position = new THREE.Vector3( 0, 1, 0 );
  3038. this.target = new THREE.Object3D();
  3039. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3040. this.distance = ( distance !== undefined ) ? distance : 0;
  3041. this.castShadow = false;
  3042. this.onlyShadow = false;
  3043. //
  3044. this.shadowCameraNear = 50;
  3045. this.shadowCameraFar = 5000;
  3046. this.shadowCameraLeft = -500;
  3047. this.shadowCameraRight = 500;
  3048. this.shadowCameraTop = 500;
  3049. this.shadowCameraBottom = -500;
  3050. this.shadowCameraVisible = false;
  3051. this.shadowBias = 0;
  3052. this.shadowDarkness = 0.5;
  3053. this.shadowMapWidth = 512;
  3054. this.shadowMapHeight = 512;
  3055. //
  3056. this.shadowCascade = false;
  3057. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3058. this.shadowCascadeCount = 2;
  3059. this.shadowCascadeBias = [ 0, 0, 0 ];
  3060. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3061. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3062. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3063. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3064. this.shadowCascadeArray = [];
  3065. //
  3066. this.shadowMap = null;
  3067. this.shadowMapSize = null;
  3068. this.shadowCamera = null;
  3069. this.shadowMatrix = null;
  3070. };
  3071. THREE.DirectionalLight.prototype = new THREE.Light();
  3072. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  3073. /**
  3074. * @author mr.doob / http://mrdoob.com/
  3075. */
  3076. THREE.PointLight = function ( hex, intensity, distance ) {
  3077. THREE.Light.call( this, hex );
  3078. this.position = new THREE.Vector3( 0, 0, 0 );
  3079. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3080. this.distance = ( distance !== undefined ) ? distance : 0;
  3081. };
  3082. THREE.PointLight.prototype = new THREE.Light();
  3083. THREE.PointLight.prototype.constructor = THREE.PointLight;
  3084. /**
  3085. * @author alteredq / http://alteredqualia.com/
  3086. */
  3087. THREE.SpotLight = function ( hex, intensity, distance ) {
  3088. THREE.Light.call( this, hex );
  3089. this.position = new THREE.Vector3( 0, 1, 0 );
  3090. this.target = new THREE.Object3D();
  3091. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3092. this.distance = ( distance !== undefined ) ? distance : 0;
  3093. this.castShadow = false;
  3094. this.onlyShadow = false;
  3095. //
  3096. this.shadowCameraNear = 50;
  3097. this.shadowCameraFar = 5000;
  3098. this.shadowCameraFov = 50;
  3099. this.shadowCameraVisible = false;
  3100. this.shadowBias = 0;
  3101. this.shadowDarkness = 0.5;
  3102. this.shadowMapWidth = 512;
  3103. this.shadowMapHeight = 512;
  3104. //
  3105. this.shadowMap = null;
  3106. this.shadowMapSize = null;
  3107. this.shadowCamera = null;
  3108. this.shadowMatrix = null;
  3109. };
  3110. THREE.SpotLight.prototype = new THREE.Light();
  3111. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  3112. /**
  3113. * @author mr.doob / http://mrdoob.com/
  3114. * @author alteredq / http://alteredqualia.com/
  3115. */
  3116. THREE.Material = function ( parameters ) {
  3117. parameters = parameters || {};
  3118. this.id = THREE.MaterialCount ++;
  3119. this.name = '';
  3120. this.opacity = parameters.opacity !== undefined ? parameters.opacity : 1;
  3121. this.transparent = parameters.transparent !== undefined ? parameters.transparent : false;
  3122. this.blending = parameters.blending !== undefined ? parameters.blending : THREE.NormalBlending;
  3123. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  3124. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  3125. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  3126. this.depthTest = parameters.depthTest !== undefined ? parameters.depthTest : true;
  3127. this.depthWrite = parameters.depthWrite !== undefined ? parameters.depthWrite : true;
  3128. this.polygonOffset = parameters.polygonOffset !== undefined ? parameters.polygonOffset : false;
  3129. this.polygonOffsetFactor = parameters.polygonOffsetFactor !== undefined ? parameters.polygonOffsetFactor : 0;
  3130. this.polygonOffsetUnits = parameters.polygonOffsetUnits !== undefined ? parameters.polygonOffsetUnits : 0;
  3131. this.alphaTest = parameters.alphaTest !== undefined ? parameters.alphaTest : 0;
  3132. this.overdraw = parameters.overdraw !== undefined ? parameters.overdraw : false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  3133. this.needsUpdate = true;
  3134. }
  3135. THREE.MaterialCount = 0;
  3136. // shading
  3137. THREE.NoShading = 0;
  3138. THREE.FlatShading = 1;
  3139. THREE.SmoothShading = 2;
  3140. // colors
  3141. THREE.NoColors = 0;
  3142. THREE.FaceColors = 1;
  3143. THREE.VertexColors = 2;
  3144. // blending modes
  3145. THREE.NoBlending = 0;
  3146. THREE.NormalBlending = 1;
  3147. THREE.AdditiveBlending = 2;
  3148. THREE.SubtractiveBlending = 3;
  3149. THREE.MultiplyBlending = 4;
  3150. THREE.AdditiveAlphaBlending = 5;
  3151. THREE.CustomBlending = 6;
  3152. // custom blending equations
  3153. // (numbers start from 100 not to clash with other
  3154. // mappings to OpenGL constants defined in Texture.js)
  3155. THREE.AddEquation = 100;
  3156. THREE.SubtractEquation = 101;
  3157. THREE.ReverseSubtractEquation = 102;
  3158. // custom blending destination factors
  3159. THREE.ZeroFactor = 200;
  3160. THREE.OneFactor = 201;
  3161. THREE.SrcColorFactor = 202;
  3162. THREE.OneMinusSrcColorFactor = 203;
  3163. THREE.SrcAlphaFactor = 204;
  3164. THREE.OneMinusSrcAlphaFactor = 205;
  3165. THREE.DstAlphaFactor = 206;
  3166. THREE.OneMinusDstAlphaFactor = 207;
  3167. // custom blending source factors
  3168. //THREE.ZeroFactor = 200;
  3169. //THREE.OneFactor = 201;
  3170. //THREE.SrcAlphaFactor = 204;
  3171. //THREE.OneMinusSrcAlphaFactor = 205;
  3172. //THREE.DstAlphaFactor = 206;
  3173. //THREE.OneMinusDstAlphaFactor = 207;
  3174. THREE.DstColorFactor = 208;
  3175. THREE.OneMinusDstColorFactor = 209;
  3176. THREE.SrcAlphaSaturateFactor = 210;
  3177. /**
  3178. * @author mr.doob / http://mrdoob.com/
  3179. * @author alteredq / http://alteredqualia.com/
  3180. *
  3181. * parameters = {
  3182. * color: <hex>,
  3183. * opacity: <float>,
  3184. *
  3185. * blending: THREE.NormalBlending,
  3186. * depthTest: <bool>,
  3187. *
  3188. * linewidth: <float>,
  3189. * linecap: "round",
  3190. * linejoin: "round",
  3191. *
  3192. * vertexColors: <bool>
  3193. *
  3194. * fog: <bool>
  3195. * }
  3196. */
  3197. THREE.LineBasicMaterial = function ( parameters ) {
  3198. THREE.Material.call( this, parameters );
  3199. parameters = parameters || {};
  3200. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3201. this.linewidth = parameters.linewidth !== undefined ? parameters.linewidth : 1;
  3202. this.linecap = parameters.linecap !== undefined ? parameters.linecap : 'round';
  3203. this.linejoin = parameters.linejoin !== undefined ? parameters.linejoin : 'round';
  3204. this.vertexColors = parameters.vertexColors ? parameters.vertexColors : false;
  3205. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3206. };
  3207. THREE.LineBasicMaterial.prototype = new THREE.Material();
  3208. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  3209. /**
  3210. * @author mr.doob / http://mrdoob.com/
  3211. * @author alteredq / http://alteredqualia.com/
  3212. *
  3213. * parameters = {
  3214. * color: <hex>,
  3215. * opacity: <float>,
  3216. * map: new THREE.Texture( <Image> ),
  3217. *
  3218. * lightMap: new THREE.Texture( <Image> ),
  3219. *
  3220. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3221. * combine: THREE.Multiply,
  3222. * reflectivity: <float>,
  3223. * refractionRatio: <float>,
  3224. *
  3225. * shading: THREE.SmoothShading,
  3226. * blending: THREE.NormalBlending,
  3227. * depthTest: <bool>,
  3228. *
  3229. * wireframe: <boolean>,
  3230. * wireframeLinewidth: <float>,
  3231. *
  3232. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3233. *
  3234. * skinning: <bool>,
  3235. * morphTargets: <bool>,
  3236. *
  3237. * fog: <bool>
  3238. * }
  3239. */
  3240. THREE.MeshBasicMaterial = function ( parameters ) {
  3241. THREE.Material.call( this, parameters );
  3242. parameters = parameters || {};
  3243. // color property represents emissive for MeshBasicMaterial
  3244. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3245. this.map = parameters.map !== undefined ? parameters.map : null;
  3246. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3247. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3248. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3249. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3250. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3251. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3252. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3253. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3254. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3255. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3256. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3257. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3258. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3259. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3260. };
  3261. THREE.MeshBasicMaterial.prototype = new THREE.Material();
  3262. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  3263. /**
  3264. * @author mr.doob / http://mrdoob.com/
  3265. * @author alteredq / http://alteredqualia.com/
  3266. *
  3267. * parameters = {
  3268. * color: <hex>,
  3269. * ambient: <hex>,
  3270. * emissive: <hex>,
  3271. * opacity: <float>,
  3272. *
  3273. * map: new THREE.Texture( <Image> ),
  3274. *
  3275. * lightMap: new THREE.Texture( <Image> ),
  3276. *
  3277. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3278. * combine: THREE.Multiply,
  3279. * reflectivity: <float>,
  3280. * refractionRatio: <float>,
  3281. *
  3282. * shading: THREE.SmoothShading,
  3283. * blending: THREE.NormalBlending,
  3284. * depthTest: <bool>,
  3285. *
  3286. * wireframe: <boolean>,
  3287. * wireframeLinewidth: <float>,
  3288. *
  3289. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3290. *
  3291. * skinning: <bool>,
  3292. * morphTargets: <bool>,
  3293. * morphNormals: <bool>,
  3294. *
  3295. * fog: <bool>
  3296. * }
  3297. */
  3298. THREE.MeshLambertMaterial = function ( parameters ) {
  3299. THREE.Material.call( this, parameters );
  3300. parameters = parameters || {};
  3301. // color property represents diffuse for MeshLambertMaterial
  3302. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3303. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3304. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3305. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3306. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3307. this.map = parameters.map !== undefined ? parameters.map : null;
  3308. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3309. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3310. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3311. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3312. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3313. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3314. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3315. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3316. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3317. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3318. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3319. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3320. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3321. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3322. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3323. };
  3324. THREE.MeshLambertMaterial.prototype = new THREE.Material();
  3325. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  3326. /**
  3327. * @author mr.doob / http://mrdoob.com/
  3328. * @author alteredq / http://alteredqualia.com/
  3329. *
  3330. * parameters = {
  3331. * color: <hex>,
  3332. * ambient: <hex>,
  3333. * emissive: <hex>,
  3334. * specular: <hex>,
  3335. * shininess: <float>,
  3336. * opacity: <float>,
  3337. *
  3338. * map: new THREE.Texture( <Image> ),
  3339. *
  3340. * lightMap: new THREE.Texture( <Image> ),
  3341. *
  3342. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3343. * combine: THREE.Multiply,
  3344. * reflectivity: <float>,
  3345. * refractionRatio: <float>,
  3346. *
  3347. * shading: THREE.SmoothShading,
  3348. * blending: THREE.NormalBlending,
  3349. * depthTest: <bool>,
  3350. *
  3351. * wireframe: <boolean>,
  3352. * wireframeLinewidth: <float>,
  3353. *
  3354. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3355. *
  3356. * skinning: <bool>,
  3357. * morphTargets: <bool>,
  3358. * morphNormals: <bool>,
  3359. *
  3360. * fog: <bool>
  3361. * }
  3362. */
  3363. THREE.MeshPhongMaterial = function ( parameters ) {
  3364. THREE.Material.call( this, parameters );
  3365. parameters = parameters || {};
  3366. // color property represents diffuse for MeshPhongMaterial
  3367. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3368. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3369. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3370. this.specular = parameters.specular !== undefined ? new THREE.Color( parameters.specular ) : new THREE.Color( 0x111111 );
  3371. this.shininess = parameters.shininess !== undefined ? parameters.shininess : 30;
  3372. this.metal = parameters.metal !== undefined ? parameters.metal : false;
  3373. this.perPixel = parameters.perPixel !== undefined ? parameters.perPixel : false;
  3374. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3375. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3376. this.map = parameters.map !== undefined ? parameters.map : null;
  3377. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3378. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3379. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3380. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3381. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3382. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3383. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3384. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3385. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3386. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3387. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3388. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3389. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3390. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3391. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3392. };
  3393. THREE.MeshPhongMaterial.prototype = new THREE.Material();
  3394. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  3395. /**
  3396. * @author mr.doob / http://mrdoob.com/
  3397. * @author alteredq / http://alteredqualia.com/
  3398. *
  3399. * parameters = {
  3400. * opacity: <float>,
  3401. * blending: THREE.NormalBlending,
  3402. * depthTest: <bool>,
  3403. * wireframe: <boolean>,
  3404. * wireframeLinewidth: <float>
  3405. * }
  3406. */
  3407. THREE.MeshDepthMaterial = function ( parameters ) {
  3408. THREE.Material.call( this, parameters );
  3409. parameters = parameters || {};
  3410. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading; // doesn't really apply here, normals are not used
  3411. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3412. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3413. };
  3414. THREE.MeshDepthMaterial.prototype = new THREE.Material();
  3415. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  3416. /**
  3417. * @author mr.doob / http://mrdoob.com/
  3418. *
  3419. * parameters = {
  3420. * opacity: <float>,
  3421. * shading: THREE.FlatShading,
  3422. * blending: THREE.NormalBlending,
  3423. * depthTest: <bool>,
  3424. * wireframe: <boolean>,
  3425. * wireframeLinewidth: <float>
  3426. * }
  3427. */
  3428. THREE.MeshNormalMaterial = function ( parameters ) {
  3429. THREE.Material.call( this, parameters );
  3430. parameters = parameters || {};
  3431. this.shading = parameters.shading ? parameters.shading : THREE.FlatShading;
  3432. this.wireframe = parameters.wireframe ? parameters.wireframe : false;
  3433. this.wireframeLinewidth = parameters.wireframeLinewidth ? parameters.wireframeLinewidth : 1;
  3434. };
  3435. THREE.MeshNormalMaterial.prototype = new THREE.Material();
  3436. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  3437. /**
  3438. * @author mr.doob / http://mrdoob.com/
  3439. */
  3440. THREE.MeshFaceMaterial = function () {
  3441. };
  3442. /**
  3443. * @author mr.doob / http://mrdoob.com/
  3444. * @author alteredq / http://alteredqualia.com/
  3445. *
  3446. * parameters = {
  3447. * color: <hex>,
  3448. * opacity: <float>,
  3449. * map: new THREE.Texture( <Image> ),
  3450. *
  3451. * size: <float>,
  3452. *
  3453. * blending: THREE.NormalBlending,
  3454. * depthTest: <bool>,
  3455. *
  3456. * vertexColors: <bool>,
  3457. *
  3458. * fog: <bool>
  3459. * }
  3460. */
  3461. THREE.ParticleBasicMaterial = function ( parameters ) {
  3462. THREE.Material.call( this, parameters );
  3463. parameters = parameters || {};
  3464. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3465. this.map = parameters.map !== undefined ? parameters.map : null;
  3466. this.size = parameters.size !== undefined ? parameters.size : 1;
  3467. this.sizeAttenuation = parameters.sizeAttenuation !== undefined ? parameters.sizeAttenuation : true;
  3468. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : false;
  3469. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3470. };
  3471. THREE.ParticleBasicMaterial.prototype = new THREE.Material();
  3472. THREE.ParticleBasicMaterial.prototype.constructor = THREE.ParticleBasicMaterial;
  3473. /**
  3474. * @author mr.doob / http://mrdoob.com/
  3475. *
  3476. * parameters = {
  3477. * color: <hex>,
  3478. * program: <function>,
  3479. * opacity: <float>,
  3480. * blending: THREE.NormalBlending
  3481. * }
  3482. */
  3483. THREE.ParticleCanvasMaterial = function ( parameters ) {
  3484. THREE.Material.call( this, parameters );
  3485. parameters = parameters || {};
  3486. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3487. this.program = parameters.program !== undefined ? parameters.program : function ( context, color ) {};
  3488. };
  3489. THREE.ParticleCanvasMaterial.prototype = new THREE.Material();
  3490. THREE.ParticleCanvasMaterial.prototype.constructor = THREE.ParticleCanvasMaterial;
  3491. /**
  3492. * @author mr.doob / http://mrdoob.com/
  3493. */
  3494. THREE.ParticleDOMMaterial = function ( domElement ) {
  3495. THREE.Material.call( this );
  3496. this.domElement = domElement;
  3497. };
  3498. /**
  3499. * @author alteredq / http://alteredqualia.com/
  3500. *
  3501. * parameters = {
  3502. * fragmentShader: <string>,
  3503. * vertexShader: <string>,
  3504. *
  3505. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  3506. *
  3507. * shading: THREE.SmoothShading,
  3508. * blending: THREE.NormalBlending,
  3509. * depthTest: <bool>,
  3510. *
  3511. * wireframe: <boolean>,
  3512. * wireframeLinewidth: <float>,
  3513. *
  3514. * lights: <bool>,
  3515. *
  3516. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3517. *
  3518. * skinning: <bool>,
  3519. * morphTargets: <bool>,
  3520. * morphNormals: <bool>,
  3521. *
  3522. * fog: <bool>
  3523. * }
  3524. */
  3525. THREE.ShaderMaterial = function ( parameters ) {
  3526. THREE.Material.call( this, parameters );
  3527. parameters = parameters || {};
  3528. this.fragmentShader = parameters.fragmentShader !== undefined ? parameters.fragmentShader : "void main() {}";
  3529. this.vertexShader = parameters.vertexShader !== undefined ? parameters.vertexShader : "void main() {}";
  3530. this.uniforms = parameters.uniforms !== undefined ? parameters.uniforms : {};
  3531. this.attributes = parameters.attributes;
  3532. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3533. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3534. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3535. this.fog = parameters.fog !== undefined ? parameters.fog : false; // set to use scene fog
  3536. this.lights = parameters.lights !== undefined ? parameters.lights : false; // set to use scene lights
  3537. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors; // set to use "color" attribute stream
  3538. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false; // set to use skinning attribute streams
  3539. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false; // set to use morph targets
  3540. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false; // set to use morph normals
  3541. };
  3542. THREE.ShaderMaterial.prototype = new THREE.Material();
  3543. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  3544. /**
  3545. * @author mr.doob / http://mrdoob.com/
  3546. * @author alteredq / http://alteredqualia.com/
  3547. * @author szimek / https://github.com/szimek/
  3548. */
  3549. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type ) {
  3550. this.id = THREE.TextureCount ++;
  3551. this.image = image;
  3552. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  3553. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  3554. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  3555. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  3556. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  3557. this.format = format !== undefined ? format : THREE.RGBAFormat;
  3558. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  3559. this.offset = new THREE.Vector2( 0, 0 );
  3560. this.repeat = new THREE.Vector2( 1, 1 );
  3561. this.generateMipmaps = true;
  3562. this.premultiplyAlpha = false;
  3563. this.needsUpdate = false;
  3564. this.onUpdate = null;
  3565. };
  3566. THREE.Texture.prototype = {
  3567. constructor: THREE.Texture,
  3568. clone: function () {
  3569. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type );
  3570. clonedTexture.offset.copy( this.offset );
  3571. clonedTexture.repeat.copy( this.repeat );
  3572. return clonedTexture;
  3573. }
  3574. };
  3575. THREE.TextureCount = 0;
  3576. THREE.MultiplyOperation = 0;
  3577. THREE.MixOperation = 1;
  3578. // Mapping modes
  3579. THREE.UVMapping = function () {};
  3580. THREE.CubeReflectionMapping = function () {};
  3581. THREE.CubeRefractionMapping = function () {};
  3582. THREE.SphericalReflectionMapping = function () {};
  3583. THREE.SphericalRefractionMapping = function () {};
  3584. // Wrapping modes
  3585. THREE.RepeatWrapping = 0;
  3586. THREE.ClampToEdgeWrapping = 1;
  3587. THREE.MirroredRepeatWrapping = 2;
  3588. // Filters
  3589. THREE.NearestFilter = 3;
  3590. THREE.NearestMipMapNearestFilter = 4;
  3591. THREE.NearestMipMapLinearFilter = 5;
  3592. THREE.LinearFilter = 6;
  3593. THREE.LinearMipMapNearestFilter = 7;
  3594. THREE.LinearMipMapLinearFilter = 8;
  3595. // Types
  3596. THREE.ByteType = 9;
  3597. THREE.UnsignedByteType = 10;
  3598. THREE.ShortType = 11;
  3599. THREE.UnsignedShortType = 12;
  3600. THREE.IntType = 13;
  3601. THREE.UnsignedIntType = 14;
  3602. THREE.FloatType = 15;
  3603. // Formats
  3604. THREE.AlphaFormat = 16;
  3605. THREE.RGBFormat = 17;
  3606. THREE.RGBAFormat = 18;
  3607. THREE.LuminanceFormat = 19;
  3608. THREE.LuminanceAlphaFormat = 20;
  3609. /**
  3610. * @author alteredq / http://alteredqualia.com/
  3611. */
  3612. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  3613. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  3614. this.image = { data: data, width: width, height: height };
  3615. };
  3616. THREE.DataTexture.prototype = new THREE.Texture();
  3617. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  3618. THREE.DataTexture.prototype.clone = function () {
  3619. 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 );
  3620. clonedTexture.offset.copy( this.offset );
  3621. clonedTexture.repeat.copy( this.repeat );
  3622. return clonedTexture;
  3623. };
  3624. /**
  3625. * @author mr.doob / http://mrdoob.com/
  3626. */
  3627. THREE.Particle = function ( material ) {
  3628. THREE.Object3D.call( this );
  3629. this.material = material;
  3630. };
  3631. THREE.Particle.prototype = new THREE.Object3D();
  3632. THREE.Particle.prototype.constructor = THREE.Particle;
  3633. /**
  3634. * @author alteredq / http://alteredqualia.com/
  3635. */
  3636. THREE.ParticleSystem = function ( geometry, material ) {
  3637. THREE.Object3D.call( this );
  3638. this.geometry = geometry;
  3639. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  3640. this.sortParticles = false;
  3641. if ( this.geometry ) {
  3642. // calc bound radius
  3643. if( !this.geometry.boundingSphere ) {
  3644. this.geometry.computeBoundingSphere();
  3645. }
  3646. this.boundRadius = geometry.boundingSphere.radius;
  3647. }
  3648. this.frustumCulled = false;
  3649. };
  3650. THREE.ParticleSystem.prototype = new THREE.Object3D();
  3651. THREE.ParticleSystem.prototype.constructor = THREE.ParticleSystem;
  3652. /**
  3653. * @author mr.doob / http://mrdoob.com/
  3654. */
  3655. THREE.Line = function ( geometry, material, type ) {
  3656. THREE.Object3D.call( this );
  3657. this.geometry = geometry;
  3658. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  3659. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  3660. if ( this.geometry ) {
  3661. if ( ! this.geometry.boundingSphere ) {
  3662. this.geometry.computeBoundingSphere();
  3663. }
  3664. }
  3665. };
  3666. THREE.LineStrip = 0;
  3667. THREE.LinePieces = 1;
  3668. THREE.Line.prototype = new THREE.Object3D();
  3669. THREE.Line.prototype.constructor = THREE.Line;
  3670. /**
  3671. * @author mr.doob / http://mrdoob.com/
  3672. * @author alteredq / http://alteredqualia.com/
  3673. * @author mikael emtinger / http://gomo.se/
  3674. */
  3675. THREE.Mesh = function ( geometry, material ) {
  3676. THREE.Object3D.call( this );
  3677. this.geometry = geometry;
  3678. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  3679. if ( this.geometry ) {
  3680. // calc bound radius
  3681. if( ! this.geometry.boundingSphere ) {
  3682. this.geometry.computeBoundingSphere();
  3683. }
  3684. this.boundRadius = geometry.boundingSphere.radius;
  3685. // setup morph targets
  3686. if( this.geometry.morphTargets.length ) {
  3687. this.morphTargetBase = -1;
  3688. this.morphTargetForcedOrder = [];
  3689. this.morphTargetInfluences = [];
  3690. this.morphTargetDictionary = {};
  3691. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  3692. this.morphTargetInfluences.push( 0 );
  3693. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  3694. }
  3695. }
  3696. }
  3697. }
  3698. THREE.Mesh.prototype = new THREE.Object3D();
  3699. THREE.Mesh.prototype.constructor = THREE.Mesh;
  3700. THREE.Mesh.prototype.supr = THREE.Object3D.prototype;
  3701. /*
  3702. * Get Morph Target Index by Name
  3703. */
  3704. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  3705. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  3706. return this.morphTargetDictionary[ name ];
  3707. }
  3708. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  3709. return 0;
  3710. }
  3711. /**
  3712. * @author mikael emtinger / http://gomo.se/
  3713. * @author alteredq / http://alteredqualia.com/
  3714. */
  3715. THREE.Bone = function( belongsToSkin ) {
  3716. THREE.Object3D.call( this );
  3717. this.skin = belongsToSkin;
  3718. this.skinMatrix = new THREE.Matrix4();
  3719. };
  3720. THREE.Bone.prototype = new THREE.Object3D();
  3721. THREE.Bone.prototype.constructor = THREE.Bone;
  3722. THREE.Bone.prototype.supr = THREE.Object3D.prototype;
  3723. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  3724. // update local
  3725. if ( this.matrixAutoUpdate ) {
  3726. forceUpdate |= this.updateMatrix();
  3727. }
  3728. // update skin matrix
  3729. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  3730. if( parentSkinMatrix ) {
  3731. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  3732. } else {
  3733. this.skinMatrix.copy( this.matrix );
  3734. }
  3735. this.matrixWorldNeedsUpdate = false;
  3736. forceUpdate = true;
  3737. }
  3738. // update children
  3739. var child, i, l = this.children.length;
  3740. for ( i = 0; i < l; i ++ ) {
  3741. this.children[ i ].update( this.skinMatrix, forceUpdate );
  3742. }
  3743. };
  3744. /**
  3745. * @author mikael emtinger / http://gomo.se/
  3746. * @author alteredq / http://alteredqualia.com/
  3747. */
  3748. THREE.SkinnedMesh = function ( geometry, material ) {
  3749. THREE.Mesh.call( this, geometry, material );
  3750. // init bones
  3751. this.identityMatrix = new THREE.Matrix4();
  3752. this.bones = [];
  3753. this.boneMatrices = [];
  3754. var b, bone, gbone, p, q, s;
  3755. if ( this.geometry.bones !== undefined ) {
  3756. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  3757. gbone = this.geometry.bones[ b ];
  3758. p = gbone.pos;
  3759. q = gbone.rotq;
  3760. s = gbone.scl;
  3761. bone = this.addBone();
  3762. bone.name = gbone.name;
  3763. bone.position.set( p[0], p[1], p[2] );
  3764. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  3765. bone.useQuaternion = true;
  3766. if ( s !== undefined ) {
  3767. bone.scale.set( s[0], s[1], s[2] );
  3768. } else {
  3769. bone.scale.set( 1, 1, 1 );
  3770. }
  3771. }
  3772. for ( b = 0; b < this.bones.length; b ++ ) {
  3773. gbone = this.geometry.bones[ b ];
  3774. bone = this.bones[ b ];
  3775. if ( gbone.parent === -1 ) {
  3776. this.add( bone );
  3777. } else {
  3778. this.bones[ gbone.parent ].add( bone );
  3779. }
  3780. }
  3781. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  3782. this.pose();
  3783. }
  3784. };
  3785. THREE.SkinnedMesh.prototype = new THREE.Mesh();
  3786. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  3787. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  3788. if ( bone === undefined ) {
  3789. bone = new THREE.Bone( this );
  3790. }
  3791. this.bones.push( bone );
  3792. return bone;
  3793. };
  3794. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  3795. this.matrixAutoUpdate && this.updateMatrix();
  3796. // update matrixWorld
  3797. if ( this.matrixWorldNeedsUpdate || force ) {
  3798. if ( this.parent ) {
  3799. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3800. } else {
  3801. this.matrixWorld.copy( this.matrix );
  3802. }
  3803. this.matrixWorldNeedsUpdate = false;
  3804. force = true;
  3805. }
  3806. // update children
  3807. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3808. var child = this.children[ i ];
  3809. if ( child instanceof THREE.Bone ) {
  3810. child.update( this.identityMatrix, false );
  3811. } else {
  3812. child.updateMatrixWorld( true );
  3813. }
  3814. }
  3815. // flatten bone matrices to array
  3816. var b, bl = this.bones.length,
  3817. ba = this.bones,
  3818. bm = this.boneMatrices;
  3819. for ( b = 0; b < bl; b ++ ) {
  3820. ba[ b ].skinMatrix.flattenToArrayOffset( bm, b * 16 );
  3821. }
  3822. };
  3823. /*
  3824. * Pose
  3825. */
  3826. THREE.SkinnedMesh.prototype.pose = function() {
  3827. this.updateMatrixWorld( true );
  3828. var bim, bone, boneInverses = [];
  3829. for ( var b = 0; b < this.bones.length; b ++ ) {
  3830. bone = this.bones[ b ];
  3831. var inverseMatrix = new THREE.Matrix4();
  3832. inverseMatrix.getInverse( bone.skinMatrix );
  3833. boneInverses.push( inverseMatrix );
  3834. bone.skinMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  3835. }
  3836. // project vertices to local
  3837. if ( this.geometry.skinVerticesA === undefined ) {
  3838. this.geometry.skinVerticesA = [];
  3839. this.geometry.skinVerticesB = [];
  3840. var orgVertex, vertex;
  3841. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  3842. orgVertex = this.geometry.vertices[ i ].position;
  3843. var indexA = this.geometry.skinIndices[ i ].x;
  3844. var indexB = this.geometry.skinIndices[ i ].y;
  3845. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3846. this.geometry.skinVerticesA.push( boneInverses[ indexA ].multiplyVector3( vertex ) );
  3847. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3848. this.geometry.skinVerticesB.push( boneInverses[ indexB ].multiplyVector3( vertex ) );
  3849. // todo: add more influences
  3850. // normalize weights
  3851. if ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y !== 1 ) {
  3852. var len = ( 1.0 - ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y ) ) * 0.5;
  3853. this.geometry.skinWeights[ i ].x += len;
  3854. this.geometry.skinWeights[ i ].y += len;
  3855. }
  3856. }
  3857. }
  3858. };
  3859. /**
  3860. * @author alteredq / http://alteredqualia.com/
  3861. */
  3862. THREE.MorphAnimMesh = function ( geometry, material ) {
  3863. THREE.Mesh.call( this, geometry, material );
  3864. // API
  3865. this.duration = 1000; // milliseconds
  3866. this.mirroredLoop = false;
  3867. this.time = 0;
  3868. // internals
  3869. this.lastKeyframe = 0;
  3870. this.currentKeyframe = 0;
  3871. this.direction = 1;
  3872. this.directionBackwards = false;
  3873. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  3874. };
  3875. THREE.MorphAnimMesh.prototype = new THREE.Mesh();
  3876. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  3877. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  3878. this.startKeyframe = start;
  3879. this.endKeyframe = end;
  3880. this.length = this.endKeyframe - this.startKeyframe + 1;
  3881. };
  3882. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  3883. this.direction = 1;
  3884. this.directionBackwards = false;
  3885. };
  3886. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  3887. this.direction = -1;
  3888. this.directionBackwards = true;
  3889. };
  3890. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  3891. var geometry = this.geometry;
  3892. if ( ! geometry.animations ) geometry.animations = {};
  3893. var firstAnimation, animations = geometry.animations;
  3894. var pattern = /([a-z]+)(\d+)/;
  3895. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  3896. var morph = geometry.morphTargets[ i ];
  3897. var parts = morph.name.match( pattern );
  3898. if ( parts && parts.length > 1 ) {
  3899. var label = parts[ 1 ];
  3900. var num = parts[ 2 ];
  3901. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  3902. var animation = animations[ label ];
  3903. if ( i < animation.start ) animation.start = i;
  3904. if ( i > animation.end ) animation.end = i;
  3905. if ( ! firstAnimation ) firstAnimation = label;
  3906. }
  3907. }
  3908. geometry.firstAnimation = firstAnimation;
  3909. };
  3910. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  3911. if ( ! this.geometry.animations ) this.geometry.animations = {};
  3912. this.geometry.animations[ label ] = { start: start, end: end };
  3913. };
  3914. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  3915. var animation = this.geometry.animations[ label ];
  3916. if ( animation ) {
  3917. this.setFrameRange( animation.start, animation.end );
  3918. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  3919. this.time = 0;
  3920. } else {
  3921. console.warn( "animation[" + label + "] undefined" );
  3922. }
  3923. };
  3924. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  3925. var frameTime = this.duration / this.length;
  3926. this.time += this.direction * delta;
  3927. if ( this.mirroredLoop ) {
  3928. if ( this.time > this.duration || this.time < 0 ) {
  3929. this.direction *= -1;
  3930. if ( this.time > this.duration ) {
  3931. this.time = this.duration;
  3932. this.directionBackwards = true;
  3933. }
  3934. if ( this.time < 0 ) {
  3935. this.time = 0;
  3936. this.directionBackwards = false;
  3937. }
  3938. }
  3939. } else {
  3940. this.time = this.time % this.duration;
  3941. if ( this.time < 0 ) this.time += this.duration;
  3942. }
  3943. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  3944. if ( keyframe !== this.currentKeyframe ) {
  3945. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  3946. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  3947. this.morphTargetInfluences[ keyframe ] = 0;
  3948. this.lastKeyframe = this.currentKeyframe;
  3949. this.currentKeyframe = keyframe;
  3950. }
  3951. var mix = ( this.time % frameTime ) / frameTime;
  3952. if ( this.directionBackwards ) {
  3953. mix = 1 - mix;
  3954. }
  3955. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  3956. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  3957. };
  3958. /**
  3959. * @author alteredq / http://alteredqualia.com/
  3960. */
  3961. THREE.Ribbon = function ( geometry, material ) {
  3962. THREE.Object3D.call( this );
  3963. this.geometry = geometry;
  3964. this.material = material;
  3965. };
  3966. THREE.Ribbon.prototype = new THREE.Object3D();
  3967. THREE.Ribbon.prototype.constructor = THREE.Ribbon;
  3968. /**
  3969. * @author mikael emtinger / http://gomo.se/
  3970. * @author alteredq / http://alteredqualia.com/
  3971. * @author mr.doob / http://mrdoob.com/
  3972. */
  3973. THREE.LOD = function () {
  3974. THREE.Object3D.call( this );
  3975. this.LODs = [];
  3976. };
  3977. THREE.LOD.prototype = new THREE.Object3D();
  3978. THREE.LOD.prototype.constructor = THREE.LOD;
  3979. THREE.LOD.prototype.supr = THREE.Object3D.prototype;
  3980. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  3981. if ( visibleAtDistance === undefined ) {
  3982. visibleAtDistance = 0;
  3983. }
  3984. visibleAtDistance = Math.abs( visibleAtDistance );
  3985. for ( var l = 0; l < this.LODs.length; l ++ ) {
  3986. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  3987. break;
  3988. }
  3989. }
  3990. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  3991. this.add( object3D );
  3992. };
  3993. THREE.LOD.prototype.update = function ( camera ) {
  3994. if ( this.LODs.length > 1 ) {
  3995. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3996. var inverse = camera.matrixWorldInverse;
  3997. 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] );
  3998. this.LODs[ 0 ].object3D.visible = true;
  3999. for ( var l = 1; l < this.LODs.length; l ++ ) {
  4000. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  4001. this.LODs[ l - 1 ].object3D.visible = false;
  4002. this.LODs[ l ].object3D.visible = true;
  4003. } else {
  4004. break;
  4005. }
  4006. }
  4007. for( ; l < this.LODs.length; l ++ ) {
  4008. this.LODs[ l ].object3D.visible = false;
  4009. }
  4010. }
  4011. };
  4012. /**
  4013. * @author mikael emtinger / http://gomo.se/
  4014. */
  4015. THREE.Sprite = function ( parameters ) {
  4016. THREE.Object3D.call( this );
  4017. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  4018. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  4019. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  4020. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  4021. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  4022. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  4023. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  4024. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  4025. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  4026. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  4027. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  4028. this.rotation3d = this.rotation;
  4029. this.rotation = 0;
  4030. this.opacity = 1;
  4031. this.uvOffset = new THREE.Vector2( 0, 0 );
  4032. this.uvScale = new THREE.Vector2( 1, 1 );
  4033. };
  4034. THREE.Sprite.prototype = new THREE.Object3D();
  4035. THREE.Sprite.prototype.constructor = THREE.Sprite;
  4036. /*
  4037. * Custom update matrix
  4038. */
  4039. THREE.Sprite.prototype.updateMatrix = function () {
  4040. this.matrix.setPosition( this.position );
  4041. this.rotation3d.set( 0, 0, this.rotation );
  4042. this.matrix.setRotationFromEuler( this.rotation3d );
  4043. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  4044. this.matrix.scale( this.scale );
  4045. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  4046. }
  4047. this.matrixWorldNeedsUpdate = true;
  4048. };
  4049. /*
  4050. * Alignment
  4051. */
  4052. THREE.SpriteAlignment = {};
  4053. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  4054. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  4055. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  4056. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  4057. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  4058. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  4059. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  4060. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  4061. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  4062. /**
  4063. * @author mr.doob / http://mrdoob.com/
  4064. */
  4065. THREE.Scene = function () {
  4066. THREE.Object3D.call( this );
  4067. this.fog = null;
  4068. this.overrideMaterial = null;
  4069. this.matrixAutoUpdate = false;
  4070. this.__objects = [];
  4071. this.__lights = [];
  4072. this.__objectsAdded = [];
  4073. this.__objectsRemoved = [];
  4074. };
  4075. THREE.Scene.prototype = new THREE.Object3D();
  4076. THREE.Scene.prototype.constructor = THREE.Scene;
  4077. THREE.Scene.prototype.__addObject = function ( object ) {
  4078. if ( object instanceof THREE.Light ) {
  4079. if ( this.__lights.indexOf( object ) === - 1 ) {
  4080. this.__lights.push( object );
  4081. }
  4082. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  4083. if ( this.__objects.indexOf( object ) === - 1 ) {
  4084. this.__objects.push( object );
  4085. this.__objectsAdded.push( object );
  4086. // check if previously removed
  4087. var i = this.__objectsRemoved.indexOf( object );
  4088. if ( i !== -1 ) {
  4089. this.__objectsRemoved.splice( i, 1 );
  4090. }
  4091. }
  4092. }
  4093. for ( var c = 0; c < object.children.length; c ++ ) {
  4094. this.__addObject( object.children[ c ] );
  4095. }
  4096. };
  4097. THREE.Scene.prototype.__removeObject = function ( object ) {
  4098. if ( object instanceof THREE.Light ) {
  4099. var i = this.__lights.indexOf( object );
  4100. if ( i !== -1 ) {
  4101. this.__lights.splice( i, 1 );
  4102. }
  4103. } else if ( !( object instanceof THREE.Camera ) ) {
  4104. var i = this.__objects.indexOf( object );
  4105. if( i !== -1 ) {
  4106. this.__objects.splice( i, 1 );
  4107. this.__objectsRemoved.push( object );
  4108. // check if previously added
  4109. var ai = this.__objectsAdded.indexOf( object );
  4110. if ( ai !== -1 ) {
  4111. this.__objectsAdded.splice( ai, 1 );
  4112. }
  4113. }
  4114. }
  4115. for ( var c = 0; c < object.children.length; c ++ ) {
  4116. this.__removeObject( object.children[ c ] );
  4117. }
  4118. };
  4119. /**
  4120. * @author mr.doob / http://mrdoob.com/
  4121. * @author alteredq / http://alteredqualia.com/
  4122. */
  4123. THREE.Fog = function ( hex, near, far ) {
  4124. this.color = new THREE.Color( hex );
  4125. this.near = ( near !== undefined ) ? near : 1;
  4126. this.far = ( far !== undefined ) ? far : 1000;
  4127. };
  4128. /**
  4129. * @author mr.doob / http://mrdoob.com/
  4130. * @author alteredq / http://alteredqualia.com/
  4131. */
  4132. THREE.FogExp2 = function ( hex, density ) {
  4133. this.color = new THREE.Color( hex );
  4134. this.density = ( density !== undefined ) ? density : 0.00025;
  4135. };
  4136. /**
  4137. * @author mr.doob / http://mrdoob.com/
  4138. */
  4139. THREE.DOMRenderer = function () {
  4140. var _renderData, _elements,
  4141. _width, _height, _widthHalf, _heightHalf, _transformProp,
  4142. _projector = new THREE.Projector();
  4143. var getSupportedProp = function ( proparray ) {
  4144. var root = document.documentElement
  4145. for ( var i = 0; i < proparray.length; i ++ ) {
  4146. if ( typeof root.style[ proparray[ i ] ] === "string" ) {
  4147. return proparray[i];
  4148. }
  4149. }
  4150. return null;
  4151. };
  4152. _transformProp = getSupportedProp( [ 'transform', 'MozTransform', 'WebkitTransform', 'msTransform', 'OTransform' ] );
  4153. this.domElement = document.createElement( 'div' );
  4154. this.setSize = function ( width, height ) {
  4155. _width = width;
  4156. _height = height;
  4157. _widthHalf = _width / 2;
  4158. _heightHalf = _height / 2;
  4159. };
  4160. this.render = function ( scene, camera ) {
  4161. var e, el, m, ml, element, material, dom, v1x, v1y;
  4162. _renderData = _projector.projectScene( scene, camera );
  4163. _elements = _renderData.elements;
  4164. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4165. element = _elements[ e ];
  4166. if ( element instanceof THREE.RenderableParticle && element.material instanceof THREE.ParticleDOMMaterial ) {
  4167. dom = element.material.domElement;
  4168. v1x = element.x * _widthHalf + _widthHalf - ( dom.offsetWidth >> 1 );
  4169. v1y = element.y * _heightHalf + _heightHalf - ( dom.offsetHeight >> 1 );
  4170. dom.style.left = v1x + 'px';
  4171. dom.style.top = v1y + 'px';
  4172. dom.style.zIndex = Math.abs( Math.floor( ( 1 - element.z ) * camera.far / camera.near ) )
  4173. if ( _transformProp ) {
  4174. var scaleX = element.scale.x * _widthHalf;
  4175. var scaleY = element.scale.y * _heightHalf;
  4176. var scaleVal = "scale(" + scaleX + "," + scaleY + ")";
  4177. dom.style[ _transformProp ] = scaleVal;
  4178. }
  4179. }
  4180. }
  4181. };
  4182. };
  4183. /**
  4184. * @author mr.doob / http://mrdoob.com/
  4185. */
  4186. THREE.CanvasRenderer = function ( parameters ) {
  4187. parameters = parameters || {};
  4188. var _this = this,
  4189. _renderData, _elements, _lights,
  4190. _projector = new THREE.Projector(),
  4191. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  4192. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  4193. _context = _canvas.getContext( '2d' ),
  4194. _clearColor = new THREE.Color( 0x000000 ),
  4195. _clearOpacity = 0,
  4196. _contextGlobalAlpha = 1,
  4197. _contextGlobalCompositeOperation = 0,
  4198. _contextStrokeStyle = null,
  4199. _contextFillStyle = null,
  4200. _contextLineWidth = null,
  4201. _contextLineCap = null,
  4202. _contextLineJoin = null,
  4203. _v1, _v2, _v3, _v4,
  4204. _v5 = new THREE.RenderableVertex(),
  4205. _v6 = new THREE.RenderableVertex(),
  4206. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  4207. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  4208. _color = new THREE.Color(),
  4209. _color1 = new THREE.Color(),
  4210. _color2 = new THREE.Color(),
  4211. _color3 = new THREE.Color(),
  4212. _color4 = new THREE.Color(),
  4213. _patterns = [], _imagedatas = [],
  4214. _near, _far,
  4215. _image, _uvs,
  4216. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  4217. _clipRect = new THREE.Rectangle(),
  4218. _clearRect = new THREE.Rectangle(),
  4219. _bboxRect = new THREE.Rectangle(),
  4220. _enableLighting = false,
  4221. _ambientLight = new THREE.Color(),
  4222. _directionalLights = new THREE.Color(),
  4223. _pointLights = new THREE.Color(),
  4224. _pi2 = Math.PI * 2,
  4225. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4226. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  4227. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  4228. _pixelMap = document.createElement( 'canvas' );
  4229. _pixelMap.width = _pixelMap.height = 2;
  4230. _pixelMapContext = _pixelMap.getContext( '2d' );
  4231. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  4232. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  4233. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  4234. _pixelMapData = _pixelMapImage.data;
  4235. _gradientMap = document.createElement( 'canvas' );
  4236. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  4237. _gradientMapContext = _gradientMap.getContext( '2d' );
  4238. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  4239. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  4240. _gradientMapQuality --; // Fix UVs
  4241. this.domElement = _canvas;
  4242. this.autoClear = true;
  4243. this.sortObjects = true;
  4244. this.sortElements = true;
  4245. this.info = {
  4246. render: {
  4247. vertices: 0,
  4248. faces: 0
  4249. }
  4250. }
  4251. this.setSize = function ( width, height ) {
  4252. _canvasWidth = width;
  4253. _canvasHeight = height;
  4254. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  4255. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  4256. _canvas.width = _canvasWidth;
  4257. _canvas.height = _canvasHeight;
  4258. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4259. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4260. _contextGlobalAlpha = 1;
  4261. _contextGlobalCompositeOperation = 0;
  4262. _contextStrokeStyle = null;
  4263. _contextFillStyle = null;
  4264. _contextLineWidth = null;
  4265. _contextLineCap = null;
  4266. _contextLineJoin = null;
  4267. };
  4268. this.setClearColor = function ( color, opacity ) {
  4269. _clearColor.copy( color );
  4270. _clearOpacity = opacity !== undefined ? opacity : 1;
  4271. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4272. };
  4273. this.setClearColorHex = function ( hex, opacity ) {
  4274. _clearColor.setHex( hex );
  4275. _clearOpacity = opacity !== undefined ? opacity : 1;
  4276. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4277. };
  4278. this.clear = function () {
  4279. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4280. if ( !_clearRect.isEmpty() ) {
  4281. _clearRect.minSelf( _clipRect );
  4282. _clearRect.inflate( 2 );
  4283. if ( _clearOpacity < 1 ) {
  4284. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4285. }
  4286. if ( _clearOpacity > 0 ) {
  4287. setBlending( THREE.NormalBlending );
  4288. setOpacity( 1 );
  4289. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  4290. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4291. }
  4292. _clearRect.empty();
  4293. }
  4294. };
  4295. this.render = function ( scene, camera ) {
  4296. var e, el, element, material;
  4297. this.autoClear ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4298. _this.info.render.vertices = 0;
  4299. _this.info.render.faces = 0;
  4300. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4301. _elements = _renderData.elements;
  4302. _lights = _renderData.lights;
  4303. /* DEBUG
  4304. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  4305. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  4306. */
  4307. _enableLighting = _lights.length > 0;
  4308. if ( _enableLighting ) {
  4309. calculateLights( _lights );
  4310. }
  4311. for ( e = 0, el = _elements.length; e < el; e++ ) {
  4312. element = _elements[ e ];
  4313. material = element.material;
  4314. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4315. if ( material == null || material.opacity == 0 ) continue;
  4316. _bboxRect.empty();
  4317. if ( element instanceof THREE.RenderableParticle ) {
  4318. _v1 = element;
  4319. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  4320. renderParticle( _v1, element, material, scene );
  4321. } else if ( element instanceof THREE.RenderableLine ) {
  4322. _v1 = element.v1; _v2 = element.v2;
  4323. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4324. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4325. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4326. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4327. if ( _clipRect.intersects( _bboxRect ) ) {
  4328. renderLine( _v1, _v2, element, material, scene );
  4329. }
  4330. } else if ( element instanceof THREE.RenderableFace3 ) {
  4331. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4332. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4333. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4334. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4335. if ( material.overdraw ) {
  4336. expand( _v1.positionScreen, _v2.positionScreen );
  4337. expand( _v2.positionScreen, _v3.positionScreen );
  4338. expand( _v3.positionScreen, _v1.positionScreen );
  4339. }
  4340. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  4341. _v2.positionScreen.x, _v2.positionScreen.y,
  4342. _v3.positionScreen.x, _v3.positionScreen.y );
  4343. if ( _clipRect.intersects( _bboxRect ) ) {
  4344. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  4345. }
  4346. } else if ( element instanceof THREE.RenderableFace4 ) {
  4347. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4348. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4349. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4350. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4351. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  4352. _v5.positionScreen.copy( _v2.positionScreen );
  4353. _v6.positionScreen.copy( _v4.positionScreen );
  4354. if ( material.overdraw ) {
  4355. expand( _v1.positionScreen, _v2.positionScreen );
  4356. expand( _v2.positionScreen, _v4.positionScreen );
  4357. expand( _v4.positionScreen, _v1.positionScreen );
  4358. expand( _v3.positionScreen, _v5.positionScreen );
  4359. expand( _v3.positionScreen, _v6.positionScreen );
  4360. }
  4361. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4362. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4363. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4364. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4365. if ( _clipRect.intersects( _bboxRect ) ) {
  4366. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  4367. }
  4368. }
  4369. /*
  4370. _context.lineWidth = 1;
  4371. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  4372. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  4373. */
  4374. _clearRect.addRectangle( _bboxRect );
  4375. }
  4376. /* DEBUG
  4377. _context.lineWidth = 1;
  4378. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  4379. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  4380. */
  4381. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  4382. //
  4383. function calculateLights( lights ) {
  4384. var l, ll, light, lightColor;
  4385. _ambientLight.setRGB( 0, 0, 0 );
  4386. _directionalLights.setRGB( 0, 0, 0 );
  4387. _pointLights.setRGB( 0, 0, 0 );
  4388. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4389. light = lights[ l ];
  4390. lightColor = light.color;
  4391. if ( light instanceof THREE.AmbientLight ) {
  4392. _ambientLight.r += lightColor.r;
  4393. _ambientLight.g += lightColor.g;
  4394. _ambientLight.b += lightColor.b;
  4395. } else if ( light instanceof THREE.DirectionalLight ) {
  4396. // for particles
  4397. _directionalLights.r += lightColor.r;
  4398. _directionalLights.g += lightColor.g;
  4399. _directionalLights.b += lightColor.b;
  4400. } else if ( light instanceof THREE.PointLight ) {
  4401. // for particles
  4402. _pointLights.r += lightColor.r;
  4403. _pointLights.g += lightColor.g;
  4404. _pointLights.b += lightColor.b;
  4405. }
  4406. }
  4407. }
  4408. function calculateLight( lights, position, normal, color ) {
  4409. var l, ll, light, lightColor, lightPosition, amount;
  4410. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4411. light = lights[ l ];
  4412. lightColor = light.color;
  4413. if ( light instanceof THREE.DirectionalLight ) {
  4414. lightPosition = light.matrixWorld.getPosition();
  4415. amount = normal.dot( lightPosition );
  4416. if ( amount <= 0 ) continue;
  4417. amount *= light.intensity;
  4418. color.r += lightColor.r * amount;
  4419. color.g += lightColor.g * amount;
  4420. color.b += lightColor.b * amount;
  4421. } else if ( light instanceof THREE.PointLight ) {
  4422. lightPosition = light.matrixWorld.getPosition();
  4423. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  4424. if ( amount <= 0 ) continue;
  4425. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  4426. if ( amount == 0 ) continue;
  4427. amount *= light.intensity;
  4428. color.r += lightColor.r * amount;
  4429. color.g += lightColor.g * amount;
  4430. color.b += lightColor.b * amount;
  4431. }
  4432. }
  4433. }
  4434. function renderParticle ( v1, element, material, scene ) {
  4435. setOpacity( material.opacity );
  4436. setBlending( material.blending );
  4437. var width, height, scaleX, scaleY,
  4438. bitmap, bitmapWidth, bitmapHeight;
  4439. if ( material instanceof THREE.ParticleBasicMaterial ) {
  4440. if ( material.map ) {
  4441. bitmap = material.map.image;
  4442. bitmapWidth = bitmap.width >> 1;
  4443. bitmapHeight = bitmap.height >> 1;
  4444. scaleX = element.scale.x * _canvasWidthHalf;
  4445. scaleY = element.scale.y * _canvasHeightHalf;
  4446. width = scaleX * bitmapWidth;
  4447. height = scaleY * bitmapHeight;
  4448. // TODO: Rotations break this...
  4449. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4450. if ( !_clipRect.intersects( _bboxRect ) ) {
  4451. return;
  4452. }
  4453. _context.save();
  4454. _context.translate( v1.x, v1.y );
  4455. _context.rotate( - element.rotation );
  4456. _context.scale( scaleX, - scaleY );
  4457. _context.translate( - bitmapWidth, - bitmapHeight );
  4458. _context.drawImage( bitmap, 0, 0 );
  4459. _context.restore();
  4460. }
  4461. /* DEBUG
  4462. _context.beginPath();
  4463. _context.moveTo( v1.x - 10, v1.y );
  4464. _context.lineTo( v1.x + 10, v1.y );
  4465. _context.moveTo( v1.x, v1.y - 10 );
  4466. _context.lineTo( v1.x, v1.y + 10 );
  4467. _context.closePath();
  4468. _context.strokeStyle = 'rgb(255,255,0)';
  4469. _context.stroke();
  4470. */
  4471. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  4472. width = element.scale.x * _canvasWidthHalf;
  4473. height = element.scale.y * _canvasHeightHalf;
  4474. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4475. if ( !_clipRect.intersects( _bboxRect ) ) {
  4476. return;
  4477. }
  4478. setStrokeStyle( material.color.getContextStyle() );
  4479. setFillStyle( material.color.getContextStyle() );
  4480. _context.save();
  4481. _context.translate( v1.x, v1.y );
  4482. _context.rotate( - element.rotation );
  4483. _context.scale( width, height );
  4484. material.program( _context );
  4485. _context.restore();
  4486. }
  4487. }
  4488. function renderLine( v1, v2, element, material, scene ) {
  4489. setOpacity( material.opacity );
  4490. setBlending( material.blending );
  4491. _context.beginPath();
  4492. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  4493. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  4494. _context.closePath();
  4495. if ( material instanceof THREE.LineBasicMaterial ) {
  4496. setLineWidth( material.linewidth );
  4497. setLineCap( material.linecap );
  4498. setLineJoin( material.linejoin );
  4499. setStrokeStyle( material.color.getContextStyle() );
  4500. _context.stroke();
  4501. _bboxRect.inflate( material.linewidth * 2 );
  4502. }
  4503. }
  4504. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  4505. _this.info.render.vertices += 3;
  4506. _this.info.render.faces ++;
  4507. setOpacity( material.opacity );
  4508. setBlending( material.blending );
  4509. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4510. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4511. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4512. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  4513. if ( material instanceof THREE.MeshBasicMaterial ) {
  4514. if ( material.map/* && !material.wireframe*/ ) {
  4515. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4516. _uvs = element.uvs[ 0 ];
  4517. 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 );
  4518. }
  4519. } else if ( material.envMap ) {
  4520. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  4521. var cameraMatrix = camera.matrixWorldInverse;
  4522. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  4523. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4524. _uv1y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4525. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  4526. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4527. _uv2y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4528. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  4529. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4530. _uv3y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4531. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  4532. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  4533. }*/
  4534. } else {
  4535. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4536. }
  4537. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4538. if ( material.map && !material.wireframe ) {
  4539. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4540. _uvs = element.uvs[ 0 ];
  4541. 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 );
  4542. }
  4543. setBlending( THREE.SubtractiveBlending );
  4544. }
  4545. if ( _enableLighting ) {
  4546. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 3 ) {
  4547. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  4548. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  4549. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  4550. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4551. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4552. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  4553. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4554. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4555. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4556. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4557. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4558. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4559. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4560. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4561. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4562. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4563. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4564. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4565. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4566. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4567. } else {
  4568. _color.r = _ambientLight.r;
  4569. _color.g = _ambientLight.g;
  4570. _color.b = _ambientLight.b;
  4571. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4572. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4573. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4574. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4575. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4576. }
  4577. } else {
  4578. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4579. }
  4580. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4581. _near = camera.near;
  4582. _far = camera.far;
  4583. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4584. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4585. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4586. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4587. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4588. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4589. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4590. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4591. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4592. _color.r = normalToComponent( element.normalWorld.x );
  4593. _color.g = normalToComponent( element.normalWorld.y );
  4594. _color.b = normalToComponent( element.normalWorld.z );
  4595. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4596. }
  4597. }
  4598. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  4599. _this.info.render.vertices += 4;
  4600. _this.info.render.faces ++;
  4601. setOpacity( material.opacity );
  4602. setBlending( material.blending );
  4603. if ( material.map || material.envMap ) {
  4604. // Let renderFace3() handle this
  4605. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  4606. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  4607. return;
  4608. }
  4609. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4610. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4611. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4612. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  4613. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  4614. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  4615. if ( material instanceof THREE.MeshBasicMaterial ) {
  4616. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4617. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4618. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4619. if ( _enableLighting ) {
  4620. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 4 ) {
  4621. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  4622. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  4623. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  4624. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4625. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4626. calculateLight( _lights, element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  4627. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  4628. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4629. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4630. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4631. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4632. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4633. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4634. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4635. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4636. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4637. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  4638. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  4639. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  4640. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4641. // TODO: UVs are incorrect, v4->v3?
  4642. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4643. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4644. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4645. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4646. } else {
  4647. _color.r = _ambientLight.r;
  4648. _color.g = _ambientLight.g;
  4649. _color.b = _ambientLight.b;
  4650. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4651. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4652. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4653. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4654. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4655. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4656. }
  4657. } else {
  4658. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4659. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4660. }
  4661. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4662. _color.r = normalToComponent( element.normalWorld.x );
  4663. _color.g = normalToComponent( element.normalWorld.y );
  4664. _color.b = normalToComponent( element.normalWorld.z );
  4665. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4666. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4667. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4668. _near = camera.near;
  4669. _far = camera.far;
  4670. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4671. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4672. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  4673. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4674. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4675. // TODO: UVs are incorrect, v4->v3?
  4676. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4677. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4678. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4679. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4680. }
  4681. }
  4682. //
  4683. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  4684. _context.beginPath();
  4685. _context.moveTo( x0, y0 );
  4686. _context.lineTo( x1, y1 );
  4687. _context.lineTo( x2, y2 );
  4688. _context.lineTo( x0, y0 );
  4689. _context.closePath();
  4690. }
  4691. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  4692. _context.beginPath();
  4693. _context.moveTo( x0, y0 );
  4694. _context.lineTo( x1, y1 );
  4695. _context.lineTo( x2, y2 );
  4696. _context.lineTo( x3, y3 );
  4697. _context.lineTo( x0, y0 );
  4698. _context.closePath();
  4699. }
  4700. function strokePath( color, linewidth, linecap, linejoin ) {
  4701. setLineWidth( linewidth );
  4702. setLineCap( linecap );
  4703. setLineJoin( linejoin );
  4704. setStrokeStyle( color.getContextStyle() );
  4705. _context.stroke();
  4706. _bboxRect.inflate( linewidth * 2 );
  4707. }
  4708. function fillPath( color ) {
  4709. setFillStyle( color.getContextStyle() );
  4710. _context.fill();
  4711. }
  4712. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  4713. if ( texture.image.width == 0 ) return;
  4714. if ( texture.needsUpdate == true || _patterns[ texture.id ] == undefined ) {
  4715. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  4716. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  4717. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX && repeatY ? 'repeat' : repeatX && !repeatY ? 'repeat-x' : !repeatX && repeatY ? 'repeat-y' : 'no-repeat' );
  4718. texture.needsUpdate = false;
  4719. }
  4720. setFillStyle( _patterns[ texture.id ] );
  4721. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4722. var a, b, c, d, e, f, det, idet,
  4723. offsetX = texture.offset.x / texture.repeat.x,
  4724. offsetY = texture.offset.y / texture.repeat.y,
  4725. width = texture.image.width * texture.repeat.x,
  4726. height = texture.image.height * texture.repeat.y;
  4727. u0 = ( u0 + offsetX ) * width;
  4728. v0 = ( v0 + offsetY ) * height;
  4729. u1 = ( u1 + offsetX ) * width;
  4730. v1 = ( v1 + offsetY ) * height;
  4731. u2 = ( u2 + offsetX ) * width;
  4732. v2 = ( v2 + offsetY ) * height;
  4733. x1 -= x0; y1 -= y0;
  4734. x2 -= x0; y2 -= y0;
  4735. u1 -= u0; v1 -= v0;
  4736. u2 -= u0; v2 -= v0;
  4737. det = u1 * v2 - u2 * v1;
  4738. if ( det == 0 ) {
  4739. if ( _imagedatas[ texture.id ] === undefined ) {
  4740. var canvas = document.createElement( 'canvas' )
  4741. canvas.width = texture.image.width;
  4742. canvas.height = texture.image.height;
  4743. var context = canvas.getContext( '2d' );
  4744. context.drawImage( texture.image, 0, 0 );
  4745. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  4746. // variables cannot be deleted in ES5 strict mode
  4747. //delete canvas;
  4748. }
  4749. var data = _imagedatas[ texture.id ];
  4750. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  4751. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  4752. fillPath( _color );
  4753. return;
  4754. }
  4755. idet = 1 / det;
  4756. a = ( v2 * x1 - v1 * x2 ) * idet;
  4757. b = ( v2 * y1 - v1 * y2 ) * idet;
  4758. c = ( u1 * x2 - u2 * x1 ) * idet;
  4759. d = ( u1 * y2 - u2 * y1 ) * idet;
  4760. e = x0 - a * u0 - c * v0;
  4761. f = y0 - b * u0 - d * v0;
  4762. _context.save();
  4763. _context.transform( a, b, c, d, e, f );
  4764. _context.fill();
  4765. _context.restore();
  4766. }
  4767. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  4768. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4769. var a, b, c, d, e, f, det, idet,
  4770. width = image.width - 1,
  4771. height = image.height - 1;
  4772. u0 *= width; v0 *= height;
  4773. u1 *= width; v1 *= height;
  4774. u2 *= width; v2 *= height;
  4775. x1 -= x0; y1 -= y0;
  4776. x2 -= x0; y2 -= y0;
  4777. u1 -= u0; v1 -= v0;
  4778. u2 -= u0; v2 -= v0;
  4779. det = u1 * v2 - u2 * v1;
  4780. idet = 1 / det;
  4781. a = ( v2 * x1 - v1 * x2 ) * idet;
  4782. b = ( v2 * y1 - v1 * y2 ) * idet;
  4783. c = ( u1 * x2 - u2 * x1 ) * idet;
  4784. d = ( u1 * y2 - u2 * y1 ) * idet;
  4785. e = x0 - a * u0 - c * v0;
  4786. f = y0 - b * u0 - d * v0;
  4787. _context.save();
  4788. _context.transform( a, b, c, d, e, f );
  4789. _context.clip();
  4790. _context.drawImage( image, 0, 0 );
  4791. _context.restore();
  4792. }
  4793. function getGradientTexture( color1, color2, color3, color4 ) {
  4794. // http://mrdoob.com/blog/post/710
  4795. var c1r = ~~ ( color1.r * 255 ), c1g = ~~ ( color1.g * 255 ), c1b = ~~ ( color1.b * 255 ),
  4796. c2r = ~~ ( color2.r * 255 ), c2g = ~~ ( color2.g * 255 ), c2b = ~~ ( color2.b * 255 ),
  4797. c3r = ~~ ( color3.r * 255 ), c3g = ~~ ( color3.g * 255 ), c3b = ~~ ( color3.b * 255 ),
  4798. c4r = ~~ ( color4.r * 255 ), c4g = ~~ ( color4.g * 255 ), c4b = ~~ ( color4.b * 255 );
  4799. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  4800. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  4801. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  4802. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  4803. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  4804. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  4805. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  4806. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  4807. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  4808. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  4809. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  4810. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  4811. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  4812. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  4813. return _gradientMap;
  4814. }
  4815. function smoothstep( value, min, max ) {
  4816. var x = ( value - min ) / ( max - min );
  4817. return x * x * ( 3 - 2 * x );
  4818. }
  4819. function normalToComponent( normal ) {
  4820. var component = ( normal + 1 ) * 0.5;
  4821. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  4822. }
  4823. // Hide anti-alias gaps
  4824. function expand( v1, v2 ) {
  4825. var x = v2.x - v1.x, y = v2.y - v1.y,
  4826. det = x * x + y * y, idet;
  4827. if ( det == 0 ) return;
  4828. idet = 1 / Math.sqrt( det );
  4829. x *= idet; y *= idet;
  4830. v2.x += x; v2.y += y;
  4831. v1.x -= x; v1.y -= y;
  4832. }
  4833. };
  4834. // Context cached methods.
  4835. function setOpacity( value ) {
  4836. if ( _contextGlobalAlpha != value ) {
  4837. _context.globalAlpha = _contextGlobalAlpha = value;
  4838. }
  4839. }
  4840. function setBlending( value ) {
  4841. if ( _contextGlobalCompositeOperation != value ) {
  4842. switch ( value ) {
  4843. case THREE.NormalBlending:
  4844. _context.globalCompositeOperation = 'source-over';
  4845. break;
  4846. case THREE.AdditiveBlending:
  4847. _context.globalCompositeOperation = 'lighter';
  4848. break;
  4849. case THREE.SubtractiveBlending:
  4850. _context.globalCompositeOperation = 'darker';
  4851. break;
  4852. }
  4853. _contextGlobalCompositeOperation = value;
  4854. }
  4855. }
  4856. function setLineWidth( value ) {
  4857. if ( _contextLineWidth != value ) {
  4858. _context.lineWidth = _contextLineWidth = value;
  4859. }
  4860. }
  4861. function setLineCap( value ) {
  4862. // "butt", "round", "square"
  4863. if ( _contextLineCap != value ) {
  4864. _context.lineCap = _contextLineCap = value;
  4865. }
  4866. }
  4867. function setLineJoin( value ) {
  4868. // "round", "bevel", "miter"
  4869. if ( _contextLineJoin != value ) {
  4870. _context.lineJoin = _contextLineJoin = value;
  4871. }
  4872. }
  4873. function setStrokeStyle( style ) {
  4874. if ( _contextStrokeStyle != style ) {
  4875. _context.strokeStyle = _contextStrokeStyle = style;
  4876. }
  4877. }
  4878. function setFillStyle( style ) {
  4879. if ( _contextFillStyle != style ) {
  4880. _context.fillStyle = _contextFillStyle = style;
  4881. }
  4882. }
  4883. };
  4884. /**
  4885. * @author mr.doob / http://mrdoob.com/
  4886. */
  4887. THREE.SVGRenderer = function () {
  4888. var _this = this,
  4889. _renderData, _elements, _lights,
  4890. _projector = new THREE.Projector(),
  4891. _svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
  4892. _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf,
  4893. _v1, _v2, _v3, _v4,
  4894. _clipRect = new THREE.Rectangle(),
  4895. _bboxRect = new THREE.Rectangle(),
  4896. _enableLighting = false,
  4897. _color = new THREE.Color(),
  4898. _ambientLight = new THREE.Color(),
  4899. _directionalLights = new THREE.Color(),
  4900. _pointLights = new THREE.Color(),
  4901. _w, // z-buffer to w-buffer
  4902. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4903. _svgPathPool = [], _svgCirclePool = [], _svgLinePool = [],
  4904. _svgNode, _pathCount, _circleCount, _lineCount,
  4905. _quality = 1;
  4906. this.domElement = _svg;
  4907. this.autoClear = true;
  4908. this.sortObjects = true;
  4909. this.sortElements = true;
  4910. this.info = {
  4911. render: {
  4912. vertices: 0,
  4913. faces: 0
  4914. }
  4915. }
  4916. this.setQuality = function( quality ) {
  4917. switch(quality) {
  4918. case "high": _quality = 1; break;
  4919. case "low": _quality = 0; break;
  4920. }
  4921. };
  4922. this.setSize = function( width, height ) {
  4923. _svgWidth = width; _svgHeight = height;
  4924. _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2;
  4925. _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight );
  4926. _svg.setAttribute( 'width', _svgWidth );
  4927. _svg.setAttribute( 'height', _svgHeight );
  4928. _clipRect.set( - _svgWidthHalf, - _svgHeightHalf, _svgWidthHalf, _svgHeightHalf );
  4929. };
  4930. this.clear = function () {
  4931. while ( _svg.childNodes.length > 0 ) {
  4932. _svg.removeChild( _svg.childNodes[ 0 ] );
  4933. }
  4934. };
  4935. this.render = function ( scene, camera ) {
  4936. var e, el, element, material;
  4937. this.autoClear && this.clear();
  4938. _this.info.render.vertices = 0;
  4939. _this.info.render.faces = 0;
  4940. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4941. _elements = _renderData.elements;
  4942. _lights = _renderData.lights;
  4943. _pathCount = 0; _circleCount = 0; _lineCount = 0;
  4944. _enableLighting = _lights.length > 0;
  4945. if ( _enableLighting ) {
  4946. calculateLights( _lights );
  4947. }
  4948. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4949. element = _elements[ e ];
  4950. material = element.material;
  4951. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4952. if ( material == null || material.opacity == 0 ) continue;
  4953. _bboxRect.empty();
  4954. if ( element instanceof THREE.RenderableParticle ) {
  4955. _v1 = element;
  4956. _v1.x *= _svgWidthHalf; _v1.y *= -_svgHeightHalf;
  4957. renderParticle( _v1, element, material, scene );
  4958. } else if ( element instanceof THREE.RenderableLine ) {
  4959. _v1 = element.v1; _v2 = element.v2;
  4960. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4961. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4962. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4963. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4964. if ( !_clipRect.intersects( _bboxRect ) ) {
  4965. continue;
  4966. }
  4967. renderLine( _v1, _v2, element, material, scene );
  4968. } else if ( element instanceof THREE.RenderableFace3 ) {
  4969. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4970. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4971. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4972. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf;
  4973. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4974. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4975. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4976. if ( !_clipRect.intersects( _bboxRect ) ) {
  4977. continue;
  4978. }
  4979. renderFace3( _v1, _v2, _v3, element, material, scene );
  4980. } else if ( element instanceof THREE.RenderableFace4 ) {
  4981. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4982. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= -_svgHeightHalf;
  4983. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= -_svgHeightHalf;
  4984. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= -_svgHeightHalf;
  4985. _v4.positionScreen.x *= _svgWidthHalf; _v4.positionScreen.y *= -_svgHeightHalf;
  4986. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4987. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4988. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4989. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4990. if ( !_clipRect.intersects( _bboxRect) ) {
  4991. continue;
  4992. }
  4993. renderFace4( _v1, _v2, _v3, _v4, element, material, scene );
  4994. }
  4995. }
  4996. };
  4997. function calculateLights( lights ) {
  4998. var l, ll, light, lightColor;
  4999. _ambientLight.setRGB( 0, 0, 0 );
  5000. _directionalLights.setRGB( 0, 0, 0 );
  5001. _pointLights.setRGB( 0, 0, 0 );
  5002. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  5003. light = lights[ l ];
  5004. lightColor = light.color;
  5005. if ( light instanceof THREE.AmbientLight ) {
  5006. _ambientLight.r += lightColor.r;
  5007. _ambientLight.g += lightColor.g;
  5008. _ambientLight.b += lightColor.b;
  5009. } else if ( light instanceof THREE.DirectionalLight ) {
  5010. _directionalLights.r += lightColor.r;
  5011. _directionalLights.g += lightColor.g;
  5012. _directionalLights.b += lightColor.b;
  5013. } else if ( light instanceof THREE.PointLight ) {
  5014. _pointLights.r += lightColor.r;
  5015. _pointLights.g += lightColor.g;
  5016. _pointLights.b += lightColor.b;
  5017. }
  5018. }
  5019. }
  5020. function calculateLight( lights, position, normal, color ) {
  5021. var l, ll, light, lightColor, lightPosition, amount;
  5022. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  5023. light = lights[ l ];
  5024. lightColor = light.color;
  5025. if ( light instanceof THREE.DirectionalLight ) {
  5026. lightPosition = light.matrixWorld.getPosition();
  5027. amount = normal.dot( lightPosition );
  5028. if ( amount <= 0 ) continue;
  5029. amount *= light.intensity;
  5030. color.r += lightColor.r * amount;
  5031. color.g += lightColor.g * amount;
  5032. color.b += lightColor.b * amount;
  5033. } else if ( light instanceof THREE.PointLight ) {
  5034. lightPosition = light.matrixWorld.getPosition();
  5035. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  5036. if ( amount <= 0 ) continue;
  5037. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  5038. if ( amount == 0 ) continue;
  5039. amount *= light.intensity;
  5040. color.r += lightColor.r * amount;
  5041. color.g += lightColor.g * amount;
  5042. color.b += lightColor.b * amount;
  5043. }
  5044. }
  5045. }
  5046. function renderParticle( v1, element, material, scene ) {
  5047. /*
  5048. _svgNode = getCircleNode( _circleCount++ );
  5049. _svgNode.setAttribute( 'cx', v1.x );
  5050. _svgNode.setAttribute( 'cy', v1.y );
  5051. _svgNode.setAttribute( 'r', element.scale.x * _svgWidthHalf );
  5052. if ( material instanceof THREE.ParticleCircleMaterial ) {
  5053. if ( _enableLighting ) {
  5054. _color.r = _ambientLight.r + _directionalLights.r + _pointLights.r;
  5055. _color.g = _ambientLight.g + _directionalLights.g + _pointLights.g;
  5056. _color.b = _ambientLight.b + _directionalLights.b + _pointLights.b;
  5057. _color.r = material.color.r * _color.r;
  5058. _color.g = material.color.g * _color.g;
  5059. _color.b = material.color.b * _color.b;
  5060. _color.updateStyleString();
  5061. } else {
  5062. _color = material.color;
  5063. }
  5064. _svgNode.setAttribute( 'style', 'fill: ' + _color.__styleString );
  5065. }
  5066. _svg.appendChild( _svgNode );
  5067. */
  5068. }
  5069. function renderLine ( v1, v2, element, material, scene ) {
  5070. _svgNode = getLineNode( _lineCount ++ );
  5071. _svgNode.setAttribute( 'x1', v1.positionScreen.x );
  5072. _svgNode.setAttribute( 'y1', v1.positionScreen.y );
  5073. _svgNode.setAttribute( 'x2', v2.positionScreen.x );
  5074. _svgNode.setAttribute( 'y2', v2.positionScreen.y );
  5075. if ( material instanceof THREE.LineBasicMaterial ) {
  5076. _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 );
  5077. _svg.appendChild( _svgNode );
  5078. }
  5079. }
  5080. function renderFace3( v1, v2, v3, element, material, scene ) {
  5081. _this.info.render.vertices += 3;
  5082. _this.info.render.faces ++;
  5083. _svgNode = getPathNode( _pathCount ++ );
  5084. _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' );
  5085. if ( material instanceof THREE.MeshBasicMaterial ) {
  5086. _color.copy( material.color );
  5087. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5088. if ( _enableLighting ) {
  5089. _color.r = _ambientLight.r;
  5090. _color.g = _ambientLight.g;
  5091. _color.b = _ambientLight.b;
  5092. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5093. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5094. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5095. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5096. } else {
  5097. _color.copy( material.color );
  5098. }
  5099. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5100. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5101. _color.setRGB( _w, _w, _w );
  5102. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5103. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5104. }
  5105. if ( material.wireframe ) {
  5106. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5107. } else {
  5108. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5109. }
  5110. _svg.appendChild( _svgNode );
  5111. }
  5112. function renderFace4( v1, v2, v3, v4, element, material, scene ) {
  5113. _this.info.render.vertices += 4;
  5114. _this.info.render.faces ++;
  5115. _svgNode = getPathNode( _pathCount ++ );
  5116. _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' );
  5117. if ( material instanceof THREE.MeshBasicMaterial ) {
  5118. _color.copy( material.color );
  5119. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5120. if ( _enableLighting ) {
  5121. _color.r = _ambientLight.r;
  5122. _color.g = _ambientLight.g;
  5123. _color.b = _ambientLight.b;
  5124. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5125. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5126. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5127. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5128. } else {
  5129. _color.copy( material.color );
  5130. }
  5131. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5132. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5133. _color.setRGB( _w, _w, _w );
  5134. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5135. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5136. }
  5137. if ( material.wireframe ) {
  5138. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5139. } else {
  5140. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5141. }
  5142. _svg.appendChild( _svgNode );
  5143. }
  5144. function getLineNode( id ) {
  5145. if ( _svgLinePool[ id ] == null ) {
  5146. _svgLinePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' );
  5147. if ( _quality == 0 ) {
  5148. _svgLinePool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5149. }
  5150. return _svgLinePool[ id ];
  5151. }
  5152. return _svgLinePool[ id ];
  5153. }
  5154. function getPathNode( id ) {
  5155. if ( _svgPathPool[ id ] == null ) {
  5156. _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  5157. if ( _quality == 0 ) {
  5158. _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5159. }
  5160. return _svgPathPool[ id ];
  5161. }
  5162. return _svgPathPool[ id ];
  5163. }
  5164. function getCircleNode( id ) {
  5165. if ( _svgCirclePool[id] == null ) {
  5166. _svgCirclePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
  5167. if ( _quality == 0 ) {
  5168. _svgCirclePool[id].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5169. }
  5170. return _svgCirclePool[ id ];
  5171. }
  5172. return _svgCirclePool[ id ];
  5173. }
  5174. function normalToComponent( normal ) {
  5175. var component = ( normal + 1 ) * 0.5;
  5176. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  5177. }
  5178. function pad( str ) {
  5179. while ( str.length < 6 ) str = '0' + str;
  5180. return str;
  5181. }
  5182. };
  5183. /**
  5184. * @author alteredq / http://alteredqualia.com/
  5185. * @author mrdoob / http://mrdoob.com/
  5186. * @author mikael emtinger / http://gomo.se/
  5187. */
  5188. THREE.ShaderChunk = {
  5189. // FOG
  5190. fog_pars_fragment: [
  5191. "#ifdef USE_FOG",
  5192. "uniform vec3 fogColor;",
  5193. "#ifdef FOG_EXP2",
  5194. "uniform float fogDensity;",
  5195. "#else",
  5196. "uniform float fogNear;",
  5197. "uniform float fogFar;",
  5198. "#endif",
  5199. "#endif"
  5200. ].join("\n"),
  5201. fog_fragment: [
  5202. "#ifdef USE_FOG",
  5203. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5204. "#ifdef FOG_EXP2",
  5205. "const float LOG2 = 1.442695;",
  5206. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  5207. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  5208. "#else",
  5209. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  5210. "#endif",
  5211. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  5212. "#endif"
  5213. ].join("\n"),
  5214. // ENVIRONMENT MAP
  5215. envmap_pars_fragment: [
  5216. "#ifdef USE_ENVMAP",
  5217. "varying vec3 vReflect;",
  5218. "uniform float reflectivity;",
  5219. "uniform samplerCube envMap;",
  5220. "uniform float flipEnvMap;",
  5221. "uniform int combine;",
  5222. "#endif"
  5223. ].join("\n"),
  5224. envmap_fragment: [
  5225. "#ifdef USE_ENVMAP",
  5226. "#ifdef DOUBLE_SIDED",
  5227. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5228. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5229. "#else",
  5230. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5231. "#endif",
  5232. "#ifdef GAMMA_INPUT",
  5233. "cubeColor.xyz *= cubeColor.xyz;",
  5234. "#endif",
  5235. "if ( combine == 1 ) {",
  5236. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, reflectivity );",
  5237. "} else {",
  5238. "gl_FragColor.xyz = gl_FragColor.xyz * cubeColor.xyz;",
  5239. "}",
  5240. "#endif"
  5241. ].join("\n"),
  5242. envmap_pars_vertex: [
  5243. "#ifdef USE_ENVMAP",
  5244. "varying vec3 vReflect;",
  5245. "uniform float refractionRatio;",
  5246. "uniform bool useRefract;",
  5247. "#endif"
  5248. ].join("\n"),
  5249. envmap_vertex : [
  5250. "#ifdef USE_ENVMAP",
  5251. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  5252. "vec3 nWorld = mat3( objectMatrix[ 0 ].xyz, objectMatrix[ 1 ].xyz, objectMatrix[ 2 ].xyz ) * normal;",
  5253. "if ( useRefract ) {",
  5254. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  5255. "} else {",
  5256. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  5257. "}",
  5258. "#endif"
  5259. ].join("\n"),
  5260. // COLOR MAP (particles)
  5261. map_particle_pars_fragment: [
  5262. "#ifdef USE_MAP",
  5263. "uniform sampler2D map;",
  5264. "#endif"
  5265. ].join("\n"),
  5266. map_particle_fragment: [
  5267. "#ifdef USE_MAP",
  5268. "gl_FragColor = gl_FragColor * texture2D( map, gl_PointCoord );",
  5269. "#endif"
  5270. ].join("\n"),
  5271. // COLOR MAP (triangles)
  5272. map_pars_vertex: [
  5273. "#ifdef USE_MAP",
  5274. "varying vec2 vUv;",
  5275. "uniform vec4 offsetRepeat;",
  5276. "#endif"
  5277. ].join("\n"),
  5278. map_pars_fragment: [
  5279. "#ifdef USE_MAP",
  5280. "varying vec2 vUv;",
  5281. "uniform sampler2D map;",
  5282. "#endif"
  5283. ].join("\n"),
  5284. map_vertex: [
  5285. "#ifdef USE_MAP",
  5286. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  5287. "#endif"
  5288. ].join("\n"),
  5289. map_fragment: [
  5290. "#ifdef USE_MAP",
  5291. "#ifdef GAMMA_INPUT",
  5292. "vec4 texelColor = texture2D( map, vUv );",
  5293. "texelColor.xyz *= texelColor.xyz;",
  5294. "gl_FragColor = gl_FragColor * texelColor;",
  5295. "#else",
  5296. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  5297. "#endif",
  5298. "#endif"
  5299. ].join("\n"),
  5300. // LIGHT MAP
  5301. lightmap_pars_fragment: [
  5302. "#ifdef USE_LIGHTMAP",
  5303. "varying vec2 vUv2;",
  5304. "uniform sampler2D lightMap;",
  5305. "#endif"
  5306. ].join("\n"),
  5307. lightmap_pars_vertex: [
  5308. "#ifdef USE_LIGHTMAP",
  5309. "varying vec2 vUv2;",
  5310. "#endif"
  5311. ].join("\n"),
  5312. lightmap_fragment: [
  5313. "#ifdef USE_LIGHTMAP",
  5314. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  5315. "#endif"
  5316. ].join("\n"),
  5317. lightmap_vertex: [
  5318. "#ifdef USE_LIGHTMAP",
  5319. "vUv2 = uv2;",
  5320. "#endif"
  5321. ].join("\n"),
  5322. // LIGHTS LAMBERT
  5323. lights_lambert_pars_vertex: [
  5324. "uniform vec3 ambient;",
  5325. "uniform vec3 diffuse;",
  5326. "uniform vec3 emissive;",
  5327. "uniform vec3 ambientLightColor;",
  5328. "#if MAX_DIR_LIGHTS > 0",
  5329. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5330. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5331. "#endif",
  5332. "#if MAX_POINT_LIGHTS > 0",
  5333. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5334. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5335. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5336. "#endif",
  5337. "#ifdef WRAP_AROUND",
  5338. "uniform vec3 wrapRGB;",
  5339. "#endif",
  5340. ].join("\n"),
  5341. lights_lambert_vertex: [
  5342. "vLightFront = vec3( 0.0 );",
  5343. "#ifdef DOUBLE_SIDED",
  5344. "vLightBack = vec3( 0.0 );",
  5345. "#endif",
  5346. "transformedNormal = normalize( transformedNormal );",
  5347. "#if MAX_DIR_LIGHTS > 0",
  5348. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5349. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5350. "vec3 dirVector = normalize( lDirection.xyz );",
  5351. "float dotProduct = dot( transformedNormal, dirVector );",
  5352. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5353. "#ifdef DOUBLE_SIDED",
  5354. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5355. "#ifdef WRAP_AROUND",
  5356. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5357. "#endif",
  5358. "#endif",
  5359. "#ifdef WRAP_AROUND",
  5360. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5361. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  5362. "#ifdef DOUBLE_SIDED",
  5363. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  5364. "#endif",
  5365. "#endif",
  5366. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  5367. "#ifdef DOUBLE_SIDED",
  5368. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  5369. "#endif",
  5370. "}",
  5371. "#endif",
  5372. "#if MAX_POINT_LIGHTS > 0",
  5373. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5374. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5375. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5376. "float lDistance = 1.0;",
  5377. "if ( pointLightDistance[ i ] > 0.0 )",
  5378. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5379. "lVector = normalize( lVector );",
  5380. "float dotProduct = dot( transformedNormal, lVector );",
  5381. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5382. "#ifdef DOUBLE_SIDED",
  5383. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5384. "#ifdef WRAP_AROUND",
  5385. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5386. "#endif",
  5387. "#endif",
  5388. "#ifdef WRAP_AROUND",
  5389. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5390. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  5391. "#ifdef DOUBLE_SIDED",
  5392. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  5393. "#endif",
  5394. "#endif",
  5395. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  5396. "#ifdef DOUBLE_SIDED",
  5397. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  5398. "#endif",
  5399. "}",
  5400. "#endif",
  5401. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  5402. "#ifdef DOUBLE_SIDED",
  5403. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  5404. "#endif",
  5405. ].join("\n"),
  5406. // LIGHTS PHONG
  5407. lights_phong_pars_vertex: [
  5408. "#if MAX_POINT_LIGHTS > 0",
  5409. "#ifndef PHONG_PER_PIXEL",
  5410. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5411. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5412. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5413. "#endif",
  5414. "#endif"
  5415. ].join("\n"),
  5416. lights_phong_vertex: [
  5417. "#if MAX_POINT_LIGHTS > 0",
  5418. "#ifndef PHONG_PER_PIXEL",
  5419. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5420. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5421. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5422. "float lDistance = 1.0;",
  5423. "if ( pointLightDistance[ i ] > 0.0 )",
  5424. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5425. "vPointLight[ i ] = vec4( lVector, lDistance );",
  5426. "}",
  5427. "#endif",
  5428. "#endif"
  5429. ].join("\n"),
  5430. lights_phong_pars_fragment: [
  5431. "uniform vec3 ambientLightColor;",
  5432. "#if MAX_DIR_LIGHTS > 0",
  5433. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5434. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5435. "#endif",
  5436. "#if MAX_POINT_LIGHTS > 0",
  5437. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5438. "#ifdef PHONG_PER_PIXEL",
  5439. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5440. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5441. "#else",
  5442. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5443. "#endif",
  5444. "#endif",
  5445. "#ifdef WRAP_AROUND",
  5446. "uniform vec3 wrapRGB;",
  5447. "#endif",
  5448. "varying vec3 vViewPosition;",
  5449. "varying vec3 vNormal;"
  5450. ].join("\n"),
  5451. lights_phong_fragment: [
  5452. "vec3 normal = normalize( vNormal );",
  5453. "vec3 viewPosition = normalize( vViewPosition );",
  5454. "#ifdef DOUBLE_SIDED",
  5455. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5456. "#endif",
  5457. "#if MAX_POINT_LIGHTS > 0",
  5458. "vec3 pointDiffuse = vec3( 0.0 );",
  5459. "vec3 pointSpecular = vec3( 0.0 );",
  5460. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5461. "#ifdef PHONG_PER_PIXEL",
  5462. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5463. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  5464. "float lDistance = 1.0;",
  5465. "if ( pointLightDistance[ i ] > 0.0 )",
  5466. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5467. "lVector = normalize( lVector );",
  5468. "#else",
  5469. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  5470. "float lDistance = vPointLight[ i ].w;",
  5471. "#endif",
  5472. // diffuse
  5473. "float dotProduct = dot( normal, lVector );",
  5474. "#ifdef WRAP_AROUND",
  5475. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  5476. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5477. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  5478. "#else",
  5479. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  5480. "#endif",
  5481. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  5482. // specular
  5483. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  5484. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  5485. "float pointSpecularWeight = max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  5486. "#ifdef PHYSICALLY_BASED_SHADING",
  5487. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5488. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5489. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  5490. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  5491. "#else",
  5492. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  5493. "#endif",
  5494. "}",
  5495. "#endif",
  5496. "#if MAX_DIR_LIGHTS > 0",
  5497. "vec3 dirDiffuse = vec3( 0.0 );",
  5498. "vec3 dirSpecular = vec3( 0.0 );" ,
  5499. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5500. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5501. "vec3 dirVector = normalize( lDirection.xyz );",
  5502. // diffuse
  5503. "float dotProduct = dot( normal, dirVector );",
  5504. "#ifdef WRAP_AROUND",
  5505. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  5506. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5507. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  5508. "#else",
  5509. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  5510. "#endif",
  5511. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  5512. // specular
  5513. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  5514. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  5515. "float dirSpecularWeight = max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  5516. "#ifdef PHYSICALLY_BASED_SHADING",
  5517. /*
  5518. // fresnel term from skin shader
  5519. "const float F0 = 0.128;",
  5520. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  5521. "float exponential = pow( base, 5.0 );",
  5522. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  5523. */
  5524. /*
  5525. // fresnel term from fresnel shader
  5526. "const float mFresnelBias = 0.08;",
  5527. "const float mFresnelScale = 0.3;",
  5528. "const float mFresnelPower = 5.0;",
  5529. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  5530. */
  5531. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5532. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5533. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  5534. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  5535. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  5536. "#else",
  5537. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  5538. "#endif",
  5539. "}",
  5540. "#endif",
  5541. "vec3 totalDiffuse = vec3( 0.0 );",
  5542. "vec3 totalSpecular = vec3( 0.0 );",
  5543. "#if MAX_DIR_LIGHTS > 0",
  5544. "totalDiffuse += dirDiffuse;",
  5545. "totalSpecular += dirSpecular;",
  5546. "#endif",
  5547. "#if MAX_POINT_LIGHTS > 0",
  5548. "totalDiffuse += pointDiffuse;",
  5549. "totalSpecular += pointSpecular;",
  5550. "#endif",
  5551. "#ifdef METAL",
  5552. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  5553. "#else",
  5554. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  5555. "#endif"
  5556. ].join("\n"),
  5557. // VERTEX COLORS
  5558. color_pars_fragment: [
  5559. "#ifdef USE_COLOR",
  5560. "varying vec3 vColor;",
  5561. "#endif"
  5562. ].join("\n"),
  5563. color_fragment: [
  5564. "#ifdef USE_COLOR",
  5565. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  5566. "#endif"
  5567. ].join("\n"),
  5568. color_pars_vertex: [
  5569. "#ifdef USE_COLOR",
  5570. "varying vec3 vColor;",
  5571. "#endif"
  5572. ].join("\n"),
  5573. color_vertex: [
  5574. "#ifdef USE_COLOR",
  5575. "#ifdef GAMMA_INPUT",
  5576. "vColor = color * color;",
  5577. "#else",
  5578. "vColor = color;",
  5579. "#endif",
  5580. "#endif"
  5581. ].join("\n"),
  5582. // SKINNING
  5583. skinning_pars_vertex: [
  5584. "#ifdef USE_SKINNING",
  5585. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  5586. "#endif"
  5587. ].join("\n"),
  5588. skinning_vertex: [
  5589. "#ifdef USE_SKINNING",
  5590. "gl_Position = ( boneGlobalMatrices[ int( skinIndex.x ) ] * skinVertexA ) * skinWeight.x;",
  5591. "gl_Position += ( boneGlobalMatrices[ int( skinIndex.y ) ] * skinVertexB ) * skinWeight.y;",
  5592. "gl_Position = projectionMatrix * modelViewMatrix * gl_Position;",
  5593. "#endif"
  5594. ].join("\n"),
  5595. // MORPHING
  5596. morphtarget_pars_vertex: [
  5597. "#ifdef USE_MORPHTARGETS",
  5598. "#ifndef USE_MORPHNORMALS",
  5599. "uniform float morphTargetInfluences[ 8 ];",
  5600. "#else",
  5601. "uniform float morphTargetInfluences[ 4 ];",
  5602. "#endif",
  5603. "#endif"
  5604. ].join("\n"),
  5605. morphtarget_vertex: [
  5606. "#ifdef USE_MORPHTARGETS",
  5607. "vec3 morphed = vec3( 0.0 );",
  5608. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  5609. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  5610. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  5611. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  5612. "#ifndef USE_MORPHNORMALS",
  5613. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  5614. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  5615. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  5616. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  5617. "#endif",
  5618. "morphed += position;",
  5619. "gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  5620. "#endif"
  5621. ].join("\n"),
  5622. default_vertex : [
  5623. "#ifndef USE_MORPHTARGETS",
  5624. "#ifndef USE_SKINNING",
  5625. "gl_Position = projectionMatrix * mvPosition;",
  5626. "#endif",
  5627. "#endif"
  5628. ].join("\n"),
  5629. morphnormal_vertex: [
  5630. "#ifdef USE_MORPHNORMALS",
  5631. "vec3 morphedNormal = vec3( 0.0 );",
  5632. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  5633. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  5634. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  5635. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  5636. "morphedNormal += normal;",
  5637. "vec3 transformedNormal = normalMatrix * morphedNormal;",
  5638. "#else",
  5639. "vec3 transformedNormal = normalMatrix * normal;",
  5640. "#endif"
  5641. ].join("\n"),
  5642. // SHADOW MAP
  5643. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  5644. // http://spidergl.org/example.php?id=6
  5645. // http://fabiensanglard.net/shadowmapping
  5646. shadowmap_pars_fragment: [
  5647. "#ifdef USE_SHADOWMAP",
  5648. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  5649. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  5650. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  5651. "uniform float shadowBias[ MAX_SHADOWS ];",
  5652. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5653. "float unpackDepth( const in vec4 rgba_depth ) {",
  5654. "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 );",
  5655. "float depth = dot( rgba_depth, bit_shift );",
  5656. "return depth;",
  5657. "}",
  5658. "#endif"
  5659. ].join("\n"),
  5660. shadowmap_fragment: [
  5661. "#ifdef USE_SHADOWMAP",
  5662. "#ifdef SHADOWMAP_DEBUG",
  5663. "vec3 frustumColors[3];",
  5664. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  5665. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  5666. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  5667. "#endif",
  5668. "#ifdef SHADOWMAP_CASCADE",
  5669. "int inFrustumCount = 0;",
  5670. "#endif",
  5671. "float fDepth;",
  5672. "vec3 shadowColor = vec3( 1.0 );",
  5673. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5674. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  5675. // "if ( something && something )" breaks ATI OpenGL shader compiler
  5676. // "if ( all( something, something ) )" using this instead
  5677. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  5678. "bool inFrustum = all( inFrustumVec );",
  5679. // don't shadow pixels outside of light frustum
  5680. // use just first frustum (for cascades)
  5681. // don't shadow pixels behind far plane of light frustum
  5682. "#ifdef SHADOWMAP_CASCADE",
  5683. "inFrustumCount += int( inFrustum );",
  5684. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  5685. "#else",
  5686. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  5687. "#endif",
  5688. "bool frustumTest = all( frustumTestVec );",
  5689. "if ( frustumTest ) {",
  5690. "shadowCoord.z += shadowBias[ i ];",
  5691. "#ifdef SHADOWMAP_SOFT",
  5692. // Percentage-close filtering
  5693. // (9 pixel kernel)
  5694. // http://fabiensanglard.net/shadowmappingPCF/
  5695. "float shadow = 0.0;",
  5696. /*
  5697. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  5698. // must enroll loop manually
  5699. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  5700. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  5701. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  5702. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  5703. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  5704. "float fDepth = unpackDepth( rgbaDepth );",
  5705. "if ( fDepth < shadowCoord.z )",
  5706. "shadow += 1.0;",
  5707. "}",
  5708. "shadow /= 9.0;",
  5709. */
  5710. "const float shadowDelta = 1.0 / 9.0;",
  5711. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  5712. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  5713. "float dx0 = -1.25 * xPixelOffset;",
  5714. "float dy0 = -1.25 * yPixelOffset;",
  5715. "float dx1 = 1.25 * xPixelOffset;",
  5716. "float dy1 = 1.25 * yPixelOffset;",
  5717. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  5718. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5719. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  5720. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5721. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  5722. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5723. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  5724. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5725. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  5726. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5727. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  5728. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5729. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  5730. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5731. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  5732. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5733. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  5734. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5735. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  5736. "#else",
  5737. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  5738. "float fDepth = unpackDepth( rgbaDepth );",
  5739. "if ( fDepth < shadowCoord.z )",
  5740. // spot with multiple shadows is darker
  5741. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  5742. // spot with multiple shadows has the same color as single shadow spot
  5743. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  5744. "#endif",
  5745. "}",
  5746. "#ifdef SHADOWMAP_DEBUG",
  5747. "#ifdef SHADOWMAP_CASCADE",
  5748. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  5749. "#else",
  5750. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  5751. "#endif",
  5752. "#endif",
  5753. "}",
  5754. "#ifdef GAMMA_OUTPUT",
  5755. "shadowColor *= shadowColor;",
  5756. "#endif",
  5757. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  5758. "#endif"
  5759. ].join("\n"),
  5760. shadowmap_pars_vertex: [
  5761. "#ifdef USE_SHADOWMAP",
  5762. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5763. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  5764. "#endif"
  5765. ].join("\n"),
  5766. shadowmap_vertex: [
  5767. "#ifdef USE_SHADOWMAP",
  5768. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5769. "#ifdef USE_MORPHTARGETS",
  5770. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( morphed, 1.0 );",
  5771. "#else",
  5772. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( position, 1.0 );",
  5773. "#endif",
  5774. "}",
  5775. "#endif"
  5776. ].join("\n"),
  5777. // ALPHATEST
  5778. alphatest_fragment: [
  5779. "#ifdef ALPHATEST",
  5780. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  5781. "#endif"
  5782. ].join("\n"),
  5783. // LINEAR SPACE
  5784. linear_to_gamma_fragment: [
  5785. "#ifdef GAMMA_OUTPUT",
  5786. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  5787. "#endif"
  5788. ].join("\n"),
  5789. };
  5790. THREE.UniformsUtils = {
  5791. merge: function ( uniforms ) {
  5792. var u, p, tmp, merged = {};
  5793. for ( u = 0; u < uniforms.length; u++ ) {
  5794. tmp = this.clone( uniforms[ u ] );
  5795. for ( p in tmp ) {
  5796. merged[ p ] = tmp[ p ];
  5797. }
  5798. }
  5799. return merged;
  5800. },
  5801. clone: function ( uniforms_src ) {
  5802. var u, p, parameter, parameter_src, uniforms_dst = {};
  5803. for ( u in uniforms_src ) {
  5804. uniforms_dst[ u ] = {};
  5805. for ( p in uniforms_src[ u ] ) {
  5806. parameter_src = uniforms_src[ u ][ p ];
  5807. if ( parameter_src instanceof THREE.Color ||
  5808. parameter_src instanceof THREE.Vector2 ||
  5809. parameter_src instanceof THREE.Vector3 ||
  5810. parameter_src instanceof THREE.Vector4 ||
  5811. parameter_src instanceof THREE.Matrix4 ||
  5812. parameter_src instanceof THREE.Texture ) {
  5813. uniforms_dst[ u ][ p ] = parameter_src.clone();
  5814. } else if ( parameter_src instanceof Array ) {
  5815. uniforms_dst[ u ][ p ] = parameter_src.slice();
  5816. } else {
  5817. uniforms_dst[ u ][ p ] = parameter_src;
  5818. }
  5819. }
  5820. }
  5821. return uniforms_dst;
  5822. }
  5823. };
  5824. THREE.UniformsLib = {
  5825. common: {
  5826. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5827. "opacity" : { type: "f", value: 1.0 },
  5828. "map" : { type: "t", value: 0, texture: null },
  5829. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  5830. "lightMap" : { type: "t", value: 2, texture: null },
  5831. "envMap" : { type: "t", value: 1, texture: null },
  5832. "flipEnvMap" : { type: "f", value: -1 },
  5833. "useRefract" : { type: "i", value: 0 },
  5834. "reflectivity" : { type: "f", value: 1.0 },
  5835. "refractionRatio" : { type: "f", value: 0.98 },
  5836. "combine" : { type: "i", value: 0 },
  5837. "morphTargetInfluences" : { type: "f", value: 0 }
  5838. },
  5839. fog : {
  5840. "fogDensity" : { type: "f", value: 0.00025 },
  5841. "fogNear" : { type: "f", value: 1 },
  5842. "fogFar" : { type: "f", value: 2000 },
  5843. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5844. },
  5845. lights: {
  5846. "ambientLightColor" : { type: "fv", value: [] },
  5847. "directionalLightDirection" : { type: "fv", value: [] },
  5848. "directionalLightColor" : { type: "fv", value: [] },
  5849. "pointLightColor" : { type: "fv", value: [] },
  5850. "pointLightPosition" : { type: "fv", value: [] },
  5851. "pointLightDistance" : { type: "fv1", value: [] }
  5852. },
  5853. particle: {
  5854. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5855. "opacity" : { type: "f", value: 1.0 },
  5856. "size" : { type: "f", value: 1.0 },
  5857. "scale" : { type: "f", value: 1.0 },
  5858. "map" : { type: "t", value: 0, texture: null },
  5859. "fogDensity" : { type: "f", value: 0.00025 },
  5860. "fogNear" : { type: "f", value: 1 },
  5861. "fogFar" : { type: "f", value: 2000 },
  5862. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5863. },
  5864. shadowmap: {
  5865. "shadowMap": { type: "tv", value: 6, texture: [] },
  5866. "shadowMapSize": { type: "v2v", value: [] },
  5867. "shadowBias" : { type: "fv1", value: [] },
  5868. "shadowDarkness": { type: "fv1", value: [] },
  5869. "shadowMatrix" : { type: "m4v", value: [] },
  5870. }
  5871. };
  5872. THREE.ShaderLib = {
  5873. 'depth': {
  5874. uniforms: {
  5875. "mNear": { type: "f", value: 1.0 },
  5876. "mFar" : { type: "f", value: 2000.0 },
  5877. "opacity" : { type: "f", value: 1.0 }
  5878. },
  5879. vertexShader: [
  5880. "void main() {",
  5881. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  5882. "}"
  5883. ].join("\n"),
  5884. fragmentShader: [
  5885. "uniform float mNear;",
  5886. "uniform float mFar;",
  5887. "uniform float opacity;",
  5888. "void main() {",
  5889. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5890. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  5891. "gl_FragColor = vec4( vec3( color ), opacity );",
  5892. "}"
  5893. ].join("\n")
  5894. },
  5895. 'normal': {
  5896. uniforms: {
  5897. "opacity" : { type: "f", value: 1.0 }
  5898. },
  5899. vertexShader: [
  5900. "varying vec3 vNormal;",
  5901. "void main() {",
  5902. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5903. "vNormal = normalMatrix * normal;",
  5904. "gl_Position = projectionMatrix * mvPosition;",
  5905. "}"
  5906. ].join("\n"),
  5907. fragmentShader: [
  5908. "uniform float opacity;",
  5909. "varying vec3 vNormal;",
  5910. "void main() {",
  5911. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  5912. "}"
  5913. ].join("\n")
  5914. },
  5915. 'basic': {
  5916. uniforms: THREE.UniformsUtils.merge( [
  5917. THREE.UniformsLib[ "common" ],
  5918. THREE.UniformsLib[ "fog" ],
  5919. THREE.UniformsLib[ "shadowmap" ]
  5920. ] ),
  5921. vertexShader: [
  5922. THREE.ShaderChunk[ "map_pars_vertex" ],
  5923. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5924. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5925. THREE.ShaderChunk[ "color_pars_vertex" ],
  5926. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5927. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5928. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5929. "void main() {",
  5930. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5931. THREE.ShaderChunk[ "map_vertex" ],
  5932. THREE.ShaderChunk[ "lightmap_vertex" ],
  5933. THREE.ShaderChunk[ "envmap_vertex" ],
  5934. THREE.ShaderChunk[ "color_vertex" ],
  5935. THREE.ShaderChunk[ "skinning_vertex" ],
  5936. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5937. THREE.ShaderChunk[ "default_vertex" ],
  5938. THREE.ShaderChunk[ "shadowmap_vertex" ],
  5939. "}"
  5940. ].join("\n"),
  5941. fragmentShader: [
  5942. "uniform vec3 diffuse;",
  5943. "uniform float opacity;",
  5944. THREE.ShaderChunk[ "color_pars_fragment" ],
  5945. THREE.ShaderChunk[ "map_pars_fragment" ],
  5946. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  5947. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  5948. THREE.ShaderChunk[ "fog_pars_fragment" ],
  5949. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  5950. "void main() {",
  5951. "gl_FragColor = vec4( diffuse, opacity );",
  5952. THREE.ShaderChunk[ "map_fragment" ],
  5953. THREE.ShaderChunk[ "alphatest_fragment" ],
  5954. THREE.ShaderChunk[ "lightmap_fragment" ],
  5955. THREE.ShaderChunk[ "color_fragment" ],
  5956. THREE.ShaderChunk[ "envmap_fragment" ],
  5957. THREE.ShaderChunk[ "shadowmap_fragment" ],
  5958. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  5959. THREE.ShaderChunk[ "fog_fragment" ],
  5960. "}"
  5961. ].join("\n")
  5962. },
  5963. 'lambert': {
  5964. uniforms: THREE.UniformsUtils.merge( [
  5965. THREE.UniformsLib[ "common" ],
  5966. THREE.UniformsLib[ "fog" ],
  5967. THREE.UniformsLib[ "lights" ],
  5968. THREE.UniformsLib[ "shadowmap" ],
  5969. {
  5970. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  5971. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  5972. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  5973. }
  5974. ] ),
  5975. vertexShader: [
  5976. "varying vec3 vLightFront;",
  5977. "#ifdef DOUBLE_SIDED",
  5978. "varying vec3 vLightBack;",
  5979. "#endif",
  5980. THREE.ShaderChunk[ "map_pars_vertex" ],
  5981. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5982. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5983. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  5984. THREE.ShaderChunk[ "color_pars_vertex" ],
  5985. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5986. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5987. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5988. "void main() {",
  5989. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5990. THREE.ShaderChunk[ "map_vertex" ],
  5991. THREE.ShaderChunk[ "lightmap_vertex" ],
  5992. THREE.ShaderChunk[ "envmap_vertex" ],
  5993. THREE.ShaderChunk[ "color_vertex" ],
  5994. THREE.ShaderChunk[ "morphnormal_vertex" ],
  5995. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  5996. THREE.ShaderChunk[ "skinning_vertex" ],
  5997. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5998. THREE.ShaderChunk[ "default_vertex" ],
  5999. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6000. "}"
  6001. ].join("\n"),
  6002. fragmentShader: [
  6003. "uniform float opacity;",
  6004. "varying vec3 vLightFront;",
  6005. "#ifdef DOUBLE_SIDED",
  6006. "varying vec3 vLightBack;",
  6007. "#endif",
  6008. THREE.ShaderChunk[ "color_pars_fragment" ],
  6009. THREE.ShaderChunk[ "map_pars_fragment" ],
  6010. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6011. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6012. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6013. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6014. "void main() {",
  6015. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6016. THREE.ShaderChunk[ "map_fragment" ],
  6017. THREE.ShaderChunk[ "alphatest_fragment" ],
  6018. "#ifdef DOUBLE_SIDED",
  6019. //"float isFront = float( gl_FrontFacing );",
  6020. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  6021. "if ( gl_FrontFacing )",
  6022. "gl_FragColor.xyz *= vLightFront;",
  6023. "else",
  6024. "gl_FragColor.xyz *= vLightBack;",
  6025. "#else",
  6026. "gl_FragColor.xyz *= vLightFront;",
  6027. "#endif",
  6028. THREE.ShaderChunk[ "lightmap_fragment" ],
  6029. THREE.ShaderChunk[ "color_fragment" ],
  6030. THREE.ShaderChunk[ "envmap_fragment" ],
  6031. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6032. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6033. THREE.ShaderChunk[ "fog_fragment" ],
  6034. "}"
  6035. ].join("\n")
  6036. },
  6037. 'phong': {
  6038. uniforms: THREE.UniformsUtils.merge( [
  6039. THREE.UniformsLib[ "common" ],
  6040. THREE.UniformsLib[ "fog" ],
  6041. THREE.UniformsLib[ "lights" ],
  6042. THREE.UniformsLib[ "shadowmap" ],
  6043. {
  6044. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  6045. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  6046. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  6047. "shininess": { type: "f", value: 30 },
  6048. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  6049. }
  6050. ] ),
  6051. vertexShader: [
  6052. "varying vec3 vViewPosition;",
  6053. "varying vec3 vNormal;",
  6054. THREE.ShaderChunk[ "map_pars_vertex" ],
  6055. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  6056. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  6057. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  6058. THREE.ShaderChunk[ "color_pars_vertex" ],
  6059. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  6060. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6061. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6062. "void main() {",
  6063. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6064. THREE.ShaderChunk[ "map_vertex" ],
  6065. THREE.ShaderChunk[ "lightmap_vertex" ],
  6066. THREE.ShaderChunk[ "envmap_vertex" ],
  6067. THREE.ShaderChunk[ "color_vertex" ],
  6068. "#ifndef USE_ENVMAP",
  6069. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  6070. "#endif",
  6071. "vViewPosition = -mvPosition.xyz;",
  6072. THREE.ShaderChunk[ "morphnormal_vertex" ],
  6073. "vNormal = transformedNormal;",
  6074. THREE.ShaderChunk[ "lights_phong_vertex" ],
  6075. THREE.ShaderChunk[ "skinning_vertex" ],
  6076. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6077. THREE.ShaderChunk[ "default_vertex" ],
  6078. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6079. "}"
  6080. ].join("\n"),
  6081. fragmentShader: [
  6082. "uniform vec3 diffuse;",
  6083. "uniform float opacity;",
  6084. "uniform vec3 ambient;",
  6085. "uniform vec3 emissive;",
  6086. "uniform vec3 specular;",
  6087. "uniform float shininess;",
  6088. THREE.ShaderChunk[ "color_pars_fragment" ],
  6089. THREE.ShaderChunk[ "map_pars_fragment" ],
  6090. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6091. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6092. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6093. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  6094. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6095. "void main() {",
  6096. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6097. THREE.ShaderChunk[ "map_fragment" ],
  6098. THREE.ShaderChunk[ "alphatest_fragment" ],
  6099. THREE.ShaderChunk[ "lights_phong_fragment" ],
  6100. THREE.ShaderChunk[ "lightmap_fragment" ],
  6101. THREE.ShaderChunk[ "color_fragment" ],
  6102. THREE.ShaderChunk[ "envmap_fragment" ],
  6103. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6104. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6105. THREE.ShaderChunk[ "fog_fragment" ],
  6106. "}"
  6107. ].join("\n")
  6108. },
  6109. 'particle_basic': {
  6110. uniforms: THREE.UniformsUtils.merge( [
  6111. THREE.UniformsLib[ "particle" ],
  6112. THREE.UniformsLib[ "shadowmap" ]
  6113. ] ),
  6114. vertexShader: [
  6115. "uniform float size;",
  6116. "uniform float scale;",
  6117. THREE.ShaderChunk[ "color_pars_vertex" ],
  6118. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6119. "void main() {",
  6120. THREE.ShaderChunk[ "color_vertex" ],
  6121. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6122. "#ifdef USE_SIZEATTENUATION",
  6123. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  6124. "#else",
  6125. "gl_PointSize = size;",
  6126. "#endif",
  6127. "gl_Position = projectionMatrix * mvPosition;",
  6128. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6129. "}"
  6130. ].join("\n"),
  6131. fragmentShader: [
  6132. "uniform vec3 psColor;",
  6133. "uniform float opacity;",
  6134. THREE.ShaderChunk[ "color_pars_fragment" ],
  6135. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  6136. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6137. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6138. "void main() {",
  6139. "gl_FragColor = vec4( psColor, opacity );",
  6140. THREE.ShaderChunk[ "map_particle_fragment" ],
  6141. THREE.ShaderChunk[ "alphatest_fragment" ],
  6142. THREE.ShaderChunk[ "color_fragment" ],
  6143. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6144. THREE.ShaderChunk[ "fog_fragment" ],
  6145. "}"
  6146. ].join("\n")
  6147. },
  6148. // Depth encoding into RGBA texture
  6149. // based on SpiderGL shadow map example
  6150. // http://spidergl.org/example.php?id=6
  6151. // originally from
  6152. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  6153. // see also here:
  6154. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  6155. 'depthRGBA': {
  6156. uniforms: {},
  6157. vertexShader: [
  6158. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6159. "void main() {",
  6160. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6161. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6162. THREE.ShaderChunk[ "default_vertex" ],
  6163. "}"
  6164. ].join("\n"),
  6165. fragmentShader: [
  6166. "vec4 pack_depth( const in float depth ) {",
  6167. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  6168. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  6169. "vec4 res = fract( depth * bit_shift );",
  6170. "res -= res.xxyz * bit_mask;",
  6171. "return res;",
  6172. "}",
  6173. "void main() {",
  6174. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  6175. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  6176. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  6177. //"gl_FragData[ 0 ] = pack_depth( z );",
  6178. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  6179. "}"
  6180. ].join("\n")
  6181. }
  6182. };/**
  6183. * @author supereggbert / http://www.paulbrunt.co.uk/
  6184. * @author mrdoob / http://mrdoob.com/
  6185. * @author alteredq / http://alteredqualia.com/
  6186. * @author szimek / https://github.com/szimek/
  6187. */
  6188. THREE.WebGLRenderer = function ( parameters ) {
  6189. // constructor parameters
  6190. parameters = parameters || {};
  6191. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6192. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  6193. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  6194. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  6195. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  6196. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  6197. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  6198. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  6199. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  6200. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  6201. // public properties
  6202. this.domElement = _canvas;
  6203. this.context = null;
  6204. // clearing
  6205. this.autoClear = true;
  6206. this.autoClearColor = true;
  6207. this.autoClearDepth = true;
  6208. this.autoClearStencil = true;
  6209. // scene graph
  6210. this.sortObjects = true;
  6211. this.autoUpdateObjects = true;
  6212. this.autoUpdateScene = true;
  6213. // physically based shading
  6214. this.gammaInput = false;
  6215. this.gammaOutput = false;
  6216. this.physicallyBasedShading = false;
  6217. // shadow map
  6218. this.shadowMapEnabled = false;
  6219. this.shadowMapAutoUpdate = true;
  6220. this.shadowMapSoft = true;
  6221. this.shadowMapCullFrontFaces = true;
  6222. this.shadowMapDebug = false;
  6223. this.shadowMapCascade = false;
  6224. // morphs
  6225. this.maxMorphTargets = 8;
  6226. this.maxMorphNormals = 4;
  6227. // flags
  6228. this.autoScaleCubemaps = true;
  6229. // custom render plugins
  6230. this.renderPluginsPre = [];
  6231. this.renderPluginsPost = [];
  6232. // info
  6233. this.info = {
  6234. memory: {
  6235. programs: 0,
  6236. geometries: 0,
  6237. textures: 0
  6238. },
  6239. render: {
  6240. calls: 0,
  6241. vertices: 0,
  6242. faces: 0,
  6243. points: 0
  6244. }
  6245. };
  6246. // internal properties
  6247. var _this = this,
  6248. _gl,
  6249. _programs = [],
  6250. // internal state cache
  6251. _currentProgram = null,
  6252. _currentFramebuffer = null,
  6253. _currentMaterialId = -1,
  6254. _currentGeometryGroupHash = null,
  6255. _currentCamera = null,
  6256. _geometryGroupCounter = 0,
  6257. // GL state cache
  6258. _oldDoubleSided = null,
  6259. _oldFlipSided = null,
  6260. _oldBlending = null,
  6261. _oldBlendEquation = null,
  6262. _oldBlendSrc = null,
  6263. _oldBlendDst = null,
  6264. _oldDepthTest = null,
  6265. _oldDepthWrite = null,
  6266. _oldPolygonOffset = null,
  6267. _oldPolygonOffsetFactor = null,
  6268. _oldPolygonOffsetUnits = null,
  6269. _oldLineWidth = null,
  6270. _viewportX = 0,
  6271. _viewportY = 0,
  6272. _viewportWidth = 0,
  6273. _viewportHeight = 0,
  6274. _currentWidth = 0,
  6275. _currentHeight = 0,
  6276. // frustum
  6277. _frustum = new THREE.Frustum(),
  6278. // camera matrices cache
  6279. _projScreenMatrix = new THREE.Matrix4(),
  6280. _projScreenMatrixPS = new THREE.Matrix4(),
  6281. _vector3 = new THREE.Vector4(),
  6282. // light arrays cache
  6283. _direction = new THREE.Vector3(),
  6284. _lights = {
  6285. ambient: [ 0, 0, 0 ],
  6286. directional: { length: 0, colors: new Array(), positions: new Array() },
  6287. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }
  6288. };
  6289. // initialize
  6290. _gl = initGL();
  6291. setDefaultGLState();
  6292. this.context = _gl;
  6293. // GPU capabilities
  6294. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  6295. _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ),
  6296. _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  6297. // API
  6298. this.getContext = function () {
  6299. return _gl;
  6300. };
  6301. this.supportsVertexTextures = function () {
  6302. return _maxVertexTextures > 0;
  6303. };
  6304. this.setSize = function ( width, height ) {
  6305. _canvas.width = width;
  6306. _canvas.height = height;
  6307. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  6308. };
  6309. this.setViewport = function ( x, y, width, height ) {
  6310. _viewportX = x;
  6311. _viewportY = y;
  6312. _viewportWidth = width;
  6313. _viewportHeight = height;
  6314. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  6315. };
  6316. this.setScissor = function ( x, y, width, height ) {
  6317. _gl.scissor( x, y, width, height );
  6318. };
  6319. this.enableScissorTest = function ( enable ) {
  6320. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  6321. };
  6322. // Clearing
  6323. this.setClearColorHex = function ( hex, alpha ) {
  6324. _clearColor.setHex( hex );
  6325. _clearAlpha = alpha;
  6326. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6327. };
  6328. this.setClearColor = function ( color, alpha ) {
  6329. _clearColor.copy( color );
  6330. _clearAlpha = alpha;
  6331. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6332. };
  6333. this.getClearColor = function () {
  6334. return _clearColor;
  6335. };
  6336. this.getClearAlpha = function () {
  6337. return _clearAlpha;
  6338. };
  6339. this.clear = function ( color, depth, stencil ) {
  6340. var bits = 0;
  6341. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  6342. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  6343. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  6344. _gl.clear( bits );
  6345. };
  6346. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  6347. this.setRenderTarget( renderTarget );
  6348. this.clear( color, depth, stencil );
  6349. };
  6350. // Plugins
  6351. this.addPostPlugin = function ( plugin ) {
  6352. plugin.init( this );
  6353. this.renderPluginsPost.push( plugin );
  6354. };
  6355. this.addPrePlugin = function ( plugin ) {
  6356. plugin.init( this );
  6357. this.renderPluginsPre.push( plugin );
  6358. };
  6359. // Deallocation
  6360. this.deallocateObject = function ( object ) {
  6361. if ( ! object.__webglInit ) return;
  6362. object.__webglInit = false;
  6363. delete object._modelViewMatrix;
  6364. delete object._normalMatrix;
  6365. delete object._normalMatrixArray;
  6366. delete object._modelViewMatrixArray;
  6367. delete object._objectMatrixArray;
  6368. if ( object instanceof THREE.Mesh ) {
  6369. for ( var g in object.geometry.geometryGroups ) {
  6370. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  6371. }
  6372. } else if ( object instanceof THREE.Ribbon ) {
  6373. deleteRibbonBuffers( object.geometry );
  6374. } else if ( object instanceof THREE.Line ) {
  6375. deleteLineBuffers( object.geometry );
  6376. } else if ( object instanceof THREE.ParticleSystem ) {
  6377. deleteParticleBuffers( object.geometry );
  6378. }
  6379. };
  6380. this.deallocateTexture = function ( texture ) {
  6381. if ( ! texture.__webglInit ) return;
  6382. texture.__webglInit = false;
  6383. _gl.deleteTexture( texture.__webglTexture );
  6384. _this.info.memory.textures --;
  6385. };
  6386. this.deallocateRenderTarget = function ( renderTarget ) {
  6387. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  6388. _gl.deleteTexture( renderTarget.__webglTexture );
  6389. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  6390. for ( var i = 0; i < 6; i ++ ) {
  6391. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  6392. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  6393. }
  6394. } else {
  6395. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  6396. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  6397. }
  6398. };
  6399. // Rendering
  6400. this.updateShadowMap = function ( scene, camera ) {
  6401. _currentProgram = null;
  6402. _oldBlending = -1;
  6403. _oldDepthTest = -1;
  6404. _oldDepthWrite = -1;
  6405. _currentGeometryGroupHash = -1;
  6406. _currentMaterialId = -1;
  6407. this.shadowMapPlugin.update( scene, camera );
  6408. };
  6409. // Internal functions
  6410. // Buffer allocation
  6411. function createParticleBuffers ( geometry ) {
  6412. geometry.__webglVertexBuffer = _gl.createBuffer();
  6413. geometry.__webglColorBuffer = _gl.createBuffer();
  6414. _this.info.geometries ++;
  6415. };
  6416. function createLineBuffers ( geometry ) {
  6417. geometry.__webglVertexBuffer = _gl.createBuffer();
  6418. geometry.__webglColorBuffer = _gl.createBuffer();
  6419. _this.info.memory.geometries ++;
  6420. };
  6421. function createRibbonBuffers ( geometry ) {
  6422. geometry.__webglVertexBuffer = _gl.createBuffer();
  6423. geometry.__webglColorBuffer = _gl.createBuffer();
  6424. _this.info.memory.geometries ++;
  6425. };
  6426. function createMeshBuffers ( geometryGroup ) {
  6427. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  6428. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  6429. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  6430. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  6431. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  6432. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  6433. geometryGroup.__webglSkinVertexABuffer = _gl.createBuffer();
  6434. geometryGroup.__webglSkinVertexBBuffer = _gl.createBuffer();
  6435. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  6436. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  6437. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  6438. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  6439. var m, ml;
  6440. if ( geometryGroup.numMorphTargets ) {
  6441. geometryGroup.__webglMorphTargetsBuffers = [];
  6442. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6443. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  6444. }
  6445. }
  6446. if ( geometryGroup.numMorphNormals ) {
  6447. geometryGroup.__webglMorphNormalsBuffers = [];
  6448. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6449. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  6450. }
  6451. }
  6452. _this.info.memory.geometries ++;
  6453. };
  6454. // Buffer deallocation
  6455. function deleteParticleBuffers ( geometry ) {
  6456. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6457. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6458. _this.info.memory.geometries --;
  6459. };
  6460. function deleteLineBuffers ( geometry ) {
  6461. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6462. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6463. _this.info.memory.geometries --;
  6464. };
  6465. function deleteRibbonBuffers ( geometry ) {
  6466. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6467. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6468. _this.info.memory.geometries --;
  6469. };
  6470. function deleteMeshBuffers ( geometryGroup ) {
  6471. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  6472. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  6473. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  6474. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  6475. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  6476. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  6477. _gl.deleteBuffer( geometryGroup.__webglSkinVertexABuffer );
  6478. _gl.deleteBuffer( geometryGroup.__webglSkinVertexBBuffer );
  6479. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  6480. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  6481. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  6482. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  6483. var m, ml;
  6484. if ( geometryGroup.numMorphTargets ) {
  6485. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6486. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  6487. }
  6488. }
  6489. if ( geometryGroup.numMorphNormals ) {
  6490. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6491. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  6492. }
  6493. }
  6494. if ( geometryGroup.__webglCustomAttributesList ) {
  6495. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  6496. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  6497. }
  6498. }
  6499. _this.info.memory.geometries --;
  6500. };
  6501. // Buffer initialization
  6502. function initCustomAttributes ( geometry, object ) {
  6503. var nvertices = geometry.vertices.length;
  6504. var material = object.material;
  6505. if ( material.attributes ) {
  6506. if ( geometry.__webglCustomAttributesList === undefined ) {
  6507. geometry.__webglCustomAttributesList = [];
  6508. }
  6509. for ( var a in material.attributes ) {
  6510. var attribute = material.attributes[ a ];
  6511. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6512. attribute.__webglInitialized = true;
  6513. var size = 1; // "f" and "i"
  6514. if ( attribute.type === "v2" ) size = 2;
  6515. else if ( attribute.type === "v3" ) size = 3;
  6516. else if ( attribute.type === "v4" ) size = 4;
  6517. else if ( attribute.type === "c" ) size = 3;
  6518. attribute.size = size;
  6519. attribute.array = new Float32Array( nvertices * size );
  6520. attribute.buffer = _gl.createBuffer();
  6521. attribute.buffer.belongsToAttribute = a;
  6522. attribute.needsUpdate = true;
  6523. }
  6524. geometry.__webglCustomAttributesList.push( attribute );
  6525. }
  6526. }
  6527. };
  6528. function initParticleBuffers ( geometry, object ) {
  6529. var nvertices = geometry.vertices.length;
  6530. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6531. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6532. geometry.__sortArray = [];
  6533. geometry.__webglParticleCount = nvertices;
  6534. initCustomAttributes ( geometry, object );
  6535. };
  6536. function initLineBuffers ( geometry, object ) {
  6537. var nvertices = geometry.vertices.length;
  6538. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6539. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6540. geometry.__webglLineCount = nvertices;
  6541. initCustomAttributes ( geometry, object );
  6542. };
  6543. function initRibbonBuffers ( geometry ) {
  6544. var nvertices = geometry.vertices.length;
  6545. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6546. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6547. geometry.__webglVertexCount = nvertices;
  6548. };
  6549. function initMeshBuffers ( geometryGroup, object ) {
  6550. var geometry = object.geometry,
  6551. faces3 = geometryGroup.faces3,
  6552. faces4 = geometryGroup.faces4,
  6553. nvertices = faces3.length * 3 + faces4.length * 4,
  6554. ntris = faces3.length * 1 + faces4.length * 2,
  6555. nlines = faces3.length * 3 + faces4.length * 4,
  6556. material = getBufferMaterial( object, geometryGroup ),
  6557. uvType = bufferGuessUVType( material ),
  6558. normalType = bufferGuessNormalType( material ),
  6559. vertexColorType = bufferGuessVertexColorType( material );
  6560. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  6561. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  6562. if ( normalType ) {
  6563. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  6564. }
  6565. if ( geometry.hasTangents ) {
  6566. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  6567. }
  6568. if ( vertexColorType ) {
  6569. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  6570. }
  6571. if ( uvType ) {
  6572. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  6573. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  6574. }
  6575. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  6576. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  6577. }
  6578. }
  6579. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  6580. geometryGroup.__skinVertexAArray = new Float32Array( nvertices * 4 );
  6581. geometryGroup.__skinVertexBArray = new Float32Array( nvertices * 4 );
  6582. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  6583. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  6584. }
  6585. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  6586. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  6587. var m, ml;
  6588. if ( geometryGroup.numMorphTargets ) {
  6589. geometryGroup.__morphTargetsArrays = [];
  6590. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6591. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  6592. }
  6593. }
  6594. if ( geometryGroup.numMorphNormals ) {
  6595. geometryGroup.__morphNormalsArrays = [];
  6596. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6597. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  6598. }
  6599. }
  6600. geometryGroup.__webglFaceCount = ntris * 3;
  6601. geometryGroup.__webglLineCount = nlines * 2;
  6602. // custom attributes
  6603. if ( material.attributes ) {
  6604. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  6605. geometryGroup.__webglCustomAttributesList = [];
  6606. }
  6607. for ( var a in material.attributes ) {
  6608. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  6609. // attribute buffers which are correctly indexed in the setMeshBuffers function
  6610. var originalAttribute = material.attributes[ a ];
  6611. var attribute = {};
  6612. for ( var property in originalAttribute ) {
  6613. attribute[ property ] = originalAttribute[ property ];
  6614. }
  6615. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6616. attribute.__webglInitialized = true;
  6617. var size = 1; // "f" and "i"
  6618. if( attribute.type === "v2" ) size = 2;
  6619. else if( attribute.type === "v3" ) size = 3;
  6620. else if( attribute.type === "v4" ) size = 4;
  6621. else if( attribute.type === "c" ) size = 3;
  6622. attribute.size = size;
  6623. attribute.array = new Float32Array( nvertices * size );
  6624. attribute.buffer = _gl.createBuffer();
  6625. attribute.buffer.belongsToAttribute = a;
  6626. originalAttribute.needsUpdate = true;
  6627. attribute.__original = originalAttribute;
  6628. }
  6629. geometryGroup.__webglCustomAttributesList.push( attribute );
  6630. }
  6631. }
  6632. geometryGroup.__inittedArrays = true;
  6633. };
  6634. function getBufferMaterial( object, geometryGroup ) {
  6635. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  6636. return object.material;
  6637. } else if ( geometryGroup.materialIndex >= 0 ) {
  6638. return object.geometry.materials[ geometryGroup.materialIndex ];
  6639. }
  6640. };
  6641. function materialNeedsSmoothNormals ( material ) {
  6642. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  6643. };
  6644. function bufferGuessNormalType ( material ) {
  6645. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  6646. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  6647. return false;
  6648. }
  6649. if ( materialNeedsSmoothNormals( material ) ) {
  6650. return THREE.SmoothShading;
  6651. } else {
  6652. return THREE.FlatShading;
  6653. }
  6654. };
  6655. function bufferGuessVertexColorType ( material ) {
  6656. if ( material.vertexColors ) {
  6657. return material.vertexColors;
  6658. }
  6659. return false;
  6660. };
  6661. function bufferGuessUVType ( material ) {
  6662. // material must use some texture to require uvs
  6663. if ( material.map || material.lightMap || material instanceof THREE.ShaderMaterial ) {
  6664. return true;
  6665. }
  6666. return false;
  6667. };
  6668. // Buffer setting
  6669. function setParticleBuffers ( geometry, hint, object ) {
  6670. var v, c, vertex, offset, index, color,
  6671. vertices = geometry.vertices,
  6672. vl = vertices.length,
  6673. colors = geometry.colors,
  6674. cl = colors.length,
  6675. vertexArray = geometry.__vertexArray,
  6676. colorArray = geometry.__colorArray,
  6677. sortArray = geometry.__sortArray,
  6678. dirtyVertices = geometry.__dirtyVertices,
  6679. dirtyElements = geometry.__dirtyElements,
  6680. dirtyColors = geometry.__dirtyColors,
  6681. customAttributes = geometry.__webglCustomAttributesList,
  6682. i, il,
  6683. a, ca, cal, value,
  6684. customAttribute;
  6685. if ( object.sortParticles ) {
  6686. _projScreenMatrixPS.copy( _projScreenMatrix );
  6687. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  6688. for ( v = 0; v < vl; v ++ ) {
  6689. vertex = vertices[ v ].position;
  6690. _vector3.copy( vertex );
  6691. _projScreenMatrixPS.multiplyVector3( _vector3 );
  6692. sortArray[ v ] = [ _vector3.z, v ];
  6693. }
  6694. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  6695. for ( v = 0; v < vl; v ++ ) {
  6696. vertex = vertices[ sortArray[v][1] ].position;
  6697. offset = v * 3;
  6698. vertexArray[ offset ] = vertex.x;
  6699. vertexArray[ offset + 1 ] = vertex.y;
  6700. vertexArray[ offset + 2 ] = vertex.z;
  6701. }
  6702. for ( c = 0; c < cl; c ++ ) {
  6703. offset = c * 3;
  6704. color = colors[ sortArray[c][1] ];
  6705. colorArray[ offset ] = color.r;
  6706. colorArray[ offset + 1 ] = color.g;
  6707. colorArray[ offset + 2 ] = color.b;
  6708. }
  6709. if ( customAttributes ) {
  6710. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6711. customAttribute = customAttributes[ i ];
  6712. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  6713. offset = 0;
  6714. cal = customAttribute.value.length;
  6715. if ( customAttribute.size === 1 ) {
  6716. for ( ca = 0; ca < cal; ca ++ ) {
  6717. index = sortArray[ ca ][ 1 ];
  6718. customAttribute.array[ ca ] = customAttribute.value[ index ];
  6719. }
  6720. } else if ( customAttribute.size === 2 ) {
  6721. for ( ca = 0; ca < cal; ca ++ ) {
  6722. index = sortArray[ ca ][ 1 ];
  6723. value = customAttribute.value[ index ];
  6724. customAttribute.array[ offset ] = value.x;
  6725. customAttribute.array[ offset + 1 ] = value.y;
  6726. offset += 2;
  6727. }
  6728. } else if ( customAttribute.size === 3 ) {
  6729. if ( customAttribute.type === "c" ) {
  6730. for ( ca = 0; ca < cal; ca ++ ) {
  6731. index = sortArray[ ca ][ 1 ];
  6732. value = customAttribute.value[ index ];
  6733. customAttribute.array[ offset ] = value.r;
  6734. customAttribute.array[ offset + 1 ] = value.g;
  6735. customAttribute.array[ offset + 2 ] = value.b;
  6736. offset += 3;
  6737. }
  6738. } else {
  6739. for ( ca = 0; ca < cal; ca ++ ) {
  6740. index = sortArray[ ca ][ 1 ];
  6741. value = customAttribute.value[ index ];
  6742. customAttribute.array[ offset ] = value.x;
  6743. customAttribute.array[ offset + 1 ] = value.y;
  6744. customAttribute.array[ offset + 2 ] = value.z;
  6745. offset += 3;
  6746. }
  6747. }
  6748. } else if ( customAttribute.size === 4 ) {
  6749. for ( ca = 0; ca < cal; ca ++ ) {
  6750. index = sortArray[ ca ][ 1 ];
  6751. value = customAttribute.value[ index ];
  6752. customAttribute.array[ offset ] = value.x;
  6753. customAttribute.array[ offset + 1 ] = value.y;
  6754. customAttribute.array[ offset + 2 ] = value.z;
  6755. customAttribute.array[ offset + 3 ] = value.w;
  6756. offset += 4;
  6757. }
  6758. }
  6759. }
  6760. }
  6761. } else {
  6762. if ( dirtyVertices ) {
  6763. for ( v = 0; v < vl; v ++ ) {
  6764. vertex = vertices[ v ].position;
  6765. offset = v * 3;
  6766. vertexArray[ offset ] = vertex.x;
  6767. vertexArray[ offset + 1 ] = vertex.y;
  6768. vertexArray[ offset + 2 ] = vertex.z;
  6769. }
  6770. }
  6771. if ( dirtyColors ) {
  6772. for ( c = 0; c < cl; c ++ ) {
  6773. color = colors[ c ];
  6774. offset = c * 3;
  6775. colorArray[ offset ] = color.r;
  6776. colorArray[ offset + 1 ] = color.g;
  6777. colorArray[ offset + 2 ] = color.b;
  6778. }
  6779. }
  6780. if ( customAttributes ) {
  6781. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6782. customAttribute = customAttributes[ i ];
  6783. if ( customAttribute.needsUpdate &&
  6784. ( customAttribute.boundTo === undefined ||
  6785. customAttribute.boundTo === "vertices") ) {
  6786. cal = customAttribute.value.length;
  6787. offset = 0;
  6788. if ( customAttribute.size === 1 ) {
  6789. for ( ca = 0; ca < cal; ca ++ ) {
  6790. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6791. }
  6792. } else if ( customAttribute.size === 2 ) {
  6793. for ( ca = 0; ca < cal; ca ++ ) {
  6794. value = customAttribute.value[ ca ];
  6795. customAttribute.array[ offset ] = value.x;
  6796. customAttribute.array[ offset + 1 ] = value.y;
  6797. offset += 2;
  6798. }
  6799. } else if ( customAttribute.size === 3 ) {
  6800. if ( customAttribute.type === "c" ) {
  6801. for ( ca = 0; ca < cal; ca ++ ) {
  6802. value = customAttribute.value[ ca ];
  6803. customAttribute.array[ offset ] = value.r;
  6804. customAttribute.array[ offset + 1 ] = value.g;
  6805. customAttribute.array[ offset + 2 ] = value.b;
  6806. offset += 3;
  6807. }
  6808. } else {
  6809. for ( ca = 0; ca < cal; ca ++ ) {
  6810. value = customAttribute.value[ ca ];
  6811. customAttribute.array[ offset ] = value.x;
  6812. customAttribute.array[ offset + 1 ] = value.y;
  6813. customAttribute.array[ offset + 2 ] = value.z;
  6814. offset += 3;
  6815. }
  6816. }
  6817. } else if ( customAttribute.size === 4 ) {
  6818. for ( ca = 0; ca < cal; ca ++ ) {
  6819. value = customAttribute.value[ ca ];
  6820. customAttribute.array[ offset ] = value.x;
  6821. customAttribute.array[ offset + 1 ] = value.y;
  6822. customAttribute.array[ offset + 2 ] = value.z;
  6823. customAttribute.array[ offset + 3 ] = value.w;
  6824. offset += 4;
  6825. }
  6826. }
  6827. }
  6828. }
  6829. }
  6830. }
  6831. if ( dirtyVertices || object.sortParticles ) {
  6832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6833. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6834. }
  6835. if ( dirtyColors || object.sortParticles ) {
  6836. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6837. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6838. }
  6839. if ( customAttributes ) {
  6840. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6841. customAttribute = customAttributes[ i ];
  6842. if ( customAttribute.needsUpdate || object.sortParticles ) {
  6843. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6844. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6845. }
  6846. }
  6847. }
  6848. };
  6849. function setLineBuffers ( geometry, hint ) {
  6850. var v, c, vertex, offset, color,
  6851. vertices = geometry.vertices,
  6852. colors = geometry.colors,
  6853. vl = vertices.length,
  6854. cl = colors.length,
  6855. vertexArray = geometry.__vertexArray,
  6856. colorArray = geometry.__colorArray,
  6857. dirtyVertices = geometry.__dirtyVertices,
  6858. dirtyColors = geometry.__dirtyColors,
  6859. customAttributes = geometry.__webglCustomAttributesList,
  6860. i, il,
  6861. a, ca, cal, value,
  6862. customAttribute;
  6863. if ( dirtyVertices ) {
  6864. for ( v = 0; v < vl; v ++ ) {
  6865. vertex = vertices[ v ].position;
  6866. offset = v * 3;
  6867. vertexArray[ offset ] = vertex.x;
  6868. vertexArray[ offset + 1 ] = vertex.y;
  6869. vertexArray[ offset + 2 ] = vertex.z;
  6870. }
  6871. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6872. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6873. }
  6874. if ( dirtyColors ) {
  6875. for ( c = 0; c < cl; c ++ ) {
  6876. color = colors[ c ];
  6877. offset = c * 3;
  6878. colorArray[ offset ] = color.r;
  6879. colorArray[ offset + 1 ] = color.g;
  6880. colorArray[ offset + 2 ] = color.b;
  6881. }
  6882. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6883. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6884. }
  6885. if ( customAttributes ) {
  6886. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6887. customAttribute = customAttributes[ i ];
  6888. if ( customAttribute.needsUpdate &&
  6889. ( customAttribute.boundTo === undefined ||
  6890. customAttribute.boundTo === "vertices" ) ) {
  6891. offset = 0;
  6892. cal = customAttribute.value.length;
  6893. if ( customAttribute.size === 1 ) {
  6894. for ( ca = 0; ca < cal; ca ++ ) {
  6895. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6896. }
  6897. } else if ( customAttribute.size === 2 ) {
  6898. for ( ca = 0; ca < cal; ca ++ ) {
  6899. value = customAttribute.value[ ca ];
  6900. customAttribute.array[ offset ] = value.x;
  6901. customAttribute.array[ offset + 1 ] = value.y;
  6902. offset += 2;
  6903. }
  6904. } else if ( customAttribute.size === 3 ) {
  6905. if ( customAttribute.type === "c" ) {
  6906. for ( ca = 0; ca < cal; ca ++ ) {
  6907. value = customAttribute.value[ ca ];
  6908. customAttribute.array[ offset ] = value.r;
  6909. customAttribute.array[ offset + 1 ] = value.g;
  6910. customAttribute.array[ offset + 2 ] = value.b;
  6911. offset += 3;
  6912. }
  6913. } else {
  6914. for ( ca = 0; ca < cal; ca ++ ) {
  6915. value = customAttribute.value[ ca ];
  6916. customAttribute.array[ offset ] = value.x;
  6917. customAttribute.array[ offset + 1 ] = value.y;
  6918. customAttribute.array[ offset + 2 ] = value.z;
  6919. offset += 3;
  6920. }
  6921. }
  6922. } else if ( customAttribute.size === 4 ) {
  6923. for ( ca = 0; ca < cal; ca ++ ) {
  6924. value = customAttribute.value[ ca ];
  6925. customAttribute.array[ offset ] = value.x;
  6926. customAttribute.array[ offset + 1 ] = value.y;
  6927. customAttribute.array[ offset + 2 ] = value.z;
  6928. customAttribute.array[ offset + 3 ] = value.w;
  6929. offset += 4;
  6930. }
  6931. }
  6932. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6933. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6934. }
  6935. }
  6936. }
  6937. };
  6938. function setRibbonBuffers ( geometry, hint ) {
  6939. var v, c, vertex, offset, color,
  6940. vertices = geometry.vertices,
  6941. colors = geometry.colors,
  6942. vl = vertices.length,
  6943. cl = colors.length,
  6944. vertexArray = geometry.__vertexArray,
  6945. colorArray = geometry.__colorArray,
  6946. dirtyVertices = geometry.__dirtyVertices,
  6947. dirtyColors = geometry.__dirtyColors;
  6948. if ( dirtyVertices ) {
  6949. for ( v = 0; v < vl; v ++ ) {
  6950. vertex = vertices[ v ].position;
  6951. offset = v * 3;
  6952. vertexArray[ offset ] = vertex.x;
  6953. vertexArray[ offset + 1 ] = vertex.y;
  6954. vertexArray[ offset + 2 ] = vertex.z;
  6955. }
  6956. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6957. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6958. }
  6959. if ( dirtyColors ) {
  6960. for ( c = 0; c < cl; c ++ ) {
  6961. color = colors[ c ];
  6962. offset = c * 3;
  6963. colorArray[ offset ] = color.r;
  6964. colorArray[ offset + 1 ] = color.g;
  6965. colorArray[ offset + 2 ] = color.b;
  6966. }
  6967. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6968. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6969. }
  6970. };
  6971. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  6972. if ( ! geometryGroup.__inittedArrays ) {
  6973. // console.log( object );
  6974. return;
  6975. }
  6976. var normalType = bufferGuessNormalType( material ),
  6977. vertexColorType = bufferGuessVertexColorType( material ),
  6978. uvType = bufferGuessUVType( material ),
  6979. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  6980. var f, fl, fi, face,
  6981. vertexNormals, faceNormal, normal,
  6982. vertexColors, faceColor,
  6983. vertexTangents,
  6984. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  6985. c1, c2, c3, c4,
  6986. sw1, sw2, sw3, sw4,
  6987. si1, si2, si3, si4,
  6988. sa1, sa2, sa3, sa4,
  6989. sb1, sb2, sb3, sb4,
  6990. m, ml, i, il,
  6991. vn, uvi, uv2i,
  6992. vk, vkl, vka,
  6993. nka, chf, faceVertexNormals,
  6994. a,
  6995. vertexIndex = 0,
  6996. offset = 0,
  6997. offset_uv = 0,
  6998. offset_uv2 = 0,
  6999. offset_face = 0,
  7000. offset_normal = 0,
  7001. offset_tangent = 0,
  7002. offset_line = 0,
  7003. offset_color = 0,
  7004. offset_skin = 0,
  7005. offset_morphTarget = 0,
  7006. offset_custom = 0,
  7007. offset_customSrc = 0,
  7008. value,
  7009. vertexArray = geometryGroup.__vertexArray,
  7010. uvArray = geometryGroup.__uvArray,
  7011. uv2Array = geometryGroup.__uv2Array,
  7012. normalArray = geometryGroup.__normalArray,
  7013. tangentArray = geometryGroup.__tangentArray,
  7014. colorArray = geometryGroup.__colorArray,
  7015. skinVertexAArray = geometryGroup.__skinVertexAArray,
  7016. skinVertexBArray = geometryGroup.__skinVertexBArray,
  7017. skinIndexArray = geometryGroup.__skinIndexArray,
  7018. skinWeightArray = geometryGroup.__skinWeightArray,
  7019. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  7020. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  7021. customAttributes = geometryGroup.__webglCustomAttributesList,
  7022. customAttribute,
  7023. faceArray = geometryGroup.__faceArray,
  7024. lineArray = geometryGroup.__lineArray,
  7025. geometry = object.geometry, // this is shared for all chunks
  7026. dirtyVertices = geometry.__dirtyVertices,
  7027. dirtyElements = geometry.__dirtyElements,
  7028. dirtyUvs = geometry.__dirtyUvs,
  7029. dirtyNormals = geometry.__dirtyNormals,
  7030. dirtyTangents = geometry.__dirtyTangents,
  7031. dirtyColors = geometry.__dirtyColors,
  7032. dirtyMorphTargets = geometry.__dirtyMorphTargets,
  7033. vertices = geometry.vertices,
  7034. chunk_faces3 = geometryGroup.faces3,
  7035. chunk_faces4 = geometryGroup.faces4,
  7036. obj_faces = geometry.faces,
  7037. obj_uvs = geometry.faceVertexUvs[ 0 ],
  7038. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  7039. obj_colors = geometry.colors,
  7040. obj_skinVerticesA = geometry.skinVerticesA,
  7041. obj_skinVerticesB = geometry.skinVerticesB,
  7042. obj_skinIndices = geometry.skinIndices,
  7043. obj_skinWeights = geometry.skinWeights,
  7044. morphTargets = geometry.morphTargets,
  7045. morphNormals = geometry.morphNormals;
  7046. if ( dirtyVertices ) {
  7047. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7048. face = obj_faces[ chunk_faces3[ f ] ];
  7049. v1 = vertices[ face.a ].position;
  7050. v2 = vertices[ face.b ].position;
  7051. v3 = vertices[ face.c ].position;
  7052. vertexArray[ offset ] = v1.x;
  7053. vertexArray[ offset + 1 ] = v1.y;
  7054. vertexArray[ offset + 2 ] = v1.z;
  7055. vertexArray[ offset + 3 ] = v2.x;
  7056. vertexArray[ offset + 4 ] = v2.y;
  7057. vertexArray[ offset + 5 ] = v2.z;
  7058. vertexArray[ offset + 6 ] = v3.x;
  7059. vertexArray[ offset + 7 ] = v3.y;
  7060. vertexArray[ offset + 8 ] = v3.z;
  7061. offset += 9;
  7062. }
  7063. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7064. face = obj_faces[ chunk_faces4[ f ] ];
  7065. v1 = vertices[ face.a ].position;
  7066. v2 = vertices[ face.b ].position;
  7067. v3 = vertices[ face.c ].position;
  7068. v4 = vertices[ face.d ].position;
  7069. vertexArray[ offset ] = v1.x;
  7070. vertexArray[ offset + 1 ] = v1.y;
  7071. vertexArray[ offset + 2 ] = v1.z;
  7072. vertexArray[ offset + 3 ] = v2.x;
  7073. vertexArray[ offset + 4 ] = v2.y;
  7074. vertexArray[ offset + 5 ] = v2.z;
  7075. vertexArray[ offset + 6 ] = v3.x;
  7076. vertexArray[ offset + 7 ] = v3.y;
  7077. vertexArray[ offset + 8 ] = v3.z;
  7078. vertexArray[ offset + 9 ] = v4.x;
  7079. vertexArray[ offset + 10 ] = v4.y;
  7080. vertexArray[ offset + 11 ] = v4.z;
  7081. offset += 12;
  7082. }
  7083. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  7084. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  7085. }
  7086. if ( dirtyMorphTargets ) {
  7087. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  7088. offset_morphTarget = 0;
  7089. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7090. chf = chunk_faces3[ f ];
  7091. face = obj_faces[ chf ];
  7092. // morph positions
  7093. v1 = morphTargets[ vk ].vertices[ face.a ].position;
  7094. v2 = morphTargets[ vk ].vertices[ face.b ].position;
  7095. v3 = morphTargets[ vk ].vertices[ face.c ].position;
  7096. vka = morphTargetsArrays[ vk ];
  7097. vka[ offset_morphTarget ] = v1.x;
  7098. vka[ offset_morphTarget + 1 ] = v1.y;
  7099. vka[ offset_morphTarget + 2 ] = v1.z;
  7100. vka[ offset_morphTarget + 3 ] = v2.x;
  7101. vka[ offset_morphTarget + 4 ] = v2.y;
  7102. vka[ offset_morphTarget + 5 ] = v2.z;
  7103. vka[ offset_morphTarget + 6 ] = v3.x;
  7104. vka[ offset_morphTarget + 7 ] = v3.y;
  7105. vka[ offset_morphTarget + 8 ] = v3.z;
  7106. // morph normals
  7107. if ( material.morphNormals ) {
  7108. if ( needsSmoothNormals ) {
  7109. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7110. n1 = faceVertexNormals.a;
  7111. n2 = faceVertexNormals.b;
  7112. n3 = faceVertexNormals.c;
  7113. } else {
  7114. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7115. n2 = n1;
  7116. n3 = n1;
  7117. }
  7118. nka = morphNormalsArrays[ vk ];
  7119. nka[ offset_morphTarget ] = n1.x;
  7120. nka[ offset_morphTarget + 1 ] = n1.y;
  7121. nka[ offset_morphTarget + 2 ] = n1.z;
  7122. nka[ offset_morphTarget + 3 ] = n2.x;
  7123. nka[ offset_morphTarget + 4 ] = n2.y;
  7124. nka[ offset_morphTarget + 5 ] = n2.z;
  7125. nka[ offset_morphTarget + 6 ] = n3.x;
  7126. nka[ offset_morphTarget + 7 ] = n3.y;
  7127. nka[ offset_morphTarget + 8 ] = n3.z;
  7128. }
  7129. //
  7130. offset_morphTarget += 9;
  7131. }
  7132. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7133. chf = chunk_faces4[ f ];
  7134. face = obj_faces[ chf ];
  7135. // morph positions
  7136. v1 = morphTargets[ vk ].vertices[ face.a ].position;
  7137. v2 = morphTargets[ vk ].vertices[ face.b ].position;
  7138. v3 = morphTargets[ vk ].vertices[ face.c ].position;
  7139. v4 = morphTargets[ vk ].vertices[ face.d ].position;
  7140. vka = morphTargetsArrays[ vk ];
  7141. vka[ offset_morphTarget ] = v1.x;
  7142. vka[ offset_morphTarget + 1 ] = v1.y;
  7143. vka[ offset_morphTarget + 2 ] = v1.z;
  7144. vka[ offset_morphTarget + 3 ] = v2.x;
  7145. vka[ offset_morphTarget + 4 ] = v2.y;
  7146. vka[ offset_morphTarget + 5 ] = v2.z;
  7147. vka[ offset_morphTarget + 6 ] = v3.x;
  7148. vka[ offset_morphTarget + 7 ] = v3.y;
  7149. vka[ offset_morphTarget + 8 ] = v3.z;
  7150. vka[ offset_morphTarget + 9 ] = v4.x;
  7151. vka[ offset_morphTarget + 10 ] = v4.y;
  7152. vka[ offset_morphTarget + 11 ] = v4.z;
  7153. // morph normals
  7154. if ( material.morphNormals ) {
  7155. if ( needsSmoothNormals ) {
  7156. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7157. n1 = faceVertexNormals.a;
  7158. n2 = faceVertexNormals.b;
  7159. n3 = faceVertexNormals.c;
  7160. n4 = faceVertexNormals.d;
  7161. } else {
  7162. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7163. n2 = n1;
  7164. n3 = n1;
  7165. n4 = n1;
  7166. }
  7167. nka = morphNormalsArrays[ vk ];
  7168. nka[ offset_morphTarget ] = n1.x;
  7169. nka[ offset_morphTarget + 1 ] = n1.y;
  7170. nka[ offset_morphTarget + 2 ] = n1.z;
  7171. nka[ offset_morphTarget + 3 ] = n2.x;
  7172. nka[ offset_morphTarget + 4 ] = n2.y;
  7173. nka[ offset_morphTarget + 5 ] = n2.z;
  7174. nka[ offset_morphTarget + 6 ] = n3.x;
  7175. nka[ offset_morphTarget + 7 ] = n3.y;
  7176. nka[ offset_morphTarget + 8 ] = n3.z;
  7177. nka[ offset_morphTarget + 9 ] = n4.x;
  7178. nka[ offset_morphTarget + 10 ] = n4.y;
  7179. nka[ offset_morphTarget + 11 ] = n4.z;
  7180. }
  7181. //
  7182. offset_morphTarget += 12;
  7183. }
  7184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  7185. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  7186. if ( material.morphNormals ) {
  7187. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  7188. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  7189. }
  7190. }
  7191. }
  7192. if ( obj_skinWeights.length ) {
  7193. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7194. face = obj_faces[ chunk_faces3[ f ] ];
  7195. // weights
  7196. sw1 = obj_skinWeights[ face.a ];
  7197. sw2 = obj_skinWeights[ face.b ];
  7198. sw3 = obj_skinWeights[ face.c ];
  7199. skinWeightArray[ offset_skin ] = sw1.x;
  7200. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7201. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7202. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7203. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7204. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7205. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7206. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7207. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7208. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7209. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7210. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7211. // indices
  7212. si1 = obj_skinIndices[ face.a ];
  7213. si2 = obj_skinIndices[ face.b ];
  7214. si3 = obj_skinIndices[ face.c ];
  7215. skinIndexArray[ offset_skin ] = si1.x;
  7216. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7217. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7218. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7219. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7220. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7221. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7222. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7223. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7224. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7225. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7226. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7227. // vertices A
  7228. sa1 = obj_skinVerticesA[ face.a ];
  7229. sa2 = obj_skinVerticesA[ face.b ];
  7230. sa3 = obj_skinVerticesA[ face.c ];
  7231. skinVertexAArray[ offset_skin ] = sa1.x;
  7232. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7233. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7234. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7235. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7236. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7237. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7238. skinVertexAArray[ offset_skin + 7 ] = 1;
  7239. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7240. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7241. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7242. skinVertexAArray[ offset_skin + 11 ] = 1;
  7243. // vertices B
  7244. sb1 = obj_skinVerticesB[ face.a ];
  7245. sb2 = obj_skinVerticesB[ face.b ];
  7246. sb3 = obj_skinVerticesB[ face.c ];
  7247. skinVertexBArray[ offset_skin ] = sb1.x;
  7248. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7249. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7250. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7251. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7252. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7253. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7254. skinVertexBArray[ offset_skin + 7 ] = 1;
  7255. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7256. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7257. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7258. skinVertexBArray[ offset_skin + 11 ] = 1;
  7259. offset_skin += 12;
  7260. }
  7261. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7262. face = obj_faces[ chunk_faces4[ f ] ];
  7263. // weights
  7264. sw1 = obj_skinWeights[ face.a ];
  7265. sw2 = obj_skinWeights[ face.b ];
  7266. sw3 = obj_skinWeights[ face.c ];
  7267. sw4 = obj_skinWeights[ face.d ];
  7268. skinWeightArray[ offset_skin ] = sw1.x;
  7269. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7270. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7271. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7272. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7273. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7274. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7275. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7276. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7277. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7278. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7279. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7280. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  7281. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  7282. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  7283. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  7284. // indices
  7285. si1 = obj_skinIndices[ face.a ];
  7286. si2 = obj_skinIndices[ face.b ];
  7287. si3 = obj_skinIndices[ face.c ];
  7288. si4 = obj_skinIndices[ face.d ];
  7289. skinIndexArray[ offset_skin ] = si1.x;
  7290. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7291. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7292. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7293. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7294. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7295. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7296. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7297. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7298. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7299. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7300. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7301. skinIndexArray[ offset_skin + 12 ] = si4.x;
  7302. skinIndexArray[ offset_skin + 13 ] = si4.y;
  7303. skinIndexArray[ offset_skin + 14 ] = si4.z;
  7304. skinIndexArray[ offset_skin + 15 ] = si4.w;
  7305. // vertices A
  7306. sa1 = obj_skinVerticesA[ face.a ];
  7307. sa2 = obj_skinVerticesA[ face.b ];
  7308. sa3 = obj_skinVerticesA[ face.c ];
  7309. sa4 = obj_skinVerticesA[ face.d ];
  7310. skinVertexAArray[ offset_skin ] = sa1.x;
  7311. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7312. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7313. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7314. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7315. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7316. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7317. skinVertexAArray[ offset_skin + 7 ] = 1;
  7318. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7319. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7320. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7321. skinVertexAArray[ offset_skin + 11 ] = 1;
  7322. skinVertexAArray[ offset_skin + 12 ] = sa4.x;
  7323. skinVertexAArray[ offset_skin + 13 ] = sa4.y;
  7324. skinVertexAArray[ offset_skin + 14 ] = sa4.z;
  7325. skinVertexAArray[ offset_skin + 15 ] = 1;
  7326. // vertices B
  7327. sb1 = obj_skinVerticesB[ face.a ];
  7328. sb2 = obj_skinVerticesB[ face.b ];
  7329. sb3 = obj_skinVerticesB[ face.c ];
  7330. sb4 = obj_skinVerticesB[ face.d ];
  7331. skinVertexBArray[ offset_skin ] = sb1.x;
  7332. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7333. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7334. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7335. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7336. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7337. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7338. skinVertexBArray[ offset_skin + 7 ] = 1;
  7339. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7340. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7341. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7342. skinVertexBArray[ offset_skin + 11 ] = 1;
  7343. skinVertexBArray[ offset_skin + 12 ] = sb4.x;
  7344. skinVertexBArray[ offset_skin + 13 ] = sb4.y;
  7345. skinVertexBArray[ offset_skin + 14 ] = sb4.z;
  7346. skinVertexBArray[ offset_skin + 15 ] = 1;
  7347. offset_skin += 16;
  7348. }
  7349. if ( offset_skin > 0 ) {
  7350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  7351. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexAArray, hint );
  7352. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  7353. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexBArray, hint );
  7354. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  7355. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  7356. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  7357. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  7358. }
  7359. }
  7360. if ( dirtyColors && vertexColorType ) {
  7361. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7362. face = obj_faces[ chunk_faces3[ f ] ];
  7363. vertexColors = face.vertexColors;
  7364. faceColor = face.color;
  7365. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  7366. c1 = vertexColors[ 0 ];
  7367. c2 = vertexColors[ 1 ];
  7368. c3 = vertexColors[ 2 ];
  7369. } else {
  7370. c1 = faceColor;
  7371. c2 = faceColor;
  7372. c3 = faceColor;
  7373. }
  7374. colorArray[ offset_color ] = c1.r;
  7375. colorArray[ offset_color + 1 ] = c1.g;
  7376. colorArray[ offset_color + 2 ] = c1.b;
  7377. colorArray[ offset_color + 3 ] = c2.r;
  7378. colorArray[ offset_color + 4 ] = c2.g;
  7379. colorArray[ offset_color + 5 ] = c2.b;
  7380. colorArray[ offset_color + 6 ] = c3.r;
  7381. colorArray[ offset_color + 7 ] = c3.g;
  7382. colorArray[ offset_color + 8 ] = c3.b;
  7383. offset_color += 9;
  7384. }
  7385. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7386. face = obj_faces[ chunk_faces4[ f ] ];
  7387. vertexColors = face.vertexColors;
  7388. faceColor = face.color;
  7389. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  7390. c1 = vertexColors[ 0 ];
  7391. c2 = vertexColors[ 1 ];
  7392. c3 = vertexColors[ 2 ];
  7393. c4 = vertexColors[ 3 ];
  7394. } else {
  7395. c1 = faceColor;
  7396. c2 = faceColor;
  7397. c3 = faceColor;
  7398. c4 = faceColor;
  7399. }
  7400. colorArray[ offset_color ] = c1.r;
  7401. colorArray[ offset_color + 1 ] = c1.g;
  7402. colorArray[ offset_color + 2 ] = c1.b;
  7403. colorArray[ offset_color + 3 ] = c2.r;
  7404. colorArray[ offset_color + 4 ] = c2.g;
  7405. colorArray[ offset_color + 5 ] = c2.b;
  7406. colorArray[ offset_color + 6 ] = c3.r;
  7407. colorArray[ offset_color + 7 ] = c3.g;
  7408. colorArray[ offset_color + 8 ] = c3.b;
  7409. colorArray[ offset_color + 9 ] = c4.r;
  7410. colorArray[ offset_color + 10 ] = c4.g;
  7411. colorArray[ offset_color + 11 ] = c4.b;
  7412. offset_color += 12;
  7413. }
  7414. if ( offset_color > 0 ) {
  7415. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  7416. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  7417. }
  7418. }
  7419. if ( dirtyTangents && geometry.hasTangents ) {
  7420. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7421. face = obj_faces[ chunk_faces3[ f ] ];
  7422. vertexTangents = face.vertexTangents;
  7423. t1 = vertexTangents[ 0 ];
  7424. t2 = vertexTangents[ 1 ];
  7425. t3 = vertexTangents[ 2 ];
  7426. tangentArray[ offset_tangent ] = t1.x;
  7427. tangentArray[ offset_tangent + 1 ] = t1.y;
  7428. tangentArray[ offset_tangent + 2 ] = t1.z;
  7429. tangentArray[ offset_tangent + 3 ] = t1.w;
  7430. tangentArray[ offset_tangent + 4 ] = t2.x;
  7431. tangentArray[ offset_tangent + 5 ] = t2.y;
  7432. tangentArray[ offset_tangent + 6 ] = t2.z;
  7433. tangentArray[ offset_tangent + 7 ] = t2.w;
  7434. tangentArray[ offset_tangent + 8 ] = t3.x;
  7435. tangentArray[ offset_tangent + 9 ] = t3.y;
  7436. tangentArray[ offset_tangent + 10 ] = t3.z;
  7437. tangentArray[ offset_tangent + 11 ] = t3.w;
  7438. offset_tangent += 12;
  7439. }
  7440. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7441. face = obj_faces[ chunk_faces4[ f ] ];
  7442. vertexTangents = face.vertexTangents;
  7443. t1 = vertexTangents[ 0 ];
  7444. t2 = vertexTangents[ 1 ];
  7445. t3 = vertexTangents[ 2 ];
  7446. t4 = vertexTangents[ 3 ];
  7447. tangentArray[ offset_tangent ] = t1.x;
  7448. tangentArray[ offset_tangent + 1 ] = t1.y;
  7449. tangentArray[ offset_tangent + 2 ] = t1.z;
  7450. tangentArray[ offset_tangent + 3 ] = t1.w;
  7451. tangentArray[ offset_tangent + 4 ] = t2.x;
  7452. tangentArray[ offset_tangent + 5 ] = t2.y;
  7453. tangentArray[ offset_tangent + 6 ] = t2.z;
  7454. tangentArray[ offset_tangent + 7 ] = t2.w;
  7455. tangentArray[ offset_tangent + 8 ] = t3.x;
  7456. tangentArray[ offset_tangent + 9 ] = t3.y;
  7457. tangentArray[ offset_tangent + 10 ] = t3.z;
  7458. tangentArray[ offset_tangent + 11 ] = t3.w;
  7459. tangentArray[ offset_tangent + 12 ] = t4.x;
  7460. tangentArray[ offset_tangent + 13 ] = t4.y;
  7461. tangentArray[ offset_tangent + 14 ] = t4.z;
  7462. tangentArray[ offset_tangent + 15 ] = t4.w;
  7463. offset_tangent += 16;
  7464. }
  7465. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  7466. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  7467. }
  7468. if ( dirtyNormals && normalType ) {
  7469. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7470. face = obj_faces[ chunk_faces3[ f ] ];
  7471. vertexNormals = face.vertexNormals;
  7472. faceNormal = face.normal;
  7473. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  7474. for ( i = 0; i < 3; i ++ ) {
  7475. vn = vertexNormals[ i ];
  7476. normalArray[ offset_normal ] = vn.x;
  7477. normalArray[ offset_normal + 1 ] = vn.y;
  7478. normalArray[ offset_normal + 2 ] = vn.z;
  7479. offset_normal += 3;
  7480. }
  7481. } else {
  7482. for ( i = 0; i < 3; i ++ ) {
  7483. normalArray[ offset_normal ] = faceNormal.x;
  7484. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7485. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7486. offset_normal += 3;
  7487. }
  7488. }
  7489. }
  7490. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7491. face = obj_faces[ chunk_faces4[ f ] ];
  7492. vertexNormals = face.vertexNormals;
  7493. faceNormal = face.normal;
  7494. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  7495. for ( i = 0; i < 4; i ++ ) {
  7496. vn = vertexNormals[ i ];
  7497. normalArray[ offset_normal ] = vn.x;
  7498. normalArray[ offset_normal + 1 ] = vn.y;
  7499. normalArray[ offset_normal + 2 ] = vn.z;
  7500. offset_normal += 3;
  7501. }
  7502. } else {
  7503. for ( i = 0; i < 4; i ++ ) {
  7504. normalArray[ offset_normal ] = faceNormal.x;
  7505. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7506. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7507. offset_normal += 3;
  7508. }
  7509. }
  7510. }
  7511. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  7512. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  7513. }
  7514. if ( dirtyUvs && obj_uvs && uvType ) {
  7515. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7516. fi = chunk_faces3[ f ];
  7517. face = obj_faces[ fi ];
  7518. uv = obj_uvs[ fi ];
  7519. if ( uv === undefined ) continue;
  7520. for ( i = 0; i < 3; i ++ ) {
  7521. uvi = uv[ i ];
  7522. uvArray[ offset_uv ] = uvi.u;
  7523. uvArray[ offset_uv + 1 ] = uvi.v;
  7524. offset_uv += 2;
  7525. }
  7526. }
  7527. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7528. fi = chunk_faces4[ f ];
  7529. face = obj_faces[ fi ];
  7530. uv = obj_uvs[ fi ];
  7531. if ( uv === undefined ) continue;
  7532. for ( i = 0; i < 4; i ++ ) {
  7533. uvi = uv[ i ];
  7534. uvArray[ offset_uv ] = uvi.u;
  7535. uvArray[ offset_uv + 1 ] = uvi.v;
  7536. offset_uv += 2;
  7537. }
  7538. }
  7539. if ( offset_uv > 0 ) {
  7540. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  7541. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  7542. }
  7543. }
  7544. if ( dirtyUvs && obj_uvs2 && uvType ) {
  7545. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7546. fi = chunk_faces3[ f ];
  7547. face = obj_faces[ fi ];
  7548. uv2 = obj_uvs2[ fi ];
  7549. if ( uv2 === undefined ) continue;
  7550. for ( i = 0; i < 3; i ++ ) {
  7551. uv2i = uv2[ i ];
  7552. uv2Array[ offset_uv2 ] = uv2i.u;
  7553. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7554. offset_uv2 += 2;
  7555. }
  7556. }
  7557. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7558. fi = chunk_faces4[ f ];
  7559. face = obj_faces[ fi ];
  7560. uv2 = obj_uvs2[ fi ];
  7561. if ( uv2 === undefined ) continue;
  7562. for ( i = 0; i < 4; i ++ ) {
  7563. uv2i = uv2[ i ];
  7564. uv2Array[ offset_uv2 ] = uv2i.u;
  7565. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7566. offset_uv2 += 2;
  7567. }
  7568. }
  7569. if ( offset_uv2 > 0 ) {
  7570. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  7571. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  7572. }
  7573. }
  7574. if ( dirtyElements ) {
  7575. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7576. face = obj_faces[ chunk_faces3[ f ] ];
  7577. faceArray[ offset_face ] = vertexIndex;
  7578. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7579. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  7580. offset_face += 3;
  7581. lineArray[ offset_line ] = vertexIndex;
  7582. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7583. lineArray[ offset_line + 2 ] = vertexIndex;
  7584. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  7585. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7586. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7587. offset_line += 6;
  7588. vertexIndex += 3;
  7589. }
  7590. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7591. face = obj_faces[ chunk_faces4[ f ] ];
  7592. faceArray[ offset_face ] = vertexIndex;
  7593. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7594. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  7595. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  7596. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  7597. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  7598. offset_face += 6;
  7599. lineArray[ offset_line ] = vertexIndex;
  7600. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7601. lineArray[ offset_line + 2 ] = vertexIndex;
  7602. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  7603. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7604. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7605. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  7606. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  7607. offset_line += 8;
  7608. vertexIndex += 4;
  7609. }
  7610. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  7611. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  7612. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  7613. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  7614. }
  7615. if ( customAttributes ) {
  7616. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  7617. customAttribute = customAttributes[ i ];
  7618. if ( ! customAttribute.__original.needsUpdate ) continue;
  7619. offset_custom = 0;
  7620. offset_customSrc = 0;
  7621. if ( customAttribute.size === 1 ) {
  7622. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7623. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7624. face = obj_faces[ chunk_faces3[ f ] ];
  7625. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7626. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7627. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7628. offset_custom += 3;
  7629. }
  7630. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7631. face = obj_faces[ chunk_faces4[ f ] ];
  7632. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7633. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7634. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7635. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  7636. offset_custom += 4;
  7637. }
  7638. } else if ( customAttribute.boundTo === "faces" ) {
  7639. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7640. value = customAttribute.value[ chunk_faces3[ f ] ];
  7641. customAttribute.array[ offset_custom ] = value;
  7642. customAttribute.array[ offset_custom + 1 ] = value;
  7643. customAttribute.array[ offset_custom + 2 ] = value;
  7644. offset_custom += 3;
  7645. }
  7646. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7647. value = customAttribute.value[ chunk_faces4[ f ] ];
  7648. customAttribute.array[ offset_custom ] = value;
  7649. customAttribute.array[ offset_custom + 1 ] = value;
  7650. customAttribute.array[ offset_custom + 2 ] = value;
  7651. customAttribute.array[ offset_custom + 3 ] = value;
  7652. offset_custom += 4;
  7653. }
  7654. }
  7655. } else if ( customAttribute.size === 2 ) {
  7656. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7657. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7658. face = obj_faces[ chunk_faces3[ f ] ];
  7659. v1 = customAttribute.value[ face.a ];
  7660. v2 = customAttribute.value[ face.b ];
  7661. v3 = customAttribute.value[ face.c ];
  7662. customAttribute.array[ offset_custom ] = v1.x;
  7663. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7664. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7665. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7666. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7667. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7668. offset_custom += 6;
  7669. }
  7670. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7671. face = obj_faces[ chunk_faces4[ f ] ];
  7672. v1 = customAttribute.value[ face.a ];
  7673. v2 = customAttribute.value[ face.b ];
  7674. v3 = customAttribute.value[ face.c ];
  7675. v4 = customAttribute.value[ face.d ];
  7676. customAttribute.array[ offset_custom ] = v1.x;
  7677. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7678. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7679. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7680. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7681. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7682. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7683. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7684. offset_custom += 8;
  7685. }
  7686. } else if ( customAttribute.boundTo === "faces" ) {
  7687. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7688. value = customAttribute.value[ chunk_faces3[ f ] ];
  7689. v1 = value;
  7690. v2 = value;
  7691. v3 = value;
  7692. customAttribute.array[ offset_custom ] = v1.x;
  7693. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7694. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7695. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7696. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7697. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7698. offset_custom += 6;
  7699. }
  7700. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7701. value = customAttribute.value[ chunk_faces4[ f ] ];
  7702. v1 = value;
  7703. v2 = value;
  7704. v3 = value;
  7705. v4 = value;
  7706. customAttribute.array[ offset_custom ] = v1.x;
  7707. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7708. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7709. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7710. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7711. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7712. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7713. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7714. offset_custom += 8;
  7715. }
  7716. }
  7717. } else if ( customAttribute.size === 3 ) {
  7718. var pp;
  7719. if ( customAttribute.type === "c" ) {
  7720. pp = [ "r", "g", "b" ];
  7721. } else {
  7722. pp = [ "x", "y", "z" ];
  7723. }
  7724. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7725. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7726. face = obj_faces[ chunk_faces3[ f ] ];
  7727. v1 = customAttribute.value[ face.a ];
  7728. v2 = customAttribute.value[ face.b ];
  7729. v3 = customAttribute.value[ face.c ];
  7730. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7731. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7732. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7733. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7734. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7735. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7736. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7737. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7738. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7739. offset_custom += 9;
  7740. }
  7741. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7742. face = obj_faces[ chunk_faces4[ f ] ];
  7743. v1 = customAttribute.value[ face.a ];
  7744. v2 = customAttribute.value[ face.b ];
  7745. v3 = customAttribute.value[ face.c ];
  7746. v4 = customAttribute.value[ face.d ];
  7747. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7748. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7749. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7750. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7751. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7752. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7753. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7754. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7755. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7756. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7757. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7758. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7759. offset_custom += 12;
  7760. }
  7761. } else if ( customAttribute.boundTo === "faces" ) {
  7762. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7763. value = customAttribute.value[ chunk_faces3[ f ] ];
  7764. v1 = value;
  7765. v2 = value;
  7766. v3 = value;
  7767. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7768. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7769. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7770. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7771. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7772. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7773. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7774. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7775. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7776. offset_custom += 9;
  7777. }
  7778. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7779. value = customAttribute.value[ chunk_faces4[ f ] ];
  7780. v1 = value;
  7781. v2 = value;
  7782. v3 = value;
  7783. v4 = value;
  7784. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7785. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7786. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7787. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7788. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7789. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7790. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7791. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7792. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7793. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7794. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7795. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7796. offset_custom += 12;
  7797. }
  7798. }
  7799. } else if ( customAttribute.size === 4 ) {
  7800. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7801. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7802. face = obj_faces[ chunk_faces3[ f ] ];
  7803. v1 = customAttribute.value[ face.a ];
  7804. v2 = customAttribute.value[ face.b ];
  7805. v3 = customAttribute.value[ face.c ];
  7806. customAttribute.array[ offset_custom ] = v1.x;
  7807. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7808. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7809. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7810. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7811. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7812. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7813. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7814. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7815. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7816. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7817. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7818. offset_custom += 12;
  7819. }
  7820. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7821. face = obj_faces[ chunk_faces4[ f ] ];
  7822. v1 = customAttribute.value[ face.a ];
  7823. v2 = customAttribute.value[ face.b ];
  7824. v3 = customAttribute.value[ face.c ];
  7825. v4 = customAttribute.value[ face.d ];
  7826. customAttribute.array[ offset_custom ] = v1.x;
  7827. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7828. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7829. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7830. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7831. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7832. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7833. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7834. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7835. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7836. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7837. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7838. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7839. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7840. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7841. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7842. offset_custom += 16;
  7843. }
  7844. } else if ( customAttribute.boundTo === "faces" ) {
  7845. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7846. value = customAttribute.value[ chunk_faces3[ f ] ];
  7847. v1 = value;
  7848. v2 = value;
  7849. v3 = value;
  7850. customAttribute.array[ offset_custom ] = v1.x;
  7851. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7852. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7853. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7854. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7855. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7856. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7857. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7858. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7859. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7860. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7861. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7862. offset_custom += 12;
  7863. }
  7864. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7865. value = customAttribute.value[ chunk_faces4[ f ] ];
  7866. v1 = value;
  7867. v2 = value;
  7868. v3 = value;
  7869. v4 = value;
  7870. customAttribute.array[ offset_custom ] = v1.x;
  7871. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7872. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7873. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7874. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7875. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7876. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7877. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7878. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7879. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7880. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7881. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7882. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7883. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7884. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7885. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7886. offset_custom += 16;
  7887. }
  7888. }
  7889. }
  7890. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  7891. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  7892. }
  7893. }
  7894. if ( dispose ) {
  7895. delete geometryGroup.__inittedArrays;
  7896. delete geometryGroup.__colorArray;
  7897. delete geometryGroup.__normalArray;
  7898. delete geometryGroup.__tangentArray;
  7899. delete geometryGroup.__uvArray;
  7900. delete geometryGroup.__uv2Array;
  7901. delete geometryGroup.__faceArray;
  7902. delete geometryGroup.__vertexArray;
  7903. delete geometryGroup.__lineArray;
  7904. delete geometryGroup.__skinVertexAArray;
  7905. delete geometryGroup.__skinVertexBArray;
  7906. delete geometryGroup.__skinIndexArray;
  7907. delete geometryGroup.__skinWeightArray;
  7908. }
  7909. };
  7910. // Buffer rendering
  7911. this.renderBufferImmediate = function ( object, program, shading ) {
  7912. if ( ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  7913. if ( ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  7914. if ( object.hasPos ) {
  7915. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  7916. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  7917. _gl.enableVertexAttribArray( program.attributes.position );
  7918. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  7919. }
  7920. if ( object.hasNormal ) {
  7921. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  7922. if ( shading === THREE.FlatShading ) {
  7923. var nx, ny, nz,
  7924. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  7925. normalArray,
  7926. i, il = object.count * 3;
  7927. for( i = 0; i < il; i += 9 ) {
  7928. normalArray = object.normalArray;
  7929. nax = normalArray[ i ];
  7930. nay = normalArray[ i + 1 ];
  7931. naz = normalArray[ i + 2 ];
  7932. nbx = normalArray[ i + 3 ];
  7933. nby = normalArray[ i + 4 ];
  7934. nbz = normalArray[ i + 5 ];
  7935. ncx = normalArray[ i + 6 ];
  7936. ncy = normalArray[ i + 7 ];
  7937. ncz = normalArray[ i + 8 ];
  7938. nx = ( nax + nbx + ncx ) / 3;
  7939. ny = ( nay + nby + ncy ) / 3;
  7940. nz = ( naz + nbz + ncz ) / 3;
  7941. normalArray[ i ] = nx;
  7942. normalArray[ i + 1 ] = ny;
  7943. normalArray[ i + 2 ] = nz;
  7944. normalArray[ i + 3 ] = nx;
  7945. normalArray[ i + 4 ] = ny;
  7946. normalArray[ i + 5 ] = nz;
  7947. normalArray[ i + 6 ] = nx;
  7948. normalArray[ i + 7 ] = ny;
  7949. normalArray[ i + 8 ] = nz;
  7950. }
  7951. }
  7952. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  7953. _gl.enableVertexAttribArray( program.attributes.normal );
  7954. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  7955. }
  7956. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  7957. object.count = 0;
  7958. };
  7959. this.renderBufferDirect = function ( camera, lights, fog, material, geometryGroup, object ) {
  7960. if ( material.opacity === 0 ) return;
  7961. var program, attributes, linewidth, primitives, a, attribute;
  7962. program = setProgram( camera, lights, fog, material, object );
  7963. attributes = program.attributes;
  7964. var updateBuffers = false,
  7965. wireframeBit = material.wireframe ? 1 : 0,
  7966. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  7967. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  7968. _currentGeometryGroupHash = geometryGroupHash;
  7969. updateBuffers = true;
  7970. }
  7971. // render mesh
  7972. if ( object instanceof THREE.Mesh ) {
  7973. var offsets = geometryGroup.offsets;
  7974. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  7975. if ( updateBuffers ) {
  7976. // vertices
  7977. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexPositionBuffer );
  7978. _gl.vertexAttribPointer( attributes.position, geometryGroup.vertexPositionBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7979. // normals
  7980. if ( attributes.normal >= 0 && geometryGroup.vertexNormalBuffer ) {
  7981. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexNormalBuffer );
  7982. _gl.vertexAttribPointer( attributes.normal, geometryGroup.vertexNormalBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7983. }
  7984. // uvs
  7985. if ( attributes.uv >= 0 && geometryGroup.vertexUvBuffer ) {
  7986. if ( geometryGroup.vertexUvBuffer ) {
  7987. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexUvBuffer );
  7988. _gl.vertexAttribPointer( attributes.uv, geometryGroup.vertexUvBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 2 );
  7989. _gl.enableVertexAttribArray( attributes.uv );
  7990. } else {
  7991. _gl.disableVertexAttribArray( attributes.uv );
  7992. }
  7993. }
  7994. // colors
  7995. if ( attributes.color >= 0 && geometryGroup.vertexColorBuffer ) {
  7996. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexColorBuffer );
  7997. _gl.vertexAttribPointer( attributes.color, geometryGroup.vertexColorBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 4 );
  7998. }
  7999. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.vertexIndexBuffer );
  8000. }
  8001. // render indexed triangles
  8002. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 = Uint16
  8003. _this.info.render.calls ++;
  8004. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  8005. _this.info.render.faces += offsets[ i ].count / 3;
  8006. }
  8007. }
  8008. };
  8009. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  8010. if ( material.opacity === 0 ) return;
  8011. var program, attributes, linewidth, primitives, a, attribute, i, il;
  8012. program = setProgram( camera, lights, fog, material, object );
  8013. attributes = program.attributes;
  8014. var updateBuffers = false,
  8015. wireframeBit = material.wireframe ? 1 : 0,
  8016. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  8017. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  8018. _currentGeometryGroupHash = geometryGroupHash;
  8019. updateBuffers = true;
  8020. }
  8021. // vertices
  8022. if ( !material.morphTargets && attributes.position >= 0 ) {
  8023. if ( updateBuffers ) {
  8024. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8025. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8026. }
  8027. } else {
  8028. if ( object.morphTargetBase ) {
  8029. setupMorphTargets( material, geometryGroup, object );
  8030. }
  8031. }
  8032. if ( updateBuffers ) {
  8033. // custom attributes
  8034. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  8035. if ( geometryGroup.__webglCustomAttributesList ) {
  8036. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  8037. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  8038. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  8039. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  8040. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  8041. }
  8042. }
  8043. }
  8044. // colors
  8045. if ( attributes.color >= 0 ) {
  8046. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  8047. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  8048. }
  8049. // normals
  8050. if ( attributes.normal >= 0 ) {
  8051. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  8052. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  8053. }
  8054. // tangents
  8055. if ( attributes.tangent >= 0 ) {
  8056. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  8057. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  8058. }
  8059. // uvs
  8060. if ( attributes.uv >= 0 ) {
  8061. if ( geometryGroup.__webglUVBuffer ) {
  8062. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  8063. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  8064. _gl.enableVertexAttribArray( attributes.uv );
  8065. } else {
  8066. _gl.disableVertexAttribArray( attributes.uv );
  8067. }
  8068. }
  8069. if ( attributes.uv2 >= 0 ) {
  8070. if ( geometryGroup.__webglUV2Buffer ) {
  8071. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  8072. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  8073. _gl.enableVertexAttribArray( attributes.uv2 );
  8074. } else {
  8075. _gl.disableVertexAttribArray( attributes.uv2 );
  8076. }
  8077. }
  8078. if ( material.skinning &&
  8079. attributes.skinVertexA >= 0 && attributes.skinVertexB >= 0 &&
  8080. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  8082. _gl.vertexAttribPointer( attributes.skinVertexA, 4, _gl.FLOAT, false, 0, 0 );
  8083. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  8084. _gl.vertexAttribPointer( attributes.skinVertexB, 4, _gl.FLOAT, false, 0, 0 );
  8085. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  8086. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  8087. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  8088. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  8089. }
  8090. }
  8091. // render mesh
  8092. if ( object instanceof THREE.Mesh ) {
  8093. // wireframe
  8094. if ( material.wireframe ) {
  8095. setLineWidth( material.wireframeLinewidth );
  8096. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  8097. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  8098. // triangles
  8099. } else {
  8100. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  8101. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  8102. }
  8103. _this.info.render.calls ++;
  8104. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  8105. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  8106. // render lines
  8107. } else if ( object instanceof THREE.Line ) {
  8108. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  8109. setLineWidth( material.linewidth );
  8110. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  8111. _this.info.render.calls ++;
  8112. // render particles
  8113. } else if ( object instanceof THREE.ParticleSystem ) {
  8114. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  8115. _this.info.render.calls ++;
  8116. _this.info.render.points += geometryGroup.__webglParticleCount;
  8117. // render ribbon
  8118. } else if ( object instanceof THREE.Ribbon ) {
  8119. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  8120. _this.info.render.calls ++;
  8121. }
  8122. };
  8123. function setupMorphTargets ( material, geometryGroup, object ) {
  8124. // set base
  8125. var attributes = material.program.attributes;
  8126. if ( object.morphTargetBase !== - 1 ) {
  8127. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  8128. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8129. } else if ( attributes.position >= 0 ) {
  8130. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8131. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8132. }
  8133. if ( object.morphTargetForcedOrder.length ) {
  8134. // set forced order
  8135. var m = 0;
  8136. var order = object.morphTargetForcedOrder;
  8137. var influences = object.morphTargetInfluences;
  8138. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  8139. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  8140. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8141. if ( material.morphNormals ) {
  8142. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  8143. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8144. }
  8145. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  8146. m ++;
  8147. }
  8148. } else {
  8149. // find most influencing
  8150. var used = [];
  8151. var candidateInfluence = - 1;
  8152. var candidate = 0;
  8153. var influences = object.morphTargetInfluences;
  8154. var i, il = influences.length;
  8155. var m = 0;
  8156. if ( object.morphTargetBase !== - 1 ) {
  8157. used[ object.morphTargetBase ] = true;
  8158. }
  8159. while ( m < material.numSupportedMorphTargets ) {
  8160. for ( i = 0; i < il; i ++ ) {
  8161. if ( !used[ i ] && influences[ i ] > candidateInfluence ) {
  8162. candidate = i;
  8163. candidateInfluence = influences[ candidate ];
  8164. }
  8165. }
  8166. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ candidate ] );
  8167. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8168. if ( material.morphNormals ) {
  8169. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ candidate ] );
  8170. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8171. }
  8172. object.__webglMorphTargetInfluences[ m ] = candidateInfluence;
  8173. used[ candidate ] = 1;
  8174. candidateInfluence = -1;
  8175. m ++;
  8176. }
  8177. }
  8178. // load updated influences uniform
  8179. if( material.program.uniforms.morphTargetInfluences !== null ) {
  8180. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  8181. }
  8182. };
  8183. function painterSort ( a, b ) {
  8184. return b.z - a.z;
  8185. };
  8186. // Rendering
  8187. this.render = function ( scene, camera, renderTarget, forceClear ) {
  8188. var i, il,
  8189. webglObject, object,
  8190. renderList,
  8191. lights = scene.__lights,
  8192. fog = scene.fog;
  8193. _currentMaterialId = -1;
  8194. // update scene graph
  8195. if ( camera.parent === undefined ) {
  8196. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  8197. scene.add( camera );
  8198. }
  8199. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  8200. // update camera matrices and frustum
  8201. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  8202. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  8203. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  8204. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  8205. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  8206. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  8207. _frustum.setFromMatrix( _projScreenMatrix );
  8208. // update WebGL objects
  8209. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  8210. // custom render plugins (pre pass)
  8211. renderPlugins( this.renderPluginsPre, scene, camera );
  8212. //
  8213. _this.info.render.calls = 0;
  8214. _this.info.render.vertices = 0;
  8215. _this.info.render.faces = 0;
  8216. _this.info.render.points = 0;
  8217. this.setRenderTarget( renderTarget );
  8218. if ( this.autoClear || forceClear ) {
  8219. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  8220. }
  8221. // set matrices for regular objects (frustum culled)
  8222. renderList = scene.__webglObjects;
  8223. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8224. webglObject = renderList[ i ];
  8225. object = webglObject.object;
  8226. webglObject.render = false;
  8227. if ( object.visible ) {
  8228. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  8229. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8230. setupMatrices( object, camera );
  8231. unrollBufferMaterial( webglObject );
  8232. webglObject.render = true;
  8233. if ( this.sortObjects ) {
  8234. if ( object.renderDepth ) {
  8235. webglObject.z = object.renderDepth;
  8236. } else {
  8237. _vector3.copy( object.matrixWorld.getPosition() );
  8238. _projScreenMatrix.multiplyVector3( _vector3 );
  8239. webglObject.z = _vector3.z;
  8240. }
  8241. }
  8242. }
  8243. }
  8244. }
  8245. if ( this.sortObjects ) {
  8246. renderList.sort( painterSort );
  8247. }
  8248. // set matrices for immediate objects
  8249. renderList = scene.__webglObjectsImmediate;
  8250. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8251. webglObject = renderList[ i ];
  8252. object = webglObject.object;
  8253. if ( object.visible ) {
  8254. if( object.matrixAutoUpdate ) {
  8255. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8256. }
  8257. setupMatrices( object, camera );
  8258. unrollImmediateBufferMaterial( webglObject );
  8259. }
  8260. }
  8261. if ( scene.overrideMaterial ) {
  8262. var material = scene.overrideMaterial;
  8263. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8264. this.setDepthTest( material.depthTest );
  8265. this.setDepthWrite( material.depthWrite );
  8266. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8267. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  8268. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  8269. } else {
  8270. // opaque pass (front-to-back order)
  8271. this.setBlending( THREE.NormalBlending );
  8272. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  8273. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  8274. // transparent pass (back-to-front order)
  8275. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  8276. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  8277. }
  8278. // custom render plugins (post pass)
  8279. renderPlugins( this.renderPluginsPost, scene, camera );
  8280. // Generate mipmap if we're using any kind of mipmap filtering
  8281. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  8282. updateRenderTargetMipmap( renderTarget );
  8283. }
  8284. // Ensure depth buffer writing is enabled so it can be cleared on next render
  8285. this.setDepthTest( true );
  8286. this.setDepthWrite( true );
  8287. // _gl.finish();
  8288. };
  8289. function renderPlugins( plugins, scene, camera ) {
  8290. if ( ! plugins.length ) return;
  8291. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  8292. _currentProgram = null;
  8293. _currentCamera = null;
  8294. _oldBlending = -1;
  8295. _oldDepthTest = -1;
  8296. _oldDepthWrite = -1;
  8297. _currentGeometryGroupHash = -1;
  8298. _currentMaterialId = -1;
  8299. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  8300. _currentProgram = null;
  8301. _currentCamera = null;
  8302. _oldBlending = -1;
  8303. _oldDepthTest = -1;
  8304. _oldDepthWrite = -1;
  8305. _currentGeometryGroupHash = -1;
  8306. _currentMaterialId = -1;
  8307. }
  8308. };
  8309. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8310. var webglObject, object, buffer, material, start, end, delta;
  8311. if ( reverse ) {
  8312. start = renderList.length - 1;
  8313. end = -1;
  8314. delta = -1;
  8315. } else {
  8316. start = 0;
  8317. end = renderList.length;
  8318. delta = 1;
  8319. }
  8320. for ( var i = start; i !== end; i += delta ) {
  8321. webglObject = renderList[ i ];
  8322. if ( webglObject.render ) {
  8323. object = webglObject.object;
  8324. buffer = webglObject.buffer;
  8325. if ( overrideMaterial ) {
  8326. material = overrideMaterial;
  8327. } else {
  8328. material = webglObject[ materialType ];
  8329. if ( ! material ) continue;
  8330. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8331. _this.setDepthTest( material.depthTest );
  8332. _this.setDepthWrite( material.depthWrite );
  8333. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8334. }
  8335. _this.setObjectFaces( object );
  8336. if ( buffer instanceof THREE.BufferGeometry ) {
  8337. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  8338. } else {
  8339. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  8340. }
  8341. }
  8342. }
  8343. };
  8344. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8345. var webglObject, object, material, program;
  8346. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  8347. webglObject = renderList[ i ];
  8348. object = webglObject.object;
  8349. if ( object.visible ) {
  8350. if ( overrideMaterial ) {
  8351. material = overrideMaterial;
  8352. } else {
  8353. material = webglObject[ materialType ];
  8354. if ( ! material ) continue;
  8355. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8356. _this.setDepthTest( material.depthTest );
  8357. _this.setDepthWrite( material.depthWrite );
  8358. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8359. }
  8360. _this.renderImmediateObject( camera, lights, fog, material, object );
  8361. }
  8362. }
  8363. };
  8364. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  8365. var program = setProgram( camera, lights, fog, material, object );
  8366. _currentGeometryGroupHash = -1;
  8367. _this.setObjectFaces( object );
  8368. if ( object.immediateRenderCallback ) {
  8369. object.immediateRenderCallback( program, _gl, _frustum );
  8370. } else {
  8371. object.render( function( object ) { _this.renderBufferImmediate( object, program, material.shading ); } );
  8372. }
  8373. };
  8374. function unrollImmediateBufferMaterial ( globject ) {
  8375. var object = globject.object,
  8376. material = object.material;
  8377. if ( material.transparent ) {
  8378. globject.transparent = material;
  8379. globject.opaque = null;
  8380. } else {
  8381. globject.opaque = material;
  8382. globject.transparent = null;
  8383. }
  8384. };
  8385. function unrollBufferMaterial ( globject ) {
  8386. var object = globject.object,
  8387. buffer = globject.buffer,
  8388. material, materialIndex, meshMaterial;
  8389. meshMaterial = object.material;
  8390. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  8391. materialIndex = buffer.materialIndex;
  8392. if ( materialIndex >= 0 ) {
  8393. material = object.geometry.materials[ materialIndex ];
  8394. if ( material.transparent ) {
  8395. globject.transparent = material;
  8396. globject.opaque = null;
  8397. } else {
  8398. globject.opaque = material;
  8399. globject.transparent = null;
  8400. }
  8401. }
  8402. } else {
  8403. material = meshMaterial;
  8404. if ( material ) {
  8405. if ( material.transparent ) {
  8406. globject.transparent = material;
  8407. globject.opaque = null;
  8408. } else {
  8409. globject.opaque = material;
  8410. globject.transparent = null;
  8411. }
  8412. }
  8413. }
  8414. };
  8415. // Geometry splitting
  8416. function sortFacesByMaterial ( geometry ) {
  8417. var f, fl, face, materialIndex, vertices,
  8418. materialHash, groupHash,
  8419. hash_map = {};
  8420. var numMorphTargets = geometry.morphTargets.length;
  8421. var numMorphNormals = geometry.morphNormals.length;
  8422. geometry.geometryGroups = {};
  8423. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8424. face = geometry.faces[ f ];
  8425. materialIndex = face.materialIndex;
  8426. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  8427. if ( hash_map[ materialHash ] === undefined ) {
  8428. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  8429. }
  8430. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8431. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8432. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8433. }
  8434. vertices = face instanceof THREE.Face3 ? 3 : 4;
  8435. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  8436. hash_map[ materialHash ].counter += 1;
  8437. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8438. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8439. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8440. }
  8441. }
  8442. if ( face instanceof THREE.Face3 ) {
  8443. geometry.geometryGroups[ groupHash ].faces3.push( f );
  8444. } else {
  8445. geometry.geometryGroups[ groupHash ].faces4.push( f );
  8446. }
  8447. geometry.geometryGroups[ groupHash ].vertices += vertices;
  8448. }
  8449. geometry.geometryGroupsList = [];
  8450. for ( var g in geometry.geometryGroups ) {
  8451. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  8452. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  8453. }
  8454. };
  8455. // Objects refresh
  8456. this.initWebGLObjects = function ( scene ) {
  8457. if ( !scene.__webglObjects ) {
  8458. scene.__webglObjects = [];
  8459. scene.__webglObjectsImmediate = [];
  8460. scene.__webglSprites = [];
  8461. scene.__webglFlares = [];
  8462. }
  8463. while ( scene.__objectsAdded.length ) {
  8464. addObject( scene.__objectsAdded[ 0 ], scene );
  8465. scene.__objectsAdded.splice( 0, 1 );
  8466. }
  8467. while ( scene.__objectsRemoved.length ) {
  8468. removeObject( scene.__objectsRemoved[ 0 ], scene );
  8469. scene.__objectsRemoved.splice( 0, 1 );
  8470. }
  8471. // update must be called after objects adding / removal
  8472. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  8473. updateObject( scene.__webglObjects[ o ].object );
  8474. }
  8475. };
  8476. // Objects adding
  8477. function addObject ( object, scene ) {
  8478. var g, geometry, geometryGroup;
  8479. if ( ! object.__webglInit ) {
  8480. object.__webglInit = true;
  8481. object._modelViewMatrix = new THREE.Matrix4();
  8482. object._normalMatrix = new THREE.Matrix3();
  8483. object._normalMatrixArray = new Float32Array( 9 );
  8484. object._modelViewMatrixArray = new Float32Array( 16 );
  8485. object._objectMatrixArray = new Float32Array( 16 );
  8486. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8487. if ( object instanceof THREE.Mesh ) {
  8488. geometry = object.geometry;
  8489. if ( geometry instanceof THREE.Geometry ) {
  8490. if ( geometry.geometryGroups === undefined ) {
  8491. sortFacesByMaterial( geometry );
  8492. }
  8493. // create separate VBOs per geometry chunk
  8494. for ( g in geometry.geometryGroups ) {
  8495. geometryGroup = geometry.geometryGroups[ g ];
  8496. // initialise VBO on the first access
  8497. if ( ! geometryGroup.__webglVertexBuffer ) {
  8498. createMeshBuffers( geometryGroup );
  8499. initMeshBuffers( geometryGroup, object );
  8500. geometry.__dirtyVertices = true;
  8501. geometry.__dirtyMorphTargets = true;
  8502. geometry.__dirtyElements = true;
  8503. geometry.__dirtyUvs = true;
  8504. geometry.__dirtyNormals = true;
  8505. geometry.__dirtyTangents = true;
  8506. geometry.__dirtyColors = true;
  8507. }
  8508. }
  8509. }
  8510. } else if ( object instanceof THREE.Ribbon ) {
  8511. geometry = object.geometry;
  8512. if( ! geometry.__webglVertexBuffer ) {
  8513. createRibbonBuffers( geometry );
  8514. initRibbonBuffers( geometry );
  8515. geometry.__dirtyVertices = true;
  8516. geometry.__dirtyColors = true;
  8517. }
  8518. } else if ( object instanceof THREE.Line ) {
  8519. geometry = object.geometry;
  8520. if( ! geometry.__webglVertexBuffer ) {
  8521. createLineBuffers( geometry );
  8522. initLineBuffers( geometry, object );
  8523. geometry.__dirtyVertices = true;
  8524. geometry.__dirtyColors = true;
  8525. }
  8526. } else if ( object instanceof THREE.ParticleSystem ) {
  8527. geometry = object.geometry;
  8528. if ( ! geometry.__webglVertexBuffer ) {
  8529. createParticleBuffers( geometry );
  8530. initParticleBuffers( geometry, object );
  8531. geometry.__dirtyVertices = true;
  8532. geometry.__dirtyColors = true;
  8533. }
  8534. }
  8535. }
  8536. if ( ! object.__webglActive ) {
  8537. if ( object instanceof THREE.Mesh ) {
  8538. geometry = object.geometry;
  8539. if ( geometry instanceof THREE.BufferGeometry ) {
  8540. addBuffer( scene.__webglObjects, geometry, object );
  8541. } else {
  8542. for ( g in geometry.geometryGroups ) {
  8543. geometryGroup = geometry.geometryGroups[ g ];
  8544. addBuffer( scene.__webglObjects, geometryGroup, object );
  8545. }
  8546. }
  8547. } else if ( object instanceof THREE.Ribbon ||
  8548. object instanceof THREE.Line ||
  8549. object instanceof THREE.ParticleSystem ) {
  8550. geometry = object.geometry;
  8551. addBuffer( scene.__webglObjects, geometry, object );
  8552. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8553. addBufferImmediate( scene.__webglObjectsImmediate, object );
  8554. } else if ( object instanceof THREE.Sprite ) {
  8555. scene.__webglSprites.push( object );
  8556. } else if ( object instanceof THREE.LensFlare ) {
  8557. scene.__webglFlares.push( object );
  8558. }
  8559. object.__webglActive = true;
  8560. }
  8561. };
  8562. function addBuffer ( objlist, buffer, object ) {
  8563. objlist.push(
  8564. {
  8565. buffer: buffer,
  8566. object: object,
  8567. opaque: null,
  8568. transparent: null
  8569. }
  8570. );
  8571. };
  8572. function addBufferImmediate ( objlist, object ) {
  8573. objlist.push(
  8574. {
  8575. object: object,
  8576. opaque: null,
  8577. transparent: null
  8578. }
  8579. );
  8580. };
  8581. // Objects updates
  8582. function updateObject ( object ) {
  8583. var geometry = object.geometry,
  8584. geometryGroup, customAttributesDirty, material;
  8585. if ( object instanceof THREE.Mesh ) {
  8586. if ( geometry instanceof THREE.BufferGeometry ) {
  8587. /*
  8588. if ( geometry.__dirtyVertices || geometry.__dirtyElements ||
  8589. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8590. geometry.__dirtyColors ) {
  8591. // TODO
  8592. // set buffers from typed arrays
  8593. }
  8594. */
  8595. geometry.__dirtyVertices = false;
  8596. geometry.__dirtyElements = false;
  8597. geometry.__dirtyUvs = false;
  8598. geometry.__dirtyNormals = false;
  8599. geometry.__dirtyColors = false;
  8600. } else {
  8601. // check all geometry groups
  8602. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  8603. geometryGroup = geometry.geometryGroupsList[ i ];
  8604. material = getBufferMaterial( object, geometryGroup );
  8605. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8606. if ( geometry.__dirtyVertices || geometry.__dirtyMorphTargets || geometry.__dirtyElements ||
  8607. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8608. geometry.__dirtyColors || geometry.__dirtyTangents || customAttributesDirty ) {
  8609. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  8610. }
  8611. }
  8612. geometry.__dirtyVertices = false;
  8613. geometry.__dirtyMorphTargets = false;
  8614. geometry.__dirtyElements = false;
  8615. geometry.__dirtyUvs = false;
  8616. geometry.__dirtyNormals = false;
  8617. geometry.__dirtyColors = false;
  8618. geometry.__dirtyTangents = false;
  8619. material.attributes && clearCustomAttributes( material );
  8620. }
  8621. } else if ( object instanceof THREE.Ribbon ) {
  8622. if ( geometry.__dirtyVertices || geometry.__dirtyColors ) {
  8623. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  8624. }
  8625. geometry.__dirtyVertices = false;
  8626. geometry.__dirtyColors = false;
  8627. } else if ( object instanceof THREE.Line ) {
  8628. material = getBufferMaterial( object, geometryGroup );
  8629. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8630. if ( geometry.__dirtyVertices || geometry.__dirtyColors || customAttributesDirty ) {
  8631. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  8632. }
  8633. geometry.__dirtyVertices = false;
  8634. geometry.__dirtyColors = false;
  8635. material.attributes && clearCustomAttributes( material );
  8636. } else if ( object instanceof THREE.ParticleSystem ) {
  8637. material = getBufferMaterial( object, geometryGroup );
  8638. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8639. if ( geometry.__dirtyVertices || geometry.__dirtyColors || object.sortParticles || customAttributesDirty ) {
  8640. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  8641. }
  8642. geometry.__dirtyVertices = false;
  8643. geometry.__dirtyColors = false;
  8644. material.attributes && clearCustomAttributes( material );
  8645. }
  8646. };
  8647. // Objects updates - custom attributes check
  8648. function areCustomAttributesDirty ( material ) {
  8649. for ( var a in material.attributes ) {
  8650. if ( material.attributes[ a ].needsUpdate ) return true;
  8651. }
  8652. return false;
  8653. };
  8654. function clearCustomAttributes ( material ) {
  8655. for ( var a in material.attributes ) {
  8656. material.attributes[ a ].needsUpdate = false;
  8657. }
  8658. };
  8659. // Objects removal
  8660. function removeObject ( object, scene ) {
  8661. if ( object instanceof THREE.Mesh ||
  8662. object instanceof THREE.ParticleSystem ||
  8663. object instanceof THREE.Ribbon ||
  8664. object instanceof THREE.Line ) {
  8665. removeInstances( scene.__webglObjects, object );
  8666. } else if ( object instanceof THREE.Sprite ) {
  8667. removeInstancesDirect( scene.__webglSprites, object );
  8668. } else if ( object instanceof THREE.LensFlare ) {
  8669. removeInstancesDirect( scene.__webglFlares, object );
  8670. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8671. removeInstances( scene.__webglObjectsImmediate, object );
  8672. }
  8673. object.__webglActive = false;
  8674. };
  8675. function removeInstances ( objlist, object ) {
  8676. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8677. if ( objlist[ o ].object === object ) {
  8678. objlist.splice( o, 1 );
  8679. }
  8680. }
  8681. };
  8682. function removeInstancesDirect ( objlist, object ) {
  8683. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8684. if ( objlist[ o ] === object ) {
  8685. objlist.splice( o, 1 );
  8686. }
  8687. }
  8688. };
  8689. // Materials
  8690. this.initMaterial = function ( material, lights, fog, object ) {
  8691. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  8692. if ( material instanceof THREE.MeshDepthMaterial ) {
  8693. shaderID = 'depth';
  8694. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8695. shaderID = 'normal';
  8696. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8697. shaderID = 'basic';
  8698. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8699. shaderID = 'lambert';
  8700. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8701. shaderID = 'phong';
  8702. } else if ( material instanceof THREE.LineBasicMaterial ) {
  8703. shaderID = 'basic';
  8704. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8705. shaderID = 'particle_basic';
  8706. }
  8707. if ( shaderID ) {
  8708. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  8709. }
  8710. // heuristics to create shader parameters according to lights in the scene
  8711. // (not to blow over maxLights budget)
  8712. maxLightCount = allocateLights( lights );
  8713. maxShadows = allocateShadows( lights );
  8714. maxBones = allocateBones( object );
  8715. parameters = {
  8716. map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap,
  8717. vertexColors: material.vertexColors,
  8718. fog: fog, useFog: material.fog,
  8719. sizeAttenuation: material.sizeAttenuation,
  8720. skinning: material.skinning,
  8721. morphTargets: material.morphTargets,
  8722. morphNormals: material.morphNormals,
  8723. maxMorphTargets: this.maxMorphTargets,
  8724. maxMorphNormals: this.maxMorphNormals,
  8725. maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point,
  8726. maxBones: maxBones,
  8727. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  8728. shadowMapSoft: this.shadowMapSoft,
  8729. shadowMapDebug: this.shadowMapDebug,
  8730. shadowMapCascade: this.shadowMapCascade,
  8731. maxShadows: maxShadows,
  8732. alphaTest: material.alphaTest,
  8733. metal: material.metal,
  8734. perPixel: material.perPixel,
  8735. wrapAround: material.wrapAround,
  8736. doubleSided: object && object.doubleSided
  8737. };
  8738. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  8739. var attributes = material.program.attributes;
  8740. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  8741. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  8742. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  8743. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  8744. if ( material.skinning &&
  8745. attributes.skinVertexA >=0 && attributes.skinVertexB >= 0 &&
  8746. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8747. _gl.enableVertexAttribArray( attributes.skinVertexA );
  8748. _gl.enableVertexAttribArray( attributes.skinVertexB );
  8749. _gl.enableVertexAttribArray( attributes.skinIndex );
  8750. _gl.enableVertexAttribArray( attributes.skinWeight );
  8751. }
  8752. if ( material.attributes ) {
  8753. for ( a in material.attributes ) {
  8754. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  8755. }
  8756. }
  8757. if ( material.morphTargets ) {
  8758. material.numSupportedMorphTargets = 0;
  8759. var id, base = "morphTarget";
  8760. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  8761. id = base + i;
  8762. if ( attributes[ id ] >= 0 ) {
  8763. _gl.enableVertexAttribArray( attributes[ id ] );
  8764. material.numSupportedMorphTargets ++;
  8765. }
  8766. }
  8767. }
  8768. if ( material.morphNormals ) {
  8769. material.numSupportedMorphNormals = 0;
  8770. var id, base = "morphNormal";
  8771. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  8772. id = base + i;
  8773. if ( attributes[ id ] >= 0 ) {
  8774. _gl.enableVertexAttribArray( attributes[ id ] );
  8775. material.numSupportedMorphNormals ++;
  8776. }
  8777. }
  8778. }
  8779. material.uniformsList = [];
  8780. for ( u in material.uniforms ) {
  8781. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  8782. }
  8783. };
  8784. function setMaterialShaders( material, shaders ) {
  8785. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  8786. material.vertexShader = shaders.vertexShader;
  8787. material.fragmentShader = shaders.fragmentShader;
  8788. };
  8789. function setProgram( camera, lights, fog, material, object ) {
  8790. if ( ! material.program || material.needsUpdate ) {
  8791. _this.initMaterial( material, lights, fog, object );
  8792. material.needsUpdate = false;
  8793. }
  8794. if ( material.morphTargets ) {
  8795. if ( ! object.__webglMorphTargetInfluences ) {
  8796. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  8797. for ( var i = 0, il = _this.maxMorphTargets; i < il; i ++ ) {
  8798. object.__webglMorphTargetInfluences[ i ] = 0;
  8799. }
  8800. }
  8801. }
  8802. var refreshMaterial = false;
  8803. var program = material.program,
  8804. p_uniforms = program.uniforms,
  8805. m_uniforms = material.uniforms;
  8806. if ( program !== _currentProgram ) {
  8807. _gl.useProgram( program );
  8808. _currentProgram = program;
  8809. refreshMaterial = true;
  8810. }
  8811. if ( material.id !== _currentMaterialId ) {
  8812. _currentMaterialId = material.id;
  8813. refreshMaterial = true;
  8814. }
  8815. if ( refreshMaterial || camera !== _currentCamera ) {
  8816. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  8817. if ( camera !== _currentCamera ) _currentCamera = camera;
  8818. }
  8819. if ( refreshMaterial ) {
  8820. // refresh uniforms common to several materials
  8821. if ( fog && material.fog ) {
  8822. refreshUniformsFog( m_uniforms, fog );
  8823. }
  8824. if ( material instanceof THREE.MeshPhongMaterial ||
  8825. material instanceof THREE.MeshLambertMaterial ||
  8826. material.lights ) {
  8827. setupLights( program, lights );
  8828. refreshUniformsLights( m_uniforms, _lights );
  8829. }
  8830. if ( material instanceof THREE.MeshBasicMaterial ||
  8831. material instanceof THREE.MeshLambertMaterial ||
  8832. material instanceof THREE.MeshPhongMaterial ) {
  8833. refreshUniformsCommon( m_uniforms, material );
  8834. }
  8835. // refresh single material specific uniforms
  8836. if ( material instanceof THREE.LineBasicMaterial ) {
  8837. refreshUniformsLine( m_uniforms, material );
  8838. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8839. refreshUniformsParticle( m_uniforms, material );
  8840. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8841. refreshUniformsPhong( m_uniforms, material );
  8842. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8843. refreshUniformsLambert( m_uniforms, material );
  8844. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8845. m_uniforms.mNear.value = camera.near;
  8846. m_uniforms.mFar.value = camera.far;
  8847. m_uniforms.opacity.value = material.opacity;
  8848. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8849. m_uniforms.opacity.value = material.opacity;
  8850. }
  8851. if ( object.receiveShadow && ! material._shadowPass ) {
  8852. refreshUniformsShadow( m_uniforms, lights );
  8853. }
  8854. // load common uniforms
  8855. loadUniformsGeneric( program, material.uniformsList );
  8856. // load material specific uniforms
  8857. // (shader material also gets them for the sake of genericity)
  8858. if ( material instanceof THREE.ShaderMaterial ||
  8859. material instanceof THREE.MeshPhongMaterial ||
  8860. material.envMap ) {
  8861. if ( p_uniforms.cameraPosition !== null ) {
  8862. var position = camera.matrixWorld.getPosition();
  8863. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  8864. }
  8865. }
  8866. if ( material instanceof THREE.MeshPhongMaterial ||
  8867. material instanceof THREE.MeshLambertMaterial ||
  8868. material instanceof THREE.ShaderMaterial ||
  8869. material.skinning ) {
  8870. if ( p_uniforms.viewMatrix !== null ) {
  8871. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  8872. }
  8873. }
  8874. if ( material.skinning ) {
  8875. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  8876. }
  8877. }
  8878. loadUniformsMatrices( p_uniforms, object );
  8879. if ( material instanceof THREE.ShaderMaterial ||
  8880. material.envMap ||
  8881. material.skinning ||
  8882. object.receiveShadow ) {
  8883. if ( p_uniforms.objectMatrix !== null ) {
  8884. _gl.uniformMatrix4fv( p_uniforms.objectMatrix, false, object.matrixWorld.elements );
  8885. }
  8886. }
  8887. return program;
  8888. };
  8889. // Uniforms (refresh uniforms objects)
  8890. function refreshUniformsCommon ( uniforms, material ) {
  8891. uniforms.opacity.value = material.opacity;
  8892. if ( _this.gammaInput ) {
  8893. uniforms.diffuse.value.copyGammaToLinear( material.color );
  8894. } else {
  8895. uniforms.diffuse.value = material.color;
  8896. }
  8897. uniforms.map.texture = material.map;
  8898. if ( material.map ) {
  8899. uniforms.offsetRepeat.value.set( material.map.offset.x, material.map.offset.y, material.map.repeat.x, material.map.repeat.y );
  8900. }
  8901. uniforms.lightMap.texture = material.lightMap;
  8902. uniforms.envMap.texture = material.envMap;
  8903. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  8904. if ( _this.gammaInput ) {
  8905. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  8906. uniforms.reflectivity.value = material.reflectivity;
  8907. } else {
  8908. uniforms.reflectivity.value = material.reflectivity;
  8909. }
  8910. uniforms.refractionRatio.value = material.refractionRatio;
  8911. uniforms.combine.value = material.combine;
  8912. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  8913. };
  8914. function refreshUniformsLine ( uniforms, material ) {
  8915. uniforms.diffuse.value = material.color;
  8916. uniforms.opacity.value = material.opacity;
  8917. };
  8918. function refreshUniformsParticle ( uniforms, material ) {
  8919. uniforms.psColor.value = material.color;
  8920. uniforms.opacity.value = material.opacity;
  8921. uniforms.size.value = material.size;
  8922. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  8923. uniforms.map.texture = material.map;
  8924. };
  8925. function refreshUniformsFog ( uniforms, fog ) {
  8926. uniforms.fogColor.value = fog.color;
  8927. if ( fog instanceof THREE.Fog ) {
  8928. uniforms.fogNear.value = fog.near;
  8929. uniforms.fogFar.value = fog.far;
  8930. } else if ( fog instanceof THREE.FogExp2 ) {
  8931. uniforms.fogDensity.value = fog.density;
  8932. }
  8933. };
  8934. function refreshUniformsPhong ( uniforms, material ) {
  8935. uniforms.shininess.value = material.shininess;
  8936. if ( _this.gammaInput ) {
  8937. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8938. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8939. uniforms.specular.value.copyGammaToLinear( material.specular );
  8940. } else {
  8941. uniforms.ambient.value = material.ambient;
  8942. uniforms.emissive.value = material.emissive;
  8943. uniforms.specular.value = material.specular;
  8944. }
  8945. if ( material.wrapAround ) {
  8946. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8947. }
  8948. };
  8949. function refreshUniformsLambert ( uniforms, material ) {
  8950. if ( _this.gammaInput ) {
  8951. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8952. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8953. } else {
  8954. uniforms.ambient.value = material.ambient;
  8955. uniforms.emissive.value = material.emissive;
  8956. }
  8957. if ( material.wrapAround ) {
  8958. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8959. }
  8960. };
  8961. function refreshUniformsLights ( uniforms, lights ) {
  8962. uniforms.ambientLightColor.value = lights.ambient;
  8963. uniforms.directionalLightColor.value = lights.directional.colors;
  8964. uniforms.directionalLightDirection.value = lights.directional.positions;
  8965. uniforms.pointLightColor.value = lights.point.colors;
  8966. uniforms.pointLightPosition.value = lights.point.positions;
  8967. uniforms.pointLightDistance.value = lights.point.distances;
  8968. };
  8969. function refreshUniformsShadow ( uniforms, lights ) {
  8970. if ( uniforms.shadowMatrix ) {
  8971. var j = 0;
  8972. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  8973. var light = lights[ i ];
  8974. if ( ! light.castShadow ) continue;
  8975. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  8976. uniforms.shadowMap.texture[ j ] = light.shadowMap;
  8977. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  8978. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  8979. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  8980. uniforms.shadowBias.value[ j ] = light.shadowBias;
  8981. j ++;
  8982. }
  8983. }
  8984. }
  8985. };
  8986. // Uniforms (load to GPU)
  8987. function loadUniformsMatrices ( uniforms, object ) {
  8988. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  8989. if ( uniforms.normalMatrix ) {
  8990. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrixArray );
  8991. }
  8992. };
  8993. function loadUniformsGeneric ( program, uniforms ) {
  8994. var uniform, value, type, location, texture, i, il, j, jl, offset;
  8995. for( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  8996. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  8997. if ( !location ) continue;
  8998. uniform = uniforms[ j ][ 0 ];
  8999. type = uniform.type;
  9000. value = uniform.value;
  9001. // single integer
  9002. if( type === "i" ) {
  9003. _gl.uniform1i( location, value );
  9004. // single float
  9005. } else if( type === "f" ) {
  9006. _gl.uniform1f( location, value );
  9007. // single THREE.Vector2
  9008. } else if( type === "v2" ) {
  9009. _gl.uniform2f( location, value.x, value.y );
  9010. // single THREE.Vector3
  9011. } else if( type === "v3" ) {
  9012. _gl.uniform3f( location, value.x, value.y, value.z );
  9013. // single THREE.Vector4
  9014. } else if( type === "v4" ) {
  9015. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  9016. // single THREE.Color
  9017. } else if( type === "c" ) {
  9018. _gl.uniform3f( location, value.r, value.g, value.b );
  9019. // flat array of floats (JS or typed array)
  9020. } else if( type === "fv1" ) {
  9021. _gl.uniform1fv( location, value );
  9022. // flat array of floats with 3 x N size (JS or typed array)
  9023. } else if( type === "fv" ) {
  9024. _gl.uniform3fv( location, value );
  9025. // array of THREE.Vector2
  9026. } else if( type === "v2v" ) {
  9027. if ( ! uniform._array ) {
  9028. uniform._array = new Float32Array( 2 * value.length );
  9029. }
  9030. for ( i = 0, il = value.length; i < il; i ++ ) {
  9031. offset = i * 2;
  9032. uniform._array[ offset ] = value[ i ].x;
  9033. uniform._array[ offset + 1 ] = value[ i ].y;
  9034. }
  9035. _gl.uniform2fv( location, uniform._array );
  9036. // array of THREE.Vector3
  9037. } else if( type === "v3v" ) {
  9038. if ( ! uniform._array ) {
  9039. uniform._array = new Float32Array( 3 * value.length );
  9040. }
  9041. for ( i = 0, il = value.length; i < il; i ++ ) {
  9042. offset = i * 3;
  9043. uniform._array[ offset ] = value[ i ].x;
  9044. uniform._array[ offset + 1 ] = value[ i ].y;
  9045. uniform._array[ offset + 2 ] = value[ i ].z;
  9046. }
  9047. _gl.uniform3fv( location, uniform._array );
  9048. // array of THREE.Vector4
  9049. } else if( type == "v4v" ) {
  9050. if ( ! uniform._array ) {
  9051. uniform._array = new Float32Array( 4 * value.length );
  9052. }
  9053. for ( i = 0, il = value.length; i < il; i ++ ) {
  9054. offset = i * 4;
  9055. uniform._array[ offset ] = value[ i ].x;
  9056. uniform._array[ offset + 1 ] = value[ i ].y;
  9057. uniform._array[ offset + 2 ] = value[ i ].z;
  9058. uniform._array[ offset + 3 ] = value[ i ].w;
  9059. }
  9060. _gl.uniform4fv( location, uniform._array );
  9061. // single THREE.Matrix4
  9062. } else if( type === "m4" ) {
  9063. if ( ! uniform._array ) {
  9064. uniform._array = new Float32Array( 16 );
  9065. }
  9066. value.flattenToArray( uniform._array );
  9067. _gl.uniformMatrix4fv( location, false, uniform._array );
  9068. // array of THREE.Matrix4
  9069. } else if( type === "m4v" ) {
  9070. if ( ! uniform._array ) {
  9071. uniform._array = new Float32Array( 16 * value.length );
  9072. }
  9073. for ( i = 0, il = value.length; i < il; i ++ ) {
  9074. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  9075. }
  9076. _gl.uniformMatrix4fv( location, false, uniform._array );
  9077. // single THREE.Texture (2d or cube)
  9078. } else if( type === "t" ) {
  9079. _gl.uniform1i( location, value );
  9080. texture = uniform.texture;
  9081. if ( !texture ) continue;
  9082. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  9083. setCubeTexture( texture, value );
  9084. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  9085. setCubeTextureDynamic( texture, value );
  9086. } else {
  9087. _this.setTexture( texture, value );
  9088. }
  9089. // array of THREE.Texture (2d)
  9090. } else if( type === "tv" ) {
  9091. if ( ! uniform._array ) {
  9092. uniform._array = [];
  9093. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9094. uniform._array[ i ] = value + i;
  9095. }
  9096. }
  9097. _gl.uniform1iv( location, uniform._array );
  9098. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9099. texture = uniform.texture[ i ];
  9100. if ( !texture ) continue;
  9101. _this.setTexture( texture, uniform._array[ i ] );
  9102. }
  9103. }
  9104. }
  9105. };
  9106. function setupMatrices ( object, camera ) {
  9107. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  9108. object._normalMatrix.getInverse( object._modelViewMatrix );
  9109. object._normalMatrix.transposeIntoArray( object._normalMatrixArray );
  9110. };
  9111. function setupLights ( program, lights ) {
  9112. var l, ll, light, n,
  9113. r = 0, g = 0, b = 0,
  9114. color, position, intensity, distance,
  9115. zlights = _lights,
  9116. dcolors = zlights.directional.colors,
  9117. dpositions = zlights.directional.positions,
  9118. pcolors = zlights.point.colors,
  9119. ppositions = zlights.point.positions,
  9120. pdistances = zlights.point.distances,
  9121. dlength = 0,
  9122. plength = 0,
  9123. doffset = 0,
  9124. poffset = 0;
  9125. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  9126. light = lights[ l ];
  9127. if ( light.onlyShadow ) continue;
  9128. color = light.color;
  9129. intensity = light.intensity;
  9130. distance = light.distance;
  9131. if ( light instanceof THREE.AmbientLight ) {
  9132. if ( _this.gammaInput ) {
  9133. r += color.r * color.r;
  9134. g += color.g * color.g;
  9135. b += color.b * color.b;
  9136. } else {
  9137. r += color.r;
  9138. g += color.g;
  9139. b += color.b;
  9140. }
  9141. } else if ( light instanceof THREE.DirectionalLight ) {
  9142. doffset = dlength * 3;
  9143. if ( _this.gammaInput ) {
  9144. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  9145. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  9146. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  9147. } else {
  9148. dcolors[ doffset ] = color.r * intensity;
  9149. dcolors[ doffset + 1 ] = color.g * intensity;
  9150. dcolors[ doffset + 2 ] = color.b * intensity;
  9151. }
  9152. _direction.copy( light.matrixWorld.getPosition() );
  9153. _direction.subSelf( light.target.matrixWorld.getPosition() );
  9154. _direction.normalize();
  9155. dpositions[ doffset ] = _direction.x;
  9156. dpositions[ doffset + 1 ] = _direction.y;
  9157. dpositions[ doffset + 2 ] = _direction.z;
  9158. dlength += 1;
  9159. } else if( light instanceof THREE.PointLight || light instanceof THREE.SpotLight ) {
  9160. poffset = plength * 3;
  9161. if ( _this.gammaInput ) {
  9162. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  9163. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  9164. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  9165. } else {
  9166. pcolors[ poffset ] = color.r * intensity;
  9167. pcolors[ poffset + 1 ] = color.g * intensity;
  9168. pcolors[ poffset + 2 ] = color.b * intensity;
  9169. }
  9170. position = light.matrixWorld.getPosition();
  9171. ppositions[ poffset ] = position.x;
  9172. ppositions[ poffset + 1 ] = position.y;
  9173. ppositions[ poffset + 2 ] = position.z;
  9174. pdistances[ plength ] = distance;
  9175. plength += 1;
  9176. }
  9177. }
  9178. // null eventual remains from removed lights
  9179. // (this is to avoid if in shader)
  9180. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  9181. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  9182. zlights.point.length = plength;
  9183. zlights.directional.length = dlength;
  9184. zlights.ambient[ 0 ] = r;
  9185. zlights.ambient[ 1 ] = g;
  9186. zlights.ambient[ 2 ] = b;
  9187. };
  9188. // GL state setting
  9189. this.setFaceCulling = function ( cullFace, frontFace ) {
  9190. if ( cullFace ) {
  9191. if ( !frontFace || frontFace === "ccw" ) {
  9192. _gl.frontFace( _gl.CCW );
  9193. } else {
  9194. _gl.frontFace( _gl.CW );
  9195. }
  9196. if( cullFace === "back" ) {
  9197. _gl.cullFace( _gl.BACK );
  9198. } else if( cullFace === "front" ) {
  9199. _gl.cullFace( _gl.FRONT );
  9200. } else {
  9201. _gl.cullFace( _gl.FRONT_AND_BACK );
  9202. }
  9203. _gl.enable( _gl.CULL_FACE );
  9204. } else {
  9205. _gl.disable( _gl.CULL_FACE );
  9206. }
  9207. };
  9208. this.setObjectFaces = function ( object ) {
  9209. if ( _oldDoubleSided !== object.doubleSided ) {
  9210. if( object.doubleSided ) {
  9211. _gl.disable( _gl.CULL_FACE );
  9212. } else {
  9213. _gl.enable( _gl.CULL_FACE );
  9214. }
  9215. _oldDoubleSided = object.doubleSided;
  9216. }
  9217. if ( _oldFlipSided !== object.flipSided ) {
  9218. if( object.flipSided ) {
  9219. _gl.frontFace( _gl.CW );
  9220. } else {
  9221. _gl.frontFace( _gl.CCW );
  9222. }
  9223. _oldFlipSided = object.flipSided;
  9224. }
  9225. };
  9226. this.setDepthTest = function ( depthTest ) {
  9227. if ( _oldDepthTest !== depthTest ) {
  9228. if ( depthTest ) {
  9229. _gl.enable( _gl.DEPTH_TEST );
  9230. } else {
  9231. _gl.disable( _gl.DEPTH_TEST );
  9232. }
  9233. _oldDepthTest = depthTest;
  9234. }
  9235. };
  9236. this.setDepthWrite = function ( depthWrite ) {
  9237. if ( _oldDepthWrite !== depthWrite ) {
  9238. _gl.depthMask( depthWrite );
  9239. _oldDepthWrite = depthWrite;
  9240. }
  9241. };
  9242. function setLineWidth ( width ) {
  9243. if ( width !== _oldLineWidth ) {
  9244. _gl.lineWidth( width );
  9245. _oldLineWidth = width;
  9246. }
  9247. };
  9248. function setPolygonOffset ( polygonoffset, factor, units ) {
  9249. if ( _oldPolygonOffset !== polygonoffset ) {
  9250. if ( polygonoffset ) {
  9251. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  9252. } else {
  9253. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  9254. }
  9255. _oldPolygonOffset = polygonoffset;
  9256. }
  9257. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  9258. _gl.polygonOffset( factor, units );
  9259. _oldPolygonOffsetFactor = factor;
  9260. _oldPolygonOffsetUnits = units;
  9261. }
  9262. };
  9263. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  9264. if ( blending !== _oldBlending ) {
  9265. switch ( blending ) {
  9266. case THREE.NoBlending:
  9267. _gl.disable( _gl.BLEND );
  9268. break;
  9269. case THREE.AdditiveBlending:
  9270. _gl.enable( _gl.BLEND );
  9271. _gl.blendEquation( _gl.FUNC_ADD );
  9272. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  9273. break;
  9274. case THREE.SubtractiveBlending:
  9275. // TODO: Find blendFuncSeparate() combination
  9276. _gl.enable( _gl.BLEND );
  9277. _gl.blendEquation( _gl.FUNC_ADD );
  9278. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  9279. break;
  9280. case THREE.MultiplyBlending:
  9281. // TODO: Find blendFuncSeparate() combination
  9282. _gl.enable( _gl.BLEND );
  9283. _gl.blendEquation( _gl.FUNC_ADD );
  9284. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  9285. break;
  9286. case THREE.CustomBlending:
  9287. _gl.enable( _gl.BLEND );
  9288. break;
  9289. default:
  9290. _gl.enable( _gl.BLEND );
  9291. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  9292. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  9293. break;
  9294. }
  9295. _oldBlending = blending;
  9296. }
  9297. if ( blending === THREE.CustomBlending ) {
  9298. if ( blendEquation !== _oldBlendEquation ) {
  9299. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  9300. _oldBlendEquation = blendEquation;
  9301. }
  9302. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  9303. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  9304. _oldBlendSrc = blendSrc;
  9305. _oldBlendDst = blendDst;
  9306. }
  9307. } else {
  9308. _oldBlendEquation = null;
  9309. _oldBlendSrc = null;
  9310. _oldBlendDst = null;
  9311. }
  9312. };
  9313. // Shaders
  9314. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  9315. var p, pl, program, code;
  9316. var chunks = [];
  9317. // Generate code
  9318. if ( shaderID ) {
  9319. chunks.push( shaderID );
  9320. } else {
  9321. chunks.push( fragmentShader );
  9322. chunks.push( vertexShader );
  9323. }
  9324. for ( p in parameters ) {
  9325. chunks.push( p );
  9326. chunks.push( parameters[ p ] );
  9327. }
  9328. code = chunks.join();
  9329. // Check if code has been already compiled
  9330. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  9331. if ( _programs[ p ].code === code ) {
  9332. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  9333. return _programs[ p ].program;
  9334. }
  9335. }
  9336. //console.log( "building new program " );
  9337. //
  9338. program = _gl.createProgram();
  9339. var prefix_vertex = [
  9340. "precision " + _precision + " float;",
  9341. ( _maxVertexTextures > 0 ) ? "#define VERTEX_TEXTURES" : "",
  9342. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9343. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9344. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9345. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9346. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9347. "#define MAX_SHADOWS " + parameters.maxShadows,
  9348. "#define MAX_BONES " + parameters.maxBones,
  9349. parameters.map ? "#define USE_MAP" : "",
  9350. parameters.envMap ? "#define USE_ENVMAP" : "",
  9351. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9352. parameters.vertexColors ? "#define USE_COLOR" : "",
  9353. parameters.skinning ? "#define USE_SKINNING" : "",
  9354. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  9355. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  9356. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9357. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9358. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9359. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9360. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9361. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9362. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9363. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  9364. "uniform mat4 objectMatrix;",
  9365. "uniform mat4 modelViewMatrix;",
  9366. "uniform mat4 projectionMatrix;",
  9367. "uniform mat4 viewMatrix;",
  9368. "uniform mat3 normalMatrix;",
  9369. "uniform vec3 cameraPosition;",
  9370. "attribute vec3 position;",
  9371. "attribute vec3 normal;",
  9372. "attribute vec2 uv;",
  9373. "attribute vec2 uv2;",
  9374. "#ifdef USE_COLOR",
  9375. "attribute vec3 color;",
  9376. "#endif",
  9377. "#ifdef USE_MORPHTARGETS",
  9378. "attribute vec3 morphTarget0;",
  9379. "attribute vec3 morphTarget1;",
  9380. "attribute vec3 morphTarget2;",
  9381. "attribute vec3 morphTarget3;",
  9382. "#ifdef USE_MORPHNORMALS",
  9383. "attribute vec3 morphNormal0;",
  9384. "attribute vec3 morphNormal1;",
  9385. "attribute vec3 morphNormal2;",
  9386. "attribute vec3 morphNormal3;",
  9387. "#else",
  9388. "attribute vec3 morphTarget4;",
  9389. "attribute vec3 morphTarget5;",
  9390. "attribute vec3 morphTarget6;",
  9391. "attribute vec3 morphTarget7;",
  9392. "#endif",
  9393. "#endif",
  9394. "#ifdef USE_SKINNING",
  9395. "attribute vec4 skinVertexA;",
  9396. "attribute vec4 skinVertexB;",
  9397. "attribute vec4 skinIndex;",
  9398. "attribute vec4 skinWeight;",
  9399. "#endif",
  9400. ""
  9401. ].join("\n");
  9402. var prefix_fragment = [
  9403. "precision " + _precision + " float;",
  9404. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9405. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9406. "#define MAX_SHADOWS " + parameters.maxShadows,
  9407. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  9408. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9409. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9410. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9411. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  9412. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  9413. parameters.map ? "#define USE_MAP" : "",
  9414. parameters.envMap ? "#define USE_ENVMAP" : "",
  9415. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9416. parameters.vertexColors ? "#define USE_COLOR" : "",
  9417. parameters.metal ? "#define METAL" : "",
  9418. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9419. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9420. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9421. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9422. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9423. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9424. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9425. "uniform mat4 viewMatrix;",
  9426. "uniform vec3 cameraPosition;",
  9427. ""
  9428. ].join("\n");
  9429. _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragmentShader ) );
  9430. _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertexShader ) );
  9431. _gl.linkProgram( program );
  9432. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  9433. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  9434. }
  9435. //console.log( prefix_fragment + fragmentShader );
  9436. //console.log( prefix_vertex + vertexShader );
  9437. program.uniforms = {};
  9438. program.attributes = {};
  9439. var identifiers, u, a, i;
  9440. // cache uniform locations
  9441. identifiers = [
  9442. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition',
  9443. 'boneGlobalMatrices', 'morphTargetInfluences'
  9444. ];
  9445. for ( u in uniforms ) {
  9446. identifiers.push( u );
  9447. }
  9448. cacheUniformLocations( program, identifiers );
  9449. // cache attributes locations
  9450. identifiers = [
  9451. "position", "normal", "uv", "uv2", "tangent", "color",
  9452. "skinVertexA", "skinVertexB", "skinIndex", "skinWeight"
  9453. ];
  9454. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  9455. identifiers.push( "morphTarget" + i );
  9456. }
  9457. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  9458. identifiers.push( "morphNormal" + i );
  9459. }
  9460. for ( a in attributes ) {
  9461. identifiers.push( a );
  9462. }
  9463. cacheAttributeLocations( program, identifiers );
  9464. program.id = _programs.length;
  9465. _programs.push( { program: program, code: code } );
  9466. _this.info.memory.programs = _programs.length;
  9467. return program;
  9468. };
  9469. // Shader parameters cache
  9470. function cacheUniformLocations ( program, identifiers ) {
  9471. var i, l, id;
  9472. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9473. id = identifiers[ i ];
  9474. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  9475. }
  9476. };
  9477. function cacheAttributeLocations ( program, identifiers ) {
  9478. var i, l, id;
  9479. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9480. id = identifiers[ i ];
  9481. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  9482. }
  9483. };
  9484. function getShader ( type, string ) {
  9485. var shader;
  9486. if ( type === "fragment" ) {
  9487. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  9488. } else if ( type === "vertex" ) {
  9489. shader = _gl.createShader( _gl.VERTEX_SHADER );
  9490. }
  9491. _gl.shaderSource( shader, string );
  9492. _gl.compileShader( shader );
  9493. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  9494. console.error( _gl.getShaderInfoLog( shader ) );
  9495. console.error( string );
  9496. return null;
  9497. }
  9498. return shader;
  9499. };
  9500. // Textures
  9501. function isPowerOfTwo ( value ) {
  9502. return ( value & ( value - 1 ) ) === 0;
  9503. };
  9504. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  9505. if ( isImagePowerOfTwo ) {
  9506. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  9507. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  9508. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  9509. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  9510. } else {
  9511. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  9512. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  9513. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  9514. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  9515. }
  9516. };
  9517. this.setTexture = function ( texture, slot ) {
  9518. if ( texture.needsUpdate ) {
  9519. if ( ! texture.__webglInit ) {
  9520. texture.__webglInit = true;
  9521. texture.__webglTexture = _gl.createTexture();
  9522. _this.info.memory.textures ++;
  9523. }
  9524. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9525. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9526. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  9527. var image = texture.image,
  9528. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9529. glFormat = paramThreeToGL( texture.format ),
  9530. glType = paramThreeToGL( texture.type );
  9531. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  9532. if ( texture instanceof THREE.DataTexture ) {
  9533. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  9534. } else {
  9535. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  9536. }
  9537. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9538. texture.needsUpdate = false;
  9539. if ( texture.onUpdate ) texture.onUpdate();
  9540. } else {
  9541. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9542. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9543. }
  9544. };
  9545. function clampToMaxSize ( image, maxSize ) {
  9546. if ( image.width <= maxSize && image.height <= maxSize ) {
  9547. return image;
  9548. }
  9549. // Warning: Scaling through the canvas will only work with images that use
  9550. // premultiplied alpha.
  9551. var maxDimension = Math.max( image.width, image.height );
  9552. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  9553. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  9554. var canvas = document.createElement( 'canvas' );
  9555. canvas.width = newWidth;
  9556. canvas.height = newHeight;
  9557. var ctx = canvas.getContext( "2d" );
  9558. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  9559. return canvas;
  9560. }
  9561. function setCubeTexture ( texture, slot ) {
  9562. if ( texture.image.length === 6 ) {
  9563. if ( texture.needsUpdate ) {
  9564. if ( ! texture.image.__webglTextureCube ) {
  9565. texture.image.__webglTextureCube = _gl.createTexture();
  9566. }
  9567. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9568. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9569. var cubeImage = [];
  9570. for ( var i = 0; i < 6; i ++ ) {
  9571. if ( _this.autoScaleCubemaps ) {
  9572. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  9573. } else {
  9574. cubeImage[ i ] = texture.image[ i ];
  9575. }
  9576. }
  9577. var image = cubeImage[ 0 ],
  9578. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9579. glFormat = paramThreeToGL( texture.format ),
  9580. glType = paramThreeToGL( texture.type );
  9581. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  9582. for ( var i = 0; i < 6; i ++ ) {
  9583. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  9584. }
  9585. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9586. texture.needsUpdate = false;
  9587. if ( texture.onUpdate ) texture.onUpdate();
  9588. } else {
  9589. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9590. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9591. }
  9592. }
  9593. };
  9594. function setCubeTextureDynamic ( texture, slot ) {
  9595. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9596. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  9597. };
  9598. // Render targets
  9599. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  9600. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9601. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  9602. };
  9603. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  9604. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  9605. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  9606. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  9607. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9608. /* For some reason this is not working. Defaulting to RGBA4.
  9609. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9610. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  9611. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9612. */
  9613. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9614. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  9615. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9616. } else {
  9617. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  9618. }
  9619. };
  9620. this.setRenderTarget = function ( renderTarget ) {
  9621. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  9622. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  9623. if( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  9624. if( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  9625. renderTarget.__webglTexture = _gl.createTexture();
  9626. // Setup texture, create render and frame buffers
  9627. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  9628. glFormat = paramThreeToGL( renderTarget.format ),
  9629. glType = paramThreeToGL( renderTarget.type );
  9630. if ( isCube ) {
  9631. renderTarget.__webglFramebuffer = [];
  9632. renderTarget.__webglRenderbuffer = [];
  9633. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9634. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  9635. for ( var i = 0; i < 6; i ++ ) {
  9636. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  9637. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  9638. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9639. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  9640. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  9641. }
  9642. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9643. } else {
  9644. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  9645. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  9646. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9647. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  9648. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9649. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  9650. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  9651. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9652. }
  9653. // Release everything
  9654. if ( isCube ) {
  9655. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9656. } else {
  9657. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9658. }
  9659. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  9660. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  9661. }
  9662. var framebuffer, width, height, vx, vy;
  9663. if ( renderTarget ) {
  9664. if ( isCube ) {
  9665. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  9666. } else {
  9667. framebuffer = renderTarget.__webglFramebuffer;
  9668. }
  9669. width = renderTarget.width;
  9670. height = renderTarget.height;
  9671. vx = 0;
  9672. vy = 0;
  9673. } else {
  9674. framebuffer = null;
  9675. width = _viewportWidth;
  9676. height = _viewportHeight;
  9677. vx = _viewportX;
  9678. vy = _viewportY;
  9679. }
  9680. if ( framebuffer !== _currentFramebuffer ) {
  9681. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9682. _gl.viewport( vx, vy, width, height );
  9683. _currentFramebuffer = framebuffer;
  9684. }
  9685. _currentWidth = width;
  9686. _currentHeight = height;
  9687. };
  9688. function updateRenderTargetMipmap ( renderTarget ) {
  9689. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9690. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9691. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9692. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9693. } else {
  9694. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9695. _gl.generateMipmap( _gl.TEXTURE_2D );
  9696. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9697. }
  9698. };
  9699. // Fallback filters for non-power-of-2 textures
  9700. function filterFallback ( f ) {
  9701. switch ( f ) {
  9702. case THREE.NearestFilter:
  9703. case THREE.NearestMipMapNearestFilter:
  9704. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST; break;
  9705. case THREE.LinearFilter:
  9706. case THREE.LinearMipMapNearestFilter:
  9707. case THREE.LinearMipMapLinearFilter:
  9708. default:
  9709. return _gl.LINEAR; break;
  9710. }
  9711. };
  9712. // Map three.js constants to WebGL constants
  9713. function paramThreeToGL ( p ) {
  9714. switch ( p ) {
  9715. case THREE.RepeatWrapping: return _gl.REPEAT; break;
  9716. case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break;
  9717. case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break;
  9718. case THREE.NearestFilter: return _gl.NEAREST; break;
  9719. case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break;
  9720. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break;
  9721. case THREE.LinearFilter: return _gl.LINEAR; break;
  9722. case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break;
  9723. case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break;
  9724. case THREE.ByteType: return _gl.BYTE; break;
  9725. case THREE.UnsignedByteType: return _gl.UNSIGNED_BYTE; break;
  9726. case THREE.ShortType: return _gl.SHORT; break;
  9727. case THREE.UnsignedShortType: return _gl.UNSIGNED_SHORT; break;
  9728. case THREE.IntType: return _gl.INT; break;
  9729. case THREE.UnsignedIntType: return _gl.UNSIGNED_INT; break;
  9730. case THREE.FloatType: return _gl.FLOAT; break;
  9731. case THREE.AlphaFormat: return _gl.ALPHA; break;
  9732. case THREE.RGBFormat: return _gl.RGB; break;
  9733. case THREE.RGBAFormat: return _gl.RGBA; break;
  9734. case THREE.LuminanceFormat: return _gl.LUMINANCE; break;
  9735. case THREE.LuminanceAlphaFormat: return _gl.LUMINANCE_ALPHA; break;
  9736. case THREE.AddEquation: return _gl.FUNC_ADD; break;
  9737. case THREE.SubtractEquation: return _gl.FUNC_SUBTRACT; break;
  9738. case THREE.ReverseSubtractEquation: return _gl.FUNC_REVERSE_SUBTRACT; break;
  9739. case THREE.ZeroFactor: return _gl.ZERO; break;
  9740. case THREE.OneFactor: return _gl.ONE; break;
  9741. case THREE.SrcColorFactor: return _gl.SRC_COLOR; break;
  9742. case THREE.OneMinusSrcColorFactor: return _gl.ONE_MINUS_SRC_COLOR; break;
  9743. case THREE.SrcAlphaFactor: return _gl.SRC_ALPHA; break;
  9744. case THREE.OneMinusSrcAlphaFactor: return _gl.ONE_MINUS_SRC_ALPHA; break;
  9745. case THREE.DstAlphaFactor: return _gl.DST_ALPHA; break;
  9746. case THREE.OneMinusDstAlphaFactor: return _gl.ONE_MINUS_DST_ALPHA; break;
  9747. case THREE.DstColorFactor: return _gl.DST_COLOR; break;
  9748. case THREE.OneMinusDstColorFactor: return _gl.ONE_MINUS_DST_COLOR; break;
  9749. case THREE.SrcAlphaSaturateFactor: return _gl.SRC_ALPHA_SATURATE; break;
  9750. }
  9751. return 0;
  9752. };
  9753. // Allocations
  9754. function allocateBones ( object ) {
  9755. // default for when object is not specified
  9756. // ( for example when prebuilding shader
  9757. // to be used with multiple objects )
  9758. //
  9759. // - leave some extra space for other uniforms
  9760. // - limit here is ANGLE's 254 max uniform vectors
  9761. // (up to 54 should be safe)
  9762. var maxBones = 50;
  9763. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  9764. maxBones = object.bones.length;
  9765. }
  9766. return maxBones;
  9767. };
  9768. function allocateLights ( lights ) {
  9769. var l, ll, light, dirLights, pointLights, maxDirLights, maxPointLights;
  9770. dirLights = pointLights = maxDirLights = maxPointLights = 0;
  9771. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9772. light = lights[ l ];
  9773. if ( light.onlyShadow ) continue;
  9774. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  9775. if ( light instanceof THREE.PointLight ) pointLights ++;
  9776. if ( light instanceof THREE.SpotLight ) pointLights ++;
  9777. }
  9778. if ( ( pointLights + dirLights ) <= _maxLights ) {
  9779. maxDirLights = dirLights;
  9780. maxPointLights = pointLights;
  9781. } else {
  9782. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  9783. maxPointLights = _maxLights - maxDirLights;
  9784. }
  9785. return { 'directional' : maxDirLights, 'point' : maxPointLights };
  9786. };
  9787. function allocateShadows ( lights ) {
  9788. var l, ll, light, maxShadows = 0;
  9789. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9790. light = lights[ l ];
  9791. if ( ! light.castShadow ) continue;
  9792. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  9793. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  9794. }
  9795. return maxShadows;
  9796. };
  9797. // Initialization
  9798. function initGL () {
  9799. var gl;
  9800. try {
  9801. if ( ! ( gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  9802. throw 'Error creating WebGL context.';
  9803. }
  9804. console.log(
  9805. navigator.userAgent + " | " +
  9806. gl.getParameter( gl.VERSION ) + " | " +
  9807. gl.getParameter( gl.VENDOR ) + " | " +
  9808. gl.getParameter( gl.RENDERER ) + " | " +
  9809. gl.getParameter( gl.SHADING_LANGUAGE_VERSION )
  9810. );
  9811. } catch ( error ) {
  9812. console.error( error );
  9813. }
  9814. return gl;
  9815. };
  9816. function setDefaultGLState () {
  9817. _gl.clearColor( 0, 0, 0, 1 );
  9818. _gl.clearDepth( 1 );
  9819. _gl.clearStencil( 0 );
  9820. _gl.enable( _gl.DEPTH_TEST );
  9821. _gl.depthFunc( _gl.LEQUAL );
  9822. _gl.frontFace( _gl.CCW );
  9823. _gl.cullFace( _gl.BACK );
  9824. _gl.enable( _gl.CULL_FACE );
  9825. _gl.enable( _gl.BLEND );
  9826. _gl.blendEquation( _gl.FUNC_ADD );
  9827. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  9828. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9829. };
  9830. // default plugins (order is important)
  9831. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  9832. this.addPrePlugin( this.shadowMapPlugin );
  9833. this.addPostPlugin( new THREE.SpritePlugin() );
  9834. this.addPostPlugin( new THREE.LensFlarePlugin() );
  9835. };
  9836. /**
  9837. * @author szimek / https://github.com/szimek/
  9838. */
  9839. THREE.WebGLRenderTarget = function ( width, height, options ) {
  9840. this.width = width;
  9841. this.height = height;
  9842. options = options || {};
  9843. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  9844. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  9845. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  9846. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  9847. this.offset = new THREE.Vector2( 0, 0 );
  9848. this.repeat = new THREE.Vector2( 1, 1 );
  9849. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  9850. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  9851. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  9852. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  9853. this.generateMipmaps = true;
  9854. };
  9855. THREE.WebGLRenderTarget.prototype.clone = function() {
  9856. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  9857. tmp.wrapS = this.wrapS;
  9858. tmp.wrapT = this.wrapT;
  9859. tmp.magFilter = this.magFilter;
  9860. tmp.minFilter = this.minFilter;
  9861. tmp.offset.copy( this.offset );
  9862. tmp.repeat.copy( this.repeat );
  9863. tmp.format = this.format;
  9864. tmp.type = this.type;
  9865. tmp.depthBuffer = this.depthBuffer;
  9866. tmp.stencilBuffer = this.stencilBuffer;
  9867. return tmp;
  9868. };
  9869. /**
  9870. * @author alteredq / http://alteredqualia.com
  9871. */
  9872. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  9873. THREE.WebGLRenderTarget.call( this, width, height, options );
  9874. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  9875. };
  9876. THREE.WebGLRenderTargetCube.prototype = new THREE.WebGLRenderTarget();
  9877. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  9878. /**
  9879. * @author mr.doob / http://mrdoob.com/
  9880. */
  9881. THREE.RenderableVertex = function () {
  9882. this.positionWorld = new THREE.Vector3();
  9883. this.positionScreen = new THREE.Vector4();
  9884. this.visible = true;
  9885. };
  9886. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  9887. this.positionWorld.copy( vertex.positionWorld );
  9888. this.positionScreen.copy( vertex.positionScreen );
  9889. }
  9890. /**
  9891. * @author mr.doob / http://mrdoob.com/
  9892. */
  9893. THREE.RenderableFace3 = function () {
  9894. this.v1 = new THREE.RenderableVertex();
  9895. this.v2 = new THREE.RenderableVertex();
  9896. this.v3 = new THREE.RenderableVertex();
  9897. this.centroidWorld = new THREE.Vector3();
  9898. this.centroidScreen = new THREE.Vector3();
  9899. this.normalWorld = new THREE.Vector3();
  9900. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9901. this.material = null;
  9902. this.faceMaterial = null;
  9903. this.uvs = [[]];
  9904. this.z = null;
  9905. };
  9906. /**
  9907. * @author mr.doob / http://mrdoob.com/
  9908. */
  9909. THREE.RenderableFace4 = function () {
  9910. this.v1 = new THREE.RenderableVertex();
  9911. this.v2 = new THREE.RenderableVertex();
  9912. this.v3 = new THREE.RenderableVertex();
  9913. this.v4 = new THREE.RenderableVertex();
  9914. this.centroidWorld = new THREE.Vector3();
  9915. this.centroidScreen = new THREE.Vector3();
  9916. this.normalWorld = new THREE.Vector3();
  9917. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9918. this.material = null;
  9919. this.faceMaterial = null;
  9920. this.uvs = [[]];
  9921. this.z = null;
  9922. };
  9923. /**
  9924. * @author mr.doob / http://mrdoob.com/
  9925. */
  9926. THREE.RenderableObject = function () {
  9927. this.object = null;
  9928. this.z = null;
  9929. };
  9930. /**
  9931. * @author mr.doob / http://mrdoob.com/
  9932. */
  9933. THREE.RenderableParticle = function () {
  9934. this.x = null;
  9935. this.y = null;
  9936. this.z = null;
  9937. this.rotation = null;
  9938. this.scale = new THREE.Vector2();
  9939. this.material = null;
  9940. };
  9941. /**
  9942. * @author mr.doob / http://mrdoob.com/
  9943. */
  9944. THREE.RenderableLine = function () {
  9945. this.z = null;
  9946. this.v1 = new THREE.RenderableVertex();
  9947. this.v2 = new THREE.RenderableVertex();
  9948. this.material = null;
  9949. };
  9950. /**
  9951. * @author alteredq / http://alteredqualia.com/
  9952. */
  9953. THREE.ColorUtils = {
  9954. adjustHSV : function ( color, h, s, v ) {
  9955. var hsv = THREE.ColorUtils.__hsv;
  9956. THREE.ColorUtils.rgbToHsv( color, hsv );
  9957. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  9958. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  9959. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  9960. color.setHSV( hsv.h, hsv.s, hsv.v );
  9961. },
  9962. // based on MochiKit implementation by Bob Ippolito
  9963. rgbToHsv : function ( color, hsv ) {
  9964. var r = color.r;
  9965. var g = color.g;
  9966. var b = color.b;
  9967. var max = Math.max( Math.max( r, g ), b );
  9968. var min = Math.min( Math.min( r, g ), b );
  9969. var hue;
  9970. var saturation;
  9971. var value = max;
  9972. if ( min === max ) {
  9973. hue = 0;
  9974. saturation = 0;
  9975. } else {
  9976. var delta = ( max - min );
  9977. saturation = delta / max;
  9978. if ( r === max ) {
  9979. hue = ( g - b ) / delta;
  9980. } else if ( g === max ) {
  9981. hue = 2 + ( ( b - r ) / delta );
  9982. } else {
  9983. hue = 4 + ( ( r - g ) / delta );
  9984. }
  9985. hue /= 6;
  9986. if ( hue < 0 ) {
  9987. hue += 1;
  9988. }
  9989. if ( hue > 1 ) {
  9990. hue -= 1;
  9991. }
  9992. }
  9993. if ( hsv === undefined ) {
  9994. hsv = { h: 0, s: 0, v: 0 };
  9995. }
  9996. hsv.h = hue;
  9997. hsv.s = saturation;
  9998. hsv.v = value;
  9999. return hsv;
  10000. }
  10001. };
  10002. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  10003. * @author mrdoob / http://mrdoob.com/
  10004. * @author alteredq / http://alteredqualia.com/
  10005. */
  10006. THREE.GeometryUtils = {
  10007. // Merge two geometries or geometry and geometry from object (using object's transform)
  10008. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  10009. var matrix, matrixRotation,
  10010. vertexOffset = geometry1.vertices.length,
  10011. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  10012. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  10013. vertices1 = geometry1.vertices,
  10014. vertices2 = geometry2.vertices,
  10015. faces1 = geometry1.faces,
  10016. faces2 = geometry2.faces,
  10017. uvs1 = geometry1.faceVertexUvs[ 0 ],
  10018. uvs2 = geometry2.faceVertexUvs[ 0 ];
  10019. var geo1MaterialsMap = {};
  10020. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  10021. var id = geometry1.materials[ i ].id;
  10022. geo1MaterialsMap[ id ] = i;
  10023. }
  10024. if ( object2 instanceof THREE.Mesh ) {
  10025. object2.matrixAutoUpdate && object2.updateMatrix();
  10026. matrix = object2.matrix;
  10027. matrixRotation = new THREE.Matrix4();
  10028. matrixRotation.extractRotation( matrix, object2.scale );
  10029. }
  10030. // vertices
  10031. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10032. var vertex = vertices2[ i ];
  10033. var vertexCopy = vertex.clone();
  10034. if ( matrix ) matrix.multiplyVector3( vertexCopy.position );
  10035. vertices1.push( vertexCopy );
  10036. }
  10037. // faces
  10038. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10039. var face = faces2[ i ], faceCopy, normal, color,
  10040. faceVertexNormals = face.vertexNormals,
  10041. faceVertexColors = face.vertexColors;
  10042. if ( face instanceof THREE.Face3 ) {
  10043. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10044. } else if ( face instanceof THREE.Face4 ) {
  10045. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  10046. }
  10047. faceCopy.normal.copy( face.normal );
  10048. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  10049. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10050. normal = faceVertexNormals[ j ].clone();
  10051. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  10052. faceCopy.vertexNormals.push( normal );
  10053. }
  10054. faceCopy.color.copy( face.color );
  10055. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10056. color = faceVertexColors[ j ];
  10057. faceCopy.vertexColors.push( color.clone() );
  10058. }
  10059. if ( face.materialIndex !== undefined ) {
  10060. var material2 = geometry2.materials[ face.materialIndex ];
  10061. var materialId2 = material2.id;
  10062. var materialIndex = geo1MaterialsMap[ materialId2 ];
  10063. if ( materialIndex === undefined ) {
  10064. materialIndex = geometry1.materials.length;
  10065. geo1MaterialsMap[ materialId2 ] = materialIndex;
  10066. geometry1.materials.push( material2 );
  10067. }
  10068. faceCopy.materialIndex = materialIndex;
  10069. }
  10070. faceCopy.centroid.copy( face.centroid );
  10071. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  10072. faces1.push( faceCopy );
  10073. }
  10074. // uvs
  10075. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10076. var uv = uvs2[ i ], uvCopy = [];
  10077. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10078. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10079. }
  10080. uvs1.push( uvCopy );
  10081. }
  10082. },
  10083. clone: function ( geometry ) {
  10084. var cloneGeo = new THREE.Geometry();
  10085. var i, il;
  10086. var vertices = geometry.vertices,
  10087. faces = geometry.faces,
  10088. uvs = geometry.faceVertexUvs[ 0 ];
  10089. // materials
  10090. if ( geometry.materials ) {
  10091. cloneGeo.materials = geometry.materials.slice();
  10092. }
  10093. // vertices
  10094. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10095. var vertex = vertices[ i ];
  10096. cloneGeo.vertices.push( vertex.clone() );
  10097. }
  10098. // faces
  10099. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10100. var face = faces[ i ];
  10101. cloneGeo.faces.push( face.clone() );
  10102. }
  10103. // uvs
  10104. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  10105. var uv = uvs[ i ], uvCopy = [];
  10106. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10107. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10108. }
  10109. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  10110. }
  10111. return cloneGeo;
  10112. },
  10113. // Get random point in triangle (via barycentric coordinates)
  10114. // (uniform distribution)
  10115. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  10116. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  10117. var a, b, c,
  10118. point = new THREE.Vector3(),
  10119. tmp = THREE.GeometryUtils.__v1;
  10120. a = THREE.GeometryUtils.random();
  10121. b = THREE.GeometryUtils.random();
  10122. if ( ( a + b ) > 1 ) {
  10123. a = 1 - a;
  10124. b = 1 - b;
  10125. }
  10126. c = 1 - a - b;
  10127. point.copy( vectorA );
  10128. point.multiplyScalar( a );
  10129. tmp.copy( vectorB );
  10130. tmp.multiplyScalar( b );
  10131. point.addSelf( tmp );
  10132. tmp.copy( vectorC );
  10133. tmp.multiplyScalar( c );
  10134. point.addSelf( tmp );
  10135. return point;
  10136. },
  10137. // Get random point in face (triangle / quad)
  10138. // (uniform distribution)
  10139. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  10140. var vA, vB, vC, vD;
  10141. if ( face instanceof THREE.Face3 ) {
  10142. vA = geometry.vertices[ face.a ].position;
  10143. vB = geometry.vertices[ face.b ].position;
  10144. vC = geometry.vertices[ face.c ].position;
  10145. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  10146. } else if ( face instanceof THREE.Face4 ) {
  10147. vA = geometry.vertices[ face.a ].position;
  10148. vB = geometry.vertices[ face.b ].position;
  10149. vC = geometry.vertices[ face.c ].position;
  10150. vD = geometry.vertices[ face.d ].position;
  10151. var area1, area2;
  10152. if ( useCachedAreas ) {
  10153. if ( face._area1 && face._area2 ) {
  10154. area1 = face._area1;
  10155. area2 = face._area2;
  10156. } else {
  10157. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10158. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10159. face._area1 = area1;
  10160. face._area2 = area2;
  10161. }
  10162. } else {
  10163. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  10164. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10165. }
  10166. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  10167. if ( r < area1 ) {
  10168. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  10169. } else {
  10170. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  10171. }
  10172. }
  10173. },
  10174. // Get uniformly distributed random points in mesh
  10175. // - create array with cumulative sums of face areas
  10176. // - pick random number from 0 to total area
  10177. // - find corresponding place in area array by binary search
  10178. // - get random point in face
  10179. randomPointsInGeometry: function ( geometry, n ) {
  10180. var face, i,
  10181. faces = geometry.faces,
  10182. vertices = geometry.vertices,
  10183. il = faces.length,
  10184. totalArea = 0,
  10185. cumulativeAreas = [],
  10186. vA, vB, vC, vD;
  10187. // precompute face areas
  10188. for ( i = 0; i < il; i ++ ) {
  10189. face = faces[ i ];
  10190. if ( face instanceof THREE.Face3 ) {
  10191. vA = vertices[ face.a ].position;
  10192. vB = vertices[ face.b ].position;
  10193. vC = vertices[ face.c ].position;
  10194. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  10195. } else if ( face instanceof THREE.Face4 ) {
  10196. vA = vertices[ face.a ].position;
  10197. vB = vertices[ face.b ].position;
  10198. vC = vertices[ face.c ].position;
  10199. vD = vertices[ face.d ].position;
  10200. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10201. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10202. face._area = face._area1 + face._area2;
  10203. }
  10204. totalArea += face._area;
  10205. cumulativeAreas[ i ] = totalArea;
  10206. }
  10207. // binary search cumulative areas array
  10208. function binarySearchIndices( value ) {
  10209. function binarySearch( start, end ) {
  10210. // return closest larger index
  10211. // if exact number is not found
  10212. if ( end < start )
  10213. return start;
  10214. var mid = start + Math.floor( ( end - start ) / 2 );
  10215. if ( cumulativeAreas[ mid ] > value ) {
  10216. return binarySearch( start, mid - 1 );
  10217. } else if ( cumulativeAreas[ mid ] < value ) {
  10218. return binarySearch( mid + 1, end );
  10219. } else {
  10220. return mid;
  10221. }
  10222. }
  10223. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  10224. return result;
  10225. }
  10226. // pick random face weighted by face area
  10227. var r, index,
  10228. result = [];
  10229. var stats = {};
  10230. for ( i = 0; i < n; i ++ ) {
  10231. r = THREE.GeometryUtils.random() * totalArea;
  10232. index = binarySearchIndices( r );
  10233. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  10234. if ( ! stats[ index ] ) {
  10235. stats[ index ] = 1;
  10236. } else {
  10237. stats[ index ] += 1;
  10238. }
  10239. }
  10240. return result;
  10241. },
  10242. // Get triangle area (by Heron's formula)
  10243. // http://en.wikipedia.org/wiki/Heron%27s_formula
  10244. triangleArea: function ( vectorA, vectorB, vectorC ) {
  10245. var s, a, b, c,
  10246. tmp = THREE.GeometryUtils.__v1;
  10247. tmp.sub( vectorA, vectorB );
  10248. a = tmp.length();
  10249. tmp.sub( vectorA, vectorC );
  10250. b = tmp.length();
  10251. tmp.sub( vectorB, vectorC );
  10252. c = tmp.length();
  10253. s = 0.5 * ( a + b + c );
  10254. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  10255. },
  10256. // Center geometry so that 0,0,0 is in center of bounding box
  10257. center: function ( geometry ) {
  10258. geometry.computeBoundingBox();
  10259. var bb = geometry.boundingBox;
  10260. var offset = new THREE.Vector3();
  10261. offset.add( bb.min, bb.max );
  10262. offset.multiplyScalar( -0.5 );
  10263. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  10264. geometry.computeBoundingBox();
  10265. return offset;
  10266. },
  10267. // Normalize UVs to be from <0,1>
  10268. // (for now just the first set of UVs)
  10269. normalizeUVs: function ( geometry ) {
  10270. var uvSet = geometry.faceVertexUvs[ 0 ];
  10271. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  10272. var uvs = uvSet[ i ];
  10273. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  10274. // texture repeat
  10275. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  10276. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  10277. }
  10278. }
  10279. },
  10280. triangulateQuads: function ( geometry ) {
  10281. var i, il, j, jl;
  10282. var faces = [];
  10283. var faceUvs = [];
  10284. var faceVertexUvs = [];
  10285. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  10286. faceUvs[ i ] = [];
  10287. }
  10288. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10289. faceVertexUvs[ i ] = [];
  10290. }
  10291. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10292. var face = geometry.faces[ i ];
  10293. if ( face instanceof THREE.Face4 ) {
  10294. var a = face.a;
  10295. var b = face.b;
  10296. var c = face.c;
  10297. var d = face.d;
  10298. var triA = new THREE.Face3();
  10299. var triB = new THREE.Face3();
  10300. triA.color.copy( face.color );
  10301. triB.color.copy( face.color );
  10302. triA.materialIndex = face.materialIndex;
  10303. triB.materialIndex = face.materialIndex;
  10304. triA.a = a;
  10305. triA.b = b;
  10306. triA.c = d;
  10307. triB.a = b;
  10308. triB.b = c;
  10309. triB.c = d;
  10310. if ( face.vertexColors.length === 4 ) {
  10311. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  10312. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  10313. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10314. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  10315. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  10316. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10317. }
  10318. faces.push( triA, triB );
  10319. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10320. if ( geometry.faceVertexUvs[ j ].length ) {
  10321. var uvs = geometry.faceVertexUvs[ j ][ i ];
  10322. var uvA = uvs[ 0 ];
  10323. var uvB = uvs[ 1 ];
  10324. var uvC = uvs[ 2 ];
  10325. var uvD = uvs[ 3 ];
  10326. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  10327. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  10328. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10329. }
  10330. }
  10331. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10332. if ( geometry.faceUvs[ j ].length ) {
  10333. var faceUv = geometry.faceUvs[ j ][ i ];
  10334. faceUvs[ j ].push( faceUv, faceUv );
  10335. }
  10336. }
  10337. } else {
  10338. faces.push( face );
  10339. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10340. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  10341. }
  10342. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10343. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10344. }
  10345. }
  10346. }
  10347. geometry.faces = faces;
  10348. geometry.faceUvs = faceUvs;
  10349. geometry.faceVertexUvs = faceVertexUvs;
  10350. geometry.computeCentroids();
  10351. geometry.computeFaceNormals();
  10352. geometry.computeVertexNormals();
  10353. if ( geometry.hasTangents ) geometry.computeTangents();
  10354. },
  10355. // Make all faces use unique vertices
  10356. // so that each face can be separated from others
  10357. explode: function( geometry ) {
  10358. var vertices = [];
  10359. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10360. var n = vertices.length;
  10361. var face = geometry.faces[ i ];
  10362. if ( face instanceof THREE.Face4 ) {
  10363. var a = face.a;
  10364. var b = face.b;
  10365. var c = face.c;
  10366. var d = face.d;
  10367. var va = geometry.vertices[ a ];
  10368. var vb = geometry.vertices[ b ];
  10369. var vc = geometry.vertices[ c ];
  10370. var vd = geometry.vertices[ d ];
  10371. vertices.push( va.clone() );
  10372. vertices.push( vb.clone() );
  10373. vertices.push( vc.clone() );
  10374. vertices.push( vd.clone() );
  10375. face.a = n;
  10376. face.b = n + 1;
  10377. face.c = n + 2;
  10378. face.d = n + 3;
  10379. } else {
  10380. var a = face.a;
  10381. var b = face.b;
  10382. var c = face.c;
  10383. var va = geometry.vertices[ a ];
  10384. var vb = geometry.vertices[ b ];
  10385. var vc = geometry.vertices[ c ];
  10386. vertices.push( va.clone() );
  10387. vertices.push( vb.clone() );
  10388. vertices.push( vc.clone() );
  10389. face.a = n;
  10390. face.b = n + 1;
  10391. face.c = n + 2;
  10392. }
  10393. }
  10394. geometry.vertices = vertices;
  10395. delete geometry.__tmpVertices;
  10396. },
  10397. // Break faces with edges longer than maxEdgeLength
  10398. // - not recursive
  10399. tessellate: function ( geometry, maxEdgeLength ) {
  10400. var i, il, face,
  10401. a, b, c, d,
  10402. va, vb, vc, vd,
  10403. dab, dbc, dac, dcd, dad,
  10404. m, m1, m2,
  10405. vm, vm1, vm2,
  10406. vnm, vnm1, vnm2,
  10407. vcm, vcm1, vcm2,
  10408. triA, triB,
  10409. quadA, quadB,
  10410. edge;
  10411. var faces = [];
  10412. var faceVertexUvs = [];
  10413. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10414. faceVertexUvs[ i ] = [];
  10415. }
  10416. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10417. face = geometry.faces[ i ];
  10418. if ( face instanceof THREE.Face3 ) {
  10419. a = face.a;
  10420. b = face.b;
  10421. c = face.c;
  10422. va = geometry.vertices[ a ];
  10423. vb = geometry.vertices[ b ];
  10424. vc = geometry.vertices[ c ];
  10425. dab = va.position.distanceTo( vb.position );
  10426. dbc = vb.position.distanceTo( vc.position );
  10427. dac = va.position.distanceTo( vc.position );
  10428. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  10429. m = geometry.vertices.length;
  10430. triA = face.clone();
  10431. triB = face.clone();
  10432. if ( dab >= dbc && dab >= dac ) {
  10433. vm = va.clone();
  10434. vm.position.lerpSelf( vb.position, 0.5 );
  10435. triA.a = a;
  10436. triA.b = m;
  10437. triA.c = c;
  10438. triB.a = m;
  10439. triB.b = b;
  10440. triB.c = c;
  10441. if ( face.vertexNormals.length === 3 ) {
  10442. vnm = face.vertexNormals[ 0 ].clone();
  10443. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10444. triA.vertexNormals[ 1 ].copy( vnm );
  10445. triB.vertexNormals[ 0 ].copy( vnm );
  10446. }
  10447. if ( face.vertexColors.length === 3 ) {
  10448. vcm = face.vertexColors[ 0 ].clone();
  10449. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10450. triA.vertexColors[ 1 ].copy( vcm );
  10451. triB.vertexColors[ 0 ].copy( vcm );
  10452. }
  10453. edge = 0;
  10454. } else if ( dbc >= dab && dbc >= dac ) {
  10455. vm = vb.clone();
  10456. vm.position.lerpSelf( vc.position, 0.5 );
  10457. triA.a = a;
  10458. triA.b = b;
  10459. triA.c = m;
  10460. triB.a = m;
  10461. triB.b = c;
  10462. triB.c = a;
  10463. if ( face.vertexNormals.length === 3 ) {
  10464. vnm = face.vertexNormals[ 1 ].clone();
  10465. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10466. triA.vertexNormals[ 2 ].copy( vnm );
  10467. triB.vertexNormals[ 0 ].copy( vnm );
  10468. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  10469. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  10470. }
  10471. if ( face.vertexColors.length === 3 ) {
  10472. vcm = face.vertexColors[ 1 ].clone();
  10473. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10474. triA.vertexColors[ 2 ].copy( vcm );
  10475. triB.vertexColors[ 0 ].copy( vcm );
  10476. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  10477. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  10478. }
  10479. edge = 1;
  10480. } else {
  10481. vm = va.clone();
  10482. vm.position.lerpSelf( vc.position, 0.5 );
  10483. triA.a = a;
  10484. triA.b = b;
  10485. triA.c = m;
  10486. triB.a = m;
  10487. triB.b = b;
  10488. triB.c = c;
  10489. if ( face.vertexNormals.length === 3 ) {
  10490. vnm = face.vertexNormals[ 0 ].clone();
  10491. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10492. triA.vertexNormals[ 2 ].copy( vnm );
  10493. triB.vertexNormals[ 0 ].copy( vnm );
  10494. }
  10495. if ( face.vertexColors.length === 3 ) {
  10496. vcm = face.vertexColors[ 0 ].clone();
  10497. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10498. triA.vertexColors[ 2 ].copy( vcm );
  10499. triB.vertexColors[ 0 ].copy( vcm );
  10500. }
  10501. edge = 2;
  10502. }
  10503. faces.push( triA, triB );
  10504. geometry.vertices.push( vm );
  10505. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  10506. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10507. if ( geometry.faceVertexUvs[ j ].length ) {
  10508. uvs = geometry.faceVertexUvs[ j ][ i ];
  10509. uvA = uvs[ 0 ];
  10510. uvB = uvs[ 1 ];
  10511. uvC = uvs[ 2 ];
  10512. // AB
  10513. if ( edge === 0 ) {
  10514. uvM = uvA.clone();
  10515. uvM.lerpSelf( uvB, 0.5 );
  10516. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  10517. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10518. // BC
  10519. } else if ( edge === 1 ) {
  10520. uvM = uvB.clone();
  10521. uvM.lerpSelf( uvC, 0.5 );
  10522. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10523. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  10524. // AC
  10525. } else {
  10526. uvM = uvA.clone();
  10527. uvM.lerpSelf( uvC, 0.5 );
  10528. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10529. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10530. }
  10531. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10532. }
  10533. }
  10534. } else {
  10535. faces.push( face );
  10536. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10537. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10538. }
  10539. }
  10540. } else {
  10541. a = face.a;
  10542. b = face.b;
  10543. c = face.c;
  10544. d = face.d;
  10545. va = geometry.vertices[ a ];
  10546. vb = geometry.vertices[ b ];
  10547. vc = geometry.vertices[ c ];
  10548. vd = geometry.vertices[ d ];
  10549. dab = va.position.distanceTo( vb.position );
  10550. dbc = vb.position.distanceTo( vc.position );
  10551. dcd = vc.position.distanceTo( vd.position );
  10552. dad = va.position.distanceTo( vd.position );
  10553. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  10554. m1 = geometry.vertices.length;
  10555. m2 = geometry.vertices.length + 1;
  10556. quadA = face.clone();
  10557. quadB = face.clone();
  10558. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  10559. vm1 = va.clone();
  10560. vm1.position.lerpSelf( vb.position, 0.5 );
  10561. vm2 = vc.clone();
  10562. vm2.position.lerpSelf( vd.position, 0.5 );
  10563. quadA.a = a;
  10564. quadA.b = m1;
  10565. quadA.c = m2;
  10566. quadA.d = d;
  10567. quadB.a = m1;
  10568. quadB.b = b;
  10569. quadB.c = c;
  10570. quadB.d = m2;
  10571. if ( face.vertexNormals.length === 4 ) {
  10572. vnm1 = face.vertexNormals[ 0 ].clone();
  10573. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10574. vnm2 = face.vertexNormals[ 2 ].clone();
  10575. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  10576. quadA.vertexNormals[ 1 ].copy( vnm1 );
  10577. quadA.vertexNormals[ 2 ].copy( vnm2 );
  10578. quadB.vertexNormals[ 0 ].copy( vnm1 );
  10579. quadB.vertexNormals[ 3 ].copy( vnm2 );
  10580. }
  10581. if ( face.vertexColors.length === 4 ) {
  10582. vcm1 = face.vertexColors[ 0 ].clone();
  10583. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10584. vcm2 = face.vertexColors[ 2 ].clone();
  10585. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  10586. quadA.vertexColors[ 1 ].copy( vcm1 );
  10587. quadA.vertexColors[ 2 ].copy( vcm2 );
  10588. quadB.vertexColors[ 0 ].copy( vcm1 );
  10589. quadB.vertexColors[ 3 ].copy( vcm2 );
  10590. }
  10591. edge = 0;
  10592. } else {
  10593. vm1 = vb.clone();
  10594. vm1.position.lerpSelf( vc.position, 0.5 );
  10595. vm2 = vd.clone();
  10596. vm2.position.lerpSelf( va.position, 0.5 );
  10597. quadA.a = a;
  10598. quadA.b = b;
  10599. quadA.c = m1;
  10600. quadA.d = m2;
  10601. quadB.a = m2;
  10602. quadB.b = m1;
  10603. quadB.c = c;
  10604. quadB.d = d;
  10605. if ( face.vertexNormals.length === 4 ) {
  10606. vnm1 = face.vertexNormals[ 1 ].clone();
  10607. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10608. vnm2 = face.vertexNormals[ 3 ].clone();
  10609. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  10610. quadA.vertexNormals[ 2 ].copy( vnm1 );
  10611. quadA.vertexNormals[ 3 ].copy( vnm2 );
  10612. quadB.vertexNormals[ 0 ].copy( vnm2 );
  10613. quadB.vertexNormals[ 1 ].copy( vnm1 );
  10614. }
  10615. if ( face.vertexColors.length === 4 ) {
  10616. vcm1 = face.vertexColors[ 1 ].clone();
  10617. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10618. vcm2 = face.vertexColors[ 3 ].clone();
  10619. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  10620. quadA.vertexColors[ 2 ].copy( vcm1 );
  10621. quadA.vertexColors[ 3 ].copy( vcm2 );
  10622. quadB.vertexColors[ 0 ].copy( vcm2 );
  10623. quadB.vertexColors[ 1 ].copy( vcm1 );
  10624. }
  10625. edge = 1;
  10626. }
  10627. faces.push( quadA, quadB );
  10628. geometry.vertices.push( vm1, vm2 );
  10629. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  10630. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10631. if ( geometry.faceVertexUvs[ j ].length ) {
  10632. uvs = geometry.faceVertexUvs[ j ][ i ];
  10633. uvA = uvs[ 0 ];
  10634. uvB = uvs[ 1 ];
  10635. uvC = uvs[ 2 ];
  10636. uvD = uvs[ 3 ];
  10637. // AB + CD
  10638. if ( edge === 0 ) {
  10639. uvM1 = uvA.clone();
  10640. uvM1.lerpSelf( uvB, 0.5 );
  10641. uvM2 = uvC.clone();
  10642. uvM2.lerpSelf( uvD, 0.5 );
  10643. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  10644. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  10645. // BC + AD
  10646. } else {
  10647. uvM1 = uvB.clone();
  10648. uvM1.lerpSelf( uvC, 0.5 );
  10649. uvM2 = uvD.clone();
  10650. uvM2.lerpSelf( uvA, 0.5 );
  10651. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  10652. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  10653. }
  10654. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  10655. }
  10656. }
  10657. } else {
  10658. faces.push( face );
  10659. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10660. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10661. }
  10662. }
  10663. }
  10664. }
  10665. geometry.faces = faces;
  10666. geometry.faceVertexUvs = faceVertexUvs;
  10667. }
  10668. };
  10669. THREE.GeometryUtils.random = THREE.Math.random16;
  10670. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  10671. /**
  10672. * @author alteredq / http://alteredqualia.com/
  10673. * @author mrdoob / http://mrdoob.com/
  10674. */
  10675. THREE.ImageUtils = {
  10676. crossOrigin: 'anonymous',
  10677. loadTexture: function ( path, mapping, callback ) {
  10678. var image = new Image(), texture = new THREE.Texture( image, mapping );
  10679. image.onload = function () { texture.needsUpdate = true; if ( callback ) callback( this ); };
  10680. image.crossOrigin = this.crossOrigin;
  10681. image.src = path;
  10682. return texture;
  10683. },
  10684. loadTextureCube: function ( array, mapping, callback ) {
  10685. var i, l, images = [], texture = new THREE.Texture( images, mapping );
  10686. images.loadCount = 0;
  10687. for ( i = 0, l = array.length; i < l; ++ i ) {
  10688. images[ i ] = new Image();
  10689. images[ i ].onload = function () {
  10690. images.loadCount += 1;
  10691. if ( images.loadCount === 6 ) texture.needsUpdate = true;
  10692. if ( callback ) callback( this );
  10693. };
  10694. images[ i ].crossOrigin = this.crossOrigin;
  10695. images[ i ].src = array[ i ];
  10696. }
  10697. return texture;
  10698. },
  10699. getNormalMap: function ( image, depth ) {
  10700. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  10701. var cross = function ( a, b ) {
  10702. 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 ] ];
  10703. }
  10704. var subtract = function ( a, b ) {
  10705. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  10706. }
  10707. var normalize = function ( a ) {
  10708. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  10709. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  10710. }
  10711. depth = depth | 1;
  10712. var width = image.width;
  10713. var height = image.height;
  10714. var canvas = document.createElement( 'canvas' );
  10715. canvas.width = width;
  10716. canvas.height = height;
  10717. var context = canvas.getContext( '2d' );
  10718. context.drawImage( image, 0, 0 );
  10719. var data = context.getImageData( 0, 0, width, height ).data;
  10720. var imageData = context.createImageData( width, height );
  10721. var output = imageData.data;
  10722. for ( var x = 0; x < width; x ++ ) {
  10723. for ( var y = 1; y < height; y ++ ) {
  10724. var ly = y - 1 < 0 ? height - 1 : y - 1;
  10725. var uy = ( y + 1 ) % height;
  10726. var lx = x - 1 < 0 ? width - 1 : x - 1;
  10727. var ux = ( x + 1 ) % width;
  10728. var points = [];
  10729. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  10730. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  10731. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  10732. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  10733. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  10734. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  10735. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  10736. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  10737. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  10738. var normals = [];
  10739. var num_points = points.length;
  10740. for ( var i = 0; i < num_points; i ++ ) {
  10741. var v1 = points[ i ];
  10742. var v2 = points[ ( i + 1 ) % num_points ];
  10743. v1 = subtract( v1, origin );
  10744. v2 = subtract( v2, origin );
  10745. normals.push( normalize( cross( v1, v2 ) ) );
  10746. }
  10747. var normal = [ 0, 0, 0 ];
  10748. for ( var i = 0; i < normals.length; i ++ ) {
  10749. normal[ 0 ] += normals[ i ][ 0 ];
  10750. normal[ 1 ] += normals[ i ][ 1 ];
  10751. normal[ 2 ] += normals[ i ][ 2 ];
  10752. }
  10753. normal[ 0 ] /= normals.length;
  10754. normal[ 1 ] /= normals.length;
  10755. normal[ 2 ] /= normals.length;
  10756. var idx = ( y * width + x ) * 4;
  10757. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  10758. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 / 2.0 ) * 255 ) | 0;
  10759. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  10760. output[ idx + 3 ] = 255;
  10761. }
  10762. }
  10763. context.putImageData( imageData, 0, 0 );
  10764. return canvas;
  10765. },
  10766. generateDataTexture: function ( width, height, color ) {
  10767. var size = width * height;
  10768. var data = new Uint8Array( 3 * size );
  10769. var r = Math.floor( color.r * 255 );
  10770. var g = Math.floor( color.g * 255 );
  10771. var b = Math.floor( color.b * 255 );
  10772. for ( var i = 0; i < size; i ++ ) {
  10773. data[ i * 3 ] = r;
  10774. data[ i * 3 + 1 ] = g;
  10775. data[ i * 3 + 2 ] = b;
  10776. }
  10777. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  10778. texture.needsUpdate = true;
  10779. return texture;
  10780. }
  10781. };
  10782. /**
  10783. * @author alteredq / http://alteredqualia.com/
  10784. */
  10785. THREE.SceneUtils = {
  10786. showHierarchy : function ( root, visible ) {
  10787. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  10788. },
  10789. traverseHierarchy : function ( root, callback ) {
  10790. var n, i, l = root.children.length;
  10791. for ( i = 0; i < l; i ++ ) {
  10792. n = root.children[ i ];
  10793. callback( n );
  10794. THREE.SceneUtils.traverseHierarchy( n, callback );
  10795. }
  10796. },
  10797. createMultiMaterialObject : function ( geometry, materials ) {
  10798. var i, il = materials.length,
  10799. group = new THREE.Object3D();
  10800. for ( i = 0; i < il; i ++ ) {
  10801. var object = new THREE.Mesh( geometry, materials[ i ] );
  10802. group.add( object );
  10803. }
  10804. return group;
  10805. },
  10806. cloneObject: function ( source ) {
  10807. var object;
  10808. // subclass specific properties
  10809. // (must process in order from more specific subclasses to more abstract classes)
  10810. if ( source instanceof THREE.MorphAnimMesh ) {
  10811. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  10812. object.duration = source.duration;
  10813. object.mirroredLoop = source.mirroredLoop;
  10814. object.time = source.time;
  10815. object.lastKeyframe = source.lastKeyframe;
  10816. object.currentKeyframe = source.currentKeyframe;
  10817. object.direction = source.direction;
  10818. object.directionBackwards = source.directionBackwards;
  10819. } else if ( source instanceof THREE.SkinnedMesh ) {
  10820. object = new THREE.SkinnedMesh( source.geometry, source.material );
  10821. } else if ( source instanceof THREE.Mesh ) {
  10822. object = new THREE.Mesh( source.geometry, source.material );
  10823. } else if ( source instanceof THREE.Line ) {
  10824. object = new THREE.Line( source.geometry, source.material, source.type );
  10825. } else if ( source instanceof THREE.Ribbon ) {
  10826. object = new THREE.Ribbon( source.geometry, source.material );
  10827. } else if ( source instanceof THREE.ParticleSystem ) {
  10828. object = new THREE.ParticleSystem( source.geometry, source.material );
  10829. object.sortParticles = source.sortParticles;
  10830. } else if ( source instanceof THREE.Particle ) {
  10831. object = new THREE.Particle( source.material );
  10832. } else if ( source instanceof THREE.Sprite ) {
  10833. object = new THREE.Sprite( {} );
  10834. object.color.copy( source.color );
  10835. object.map = source.map;
  10836. object.blending = source.blending;
  10837. object.useScreenCoordinates = source.useScreenCoordinates;
  10838. object.mergeWith3D = source.mergeWith3D;
  10839. object.affectedByDistance = source.affectedByDistance;
  10840. object.scaleByViewport = source.scaleByViewport;
  10841. object.alignment = source.alignment;
  10842. object.rotation3d.copy( source.rotation3d );
  10843. object.rotation = source.rotation;
  10844. object.opacity = source.opacity;
  10845. object.uvOffset.copy( source.uvOffset );
  10846. object.uvScale.copy( source.uvScale);
  10847. } else if ( source instanceof THREE.LOD ) {
  10848. object = new THREE.LOD();
  10849. } else if ( source instanceof THREE.MarchingCubes ) {
  10850. object = new THREE.MarchingCubes( source.resolution, source.material );
  10851. object.field.set( source.field );
  10852. object.isolation = source.isolation;
  10853. } else if ( source instanceof THREE.Object3D ) {
  10854. object = new THREE.Object3D();
  10855. }
  10856. // base class properties
  10857. object.name = source.name;
  10858. object.parent = source.parent;
  10859. object.up.copy( source.up );
  10860. object.position.copy( source.position );
  10861. // because of Sprite madness
  10862. if ( object.rotation instanceof THREE.Vector3 )
  10863. object.rotation.copy( source.rotation );
  10864. object.eulerOrder = source.eulerOrder;
  10865. object.scale.copy( source.scale );
  10866. object.dynamic = source.dynamic;
  10867. object.doubleSided = source.doubleSided;
  10868. object.flipSided = source.flipSided;
  10869. object.renderDepth = source.renderDepth;
  10870. object.rotationAutoUpdate = source.rotationAutoUpdate;
  10871. object.matrix.copy( source.matrix );
  10872. object.matrixWorld.copy( source.matrixWorld );
  10873. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  10874. object.matrixAutoUpdate = source.matrixAutoUpdate;
  10875. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10876. object.quaternion.copy( source.quaternion );
  10877. object.useQuaternion = source.useQuaternion;
  10878. object.boundRadius = source.boundRadius;
  10879. object.boundRadiusScale = source.boundRadiusScale;
  10880. object.visible = source.visible;
  10881. object.castShadow = source.castShadow;
  10882. object.receiveShadow = source.receiveShadow;
  10883. object.frustumCulled = source.frustumCulled;
  10884. // children
  10885. for ( var i = 0; i < source.children.length; i ++ ) {
  10886. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  10887. object.children[ i ] = child;
  10888. child.parent = object;
  10889. }
  10890. // LODs need to be patched separately to use cloned children
  10891. if ( source instanceof THREE.LOD ) {
  10892. for ( var i = 0; i < source.LODs.length; i ++ ) {
  10893. var lod = source.LODs[ i ];
  10894. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  10895. }
  10896. }
  10897. return object;
  10898. },
  10899. detach : function ( child, parent, scene ) {
  10900. child.applyMatrix( parent.matrixWorld );
  10901. parent.remove( child );
  10902. scene.add( child );
  10903. },
  10904. attach: function ( child, scene, parent ) {
  10905. var matrixWorldInverse = new THREE.Matrix4();
  10906. matrixWorldInverse.getInverse( parent.matrixWorld );
  10907. child.applyMatrix( matrixWorldInverse );
  10908. scene.remove( child );
  10909. parent.add( child );
  10910. }
  10911. };
  10912. /**
  10913. * @author alteredq / http://alteredqualia.com/
  10914. * @author mr.doob / http://mrdoob.com/
  10915. *
  10916. * ShaderUtils currently contains:
  10917. *
  10918. * fresnel
  10919. * normal
  10920. * cube
  10921. *
  10922. */
  10923. if ( THREE.WebGLRenderer ) {
  10924. THREE.ShaderUtils = {
  10925. lib: {
  10926. /* -------------------------------------------------------------------------
  10927. // Fresnel shader
  10928. // - based on Nvidia Cg tutorial
  10929. ------------------------------------------------------------------------- */
  10930. 'fresnel': {
  10931. uniforms: {
  10932. "mRefractionRatio": { type: "f", value: 1.02 },
  10933. "mFresnelBias": { type: "f", value: 0.1 },
  10934. "mFresnelPower": { type: "f", value: 2.0 },
  10935. "mFresnelScale": { type: "f", value: 1.0 },
  10936. "tCube": { type: "t", value: 1, texture: null }
  10937. },
  10938. fragmentShader: [
  10939. "uniform samplerCube tCube;",
  10940. "varying vec3 vReflect;",
  10941. "varying vec3 vRefract[3];",
  10942. "varying float vReflectionFactor;",
  10943. "void main() {",
  10944. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10945. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  10946. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  10947. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  10948. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  10949. "refractedColor.a = 1.0;",
  10950. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  10951. "}"
  10952. ].join("\n"),
  10953. vertexShader: [
  10954. "uniform float mRefractionRatio;",
  10955. "uniform float mFresnelBias;",
  10956. "uniform float mFresnelScale;",
  10957. "uniform float mFresnelPower;",
  10958. "varying vec3 vReflect;",
  10959. "varying vec3 vRefract[3];",
  10960. "varying float vReflectionFactor;",
  10961. "void main() {",
  10962. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10963. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  10964. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  10965. "vec3 I = mPosition.xyz - cameraPosition;",
  10966. "vReflect = reflect( I, nWorld );",
  10967. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  10968. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  10969. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  10970. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  10971. "gl_Position = projectionMatrix * mvPosition;",
  10972. "}"
  10973. ].join("\n")
  10974. },
  10975. /* -------------------------------------------------------------------------
  10976. // Normal map shader
  10977. // - Blinn-Phong
  10978. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10979. // - point and directional lights (use with "lights: true" material option)
  10980. ------------------------------------------------------------------------- */
  10981. 'normal' : {
  10982. uniforms: THREE.UniformsUtils.merge( [
  10983. THREE.UniformsLib[ "fog" ],
  10984. THREE.UniformsLib[ "lights" ],
  10985. THREE.UniformsLib[ "shadowmap" ],
  10986. {
  10987. "enableAO" : { type: "i", value: 0 },
  10988. "enableDiffuse" : { type: "i", value: 0 },
  10989. "enableSpecular" : { type: "i", value: 0 },
  10990. "enableReflection": { type: "i", value: 0 },
  10991. "tDiffuse" : { type: "t", value: 0, texture: null },
  10992. "tCube" : { type: "t", value: 1, texture: null },
  10993. "tNormal" : { type: "t", value: 2, texture: null },
  10994. "tSpecular" : { type: "t", value: 3, texture: null },
  10995. "tAO" : { type: "t", value: 4, texture: null },
  10996. "tDisplacement": { type: "t", value: 5, texture: null },
  10997. "uNormalScale": { type: "f", value: 1.0 },
  10998. "uDisplacementBias": { type: "f", value: 0.0 },
  10999. "uDisplacementScale": { type: "f", value: 1.0 },
  11000. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11001. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11002. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11003. "uShininess": { type: "f", value: 30 },
  11004. "uOpacity": { type: "f", value: 1 },
  11005. "uReflectivity": { type: "f", value: 0.5 },
  11006. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11007. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11008. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11009. }
  11010. ] ),
  11011. fragmentShader: [
  11012. "uniform vec3 uAmbientColor;",
  11013. "uniform vec3 uDiffuseColor;",
  11014. "uniform vec3 uSpecularColor;",
  11015. "uniform float uShininess;",
  11016. "uniform float uOpacity;",
  11017. "uniform bool enableDiffuse;",
  11018. "uniform bool enableSpecular;",
  11019. "uniform bool enableAO;",
  11020. "uniform bool enableReflection;",
  11021. "uniform sampler2D tDiffuse;",
  11022. "uniform sampler2D tNormal;",
  11023. "uniform sampler2D tSpecular;",
  11024. "uniform sampler2D tAO;",
  11025. "uniform samplerCube tCube;",
  11026. "uniform float uNormalScale;",
  11027. "uniform float uReflectivity;",
  11028. "varying vec3 vTangent;",
  11029. "varying vec3 vBinormal;",
  11030. "varying vec3 vNormal;",
  11031. "varying vec2 vUv;",
  11032. "uniform vec3 ambientLightColor;",
  11033. "#if MAX_DIR_LIGHTS > 0",
  11034. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11035. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11036. "#endif",
  11037. "#if MAX_POINT_LIGHTS > 0",
  11038. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11039. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11040. "#endif",
  11041. "#ifdef WRAP_AROUND",
  11042. "uniform vec3 wrapRGB;",
  11043. "#endif",
  11044. "varying vec3 vViewPosition;",
  11045. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11046. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11047. "void main() {",
  11048. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11049. "vec3 specularTex = vec3( 1.0 );",
  11050. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11051. "normalTex.xy *= uNormalScale;",
  11052. "normalTex = normalize( normalTex );",
  11053. "if( enableDiffuse ) {",
  11054. "#ifdef GAMMA_INPUT",
  11055. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11056. "texelColor.xyz *= texelColor.xyz;",
  11057. "gl_FragColor = gl_FragColor * texelColor;",
  11058. "#else",
  11059. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11060. "#endif",
  11061. "}",
  11062. "if( enableAO ) {",
  11063. "#ifdef GAMMA_INPUT",
  11064. "vec4 aoColor = texture2D( tAO, vUv );",
  11065. "aoColor.xyz *= aoColor.xyz;",
  11066. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11067. "#else",
  11068. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11069. "#endif",
  11070. "}",
  11071. "if( enableSpecular )",
  11072. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11073. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11074. "vec3 finalNormal = tsb * normalTex;",
  11075. "vec3 normal = normalize( finalNormal );",
  11076. "vec3 viewPosition = normalize( vViewPosition );",
  11077. // point lights
  11078. "#if MAX_POINT_LIGHTS > 0",
  11079. "vec3 pointDiffuse = vec3( 0.0 );",
  11080. "vec3 pointSpecular = vec3( 0.0 );",
  11081. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11082. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  11083. "float pointDistance = vPointLight[ i ].w;",
  11084. // diffuse
  11085. "#ifdef WRAP_AROUND",
  11086. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11087. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11088. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11089. "#else",
  11090. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11091. "#endif",
  11092. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11093. // specular
  11094. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11095. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11096. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11097. "#ifdef PHYSICALLY_BASED_SHADING",
  11098. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11099. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11100. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11101. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11102. "#else",
  11103. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11104. "#endif",
  11105. "}",
  11106. "#endif",
  11107. // directional lights
  11108. "#if MAX_DIR_LIGHTS > 0",
  11109. "vec3 dirDiffuse = vec3( 0.0 );",
  11110. "vec3 dirSpecular = vec3( 0.0 );",
  11111. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11112. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11113. "vec3 dirVector = normalize( lDirection.xyz );",
  11114. // diffuse
  11115. "#ifdef WRAP_AROUND",
  11116. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11117. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11118. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11119. "#else",
  11120. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11121. "#endif",
  11122. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11123. // specular
  11124. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11125. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11126. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11127. "#ifdef PHYSICALLY_BASED_SHADING",
  11128. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11129. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11130. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11131. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11132. "#else",
  11133. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11134. "#endif",
  11135. "}",
  11136. "#endif",
  11137. // all lights contribution summation
  11138. "vec3 totalDiffuse = vec3( 0.0 );",
  11139. "vec3 totalSpecular = vec3( 0.0 );",
  11140. "#if MAX_DIR_LIGHTS > 0",
  11141. "totalDiffuse += dirDiffuse;",
  11142. "totalSpecular += dirSpecular;",
  11143. "#endif",
  11144. "#if MAX_POINT_LIGHTS > 0",
  11145. "totalDiffuse += pointDiffuse;",
  11146. "totalSpecular += pointSpecular;",
  11147. "#endif",
  11148. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  11149. "if ( enableReflection ) {",
  11150. "vec3 wPos = cameraPosition - vViewPosition;",
  11151. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  11152. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11153. "#ifdef GAMMA_INPUT",
  11154. "cubeColor.xyz *= cubeColor.xyz;",
  11155. "#endif",
  11156. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11157. "}",
  11158. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11159. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11160. THREE.ShaderChunk[ "fog_fragment" ],
  11161. "}"
  11162. ].join("\n"),
  11163. vertexShader: [
  11164. "attribute vec4 tangent;",
  11165. "uniform vec2 uOffset;",
  11166. "uniform vec2 uRepeat;",
  11167. "#ifdef VERTEX_TEXTURES",
  11168. "uniform sampler2D tDisplacement;",
  11169. "uniform float uDisplacementScale;",
  11170. "uniform float uDisplacementBias;",
  11171. "#endif",
  11172. "varying vec3 vTangent;",
  11173. "varying vec3 vBinormal;",
  11174. "varying vec3 vNormal;",
  11175. "varying vec2 vUv;",
  11176. "#if MAX_POINT_LIGHTS > 0",
  11177. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11178. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11179. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11180. "#endif",
  11181. "varying vec3 vViewPosition;",
  11182. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11183. "void main() {",
  11184. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11185. "vViewPosition = -mvPosition.xyz;",
  11186. // normal, tangent and binormal vectors
  11187. "vNormal = normalMatrix * normal;",
  11188. "vTangent = normalMatrix * tangent.xyz;",
  11189. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  11190. "vUv = uv * uRepeat + uOffset;",
  11191. // point lights
  11192. "#if MAX_POINT_LIGHTS > 0",
  11193. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  11194. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11195. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  11196. "float lDistance = 1.0;",
  11197. "if ( pointLightDistance[ i ] > 0.0 )",
  11198. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11199. "lVector = normalize( lVector );",
  11200. "vPointLight[ i ] = vec4( lVector, lDistance );",
  11201. "}",
  11202. "#endif",
  11203. // displacement mapping
  11204. "#ifdef VERTEX_TEXTURES",
  11205. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11206. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11207. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  11208. "gl_Position = projectionMatrix * displacedPosition;",
  11209. "#else",
  11210. "gl_Position = projectionMatrix * mvPosition;",
  11211. "#endif",
  11212. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11213. "}"
  11214. ].join("\n")
  11215. },
  11216. /* -------------------------------------------------------------------------
  11217. // Cube map shader
  11218. ------------------------------------------------------------------------- */
  11219. 'cube': {
  11220. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  11221. "tFlip": { type: "f", value: -1 } },
  11222. vertexShader: [
  11223. "varying vec3 vViewPosition;",
  11224. "void main() {",
  11225. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  11226. "vViewPosition = cameraPosition - mPosition.xyz;",
  11227. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11228. "}"
  11229. ].join("\n"),
  11230. fragmentShader: [
  11231. "uniform samplerCube tCube;",
  11232. "uniform float tFlip;",
  11233. "varying vec3 vViewPosition;",
  11234. "void main() {",
  11235. "vec3 wPos = cameraPosition - vViewPosition;",
  11236. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  11237. "}"
  11238. ].join("\n")
  11239. }
  11240. }
  11241. };
  11242. };/**
  11243. * @author alteredq / http://alteredqualia.com/
  11244. */
  11245. THREE.BufferGeometry = function () {
  11246. this.id = THREE.GeometryCount ++;
  11247. // GL buffers
  11248. this.vertexIndexBuffer = null;
  11249. this.vertexPositionBuffer = null;
  11250. this.vertexNormalBuffer = null;
  11251. this.vertexUvBuffer = null;
  11252. this.vertexColorBuffer = null;
  11253. // typed arrays (kept only if dynamic flag is set)
  11254. this.vertexIndexArray = null;
  11255. this.vertexPositionArray = null;
  11256. this.vertexNormalArray = null;
  11257. this.vertexUvArray = null;
  11258. this.vertexColorArray = null;
  11259. this.dynamic = false;
  11260. // boundings
  11261. this.boundingBox = null;
  11262. this.boundingSphere = null;
  11263. // for compatibility
  11264. this.morphTargets = [];
  11265. };
  11266. THREE.BufferGeometry.prototype = {
  11267. constructor : THREE.BufferGeometry,
  11268. // for compatibility
  11269. computeBoundingBox: function () {
  11270. },
  11271. // for compatibility
  11272. computeBoundingSphere: function () {
  11273. }
  11274. };
  11275. /**
  11276. * @author zz85 / http://www.lab4games.net/zz85/blog
  11277. * Extensible curve object
  11278. *
  11279. * Some common of Curve methods
  11280. * .getPoint(t), getTangent(t)
  11281. * .getPointAt(u), getTagentAt(u)
  11282. * .getPoints(), .getSpacedPoints()
  11283. * .getLength()
  11284. *
  11285. * This file contains following classes:
  11286. *
  11287. * -- 2d classes --
  11288. * THREE.Curve
  11289. * THREE.LineCurve
  11290. * THREE.QuadraticBezierCurve
  11291. * THREE.CubicBezierCurve
  11292. * THREE.SplineCurve
  11293. * THREE.ArcCurve
  11294. *
  11295. * -- 3d classes --
  11296. * THREE.LineCurve3
  11297. * THREE.QuadraticBezierCurve3
  11298. * THREE.CubicBezierCurve3
  11299. * THREE.SplineCurve3
  11300. * THREE.ClosedSplineCurve3
  11301. *
  11302. **/
  11303. /**************************************************************
  11304. * Abstract Curve base class
  11305. **************************************************************/
  11306. THREE.Curve = function () {
  11307. };
  11308. // Virtual base class method to overwrite and implement in subclasses
  11309. // - t [0 .. 1]
  11310. THREE.Curve.prototype.getPoint = function ( t ) {
  11311. console.log( "Warning, getPoint() not implemented!" );
  11312. return null;
  11313. };
  11314. // Get point at relative position in curve according to arc length
  11315. // - u [0 .. 1]
  11316. THREE.Curve.prototype.getPointAt = function ( u ) {
  11317. var t = this.getUtoTmapping( u );
  11318. return this.getPoint( t );
  11319. };
  11320. // Get sequence of points using getPoint( t )
  11321. THREE.Curve.prototype.getPoints = function ( divisions ) {
  11322. if ( !divisions ) divisions = 5;
  11323. var d, pts = [];
  11324. for ( d = 0; d <= divisions; d ++ ) {
  11325. pts.push( this.getPoint( d / divisions ) );
  11326. };
  11327. return pts;
  11328. };
  11329. // Get sequence of points using getPointAt( u )
  11330. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  11331. if ( !divisions ) divisions = 5;
  11332. var d, pts = [];
  11333. for ( d = 0; d <= divisions; d ++ ) {
  11334. pts.push( this.getPointAt( d / divisions ) );
  11335. };
  11336. return pts;
  11337. };
  11338. // Get total curve length
  11339. THREE.Curve.prototype.getLength = function () {
  11340. var lengths = this.getLengths();
  11341. return lengths[ lengths.length - 1 ];
  11342. };
  11343. // Get list of cumulative segment lengths
  11344. THREE.Curve.prototype.getLengths = function ( divisions ) {
  11345. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  11346. if ( this.cacheArcLengths
  11347. && ( this.cacheArcLengths.length == divisions + 1 )
  11348. && !this.needsUpdate) {
  11349. //console.log( "cached", this.cacheArcLengths );
  11350. return this.cacheArcLengths;
  11351. }
  11352. this.needsUpdate = false;
  11353. var cache = [];
  11354. var current, last = this.getPoint( 0 );
  11355. var p, sum = 0;
  11356. cache.push( 0 );
  11357. for ( p = 1; p <= divisions; p ++ ) {
  11358. current = this.getPoint ( p / divisions );
  11359. sum += current.distanceTo( last );
  11360. cache.push( sum );
  11361. last = current;
  11362. }
  11363. this.cacheArcLengths = cache;
  11364. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  11365. };
  11366. THREE.Curve.prototype.updateArcLengths = function() {
  11367. this.needsUpdate = true;
  11368. this.getLengths();
  11369. };
  11370. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  11371. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  11372. var arcLengths = this.getLengths();
  11373. var i = 0, il = arcLengths.length;
  11374. var targetArcLength; // The targeted u distance value to get
  11375. if ( distance ) {
  11376. targetArcLength = distance;
  11377. } else {
  11378. targetArcLength = u * arcLengths[ il - 1 ];
  11379. }
  11380. //var time = Date.now();
  11381. // binary search for the index with largest value smaller than target u distance
  11382. var low = 0, high = il - 1, comparison;
  11383. while ( low <= high ) {
  11384. 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
  11385. comparison = arcLengths[ i ] - targetArcLength;
  11386. if ( comparison < 0 ) {
  11387. low = i + 1;
  11388. continue;
  11389. } else if ( comparison > 0 ) {
  11390. high = i - 1;
  11391. continue;
  11392. } else {
  11393. high = i;
  11394. break;
  11395. // DONE
  11396. }
  11397. }
  11398. i = high;
  11399. //console.log('b' , i, low, high, Date.now()- time);
  11400. if ( arcLengths[ i ] == targetArcLength ) {
  11401. var t = i / ( il - 1 );
  11402. return t;
  11403. }
  11404. // we could get finer grain at lengths, or use simple interpolatation between two points
  11405. var lengthBefore = arcLengths[ i ];
  11406. var lengthAfter = arcLengths[ i + 1 ];
  11407. var segmentLength = lengthAfter - lengthBefore;
  11408. // determine where we are between the 'before' and 'after' points
  11409. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  11410. // add that fractional amount to t
  11411. t = ( i + segmentFraction ) / ( il -1 );
  11412. return t;
  11413. };
  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.getNormalVector = function( t ) {
  11418. var vec = this.getTangent( t );
  11419. return new THREE.Vector2( -vec.y , vec.x );
  11420. };
  11421. // Returns a unit vector tangent at t
  11422. THREE.Curve.prototype.getTangent = function( t ) {
  11423. var delta = 0.0001;
  11424. var t1 = t - delta;
  11425. var t2 = t + delta;
  11426. // Capping in case of danger
  11427. if ( t1 < 0 ) t1 = 0;
  11428. if ( t2 > 1 ) t2 = 1;
  11429. var pt1 = this.getPoint( t1 );
  11430. var pt2 = this.getPoint( t2 );
  11431. var vec = pt2.clone().subSelf(pt1);
  11432. return vec.normalize();
  11433. };
  11434. THREE.Curve.prototype.getTangentAt = function ( u ) {
  11435. var t = this.getUtoTmapping( u );
  11436. return this.getTangent( t );
  11437. };
  11438. /**************************************************************
  11439. * Line
  11440. **************************************************************/
  11441. THREE.LineCurve = function ( v1, v2 ) {
  11442. if ( ! ( v1 instanceof THREE.Vector2 ) ) {
  11443. // Fall back for old constuctor signature - should be removed over time
  11444. THREE.LineCurve.oldConstructor.apply( this, arguments );
  11445. return;
  11446. }
  11447. this.v1 = v1;
  11448. this.v2 = v2;
  11449. };
  11450. THREE.LineCurve.oldConstructor = function ( x1, y1, x2, y2 ) {
  11451. this.constructor( new THREE.Vector2( x1, y1 ), new THREE.Vector2( x2, y2 ) );
  11452. };
  11453. THREE.LineCurve.prototype = new THREE.Curve();
  11454. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  11455. THREE.LineCurve.prototype.getPoint = function ( t ) {
  11456. var point = new THREE.Vector2();
  11457. point.sub( this.v2, this.v1 );
  11458. point.multiplyScalar( t ).addSelf( this.v1 );
  11459. return point;
  11460. };
  11461. // Line curve is linear, so we can overwrite default getPointAt
  11462. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  11463. return this.getPoint( u );
  11464. };
  11465. THREE.LineCurve.prototype.getTangent = function( t ) {
  11466. var tangent = new THREE.Vector2();
  11467. tangent.sub( this.v2, this.v1 );
  11468. tangent.normalize();
  11469. return tangent;
  11470. };
  11471. /**************************************************************
  11472. * Quadratic Bezier curve
  11473. **************************************************************/
  11474. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  11475. if ( !( v1 instanceof THREE.Vector2 ) ) {
  11476. var args = Array.prototype.slice.call( arguments );
  11477. v0 = new THREE.Vector2( args[ 0 ], args[ 1 ] );
  11478. v1 = new THREE.Vector2( args[ 2 ], args[ 3 ] );
  11479. v2 = new THREE.Vector2( args[ 4 ], args[ 5 ] );
  11480. }
  11481. this.v0 = v0;
  11482. this.v1 = v1;
  11483. this.v2 = v2;
  11484. };
  11485. THREE.QuadraticBezierCurve.prototype = new THREE.Curve();
  11486. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  11487. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  11488. var tx, ty;
  11489. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11490. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11491. return new THREE.Vector2( tx, ty );
  11492. };
  11493. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  11494. // iterate sub segments
  11495. // get lengths for sub segments
  11496. // if segment is bezier
  11497. // perform subdivisions
  11498. var tx, ty;
  11499. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  11500. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  11501. // returns unit vector
  11502. var tangent = new THREE.Vector2( tx, ty );
  11503. tangent.normalize();
  11504. return tangent;
  11505. };
  11506. /**************************************************************
  11507. * Cubic Bezier curve
  11508. **************************************************************/
  11509. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  11510. if ( ! ( v1 instanceof THREE.Vector2 ) ) {
  11511. var args = Array.prototype.slice.call( arguments );
  11512. v0 = new THREE.Vector2( args[ 0 ], args[ 1 ] );
  11513. v1 = new THREE.Vector2( args[ 2 ], args[ 3 ] );
  11514. v2 = new THREE.Vector2( args[ 4 ], args[ 5 ] );
  11515. v3 = new THREE.Vector2( args[ 6 ], args[ 7 ] );
  11516. }
  11517. this.v0 = v0;
  11518. this.v1 = v1;
  11519. this.v2 = v2;
  11520. this.v3 = v3;
  11521. };
  11522. THREE.CubicBezierCurve.prototype = new THREE.Curve();
  11523. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  11524. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  11525. var tx, ty;
  11526. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11527. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11528. return new THREE.Vector2( tx, ty );
  11529. };
  11530. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  11531. var tx, ty;
  11532. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11533. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11534. // return normal unit vector
  11535. var tangent = new THREE.Vector2( tx, ty );
  11536. tangent.normalize();
  11537. return tangent;
  11538. };
  11539. /**************************************************************
  11540. * Spline curve
  11541. **************************************************************/
  11542. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  11543. this.points = (points == undefined) ? [] : points;
  11544. };
  11545. THREE.SplineCurve.prototype = new THREE.Curve();
  11546. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  11547. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  11548. var v = new THREE.Vector2();
  11549. var c = [];
  11550. var points = this.points, point, intPoint, weight;
  11551. point = ( points.length - 1 ) * t;
  11552. intPoint = Math.floor( point );
  11553. weight = point - intPoint;
  11554. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11555. c[ 1 ] = intPoint;
  11556. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  11557. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  11558. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11559. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11560. return v;
  11561. };
  11562. /**************************************************************
  11563. * Arc curve
  11564. **************************************************************/
  11565. THREE.ArcCurve = function ( aX, aY, aRadius,
  11566. aStartAngle, aEndAngle,
  11567. aClockwise ) {
  11568. this.aX = aX;
  11569. this.aY = aY;
  11570. this.aRadius = aRadius;
  11571. this.aStartAngle = aStartAngle;
  11572. this.aEndAngle = aEndAngle;
  11573. this.aClockwise = aClockwise;
  11574. };
  11575. THREE.ArcCurve.prototype = new THREE.Curve();
  11576. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  11577. THREE.ArcCurve.prototype.getPoint = function ( t ) {
  11578. var deltaAngle = this.aEndAngle - this.aStartAngle;
  11579. if ( !this.aClockwise ) {
  11580. t = 1 - t;
  11581. }
  11582. var angle = this.aStartAngle + t * deltaAngle;
  11583. var tx = this.aX + this.aRadius * Math.cos( angle );
  11584. var ty = this.aY + this.aRadius * Math.sin( angle );
  11585. return new THREE.Vector2( tx, ty );
  11586. };
  11587. /**************************************************************
  11588. * Utils
  11589. **************************************************************/
  11590. THREE.Curve.Utils = {
  11591. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  11592. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  11593. },
  11594. // Puay Bing, thanks for helping with this derivative!
  11595. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  11596. return -3 * p0 * (1 - t) * (1 - t) +
  11597. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  11598. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  11599. 3 * t * t * p3;
  11600. },
  11601. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  11602. // To check if my formulas are correct
  11603. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  11604. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  11605. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  11606. var h11 = 3 * t * t - 2 * t; // t3 − t2
  11607. return h00 + h10 + h01 + h11;
  11608. },
  11609. // Catmull-Rom
  11610. interpolate: function( p0, p1, p2, p3, t ) {
  11611. var v0 = ( p2 - p0 ) * 0.5;
  11612. var v1 = ( p3 - p1 ) * 0.5;
  11613. var t2 = t * t;
  11614. var t3 = t * t2;
  11615. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  11616. }
  11617. };
  11618. /*
  11619. getPoint DONE
  11620. getLength DONE
  11621. getLengths DONE
  11622. curve.getPoints(); DONE
  11623. curve.getPointAtArcLength(t); DONE
  11624. curve.transform(params);
  11625. curve.getTangentAt(t); DONE
  11626. */
  11627. /**************************************************************
  11628. * 3D Curves
  11629. **************************************************************/
  11630. // A Factory method for creating new curve subclasses
  11631. THREE.Curve.create = function( constructor, getPointFunc ) {
  11632. var subClass = constructor;
  11633. subClass.prototype = new THREE.Curve();
  11634. subClass.prototype.constructor = constructor;
  11635. subClass.prototype.getPoint = getPointFunc;
  11636. return subClass;
  11637. };
  11638. /**************************************************************
  11639. * Line3D
  11640. **************************************************************/
  11641. THREE.LineCurve3 = THREE.Curve.create(
  11642. function ( v1, v2 ) {
  11643. this.v1 = v1;
  11644. this.v2 = v2;
  11645. },
  11646. function ( t ) {
  11647. var r = new THREE.Vector3();
  11648. r.sub( this.v2, this.v1 ); // diff
  11649. r.multiplyScalar( t );
  11650. r.addSelf( this.v1 );
  11651. return r;
  11652. }
  11653. );
  11654. /**************************************************************
  11655. * Quadratic Bezier 3D curve
  11656. **************************************************************/
  11657. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  11658. function ( v0, v1, v2 ) {
  11659. this.v0 = v0;
  11660. this.v1 = v1;
  11661. this.v2 = v2;
  11662. },
  11663. function ( t ) {
  11664. var tx, ty, tz;
  11665. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11666. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11667. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  11668. return new THREE.Vector3( tx, ty, tz );
  11669. }
  11670. );
  11671. /**************************************************************
  11672. * Cubic Bezier 3D curve
  11673. **************************************************************/
  11674. THREE.CubicBezierCurve3 = THREE.Curve.create(
  11675. function ( v0, v1, v2, v3 ) {
  11676. this.v0 = v0;
  11677. this.v1 = v1;
  11678. this.v2 = v2;
  11679. this.v3 = v3;
  11680. },
  11681. function ( t ) {
  11682. var tx, ty, tz;
  11683. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11684. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11685. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  11686. return new THREE.Vector3( tx, ty, tz );
  11687. }
  11688. );
  11689. /**************************************************************
  11690. * Spline 3D curve
  11691. **************************************************************/
  11692. THREE.SplineCurve3 = THREE.Curve.create(
  11693. function ( points /* array of Vector3 */) {
  11694. this.points = (points == undefined) ? [] : points;
  11695. },
  11696. function ( t ) {
  11697. var v = new THREE.Vector3();
  11698. var c = [];
  11699. var points = this.points, point, intPoint, weight;
  11700. point = ( points.length - 1 ) * t;
  11701. intPoint = Math.floor( point );
  11702. weight = point - intPoint;
  11703. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11704. c[ 1 ] = intPoint;
  11705. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11706. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11707. var pt0 = points[ c[0] ],
  11708. pt1 = points[ c[1] ],
  11709. pt2 = points[ c[2] ],
  11710. pt3 = points[ c[3] ];
  11711. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  11712. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  11713. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  11714. return v;
  11715. }
  11716. );
  11717. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  11718. // var v = new THREE.Vector3();
  11719. // var c = [];
  11720. // var points = this.points, point, intPoint, weight;
  11721. // point = ( points.length - 1 ) * t;
  11722. // intPoint = Math.floor( point );
  11723. // weight = point - intPoint;
  11724. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11725. // c[ 1 ] = intPoint;
  11726. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11727. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11728. // var pt0 = points[ c[0] ],
  11729. // pt1 = points[ c[1] ],
  11730. // pt2 = points[ c[2] ],
  11731. // pt3 = points[ c[3] ];
  11732. // // t = weight;
  11733. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  11734. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  11735. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  11736. // return v;
  11737. // }
  11738. /**************************************************************
  11739. * Closed Spline 3D curve
  11740. **************************************************************/
  11741. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  11742. function ( points /* array of Vector3 */) {
  11743. this.points = (points == undefined) ? [] : points;
  11744. },
  11745. function ( t ) {
  11746. var v = new THREE.Vector3();
  11747. var c = [];
  11748. var points = this.points, point, intPoint, weight;
  11749. point = ( points.length - 0 ) * t;
  11750. // This needs to be from 0-length +1
  11751. intPoint = Math.floor( point );
  11752. weight = point - intPoint;
  11753. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  11754. c[ 0 ] = ( intPoint - 1 ) % points.length;
  11755. c[ 1 ] = ( intPoint ) % points.length;
  11756. c[ 2 ] = ( intPoint + 1 ) % points.length;
  11757. c[ 3 ] = ( intPoint + 2 ) % points.length;
  11758. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11759. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11760. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  11761. return v;
  11762. }
  11763. );/**
  11764. * @author zz85 / http://www.lab4games.net/zz85/blog
  11765. *
  11766. **/
  11767. /**************************************************************
  11768. * Curved Path - a curve path is simply a array of connected
  11769. * curves, but retains the api of a curve
  11770. **************************************************************/
  11771. THREE.CurvePath = function () {
  11772. this.curves = [];
  11773. this.bends = [];
  11774. this.autoClose = false; // Automatically closes the path
  11775. };
  11776. THREE.CurvePath.prototype = new THREE.Curve();
  11777. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  11778. THREE.CurvePath.prototype.add = function ( curve ) {
  11779. this.curves.push( curve );
  11780. };
  11781. THREE.CurvePath.prototype.checkConnection = function() {
  11782. // TODO
  11783. // If the ending of curve is not connected to the starting
  11784. // or the next curve, then, this is not a real path
  11785. };
  11786. THREE.CurvePath.prototype.closePath = function() {
  11787. // TODO Test
  11788. // and verify for vector3 (needs to implement equals)
  11789. // Add a line curve if start and end of lines are not connected
  11790. var startPoint = this.curves[0].getPoint(0);
  11791. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  11792. if (!startPoint.equals(endPoint)) {
  11793. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  11794. }
  11795. };
  11796. // To get accurate point with reference to
  11797. // entire path distance at time t,
  11798. // following has to be done:
  11799. // 1. Length of each sub path have to be known
  11800. // 2. Locate and identify type of curve
  11801. // 3. Get t for the curve
  11802. // 4. Return curve.getPointAt(t')
  11803. THREE.CurvePath.prototype.getPoint = function( t ) {
  11804. var d = t * this.getLength();
  11805. var curveLengths = this.getCurveLengths();
  11806. var i = 0, diff, curve;
  11807. // To think about boundaries points.
  11808. while ( i < curveLengths.length ) {
  11809. if ( curveLengths[ i ] >= d ) {
  11810. diff = curveLengths[ i ] - d;
  11811. curve = this.curves[ i ];
  11812. var u = 1 - diff / curve.getLength();
  11813. return curve.getPointAt( u );
  11814. break;
  11815. }
  11816. i ++;
  11817. }
  11818. return null;
  11819. // loop where sum != 0, sum > d , sum+1 <d
  11820. };
  11821. /*
  11822. THREE.CurvePath.prototype.getTangent = function( t ) {
  11823. };*/
  11824. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11825. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11826. // getPoint() depends on getLength
  11827. THREE.CurvePath.prototype.getLength = function() {
  11828. var lens = this.getCurveLengths();
  11829. return lens[ lens.length - 1 ];
  11830. };
  11831. // Compute lengths and cache them
  11832. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11833. THREE.CurvePath.prototype.getCurveLengths = function() {
  11834. // We use cache values if curves and cache array are same length
  11835. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  11836. return this.cacheLengths;
  11837. };
  11838. // Get length of subsurve
  11839. // Push sums into cached array
  11840. var lengths = [], sums = 0;
  11841. var i, il = this.curves.length;
  11842. for ( i = 0; i < il; i ++ ) {
  11843. sums += this.curves[ i ].getLength();
  11844. lengths.push( sums );
  11845. }
  11846. this.cacheLengths = lengths;
  11847. return lengths;
  11848. };
  11849. // Returns min and max coordinates, as well as centroid
  11850. THREE.CurvePath.prototype.getBoundingBox = function () {
  11851. var points = this.getPoints();
  11852. var maxX, maxY;
  11853. var minX, minY;
  11854. maxX = maxY = Number.NEGATIVE_INFINITY;
  11855. minX = minY = Number.POSITIVE_INFINITY;
  11856. var p, i, il, sum;
  11857. sum = new THREE.Vector2();
  11858. for ( i = 0, il = points.length; i < il; i ++ ) {
  11859. p = points[ i ];
  11860. if ( p.x > maxX ) maxX = p.x;
  11861. else if ( p.x < minX ) minX = p.x;
  11862. if ( p.y > maxY ) maxY = p.y;
  11863. else if ( p.y < maxY ) minY = p.y;
  11864. sum.addSelf( p.x, p.y );
  11865. }
  11866. return {
  11867. minX: minX,
  11868. minY: minY,
  11869. maxX: maxX,
  11870. maxY: maxY,
  11871. centroid: sum.divideScalar( il )
  11872. };
  11873. };
  11874. /**************************************************************
  11875. * Create Geometries Helpers
  11876. **************************************************************/
  11877. /// Generate geometry from path points (for Line or ParticleSystem objects)
  11878. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  11879. var pts = this.getPoints( divisions, true );
  11880. return this.createGeometry( pts );
  11881. };
  11882. // Generate geometry from equidistance sampling along the path
  11883. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  11884. var pts = this.getSpacedPoints( divisions, true );
  11885. return this.createGeometry( pts );
  11886. };
  11887. THREE.CurvePath.prototype.createGeometry = function( points ) {
  11888. var geometry = new THREE.Geometry();
  11889. for( var i = 0; i < points.length; i ++ ) {
  11890. geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( points[ i ].x, points[ i ].y, 0 ) ) );
  11891. }
  11892. return geometry;
  11893. };
  11894. /**************************************************************
  11895. * Bend / Wrap Helper Methods
  11896. **************************************************************/
  11897. // Wrap path / Bend modifiers?
  11898. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  11899. this.bends.push( bendpath );
  11900. };
  11901. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  11902. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  11903. var i, il;
  11904. if ( !bends ) {
  11905. bends = this.bends;
  11906. }
  11907. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11908. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11909. }
  11910. return oldPts;
  11911. };
  11912. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  11913. var oldPts = this.getSpacedPoints( segments );
  11914. var i, il;
  11915. if ( !bends ) {
  11916. bends = this.bends;
  11917. }
  11918. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11919. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11920. }
  11921. return oldPts;
  11922. };
  11923. // This returns getPoints() bend/wrapped around the contour of a path.
  11924. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  11925. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  11926. var bounds = this.getBoundingBox();
  11927. var i, il, p, oldX, oldY, xNorm;
  11928. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  11929. p = oldPts[ i ];
  11930. oldX = p.x;
  11931. oldY = p.y;
  11932. xNorm = oldX / bounds.maxX;
  11933. // If using actual distance, for length > path, requires line extrusions
  11934. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  11935. xNorm = path.getUtoTmapping( xNorm, oldX );
  11936. // check for out of bounds?
  11937. var pathPt = path.getPoint( xNorm );
  11938. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  11939. p.x = pathPt.x + normal.x;
  11940. p.y = pathPt.y + normal.y;
  11941. }
  11942. return oldPts;
  11943. };
  11944. /**
  11945. * https://github.com/mrdoob/eventtarget.js/
  11946. */
  11947. THREE.EventTarget = function () {
  11948. var listeners = {};
  11949. this.addEventListener = function ( type, listener ) {
  11950. if ( listeners[ type ] == undefined ) {
  11951. listeners[ type ] = [];
  11952. }
  11953. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  11954. listeners[ type ].push( listener );
  11955. }
  11956. };
  11957. this.dispatchEvent = function ( event ) {
  11958. for ( var listener in listeners[ event.type ] ) {
  11959. listeners[ event.type ][ listener ]( event );
  11960. }
  11961. };
  11962. this.removeEventListener = function ( type, listener ) {
  11963. var index = listeners[ type ].indexOf( listener );
  11964. if ( index !== - 1 ) {
  11965. listeners[ type ].splice( index, 1 );
  11966. }
  11967. };
  11968. };
  11969. /**
  11970. * @author alteredq / http://alteredqualia.com/
  11971. */
  11972. THREE.Gyroscope = function () {
  11973. THREE.Object3D.call( this );
  11974. };
  11975. THREE.Gyroscope.prototype = new THREE.Object3D();
  11976. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  11977. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  11978. this.matrixAutoUpdate && this.updateMatrix();
  11979. // update matrixWorld
  11980. if ( this.matrixWorldNeedsUpdate || force ) {
  11981. if ( this.parent ) {
  11982. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  11983. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  11984. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  11985. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  11986. } else {
  11987. this.matrixWorld.copy( this.matrix );
  11988. }
  11989. this.matrixWorldNeedsUpdate = false;
  11990. force = true;
  11991. }
  11992. // update children
  11993. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  11994. this.children[ i ].updateMatrixWorld( force );
  11995. }
  11996. };
  11997. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  11998. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  11999. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  12000. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  12001. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  12002. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  12003. /**
  12004. * @author zz85 / http://www.lab4games.net/zz85/blog
  12005. * Creates free form 2d path using series of points, lines or curves.
  12006. *
  12007. **/
  12008. THREE.Path = function ( points ) {
  12009. THREE.CurvePath.call(this);
  12010. this.actions = [];
  12011. if ( points ) {
  12012. this.fromPoints( points );
  12013. }
  12014. };
  12015. THREE.Path.prototype = new THREE.CurvePath();
  12016. THREE.Path.prototype.constructor = THREE.Path;
  12017. THREE.PathActions = {
  12018. MOVE_TO: 'moveTo',
  12019. LINE_TO: 'lineTo',
  12020. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  12021. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  12022. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  12023. ARC: 'arc' // Circle
  12024. };
  12025. // TODO Clean up PATH API
  12026. // Create path using straight lines to connect all points
  12027. // - vectors: array of Vector2
  12028. THREE.Path.prototype.fromPoints = function ( vectors ) {
  12029. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  12030. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  12031. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  12032. };
  12033. };
  12034. // startPath() endPath()?
  12035. THREE.Path.prototype.moveTo = function ( x, y ) {
  12036. var args = Array.prototype.slice.call( arguments );
  12037. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  12038. };
  12039. THREE.Path.prototype.lineTo = function ( x, y ) {
  12040. var args = Array.prototype.slice.call( arguments );
  12041. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12042. var x0 = lastargs[ lastargs.length - 2 ];
  12043. var y0 = lastargs[ lastargs.length - 1 ];
  12044. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  12045. this.curves.push( curve );
  12046. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  12047. };
  12048. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  12049. var args = Array.prototype.slice.call( arguments );
  12050. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12051. var x0 = lastargs[ lastargs.length - 2 ];
  12052. var y0 = lastargs[ lastargs.length - 1 ];
  12053. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  12054. new THREE.Vector2( aCPx, aCPy ),
  12055. new THREE.Vector2( aX, aY ) );
  12056. this.curves.push( curve );
  12057. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  12058. };
  12059. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  12060. aCP2x, aCP2y,
  12061. aX, aY ) {
  12062. var args = Array.prototype.slice.call( arguments );
  12063. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12064. var x0 = lastargs[ lastargs.length - 2 ];
  12065. var y0 = lastargs[ lastargs.length - 1 ];
  12066. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  12067. new THREE.Vector2( aCP1x, aCP1y ),
  12068. new THREE.Vector2( aCP2x, aCP2y ),
  12069. new THREE.Vector2( aX, aY ) );
  12070. this.curves.push( curve );
  12071. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  12072. };
  12073. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  12074. var args = Array.prototype.slice.call( arguments );
  12075. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12076. var x0 = lastargs[ lastargs.length - 2 ];
  12077. var y0 = lastargs[ lastargs.length - 1 ];
  12078. //---
  12079. var npts = [ new THREE.Vector2( x0, y0 ) ];
  12080. Array.prototype.push.apply( npts, pts );
  12081. var curve = new THREE.SplineCurve( npts );
  12082. this.curves.push( curve );
  12083. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  12084. };
  12085. // FUTURE: Change the API or follow canvas API?
  12086. // TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )
  12087. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  12088. aStartAngle, aEndAngle, aClockwise ) {
  12089. var args = Array.prototype.slice.call( arguments );
  12090. var laste = this.actions[ this.actions.length - 1];
  12091. var curve = new THREE.ArcCurve( laste.x + aX, laste.y + aY, aRadius,
  12092. aStartAngle, aEndAngle, aClockwise );
  12093. this.curves.push( curve );
  12094. // All of the other actions look to the last two elements in the list to
  12095. // find the ending point, so we need to append them.
  12096. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12097. args.push(lastPoint.x);
  12098. args.push(lastPoint.y);
  12099. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12100. };
  12101. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  12102. aStartAngle, aEndAngle, aClockwise ) {
  12103. var args = Array.prototype.slice.call( arguments );
  12104. var curve = new THREE.ArcCurve( aX, aY, aRadius,
  12105. aStartAngle, aEndAngle, aClockwise );
  12106. this.curves.push( curve );
  12107. // console.log( 'arc', args );
  12108. // All of the other actions look to the last two elements in the list to
  12109. // find the ending point, so we need to append them.
  12110. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12111. args.push(lastPoint.x);
  12112. args.push(lastPoint.y);
  12113. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12114. };
  12115. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  12116. if ( ! divisions ) divisions = 40;
  12117. var points = [];
  12118. for ( var i = 0; i < divisions; i ++ ) {
  12119. points.push( this.getPoint( i / divisions ) );
  12120. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  12121. }
  12122. // if ( closedPath ) {
  12123. //
  12124. // points.push( points[ 0 ] );
  12125. //
  12126. // }
  12127. return points;
  12128. };
  12129. /* Return an array of vectors based on contour of the path */
  12130. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  12131. if (this.useSpacedPoints) {
  12132. console.log('tata');
  12133. return this.getSpacedPoints( divisions, closedPath );
  12134. }
  12135. divisions = divisions || 12;
  12136. var points = [];
  12137. var i, il, item, action, args;
  12138. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  12139. laste, j,
  12140. t, tx, ty;
  12141. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12142. item = this.actions[ i ];
  12143. action = item.action;
  12144. args = item.args;
  12145. switch( action ) {
  12146. case THREE.PathActions.MOVE_TO:
  12147. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12148. break;
  12149. case THREE.PathActions.LINE_TO:
  12150. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12151. break;
  12152. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12153. cpx = args[ 2 ];
  12154. cpy = args[ 3 ];
  12155. cpx1 = args[ 0 ];
  12156. cpy1 = args[ 1 ];
  12157. if ( points.length > 0 ) {
  12158. laste = points[ points.length - 1 ];
  12159. cpx0 = laste.x;
  12160. cpy0 = laste.y;
  12161. } else {
  12162. laste = this.actions[ i - 1 ].args;
  12163. cpx0 = laste[ laste.length - 2 ];
  12164. cpy0 = laste[ laste.length - 1 ];
  12165. }
  12166. for ( j = 1; j <= divisions; j ++ ) {
  12167. t = j / divisions;
  12168. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  12169. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  12170. points.push( new THREE.Vector2( tx, ty ) );
  12171. }
  12172. break;
  12173. case THREE.PathActions.BEZIER_CURVE_TO:
  12174. cpx = args[ 4 ];
  12175. cpy = args[ 5 ];
  12176. cpx1 = args[ 0 ];
  12177. cpy1 = args[ 1 ];
  12178. cpx2 = args[ 2 ];
  12179. cpy2 = args[ 3 ];
  12180. if ( points.length > 0 ) {
  12181. laste = points[ points.length - 1 ];
  12182. cpx0 = laste.x;
  12183. cpy0 = laste.y;
  12184. } else {
  12185. laste = this.actions[ i - 1 ].args;
  12186. cpx0 = laste[ laste.length - 2 ];
  12187. cpy0 = laste[ laste.length - 1 ];
  12188. }
  12189. for ( j = 1; j <= divisions; j ++ ) {
  12190. t = j / divisions;
  12191. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  12192. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  12193. points.push( new THREE.Vector2( tx, ty ) );
  12194. }
  12195. break;
  12196. case THREE.PathActions.CSPLINE_THRU:
  12197. laste = this.actions[ i - 1 ].args;
  12198. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  12199. var spts = [ last ];
  12200. var n = divisions * args[ 0 ].length;
  12201. spts = spts.concat( args[ 0 ] );
  12202. var spline = new THREE.SplineCurve( spts );
  12203. for ( j = 1; j <= n; j ++ ) {
  12204. points.push( spline.getPointAt( j / n ) ) ;
  12205. }
  12206. break;
  12207. case THREE.PathActions.ARC:
  12208. laste = this.actions[ i - 1 ].args;
  12209. var aX = args[ 0 ], aY = args[ 1 ],
  12210. aRadius = args[ 2 ],
  12211. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  12212. aClockwise = !!args[ 5 ];
  12213. var deltaAngle = aEndAngle - aStartAngle;
  12214. var angle;
  12215. var tdivisions = divisions * 2;
  12216. for ( j = 1; j <= tdivisions; j ++ ) {
  12217. t = j / tdivisions;
  12218. if ( ! aClockwise ) {
  12219. t = 1 - t;
  12220. }
  12221. angle = aStartAngle + t * deltaAngle;
  12222. tx = aX + aRadius * Math.cos( angle );
  12223. ty = aY + aRadius * Math.sin( angle );
  12224. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  12225. points.push( new THREE.Vector2( tx, ty ) );
  12226. }
  12227. //console.log(points);
  12228. break;
  12229. } // end switch
  12230. }
  12231. // Normalize to remove the closing point by default.
  12232. var lastPoint = points[ points.length - 1];
  12233. var EPSILON = 0.0000000001;
  12234. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  12235. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  12236. points.splice( points.length - 1, 1);
  12237. if ( closedPath ) {
  12238. points.push( points[ 0 ] );
  12239. }
  12240. return points;
  12241. };
  12242. // This was used for testing purposes. Should be removed soon.
  12243. THREE.Path.prototype.transform = function( path, segments ) {
  12244. var bounds = this.getBoundingBox();
  12245. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  12246. //console.log( path.cacheArcLengths() );
  12247. //path.getLengths(400);
  12248. //segments = 40;
  12249. return this.getWrapPoints( oldPts, path );
  12250. };
  12251. // Read http://www.tinaja.com/glib/nonlingr.pdf
  12252. // nonlinear transforms
  12253. THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {
  12254. // a - horizontal size
  12255. // b - lean
  12256. // c - x offset
  12257. // d - vertical size
  12258. // e - climb
  12259. // f - y offset
  12260. var oldPts = this.getPoints();
  12261. var i, il, p, oldX, oldY;
  12262. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  12263. p = oldPts[i];
  12264. oldX = p.x;
  12265. oldY = p.y;
  12266. p.x = a * oldX + b * oldY + c;
  12267. p.y = d * oldY + e * oldX + f;
  12268. }
  12269. return oldPts;
  12270. };
  12271. // FUTURE Export JSON Format
  12272. /* Draws this path onto a 2d canvas easily */
  12273. THREE.Path.prototype.debug = function( canvas ) {
  12274. var bounds = this.getBoundingBox();
  12275. if ( !canvas ) {
  12276. canvas = document.createElement( "canvas" );
  12277. canvas.setAttribute( 'width', bounds.maxX + 100 );
  12278. canvas.setAttribute( 'height', bounds.maxY + 100 );
  12279. document.body.appendChild( canvas );
  12280. }
  12281. var ctx = canvas.getContext( "2d" );
  12282. ctx.fillStyle = "white";
  12283. ctx.fillRect( 0, 0, canvas.width, canvas.height );
  12284. ctx.strokeStyle = "black";
  12285. ctx.beginPath();
  12286. var i, il, item, action, args;
  12287. // Debug Path
  12288. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12289. item = this.actions[ i ];
  12290. args = item.args;
  12291. action = item.action;
  12292. // Short hand for now
  12293. if ( action != THREE.PathActions.CSPLINE_THRU ) {
  12294. ctx[ action ].apply( ctx, args );
  12295. }
  12296. /*
  12297. switch ( action ) {
  12298. case THREE.PathActions.MOVE_TO:
  12299. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12300. break;
  12301. case THREE.PathActions.LINE_TO:
  12302. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12303. break;
  12304. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12305. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
  12306. break;
  12307. case THREE.PathActions.CUBIC_CURVE_TO:
  12308. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
  12309. break;
  12310. }
  12311. */
  12312. }
  12313. ctx.stroke();
  12314. ctx.closePath();
  12315. // Debug Points
  12316. ctx.strokeStyle = "red";
  12317. /* TO CLEAN UP */
  12318. var p, points = this.getPoints();
  12319. for ( i = 0, il = points.length; i < il; i ++ ) {
  12320. p = points[ i ];
  12321. ctx.beginPath();
  12322. ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
  12323. ctx.stroke();
  12324. ctx.closePath();
  12325. }
  12326. };
  12327. // Breaks path into shapes
  12328. THREE.Path.prototype.toShapes = function() {
  12329. var i, il, item, action, args;
  12330. var subPaths = [], lastPath = new THREE.Path();
  12331. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12332. item = this.actions[ i ];
  12333. args = item.args;
  12334. action = item.action;
  12335. if ( action == THREE.PathActions.MOVE_TO ) {
  12336. if ( lastPath.actions.length != 0 ) {
  12337. subPaths.push( lastPath );
  12338. lastPath = new THREE.Path();
  12339. }
  12340. }
  12341. lastPath[ action ].apply( lastPath, args );
  12342. }
  12343. if ( lastPath.actions.length != 0 ) {
  12344. subPaths.push( lastPath );
  12345. }
  12346. // console.log(subPaths);
  12347. if ( subPaths.length == 0 ) return [];
  12348. var tmpPath, tmpShape, shapes = [];
  12349. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  12350. // console.log("Holes first", holesFirst);
  12351. if ( subPaths.length == 1) {
  12352. tmpPath = subPaths[0];
  12353. tmpShape = new THREE.Shape();
  12354. tmpShape.actions = tmpPath.actions;
  12355. tmpShape.curves = tmpPath.curves;
  12356. shapes.push( tmpShape );
  12357. return shapes;
  12358. };
  12359. if ( holesFirst ) {
  12360. tmpShape = new THREE.Shape();
  12361. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12362. tmpPath = subPaths[ i ];
  12363. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12364. tmpShape.actions = tmpPath.actions;
  12365. tmpShape.curves = tmpPath.curves;
  12366. shapes.push( tmpShape );
  12367. tmpShape = new THREE.Shape();
  12368. //console.log('cw', i);
  12369. } else {
  12370. tmpShape.holes.push( tmpPath );
  12371. //console.log('ccw', i);
  12372. }
  12373. }
  12374. } else {
  12375. // Shapes first
  12376. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12377. tmpPath = subPaths[ i ];
  12378. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12379. if ( tmpShape ) shapes.push( tmpShape );
  12380. tmpShape = new THREE.Shape();
  12381. tmpShape.actions = tmpPath.actions;
  12382. tmpShape.curves = tmpPath.curves;
  12383. } else {
  12384. tmpShape.holes.push( tmpPath );
  12385. }
  12386. }
  12387. shapes.push( tmpShape );
  12388. }
  12389. //console.log("shape", shapes);
  12390. return shapes;
  12391. };
  12392. /**
  12393. * @author zz85 / http://www.lab4games.net/zz85/blog
  12394. * Defines a 2d shape plane using paths.
  12395. **/
  12396. // STEP 1 Create a path.
  12397. // STEP 2 Turn path into shape.
  12398. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  12399. // STEP 3a - Extract points from each shape, turn to vertices
  12400. // STEP 3b - Triangulate each shape, add faces.
  12401. THREE.Shape = function ( ) {
  12402. THREE.Path.apply( this, arguments );
  12403. this.holes = [];
  12404. };
  12405. THREE.Shape.prototype = new THREE.Path();
  12406. THREE.Shape.prototype.constructor = THREE.Path;
  12407. // Convenience method to return ExtrudeGeometry
  12408. THREE.Shape.prototype.extrude = function ( options ) {
  12409. var extruded = new THREE.ExtrudeGeometry( this, options );
  12410. return extruded;
  12411. };
  12412. // Get points of holes
  12413. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  12414. var i, il = this.holes.length, holesPts = [];
  12415. for ( i = 0; i < il; i ++ ) {
  12416. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  12417. }
  12418. return holesPts;
  12419. };
  12420. // Get points of holes (spaced by regular distance)
  12421. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  12422. var i, il = this.holes.length, holesPts = [];
  12423. for ( i = 0; i < il; i ++ ) {
  12424. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  12425. }
  12426. return holesPts;
  12427. };
  12428. // Get points of shape and holes (keypoints based on segments parameter)
  12429. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  12430. return {
  12431. shape: this.getTransformedPoints( divisions ),
  12432. holes: this.getPointsHoles( divisions )
  12433. };
  12434. };
  12435. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  12436. if (this.useSpacedPoints) {
  12437. return this.extractAllSpacedPoints(divisions);
  12438. }
  12439. return this.extractAllPoints(divisions);
  12440. };
  12441. //
  12442. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  12443. //
  12444. // return {
  12445. //
  12446. // shape: this.transform( bend, divisions ),
  12447. // holes: this.getPointsHoles( divisions, bend )
  12448. //
  12449. // };
  12450. //
  12451. // };
  12452. // Get points of shape and holes (spaced by regular distance)
  12453. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  12454. return {
  12455. shape: this.getTransformedSpacedPoints( divisions ),
  12456. holes: this.getSpacedPointsHoles( divisions )
  12457. };
  12458. };
  12459. /**************************************************************
  12460. * Utils
  12461. **************************************************************/
  12462. THREE.Shape.Utils = {
  12463. /*
  12464. contour - array of vector2 for contour
  12465. holes - array of array of vector2
  12466. */
  12467. removeHoles: function ( contour, holes ) {
  12468. var shape = contour.concat(); // work on this shape
  12469. var allpoints = shape.concat();
  12470. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  12471. var prevShapeVert, nextShapeVert,
  12472. prevHoleVert, nextHoleVert,
  12473. holeIndex, shapeIndex,
  12474. shapeId, shapeGroup,
  12475. h, h2,
  12476. hole, shortest, d,
  12477. p, pts1, pts2,
  12478. tmpShape1, tmpShape2,
  12479. tmpHole1, tmpHole2,
  12480. verts = [];
  12481. for ( h = 0; h < holes.length; h ++ ) {
  12482. hole = holes[ h ];
  12483. /*
  12484. shapeholes[ h ].concat(); // preserves original
  12485. holes.push( hole );
  12486. */
  12487. Array.prototype.push.apply( allpoints, hole );
  12488. shortest = Number.POSITIVE_INFINITY;
  12489. // Find the shortest pair of pts between shape and hole
  12490. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  12491. // Using distanceToSquared() intead of distanceTo() should speed a little
  12492. // since running square roots operations are reduced.
  12493. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  12494. pts1 = hole[ h2 ];
  12495. var dist = [];
  12496. for ( p = 0; p < shape.length; p++ ) {
  12497. pts2 = shape[ p ];
  12498. d = pts1.distanceToSquared( pts2 );
  12499. dist.push( d );
  12500. if ( d < shortest ) {
  12501. shortest = d;
  12502. holeIndex = h2;
  12503. shapeIndex = p;
  12504. }
  12505. }
  12506. }
  12507. //console.log("shortest", shortest, dist);
  12508. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12509. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12510. var areaapts = [
  12511. hole[ holeIndex ],
  12512. shape[ shapeIndex ],
  12513. shape[ prevShapeVert ]
  12514. ];
  12515. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  12516. var areabpts = [
  12517. hole[ holeIndex ],
  12518. hole[ prevHoleVert ],
  12519. shape[ shapeIndex ]
  12520. ];
  12521. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  12522. var shapeOffset = 1;
  12523. var holeOffset = -1;
  12524. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  12525. shapeIndex += shapeOffset;
  12526. holeIndex += holeOffset;
  12527. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12528. shapeIndex %= shape.length;
  12529. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12530. holeIndex %= hole.length;
  12531. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12532. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12533. areaapts = [
  12534. hole[ holeIndex ],
  12535. shape[ shapeIndex ],
  12536. shape[ prevShapeVert ]
  12537. ];
  12538. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  12539. areabpts = [
  12540. hole[ holeIndex ],
  12541. hole[ prevHoleVert ],
  12542. shape[ shapeIndex ]
  12543. ];
  12544. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  12545. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  12546. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  12547. // In case areas are not correct.
  12548. //console.log("USE THIS");
  12549. shapeIndex = oldShapeIndex;
  12550. holeIndex = oldHoleIndex ;
  12551. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12552. shapeIndex %= shape.length;
  12553. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12554. holeIndex %= hole.length;
  12555. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12556. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12557. } else {
  12558. //console.log("USE THAT ")
  12559. }
  12560. tmpShape1 = shape.slice( 0, shapeIndex );
  12561. tmpShape2 = shape.slice( shapeIndex );
  12562. tmpHole1 = hole.slice( holeIndex );
  12563. tmpHole2 = hole.slice( 0, holeIndex );
  12564. // Should check orders here again?
  12565. var trianglea = [
  12566. hole[ holeIndex ],
  12567. shape[ shapeIndex ],
  12568. shape[ prevShapeVert ]
  12569. ];
  12570. var triangleb = [
  12571. hole[ holeIndex ] ,
  12572. hole[ prevHoleVert ],
  12573. shape[ shapeIndex ]
  12574. ];
  12575. verts.push( trianglea );
  12576. verts.push( triangleb );
  12577. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  12578. }
  12579. return {
  12580. shape:shape, /* shape with no holes */
  12581. isolatedPts: verts, /* isolated faces */
  12582. allpoints: allpoints
  12583. }
  12584. },
  12585. triangulateShape: function ( contour, holes ) {
  12586. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  12587. var shape = shapeWithoutHoles.shape,
  12588. allpoints = shapeWithoutHoles.allpoints,
  12589. isolatedPts = shapeWithoutHoles.isolatedPts;
  12590. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  12591. // 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.
  12592. //console.log( "triangles",triangles, triangles.length );
  12593. //console.log( "allpoints",allpoints, allpoints.length );
  12594. var i, il, f, face,
  12595. key, index,
  12596. allPointsMap = {},
  12597. isolatedPointsMap = {};
  12598. // prepare all points map
  12599. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  12600. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  12601. if ( allPointsMap[ key ] !== undefined ) {
  12602. console.log( "Duplicate point", key );
  12603. }
  12604. allPointsMap[ key ] = i;
  12605. }
  12606. // check all face vertices against all points map
  12607. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  12608. face = triangles[ i ];
  12609. for ( f = 0; f < 3; f ++ ) {
  12610. key = face[ f ].x + ":" + face[ f ].y;
  12611. index = allPointsMap[ key ];
  12612. if ( index !== undefined ) {
  12613. face[ f ] = index;
  12614. }
  12615. }
  12616. }
  12617. // check isolated points vertices against all points map
  12618. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  12619. face = isolatedPts[ i ];
  12620. for ( f = 0; f < 3; f ++ ) {
  12621. key = face[ f ].x + ":" + face[ f ].y;
  12622. index = allPointsMap[ key ];
  12623. if ( index !== undefined ) {
  12624. face[ f ] = index;
  12625. }
  12626. }
  12627. }
  12628. return triangles.concat( isolatedPts );
  12629. }, // end triangulate shapes
  12630. /*
  12631. triangulate2 : function( pts, holes ) {
  12632. // For use with Poly2Tri.js
  12633. var allpts = pts.concat();
  12634. var shape = [];
  12635. for (var p in pts) {
  12636. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  12637. }
  12638. var swctx = new js.poly2tri.SweepContext(shape);
  12639. for (var h in holes) {
  12640. var aHole = holes[h];
  12641. var newHole = []
  12642. for (i in aHole) {
  12643. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  12644. allpts.push(aHole[i]);
  12645. }
  12646. swctx.AddHole(newHole);
  12647. }
  12648. var find;
  12649. var findIndexForPt = function (pt) {
  12650. find = new THREE.Vector2(pt.x, pt.y);
  12651. var p;
  12652. for (p=0, pl = allpts.length; p<pl; p++) {
  12653. if (allpts[p].equals(find)) return p;
  12654. }
  12655. return -1;
  12656. };
  12657. // triangulate
  12658. js.poly2tri.sweep.Triangulate(swctx);
  12659. var triangles = swctx.GetTriangles();
  12660. var tr ;
  12661. var facesPts = [];
  12662. for (var t in triangles) {
  12663. tr = triangles[t];
  12664. facesPts.push([
  12665. findIndexForPt(tr.GetPoint(0)),
  12666. findIndexForPt(tr.GetPoint(1)),
  12667. findIndexForPt(tr.GetPoint(2))
  12668. ]);
  12669. }
  12670. // console.log(facesPts);
  12671. // console.log("triangles", triangles.length, triangles);
  12672. // Returns array of faces with 3 element each
  12673. return facesPts;
  12674. },
  12675. */
  12676. isClockWise: function ( pts ) {
  12677. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  12678. },
  12679. // Bezier Curves formulas obtained from
  12680. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  12681. // Quad Bezier Functions
  12682. b2p0: function ( t, p ) {
  12683. var k = 1 - t;
  12684. return k * k * p;
  12685. },
  12686. b2p1: function ( t, p ) {
  12687. return 2 * ( 1 - t ) * t * p;
  12688. },
  12689. b2p2: function ( t, p ) {
  12690. return t * t * p;
  12691. },
  12692. b2: function ( t, p0, p1, p2 ) {
  12693. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  12694. },
  12695. // Cubic Bezier Functions
  12696. b3p0: function ( t, p ) {
  12697. var k = 1 - t;
  12698. return k * k * k * p;
  12699. },
  12700. b3p1: function ( t, p ) {
  12701. var k = 1 - t;
  12702. return 3 * k * k * t * p;
  12703. },
  12704. b3p2: function ( t, p ) {
  12705. var k = 1 - t;
  12706. return 3 * k * t * t * p;
  12707. },
  12708. b3p3: function ( t, p ) {
  12709. return t * t * t * p;
  12710. },
  12711. b3: function ( t, p0, p1, p2, p3 ) {
  12712. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  12713. }
  12714. };
  12715. /**
  12716. * @author zz85 / http://www.lab4games.net/zz85/blog
  12717. *
  12718. * TextPath
  12719. *
  12720. **/
  12721. THREE.TextPath = function ( text, parameters ) {
  12722. THREE.Path.call( this );
  12723. this.parameters = parameters || {};
  12724. this.set( text );
  12725. };
  12726. THREE.TextPath.prototype.set = function ( text, parameters ) {
  12727. parameters = parameters || this.parameters;
  12728. this.text = text;
  12729. var size = parameters.size !== undefined ? parameters.size : 100;
  12730. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  12731. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  12732. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  12733. var style = parameters.style !== undefined ? parameters.style : "normal";
  12734. THREE.FontUtils.size = size;
  12735. THREE.FontUtils.divisions = curveSegments;
  12736. THREE.FontUtils.face = font;
  12737. THREE.FontUtils.weight = weight;
  12738. THREE.FontUtils.style = style;
  12739. };
  12740. THREE.TextPath.prototype.toShapes = function () {
  12741. // Get a Font data json object
  12742. var data = THREE.FontUtils.drawText( this.text );
  12743. var paths = data.paths;
  12744. var shapes = [];
  12745. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  12746. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  12747. }
  12748. return shapes;
  12749. //console.log(path);
  12750. //console.log(fontShapes);
  12751. // Either find actions or curves.
  12752. //var text3d = new THREE.ExtrudeGeometry( shapes , { amount: 20, bevelEnabled:true, bevelThickness:3 } );
  12753. //return text3d;
  12754. };
  12755. /**
  12756. * @author mikael emtinger / http://gomo.se/
  12757. */
  12758. THREE.AnimationHandler = (function() {
  12759. var playing = [];
  12760. var library = {};
  12761. var that = {};
  12762. //--- update ---
  12763. that.update = function( deltaTimeMS ) {
  12764. for( var i = 0; i < playing.length; i++ )
  12765. playing[ i ].update( deltaTimeMS );
  12766. };
  12767. //--- add ---
  12768. that.addToUpdate = function( animation ) {
  12769. if( playing.indexOf( animation ) === -1 )
  12770. playing.push( animation );
  12771. };
  12772. //--- remove ---
  12773. that.removeFromUpdate = function( animation ) {
  12774. var index = playing.indexOf( animation );
  12775. if( index !== -1 )
  12776. playing.splice( index, 1 );
  12777. };
  12778. //--- add ---
  12779. that.add = function( data ) {
  12780. if( library[ data.name ] !== undefined )
  12781. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  12782. library[ data.name ] = data;
  12783. initData( data );
  12784. };
  12785. //--- get ---
  12786. that.get = function( name ) {
  12787. if( typeof name === "string" ) {
  12788. if( library[ name ] ) {
  12789. return library[ name ];
  12790. } else {
  12791. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  12792. return null;
  12793. }
  12794. } else {
  12795. // todo: add simple tween library
  12796. }
  12797. };
  12798. //--- parse ---
  12799. that.parse = function( root ) {
  12800. // setup hierarchy
  12801. var hierarchy = [];
  12802. if ( root instanceof THREE.SkinnedMesh ) {
  12803. for( var b = 0; b < root.bones.length; b++ ) {
  12804. hierarchy.push( root.bones[ b ] );
  12805. }
  12806. } else {
  12807. parseRecurseHierarchy( root, hierarchy );
  12808. }
  12809. return hierarchy;
  12810. };
  12811. var parseRecurseHierarchy = function( root, hierarchy ) {
  12812. hierarchy.push( root );
  12813. for( var c = 0; c < root.children.length; c++ )
  12814. parseRecurseHierarchy( root.children[ c ], hierarchy );
  12815. }
  12816. //--- init data ---
  12817. var initData = function( data ) {
  12818. if( data.initialized === true )
  12819. return;
  12820. // loop through all keys
  12821. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  12822. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12823. // remove minus times
  12824. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  12825. data.hierarchy[ h ].keys[ k ].time = 0;
  12826. // create quaternions
  12827. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  12828. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  12829. var quat = data.hierarchy[ h ].keys[ k ].rot;
  12830. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  12831. }
  12832. }
  12833. // prepare morph target keys
  12834. if( data.hierarchy[h].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  12835. // get all used
  12836. var usedMorphTargets = {};
  12837. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12838. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12839. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  12840. usedMorphTargets[ morphTargetName ] = -1;
  12841. }
  12842. }
  12843. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  12844. // set all used on all frames
  12845. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12846. var influences = {};
  12847. for( var morphTargetName in usedMorphTargets ) {
  12848. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12849. if( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  12850. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  12851. break;
  12852. }
  12853. }
  12854. if( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  12855. influences[ morphTargetName ] = 0;
  12856. }
  12857. }
  12858. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  12859. }
  12860. }
  12861. // remove all keys that are on the same time
  12862. for( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12863. if( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  12864. data.hierarchy[ h ].keys.splice( k, 1 );
  12865. k --;
  12866. }
  12867. }
  12868. // set index
  12869. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12870. data.hierarchy[ h ].keys[ k ].index = k;
  12871. }
  12872. }
  12873. // JIT
  12874. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  12875. data.JIT = {};
  12876. data.JIT.hierarchy = [];
  12877. for( var h = 0; h < data.hierarchy.length; h ++ )
  12878. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  12879. // done
  12880. data.initialized = true;
  12881. };
  12882. // interpolation types
  12883. that.LINEAR = 0;
  12884. that.CATMULLROM = 1;
  12885. that.CATMULLROM_FORWARD = 2;
  12886. return that;
  12887. }());
  12888. /**
  12889. * @author mikael emtinger / http://gomo.se/
  12890. * @author mrdoob / http://mrdoob.com/
  12891. * @author alteredq / http://alteredqualia.com/
  12892. */
  12893. THREE.Animation = function( root, data, interpolationType, JITCompile ) {
  12894. this.root = root;
  12895. this.data = THREE.AnimationHandler.get( data );
  12896. this.hierarchy = THREE.AnimationHandler.parse( root );
  12897. this.currentTime = 0;
  12898. this.timeScale = 1;
  12899. this.isPlaying = false;
  12900. this.isPaused = true;
  12901. this.loop = true;
  12902. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  12903. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  12904. this.points = [];
  12905. this.target = new THREE.Vector3();
  12906. };
  12907. // Play
  12908. THREE.Animation.prototype.play = function( loop, startTimeMS ) {
  12909. if( !this.isPlaying ) {
  12910. this.isPlaying = true;
  12911. this.loop = loop !== undefined ? loop : true;
  12912. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  12913. // reset key cache
  12914. var h, hl = this.hierarchy.length,
  12915. object;
  12916. for ( h = 0; h < hl; h++ ) {
  12917. object = this.hierarchy[ h ];
  12918. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  12919. object.useQuaternion = true;
  12920. }
  12921. object.matrixAutoUpdate = true;
  12922. if ( object.animationCache === undefined ) {
  12923. object.animationCache = {};
  12924. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  12925. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  12926. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  12927. }
  12928. var prevKey = object.animationCache.prevKey;
  12929. var nextKey = object.animationCache.nextKey;
  12930. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  12931. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  12932. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  12933. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  12934. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  12935. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  12936. }
  12937. this.update( 0 );
  12938. }
  12939. this.isPaused = false;
  12940. THREE.AnimationHandler.addToUpdate( this );
  12941. };
  12942. // Pause
  12943. THREE.Animation.prototype.pause = function() {
  12944. if( this.isPaused ) {
  12945. THREE.AnimationHandler.addToUpdate( this );
  12946. } else {
  12947. THREE.AnimationHandler.removeFromUpdate( this );
  12948. }
  12949. this.isPaused = !this.isPaused;
  12950. };
  12951. // Stop
  12952. THREE.Animation.prototype.stop = function() {
  12953. this.isPlaying = false;
  12954. this.isPaused = false;
  12955. THREE.AnimationHandler.removeFromUpdate( this );
  12956. // reset JIT matrix and remove cache
  12957. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  12958. if ( this.hierarchy[ h ].animationCache !== undefined ) {
  12959. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  12960. this.hierarchy[ h ].skinMatrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12961. } else {
  12962. this.hierarchy[ h ].matrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12963. }
  12964. delete this.hierarchy[ h ].animationCache;
  12965. }
  12966. }
  12967. };
  12968. // Update
  12969. THREE.Animation.prototype.update = function( deltaTimeMS ) {
  12970. // early out
  12971. if( !this.isPlaying ) return;
  12972. // vars
  12973. var types = [ "pos", "rot", "scl" ];
  12974. var type;
  12975. var scale;
  12976. var vector;
  12977. var prevXYZ, nextXYZ;
  12978. var prevKey, nextKey;
  12979. var object;
  12980. var animationCache;
  12981. var frame;
  12982. var JIThierarchy = this.data.JIT.hierarchy;
  12983. var currentTime, unloopedCurrentTime;
  12984. var currentPoint, forwardPoint, angle;
  12985. // update
  12986. this.currentTime += deltaTimeMS * this.timeScale;
  12987. unloopedCurrentTime = this.currentTime;
  12988. currentTime = this.currentTime = this.currentTime % this.data.length;
  12989. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  12990. // update
  12991. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  12992. object = this.hierarchy[ h ];
  12993. animationCache = object.animationCache;
  12994. // use JIT?
  12995. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  12996. if( object instanceof THREE.Bone ) {
  12997. object.skinMatrix = JIThierarchy[ h ][ frame ];
  12998. object.matrixAutoUpdate = false;
  12999. object.matrixWorldNeedsUpdate = false;
  13000. } else {
  13001. object.matrix = JIThierarchy[ h ][ frame ];
  13002. object.matrixAutoUpdate = false;
  13003. object.matrixWorldNeedsUpdate = true;
  13004. }
  13005. // use interpolation
  13006. } else {
  13007. // make sure so original matrix and not JIT matrix is set
  13008. if ( this.JITCompile ) {
  13009. if( object instanceof THREE.Bone ) {
  13010. object.skinMatrix = object.animationCache.originalMatrix;
  13011. } else {
  13012. object.matrix = object.animationCache.originalMatrix;
  13013. }
  13014. }
  13015. // loop through pos/rot/scl
  13016. for ( var t = 0; t < 3; t++ ) {
  13017. // get keys
  13018. type = types[ t ];
  13019. prevKey = animationCache.prevKey[ type ];
  13020. nextKey = animationCache.nextKey[ type ];
  13021. // switch keys?
  13022. if ( nextKey.time <= unloopedCurrentTime ) {
  13023. // did we loop?
  13024. if ( currentTime < unloopedCurrentTime ) {
  13025. if ( this.loop ) {
  13026. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  13027. nextKey = this.getNextKeyWith( type, h, 1 );
  13028. while( nextKey.time < currentTime ) {
  13029. prevKey = nextKey;
  13030. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  13031. }
  13032. } else {
  13033. this.stop();
  13034. return;
  13035. }
  13036. } else {
  13037. do {
  13038. prevKey = nextKey;
  13039. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  13040. } while( nextKey.time < currentTime )
  13041. }
  13042. animationCache.prevKey[ type ] = prevKey;
  13043. animationCache.nextKey[ type ] = nextKey;
  13044. }
  13045. object.matrixAutoUpdate = true;
  13046. object.matrixWorldNeedsUpdate = true;
  13047. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  13048. prevXYZ = prevKey[ type ];
  13049. nextXYZ = nextKey[ type ];
  13050. // check scale error
  13051. if ( scale < 0 || scale > 1 ) {
  13052. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  13053. scale = scale < 0 ? 0 : 1;
  13054. }
  13055. // interpolate
  13056. if ( type === "pos" ) {
  13057. vector = object.position;
  13058. if( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  13059. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13060. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13061. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13062. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13063. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13064. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  13065. this.points[ 1 ] = prevXYZ;
  13066. this.points[ 2 ] = nextXYZ;
  13067. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  13068. scale = scale * 0.33 + 0.33;
  13069. currentPoint = this.interpolateCatmullRom( this.points, scale );
  13070. vector.x = currentPoint[ 0 ];
  13071. vector.y = currentPoint[ 1 ];
  13072. vector.z = currentPoint[ 2 ];
  13073. if( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13074. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  13075. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  13076. this.target.subSelf( vector );
  13077. this.target.y = 0;
  13078. this.target.normalize();
  13079. angle = Math.atan2( this.target.x, this.target.z );
  13080. object.rotation.set( 0, angle, 0 );
  13081. }
  13082. }
  13083. } else if ( type === "rot" ) {
  13084. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  13085. } else if( type === "scl" ) {
  13086. vector = object.scale;
  13087. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13088. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13089. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13090. }
  13091. }
  13092. }
  13093. }
  13094. // update JIT?
  13095. if ( this.JITCompile ) {
  13096. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13097. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13098. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13099. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13100. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13101. } else {
  13102. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13103. }
  13104. }
  13105. }
  13106. }
  13107. };
  13108. // Catmull-Rom spline
  13109. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  13110. var c = [], v3 = [],
  13111. point, intPoint, weight, w2, w3,
  13112. pa, pb, pc, pd;
  13113. point = ( points.length - 1 ) * scale;
  13114. intPoint = Math.floor( point );
  13115. weight = point - intPoint;
  13116. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  13117. c[ 1 ] = intPoint;
  13118. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  13119. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  13120. pa = points[ c[ 0 ] ];
  13121. pb = points[ c[ 1 ] ];
  13122. pc = points[ c[ 2 ] ];
  13123. pd = points[ c[ 3 ] ];
  13124. w2 = weight * weight;
  13125. w3 = weight * w2;
  13126. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  13127. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  13128. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  13129. return v3;
  13130. };
  13131. THREE.Animation.prototype.interpolate = function( p0, p1, p2, p3, t, t2, t3 ) {
  13132. var v0 = ( p2 - p0 ) * 0.5,
  13133. v1 = ( p3 - p1 ) * 0.5;
  13134. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  13135. };
  13136. // Get next key with
  13137. THREE.Animation.prototype.getNextKeyWith = function( type, h, key ) {
  13138. var keys = this.data.hierarchy[ h ].keys;
  13139. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13140. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13141. key = key < keys.length - 1 ? key : keys.length - 1;
  13142. } else {
  13143. key = key % keys.length;
  13144. }
  13145. for ( ; key < keys.length; key++ ) {
  13146. if ( keys[ key ][ type ] !== undefined ) {
  13147. return keys[ key ];
  13148. }
  13149. }
  13150. return this.data.hierarchy[ h ].keys[ 0 ];
  13151. };
  13152. // Get previous key with
  13153. THREE.Animation.prototype.getPrevKeyWith = function( type, h, key ) {
  13154. var keys = this.data.hierarchy[ h ].keys;
  13155. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13156. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13157. key = key > 0 ? key : 0;
  13158. } else {
  13159. key = key >= 0 ? key : key + keys.length;
  13160. }
  13161. for ( ; key >= 0; key-- ) {
  13162. if ( keys[ key ][ type ] !== undefined ) {
  13163. return keys[ key ];
  13164. }
  13165. }
  13166. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  13167. };/**
  13168. * @author mikael emtinger / http://gomo.se/
  13169. * @author mrdoob / http://mrdoob.com/
  13170. * @author alteredq / http://alteredqualia.com/
  13171. * @author khang duong
  13172. * @author erik kitson
  13173. */
  13174. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  13175. this.root = root;
  13176. this.data = THREE.AnimationHandler.get( data );
  13177. this.hierarchy = THREE.AnimationHandler.parse( root );
  13178. this.currentTime = 0;
  13179. this.timeScale = 0.001;
  13180. this.isPlaying = false;
  13181. this.isPaused = true;
  13182. this.loop = true;
  13183. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  13184. // initialize to first keyframes
  13185. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13186. var keys = this.data.hierarchy[h].keys,
  13187. sids = this.data.hierarchy[h].sids,
  13188. obj = this.hierarchy[h];
  13189. if ( keys.length && sids ) {
  13190. for ( var s = 0; s < sids.length; s++ ) {
  13191. var sid = sids[ s ],
  13192. next = this.getNextKeyWith( sid, h, 0 );
  13193. if ( next ) {
  13194. next.apply( sid );
  13195. }
  13196. }
  13197. obj.matrixAutoUpdate = false;
  13198. this.data.hierarchy[h].node.updateMatrix();
  13199. obj.matrixWorldNeedsUpdate = true;
  13200. }
  13201. }
  13202. };
  13203. // Play
  13204. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  13205. if( !this.isPlaying ) {
  13206. this.isPlaying = true;
  13207. this.loop = loop !== undefined ? loop : true;
  13208. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  13209. this.startTimeMs = startTimeMS;
  13210. this.startTime = 10000000;
  13211. this.endTime = -this.startTime;
  13212. // reset key cache
  13213. var h, hl = this.hierarchy.length,
  13214. object,
  13215. node;
  13216. for ( h = 0; h < hl; h++ ) {
  13217. object = this.hierarchy[ h ];
  13218. node = this.data.hierarchy[ h ];
  13219. object.useQuaternion = true;
  13220. if ( node.animationCache === undefined ) {
  13221. node.animationCache = {};
  13222. node.animationCache.prevKey = null;
  13223. node.animationCache.nextKey = null;
  13224. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  13225. }
  13226. var keys = this.data.hierarchy[h].keys;
  13227. if (keys.length) {
  13228. node.animationCache.prevKey = keys[ 0 ];
  13229. node.animationCache.nextKey = keys[ 1 ];
  13230. this.startTime = Math.min( keys[0].time, this.startTime );
  13231. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  13232. }
  13233. }
  13234. this.update( 0 );
  13235. }
  13236. this.isPaused = false;
  13237. THREE.AnimationHandler.addToUpdate( this );
  13238. };
  13239. // Pause
  13240. THREE.KeyFrameAnimation.prototype.pause = function() {
  13241. if( this.isPaused ) {
  13242. THREE.AnimationHandler.addToUpdate( this );
  13243. } else {
  13244. THREE.AnimationHandler.removeFromUpdate( this );
  13245. }
  13246. this.isPaused = !this.isPaused;
  13247. };
  13248. // Stop
  13249. THREE.KeyFrameAnimation.prototype.stop = function() {
  13250. this.isPlaying = false;
  13251. this.isPaused = false;
  13252. THREE.AnimationHandler.removeFromUpdate( this );
  13253. // reset JIT matrix and remove cache
  13254. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  13255. var obj = this.hierarchy[ h ];
  13256. var node = this.data.hierarchy[ h ];
  13257. if ( node.animationCache !== undefined ) {
  13258. var original = node.animationCache.originalMatrix;
  13259. if( obj instanceof THREE.Bone ) {
  13260. original.copy( obj.skinMatrix );
  13261. obj.skinMatrix = original;
  13262. } else {
  13263. original.copy( obj.matrix );
  13264. obj.matrix = original;
  13265. }
  13266. delete node.animationCache;
  13267. }
  13268. }
  13269. };
  13270. // Update
  13271. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  13272. // early out
  13273. if( !this.isPlaying ) return;
  13274. // vars
  13275. var prevKey, nextKey;
  13276. var object;
  13277. var node;
  13278. var frame;
  13279. var JIThierarchy = this.data.JIT.hierarchy;
  13280. var currentTime, unloopedCurrentTime;
  13281. var looped;
  13282. // update
  13283. this.currentTime += deltaTimeMS * this.timeScale;
  13284. unloopedCurrentTime = this.currentTime;
  13285. currentTime = this.currentTime = this.currentTime % this.data.length;
  13286. // if looped around, the current time should be based on the startTime
  13287. if ( currentTime < this.startTimeMs ) {
  13288. currentTime = this.currentTime = this.startTimeMs + currentTime;
  13289. }
  13290. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  13291. looped = currentTime < unloopedCurrentTime;
  13292. if ( looped && !this.loop ) {
  13293. // Set the animation to the last keyframes and stop
  13294. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13295. var keys = this.data.hierarchy[h].keys,
  13296. sids = this.data.hierarchy[h].sids,
  13297. end = keys.length-1,
  13298. obj = this.hierarchy[h];
  13299. if ( keys.length ) {
  13300. for ( var s = 0; s < sids.length; s++ ) {
  13301. var sid = sids[ s ],
  13302. prev = this.getPrevKeyWith( sid, h, end );
  13303. if ( prev ) {
  13304. prev.apply( sid );
  13305. }
  13306. }
  13307. this.data.hierarchy[h].node.updateMatrix();
  13308. obj.matrixWorldNeedsUpdate = true;
  13309. }
  13310. }
  13311. this.stop();
  13312. return;
  13313. }
  13314. // check pre-infinity
  13315. if ( currentTime < this.startTime ) {
  13316. return;
  13317. }
  13318. // update
  13319. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13320. object = this.hierarchy[ h ];
  13321. node = this.data.hierarchy[ h ];
  13322. var keys = node.keys,
  13323. animationCache = node.animationCache;
  13324. // use JIT?
  13325. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  13326. if( object instanceof THREE.Bone ) {
  13327. object.skinMatrix = JIThierarchy[ h ][ frame ];
  13328. object.matrixWorldNeedsUpdate = false;
  13329. } else {
  13330. object.matrix = JIThierarchy[ h ][ frame ];
  13331. object.matrixWorldNeedsUpdate = true;
  13332. }
  13333. // use interpolation
  13334. } else if ( keys.length ) {
  13335. // make sure so original matrix and not JIT matrix is set
  13336. if ( this.JITCompile && animationCache ) {
  13337. if( object instanceof THREE.Bone ) {
  13338. object.skinMatrix = animationCache.originalMatrix;
  13339. } else {
  13340. object.matrix = animationCache.originalMatrix;
  13341. }
  13342. }
  13343. prevKey = animationCache.prevKey;
  13344. nextKey = animationCache.nextKey;
  13345. if ( prevKey && nextKey ) {
  13346. // switch keys?
  13347. if ( nextKey.time <= unloopedCurrentTime ) {
  13348. // did we loop?
  13349. if ( looped && this.loop ) {
  13350. prevKey = keys[ 0 ];
  13351. nextKey = keys[ 1 ];
  13352. while ( nextKey.time < currentTime ) {
  13353. prevKey = nextKey;
  13354. nextKey = keys[ prevKey.index + 1 ];
  13355. }
  13356. } else if ( !looped ) {
  13357. var lastIndex = keys.length - 1;
  13358. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  13359. prevKey = nextKey;
  13360. nextKey = keys[ prevKey.index + 1 ];
  13361. }
  13362. }
  13363. animationCache.prevKey = prevKey;
  13364. animationCache.nextKey = nextKey;
  13365. }
  13366. if(nextKey.time >= currentTime)
  13367. prevKey.interpolate( nextKey, currentTime );
  13368. else
  13369. prevKey.interpolate( nextKey, nextKey.time);
  13370. }
  13371. this.data.hierarchy[h].node.updateMatrix();
  13372. object.matrixWorldNeedsUpdate = true;
  13373. }
  13374. }
  13375. // update JIT?
  13376. if ( this.JITCompile ) {
  13377. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13378. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13379. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13380. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13381. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13382. } else {
  13383. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13384. }
  13385. }
  13386. }
  13387. }
  13388. };
  13389. // Get next key with
  13390. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  13391. var keys = this.data.hierarchy[ h ].keys;
  13392. key = key % keys.length;
  13393. for ( ; key < keys.length; key++ ) {
  13394. if ( keys[ key ].hasTarget( sid ) ) {
  13395. return keys[ key ];
  13396. }
  13397. }
  13398. return keys[ 0 ];
  13399. };
  13400. // Get previous key with
  13401. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  13402. var keys = this.data.hierarchy[ h ].keys;
  13403. key = key >= 0 ? key : key + keys.length;
  13404. for ( ; key >= 0; key-- ) {
  13405. if ( keys[ key ].hasTarget( sid ) ) {
  13406. return keys[ key ];
  13407. }
  13408. }
  13409. return keys[ keys.length - 1 ];
  13410. };
  13411. /**
  13412. * Camera for rendering cube maps
  13413. * - renders scene into axis-aligned cube
  13414. *
  13415. * @author alteredq / http://alteredqualia.com/
  13416. */
  13417. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  13418. this.position = new THREE.Vector3();
  13419. var fov = 90, aspect = 1;
  13420. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13421. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13422. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13423. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13424. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13425. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13426. cameraPX.position = this.position;
  13427. cameraPX.up.set( 0, -1, 0 );
  13428. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  13429. cameraNX.position = this.position;
  13430. cameraNX.up.set( 0, -1, 0 );
  13431. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  13432. cameraPY.position = this.position;
  13433. cameraPY.up.set( 0, 0, 1 );
  13434. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  13435. cameraNY.position = this.position;
  13436. cameraNY.up.set( 0, 0, -1 );
  13437. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  13438. cameraPZ.position = this.position;
  13439. cameraPZ.up.set( 0, -1, 0 );
  13440. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  13441. cameraNZ.position = this.position;
  13442. cameraNZ.up.set( 0, -1, 0 );
  13443. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  13444. // cube render target
  13445. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  13446. this.updateCubeMap = function ( renderer, scene ) {
  13447. var cubeTarget = this.renderTarget;
  13448. var oldGenerateMipmaps = cubeTarget.generateMipmaps;
  13449. cubeTarget.generateMipmaps = false;
  13450. cubeTarget.activeCubeFace = 0;
  13451. renderer.render( scene, cameraPX, cubeTarget );
  13452. cubeTarget.activeCubeFace = 1;
  13453. renderer.render( scene, cameraNX, cubeTarget );
  13454. cubeTarget.activeCubeFace = 2;
  13455. renderer.render( scene, cameraPY, cubeTarget );
  13456. cubeTarget.activeCubeFace = 3;
  13457. renderer.render( scene, cameraNY, cubeTarget );
  13458. cubeTarget.activeCubeFace = 4;
  13459. renderer.render( scene, cameraPZ, cubeTarget );
  13460. cubeTarget.generateMipmaps = oldGenerateMipmaps;
  13461. cubeTarget.activeCubeFace = 5;
  13462. renderer.render( scene, cameraNZ, cubeTarget );
  13463. };
  13464. };
  13465. /*
  13466. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  13467. *
  13468. * A handy general perpose camera, for setting FOV, Lens Focal Length,
  13469. * and switching between perspective and orthographic views easily.
  13470. *
  13471. */
  13472. THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) {
  13473. THREE.Camera.call( this );
  13474. this.fov = fov;
  13475. this.left = -width / 2;
  13476. this.right = width / 2
  13477. this.top = height / 2;
  13478. this.bottom = -height / 2;
  13479. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  13480. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthonear, orthofar );
  13481. this.cameraP = new THREE.PerspectiveCamera( fov, width/height, near, far );
  13482. this.zoom = 1;
  13483. this.toPerspective();
  13484. var aspect = width/height;
  13485. };
  13486. THREE.CombinedCamera.prototype = new THREE.Camera();
  13487. THREE.CombinedCamera.prototype.constructor = THREE.CoolCamera;
  13488. THREE.CombinedCamera.prototype.toPerspective = function () {
  13489. this.near = this.cameraP.near;
  13490. this.far = this.cameraP.far;
  13491. this.cameraP.fov = this.fov / this.zoom ;
  13492. this.cameraP.updateProjectionMatrix();
  13493. this.projectionMatrix = this.cameraP.projectionMatrix;
  13494. this.inPersepectiveMode = true;
  13495. this.inOrthographicMode = false;
  13496. };
  13497. THREE.CombinedCamera.prototype.toOrthographic = function () {
  13498. // Orthographic from Perspective
  13499. var fov = this.fov;
  13500. var aspect = this.cameraP.aspect;
  13501. var near = this.cameraP.near;
  13502. var far = this.cameraP.far;
  13503. // Just pretend we want the mid plane of the viewing frustum
  13504. var hyperfocus = ( near + far ) / 2;
  13505. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  13506. var planeHeight = 2 * halfHeight;
  13507. var planeWidth = planeHeight * aspect;
  13508. var halfWidth = planeWidth / 2;
  13509. halfHeight /= this.zoom;
  13510. halfWidth /= this.zoom;
  13511. this.cameraO.left = -halfWidth;
  13512. this.cameraO.right = halfWidth;
  13513. this.cameraO.top = halfHeight;
  13514. this.cameraO.bottom = -halfHeight;
  13515. // this.cameraO.left = -farHalfWidth;
  13516. // this.cameraO.right = farHalfWidth;
  13517. // this.cameraO.top = farHalfHeight;
  13518. // this.cameraO.bottom = -farHalfHeight;
  13519. // this.cameraO.left = this.left / this.zoom;
  13520. // this.cameraO.right = this.right / this.zoom;
  13521. // this.cameraO.top = this.top / this.zoom;
  13522. // this.cameraO.bottom = this.bottom / this.zoom;
  13523. this.cameraO.updateProjectionMatrix();
  13524. this.near = this.cameraO.near;
  13525. this.far = this.cameraO.far;
  13526. this.projectionMatrix = this.cameraO.projectionMatrix;
  13527. this.inPersepectiveMode = false;
  13528. this.inOrthographicMode = true;
  13529. };
  13530. THREE.CombinedCamera.prototype.setFov = function(fov) {
  13531. this.fov = fov;
  13532. if (this.inPersepectiveMode) {
  13533. this.toPerspective();
  13534. } else {
  13535. this.toOrthographic();
  13536. }
  13537. };
  13538. /*
  13539. * Uses Focal Length (in mm) to estimate and set FOV
  13540. * 35mm (fullframe) camera is used if frame size is not specified;
  13541. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  13542. */
  13543. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  13544. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  13545. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  13546. this.setFov( fov );
  13547. return fov;
  13548. };
  13549. THREE.CombinedCamera.prototype.setZoom = function(zoom) {
  13550. this.zoom = zoom;
  13551. if (this.inPersepectiveMode) {
  13552. this.toPerspective();
  13553. } else {
  13554. this.toOrthographic();
  13555. }
  13556. };
  13557. THREE.CombinedCamera.prototype.toFrontView = function() {
  13558. this.rotation.x = 0;
  13559. this.rotation.y = 0;
  13560. this.rotation.z = 0;
  13561. //TODO: Better way to disable camera.lookAt()?
  13562. this.rotationAutoUpdate = false;
  13563. };
  13564. THREE.CombinedCamera.prototype.toBackView = function() {
  13565. this.rotation.x = 0;
  13566. this.rotation.y = Math.PI;
  13567. this.rotation.z = 0;
  13568. this.rotationAutoUpdate = false;
  13569. };
  13570. THREE.CombinedCamera.prototype.toLeftView = function() {
  13571. this.rotation.x = 0;
  13572. this.rotation.y = - Math.PI / 2;
  13573. this.rotation.z = 0;
  13574. this.rotationAutoUpdate = false;
  13575. };
  13576. THREE.CombinedCamera.prototype.toRightView = function() {
  13577. this.rotation.x = 0;
  13578. this.rotation.y = Math.PI / 2;
  13579. this.rotation.z = 0;
  13580. this.rotationAutoUpdate = false;
  13581. };
  13582. THREE.CombinedCamera.prototype.toTopView = function() {
  13583. this.rotation.x = - Math.PI / 2;
  13584. this.rotation.y = 0;
  13585. this.rotation.z = 0;
  13586. this.rotationAutoUpdate = false;
  13587. };
  13588. THREE.CombinedCamera.prototype.toBottomView = function() {
  13589. this.rotation.x = Math.PI / 2;
  13590. this.rotation.y = 0;
  13591. this.rotation.z = 0;
  13592. this.rotationAutoUpdate = false;
  13593. };
  13594. /**
  13595. * @author mrdoob / http://mrdoob.com/
  13596. * @author alteredq / http://alteredqualia.com/
  13597. * @author paulirish / http://paulirish.com/
  13598. */
  13599. THREE.FirstPersonControls = function ( object, domElement ) {
  13600. this.object = object;
  13601. this.target = new THREE.Vector3( 0, 0, 0 );
  13602. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13603. this.movementSpeed = 1.0;
  13604. this.lookSpeed = 0.005;
  13605. this.noFly = false;
  13606. this.lookVertical = true;
  13607. this.autoForward = false;
  13608. this.activeLook = true;
  13609. this.heightSpeed = false;
  13610. this.heightCoef = 1.0;
  13611. this.heightMin = 0.0;
  13612. this.constrainVertical = false;
  13613. this.verticalMin = 0;
  13614. this.verticalMax = Math.PI;
  13615. this.autoSpeedFactor = 0.0;
  13616. this.mouseX = 0;
  13617. this.mouseY = 0;
  13618. this.lat = 0;
  13619. this.lon = 0;
  13620. this.phi = 0;
  13621. this.theta = 0;
  13622. this.moveForward = false;
  13623. this.moveBackward = false;
  13624. this.moveLeft = false;
  13625. this.moveRight = false;
  13626. this.freeze = false;
  13627. this.mouseDragOn = false;
  13628. if ( this.domElement === document ) {
  13629. this.viewHalfX = window.innerWidth / 2;
  13630. this.viewHalfY = window.innerHeight / 2;
  13631. } else {
  13632. this.viewHalfX = this.domElement.offsetWidth / 2;
  13633. this.viewHalfY = this.domElement.offsetHeight / 2;
  13634. this.domElement.setAttribute( 'tabindex', -1 );
  13635. }
  13636. this.onMouseDown = function ( event ) {
  13637. if ( this.domElement !== document ) {
  13638. this.domElement.focus();
  13639. }
  13640. event.preventDefault();
  13641. event.stopPropagation();
  13642. if ( this.activeLook ) {
  13643. switch ( event.button ) {
  13644. case 0: this.moveForward = true; break;
  13645. case 2: this.moveBackward = true; break;
  13646. }
  13647. }
  13648. this.mouseDragOn = true;
  13649. };
  13650. this.onMouseUp = function ( event ) {
  13651. event.preventDefault();
  13652. event.stopPropagation();
  13653. if ( this.activeLook ) {
  13654. switch ( event.button ) {
  13655. case 0: this.moveForward = false; break;
  13656. case 2: this.moveBackward = false; break;
  13657. }
  13658. }
  13659. this.mouseDragOn = false;
  13660. };
  13661. this.onMouseMove = function ( event ) {
  13662. if ( this.domElement === document ) {
  13663. this.mouseX = event.pageX - this.viewHalfX;
  13664. this.mouseY = event.pageY - this.viewHalfY;
  13665. } else {
  13666. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13667. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13668. }
  13669. };
  13670. this.onKeyDown = function ( event ) {
  13671. switch( event.keyCode ) {
  13672. case 38: /*up*/
  13673. case 87: /*W*/ this.moveForward = true; break;
  13674. case 37: /*left*/
  13675. case 65: /*A*/ this.moveLeft = true; break;
  13676. case 40: /*down*/
  13677. case 83: /*S*/ this.moveBackward = true; break;
  13678. case 39: /*right*/
  13679. case 68: /*D*/ this.moveRight = true; break;
  13680. case 82: /*R*/ this.moveUp = true; break;
  13681. case 70: /*F*/ this.moveDown = true; break;
  13682. case 81: /*Q*/ this.freeze = !this.freeze; break;
  13683. }
  13684. };
  13685. this.onKeyUp = function ( event ) {
  13686. switch( event.keyCode ) {
  13687. case 38: /*up*/
  13688. case 87: /*W*/ this.moveForward = false; break;
  13689. case 37: /*left*/
  13690. case 65: /*A*/ this.moveLeft = false; break;
  13691. case 40: /*down*/
  13692. case 83: /*S*/ this.moveBackward = false; break;
  13693. case 39: /*right*/
  13694. case 68: /*D*/ this.moveRight = false; break;
  13695. case 82: /*R*/ this.moveUp = false; break;
  13696. case 70: /*F*/ this.moveDown = false; break;
  13697. }
  13698. };
  13699. this.update = function( delta ) {
  13700. var actualMoveSpeed = 0;
  13701. if ( this.freeze ) {
  13702. return;
  13703. } else {
  13704. if ( this.heightSpeed ) {
  13705. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  13706. var heightDelta = y - this.heightMin;
  13707. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  13708. } else {
  13709. this.autoSpeedFactor = 0.0;
  13710. }
  13711. actualMoveSpeed = delta * this.movementSpeed;
  13712. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  13713. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  13714. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  13715. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  13716. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  13717. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  13718. var actualLookSpeed = delta * this.lookSpeed;
  13719. if ( !this.activeLook ) {
  13720. actualLookSpeed = 0;
  13721. }
  13722. this.lon += this.mouseX * actualLookSpeed;
  13723. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed;
  13724. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13725. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13726. this.theta = this.lon * Math.PI / 180;
  13727. var targetPosition = this.target,
  13728. position = this.object.position;
  13729. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13730. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13731. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13732. }
  13733. var verticalLookRatio = 1;
  13734. if ( this.constrainVertical ) {
  13735. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  13736. }
  13737. this.lon += this.mouseX * actualLookSpeed;
  13738. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  13739. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13740. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13741. this.theta = this.lon * Math.PI / 180;
  13742. if ( this.constrainVertical ) {
  13743. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  13744. }
  13745. var targetPosition = this.target,
  13746. position = this.object.position;
  13747. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13748. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13749. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13750. this.object.lookAt( targetPosition );
  13751. };
  13752. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  13753. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13754. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  13755. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  13756. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  13757. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  13758. function bind( scope, fn ) {
  13759. return function () {
  13760. fn.apply( scope, arguments );
  13761. };
  13762. };
  13763. };
  13764. /**
  13765. * @author alteredq / http://alteredqualia.com/
  13766. */
  13767. THREE.PathControls = function ( object, domElement ) {
  13768. this.object = object;
  13769. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13770. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  13771. // API
  13772. this.duration = 10 * 1000; // milliseconds
  13773. this.waypoints = [];
  13774. this.useConstantSpeed = true;
  13775. this.resamplingCoef = 50;
  13776. this.debugPath = new THREE.Object3D();
  13777. this.debugDummy = new THREE.Object3D();
  13778. this.animationParent = new THREE.Object3D();
  13779. this.lookSpeed = 0.005;
  13780. this.lookVertical = true;
  13781. this.lookHorizontal = true;
  13782. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13783. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13784. // internals
  13785. this.target = new THREE.Object3D();
  13786. this.mouseX = 0;
  13787. this.mouseY = 0;
  13788. this.lat = 0;
  13789. this.lon = 0;
  13790. this.phi = 0;
  13791. this.theta = 0;
  13792. if ( this.domElement === document ) {
  13793. this.viewHalfX = window.innerWidth / 2;
  13794. this.viewHalfY = window.innerHeight / 2;
  13795. } else {
  13796. this.viewHalfX = this.domElement.offsetWidth / 2;
  13797. this.viewHalfY = this.domElement.offsetHeight / 2;
  13798. this.domElement.setAttribute( 'tabindex', -1 );
  13799. }
  13800. var PI2 = Math.PI * 2,
  13801. PI180 = Math.PI / 180;
  13802. // methods
  13803. this.update = function ( delta ) {
  13804. var srcRange, dstRange;
  13805. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  13806. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  13807. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  13808. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13809. this.phi = ( 90 - this.lat ) * PI180;
  13810. this.theta = this.lon * PI180;
  13811. this.phi = normalize_angle_rad( this.phi );
  13812. // constrain vertical look angle
  13813. srcRange = this.verticalAngleMap.srcRange;
  13814. dstRange = this.verticalAngleMap.dstRange;
  13815. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13816. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13817. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  13818. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  13819. // constrain horizontal look angle
  13820. srcRange = this.horizontalAngleMap.srcRange;
  13821. dstRange = this.horizontalAngleMap.dstRange;
  13822. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13823. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13824. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  13825. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  13826. var targetPosition = this.target.position,
  13827. position = this.object.position;
  13828. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13829. targetPosition.y = 100 * Math.cos( this.phi );
  13830. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13831. this.object.lookAt( this.target.position );
  13832. };
  13833. this.onMouseMove = function ( event ) {
  13834. if ( this.domElement === document ) {
  13835. this.mouseX = event.pageX - this.viewHalfX;
  13836. this.mouseY = event.pageY - this.viewHalfY;
  13837. } else {
  13838. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13839. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13840. }
  13841. };
  13842. // utils
  13843. function normalize_angle_rad( a ) {
  13844. var b = a % PI2;
  13845. return b >= 0 ? b : b + PI2;
  13846. };
  13847. function distance( a, b ) {
  13848. var dx = a[ 0 ] - b[ 0 ],
  13849. dy = a[ 1 ] - b[ 1 ],
  13850. dz = a[ 2 ] - b[ 2 ];
  13851. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  13852. };
  13853. function QuadraticEaseInOut ( k ) {
  13854. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  13855. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  13856. };
  13857. function bind( scope, fn ) {
  13858. return function () {
  13859. fn.apply( scope, arguments );
  13860. };
  13861. };
  13862. function initAnimationPath( parent, spline, name, duration ) {
  13863. var animationData = {
  13864. name: name,
  13865. fps: 0.6,
  13866. length: duration,
  13867. hierarchy: []
  13868. };
  13869. var i,
  13870. parentAnimation, childAnimation,
  13871. path = spline.getControlPointsArray(),
  13872. sl = spline.getLength(),
  13873. pl = path.length,
  13874. t = 0,
  13875. first = 0,
  13876. last = pl - 1;
  13877. parentAnimation = { parent: -1, keys: [] };
  13878. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13879. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13880. for ( i = 1; i < pl - 1; i++ ) {
  13881. // real distance (approximation via linear segments)
  13882. t = duration * sl.chunks[ i ] / sl.total;
  13883. // equal distance
  13884. //t = duration * ( i / pl );
  13885. // linear distance
  13886. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  13887. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  13888. }
  13889. animationData.hierarchy[ 0 ] = parentAnimation;
  13890. THREE.AnimationHandler.add( animationData );
  13891. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  13892. };
  13893. function createSplineGeometry( spline, n_sub ) {
  13894. var i, index, position,
  13895. geometry = new THREE.Geometry();
  13896. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  13897. index = i / ( spline.points.length * n_sub );
  13898. position = spline.getPoint( index );
  13899. geometry.vertices[ i ] = new THREE.Vertex( new THREE.Vector3( position.x, position.y, position.z ) );
  13900. }
  13901. return geometry;
  13902. };
  13903. function createPath( parent, spline ) {
  13904. var lineGeo = createSplineGeometry( spline, 10 ),
  13905. particleGeo = createSplineGeometry( spline, 10 ),
  13906. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  13907. lineObj = new THREE.Line( lineGeo, lineMat ),
  13908. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  13909. lineObj.scale.set( 1, 1, 1 );
  13910. parent.add( lineObj );
  13911. particleObj.scale.set( 1, 1, 1 );
  13912. parent.add( particleObj );
  13913. var waypoint,
  13914. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  13915. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  13916. for ( var i = 0; i < spline.points.length; i ++ ) {
  13917. waypoint = new THREE.Mesh( geo, mat );
  13918. waypoint.position.copy( spline.points[ i ] );
  13919. parent.add( waypoint );
  13920. }
  13921. };
  13922. this.init = function ( ) {
  13923. // constructor
  13924. this.spline = new THREE.Spline();
  13925. this.spline.initFromArray( this.waypoints );
  13926. if ( this.useConstantSpeed ) {
  13927. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  13928. }
  13929. if ( this.createDebugDummy ) {
  13930. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  13931. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  13932. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  13933. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  13934. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  13935. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  13936. dummyChild.position.set( 0, 10, 0 );
  13937. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13938. this.animationParent.add( this.object );
  13939. this.animationParent.add( this.target );
  13940. this.animationParent.add( dummyChild );
  13941. } else {
  13942. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13943. this.animationParent.add( this.target );
  13944. this.animationParent.add( this.object );
  13945. }
  13946. if ( this.createDebugPath ) {
  13947. createPath( this.debugPath, this.spline );
  13948. }
  13949. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13950. };
  13951. };
  13952. THREE.PathControlsIdCounter = 0;
  13953. /**
  13954. * @author James Baicoianu / http://www.baicoianu.com/
  13955. */
  13956. THREE.FlyControls = function ( object, domElement ) {
  13957. this.object = object;
  13958. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13959. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  13960. // API
  13961. this.movementSpeed = 1.0;
  13962. this.rollSpeed = 0.005;
  13963. this.dragToLook = false;
  13964. this.autoForward = false;
  13965. // disable default target object behavior
  13966. this.object.useQuaternion = true;
  13967. // internals
  13968. this.tmpQuaternion = new THREE.Quaternion();
  13969. this.mouseStatus = 0;
  13970. 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 };
  13971. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  13972. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  13973. this.handleEvent = function ( event ) {
  13974. if ( typeof this[ event.type ] == 'function' ) {
  13975. this[ event.type ]( event );
  13976. }
  13977. };
  13978. this.keydown = function( event ) {
  13979. if ( event.altKey ) {
  13980. return;
  13981. }
  13982. switch( event.keyCode ) {
  13983. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  13984. case 87: /*W*/ this.moveState.forward = 1; break;
  13985. case 83: /*S*/ this.moveState.back = 1; break;
  13986. case 65: /*A*/ this.moveState.left = 1; break;
  13987. case 68: /*D*/ this.moveState.right = 1; break;
  13988. case 82: /*R*/ this.moveState.up = 1; break;
  13989. case 70: /*F*/ this.moveState.down = 1; break;
  13990. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  13991. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  13992. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  13993. case 39: /*right*/ this.moveState.yawRight = 1; break;
  13994. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  13995. case 69: /*E*/ this.moveState.rollRight = 1; break;
  13996. }
  13997. this.updateMovementVector();
  13998. this.updateRotationVector();
  13999. };
  14000. this.keyup = function( event ) {
  14001. switch( event.keyCode ) {
  14002. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  14003. case 87: /*W*/ this.moveState.forward = 0; break;
  14004. case 83: /*S*/ this.moveState.back = 0; break;
  14005. case 65: /*A*/ this.moveState.left = 0; break;
  14006. case 68: /*D*/ this.moveState.right = 0; break;
  14007. case 82: /*R*/ this.moveState.up = 0; break;
  14008. case 70: /*F*/ this.moveState.down = 0; break;
  14009. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  14010. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  14011. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  14012. case 39: /*right*/ this.moveState.yawRight = 0; break;
  14013. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  14014. case 69: /*E*/ this.moveState.rollRight = 0; break;
  14015. }
  14016. this.updateMovementVector();
  14017. this.updateRotationVector();
  14018. };
  14019. this.mousedown = function( event ) {
  14020. if ( this.domElement !== document ) {
  14021. this.domElement.focus();
  14022. }
  14023. event.preventDefault();
  14024. event.stopPropagation();
  14025. if ( this.dragToLook ) {
  14026. this.mouseStatus ++;
  14027. } else {
  14028. switch ( event.button ) {
  14029. case 0: this.object.moveForward = true; break;
  14030. case 2: this.object.moveBackward = true; break;
  14031. }
  14032. }
  14033. };
  14034. this.mousemove = function( event ) {
  14035. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  14036. var container = this.getContainerDimensions();
  14037. var halfWidth = container.size[ 0 ] / 2;
  14038. var halfHeight = container.size[ 1 ] / 2;
  14039. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  14040. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  14041. this.updateRotationVector();
  14042. }
  14043. };
  14044. this.mouseup = function( event ) {
  14045. event.preventDefault();
  14046. event.stopPropagation();
  14047. if ( this.dragToLook ) {
  14048. this.mouseStatus --;
  14049. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  14050. } else {
  14051. switch ( event.button ) {
  14052. case 0: this.moveForward = false; break;
  14053. case 2: this.moveBackward = false; break;
  14054. }
  14055. }
  14056. this.updateRotationVector();
  14057. };
  14058. this.update = function( delta ) {
  14059. var moveMult = delta * this.movementSpeed;
  14060. var rotMult = delta * this.rollSpeed;
  14061. this.object.translateX( this.moveVector.x * moveMult );
  14062. this.object.translateY( this.moveVector.y * moveMult );
  14063. this.object.translateZ( this.moveVector.z * moveMult );
  14064. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  14065. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  14066. this.object.matrix.setPosition( this.object.position );
  14067. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  14068. this.object.matrixWorldNeedsUpdate = true;
  14069. };
  14070. this.updateMovementVector = function() {
  14071. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  14072. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  14073. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  14074. this.moveVector.z = ( -forward + this.moveState.back );
  14075. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  14076. };
  14077. this.updateRotationVector = function() {
  14078. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  14079. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  14080. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  14081. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  14082. };
  14083. this.getContainerDimensions = function() {
  14084. if ( this.domElement != document ) {
  14085. return {
  14086. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  14087. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  14088. };
  14089. } else {
  14090. return {
  14091. size : [ window.innerWidth, window.innerHeight ],
  14092. offset : [ 0, 0 ]
  14093. };
  14094. }
  14095. };
  14096. function bind( scope, fn ) {
  14097. return function () {
  14098. fn.apply( scope, arguments );
  14099. };
  14100. };
  14101. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  14102. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  14103. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  14104. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  14105. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  14106. this.updateMovementVector();
  14107. this.updateRotationVector();
  14108. };
  14109. /**
  14110. * @author mikael emtinger / http://gomo.se/
  14111. * @author alteredq / http://alteredqualia.com/
  14112. */
  14113. THREE.RollControls = function ( object, domElement ) {
  14114. this.object = object;
  14115. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14116. // API
  14117. this.mouseLook = true;
  14118. this.autoForward = false;
  14119. this.lookSpeed = 1;
  14120. this.movementSpeed = 1;
  14121. this.rollSpeed = 1;
  14122. this.constrainVertical = [ -0.9, 0.9 ];
  14123. // disable default target object behavior
  14124. this.object.matrixAutoUpdate = false;
  14125. // internals
  14126. this.forward = new THREE.Vector3( 0, 0, 1 );
  14127. this.roll = 0;
  14128. var xTemp = new THREE.Vector3();
  14129. var yTemp = new THREE.Vector3();
  14130. var zTemp = new THREE.Vector3();
  14131. var rollMatrix = new THREE.Matrix4();
  14132. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  14133. var mouseX = 0, mouseY = 0;
  14134. var windowHalfX = window.innerWidth / 2;
  14135. var windowHalfY = window.innerHeight / 2;
  14136. // custom update
  14137. this.update = function ( delta ) {
  14138. if ( this.mouseLook ) {
  14139. var actualLookSpeed = delta * this.lookSpeed;
  14140. this.rotateHorizontally( actualLookSpeed * mouseX );
  14141. this.rotateVertically( actualLookSpeed * mouseY );
  14142. }
  14143. var actualSpeed = delta * this.movementSpeed;
  14144. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  14145. this.object.translateZ( -actualSpeed * forwardOrAuto );
  14146. this.object.translateX( actualSpeed * sideSpeed );
  14147. this.object.translateY( actualSpeed * upSpeed );
  14148. if( doRoll ) {
  14149. this.roll += this.rollSpeed * delta * rollDirection;
  14150. }
  14151. // cap forward up / down
  14152. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  14153. this.forward.y = this.constrainVertical[ 1 ];
  14154. this.forward.normalize();
  14155. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  14156. this.forward.y = this.constrainVertical[ 0 ];
  14157. this.forward.normalize();
  14158. }
  14159. // construct unrolled camera matrix
  14160. zTemp.copy( this.forward );
  14161. yTemp.set( 0, 1, 0 );
  14162. xTemp.cross( yTemp, zTemp ).normalize();
  14163. yTemp.cross( zTemp, xTemp ).normalize();
  14164. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  14165. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  14166. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  14167. // calculate roll matrix
  14168. rollMatrix.identity();
  14169. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  14170. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  14171. // multiply camera with roll
  14172. this.object.matrix.multiplySelf( rollMatrix );
  14173. this.object.matrixWorldNeedsUpdate = true;
  14174. // set position
  14175. this.object.matrix.elements[12] = this.object.position.x;
  14176. this.object.matrix.elements[13] = this.object.position.y;
  14177. this.object.matrix.elements[14] = this.object.position.z;
  14178. };
  14179. this.translateX = function ( distance ) {
  14180. this.object.position.x += this.object.matrix.elements[0] * distance;
  14181. this.object.position.y += this.object.matrix.elements[1] * distance;
  14182. this.object.position.z += this.object.matrix.elements[2] * distance;
  14183. };
  14184. this.translateY = function ( distance ) {
  14185. this.object.position.x += this.object.matrix.elements[4] * distance;
  14186. this.object.position.y += this.object.matrix.elements[5] * distance;
  14187. this.object.position.z += this.object.matrix.elements[6] * distance;
  14188. };
  14189. this.translateZ = function ( distance ) {
  14190. this.object.position.x -= this.object.matrix.elements[8] * distance;
  14191. this.object.position.y -= this.object.matrix.elements[9] * distance;
  14192. this.object.position.z -= this.object.matrix.elements[10] * distance;
  14193. };
  14194. this.rotateHorizontally = function ( amount ) {
  14195. // please note that the amount is NOT degrees, but a scale value
  14196. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  14197. xTemp.multiplyScalar( amount );
  14198. this.forward.subSelf( xTemp );
  14199. this.forward.normalize();
  14200. };
  14201. this.rotateVertically = function ( amount ) {
  14202. // please note that the amount is NOT degrees, but a scale value
  14203. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  14204. yTemp.multiplyScalar( amount );
  14205. this.forward.addSelf( yTemp );
  14206. this.forward.normalize();
  14207. };
  14208. function onKeyDown( event ) {
  14209. switch( event.keyCode ) {
  14210. case 38: /*up*/
  14211. case 87: /*W*/ forwardSpeed = 1; break;
  14212. case 37: /*left*/
  14213. case 65: /*A*/ sideSpeed = -1; break;
  14214. case 40: /*down*/
  14215. case 83: /*S*/ forwardSpeed = -1; break;
  14216. case 39: /*right*/
  14217. case 68: /*D*/ sideSpeed = 1; break;
  14218. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  14219. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  14220. case 82: /*R*/ upSpeed = 1; break;
  14221. case 70: /*F*/ upSpeed = -1; break;
  14222. }
  14223. };
  14224. function onKeyUp( event ) {
  14225. switch( event.keyCode ) {
  14226. case 38: /*up*/
  14227. case 87: /*W*/ forwardSpeed = 0; break;
  14228. case 37: /*left*/
  14229. case 65: /*A*/ sideSpeed = 0; break;
  14230. case 40: /*down*/
  14231. case 83: /*S*/ forwardSpeed = 0; break;
  14232. case 39: /*right*/
  14233. case 68: /*D*/ sideSpeed = 0; break;
  14234. case 81: /*Q*/ doRoll = false; break;
  14235. case 69: /*E*/ doRoll = false; break;
  14236. case 82: /*R*/ upSpeed = 0; break;
  14237. case 70: /*F*/ upSpeed = 0; break;
  14238. }
  14239. };
  14240. function onMouseMove( event ) {
  14241. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  14242. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  14243. };
  14244. function onMouseDown ( event ) {
  14245. event.preventDefault();
  14246. event.stopPropagation();
  14247. switch ( event.button ) {
  14248. case 0: forwardSpeed = 1; break;
  14249. case 2: forwardSpeed = -1; break;
  14250. }
  14251. };
  14252. function onMouseUp ( event ) {
  14253. event.preventDefault();
  14254. event.stopPropagation();
  14255. switch ( event.button ) {
  14256. case 0: forwardSpeed = 0; break;
  14257. case 2: forwardSpeed = 0; break;
  14258. }
  14259. };
  14260. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14261. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  14262. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  14263. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  14264. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  14265. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  14266. };
  14267. /**
  14268. * @author Eberhard Graether / http://egraether.com/
  14269. */
  14270. THREE.TrackballControls = function ( object, domElement ) {
  14271. THREE.EventTarget.call( this );
  14272. var _this = this,
  14273. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  14274. this.object = object;
  14275. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14276. // API
  14277. this.enabled = true;
  14278. this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
  14279. this.radius = ( this.screen.width + this.screen.height ) / 4;
  14280. this.rotateSpeed = 1.0;
  14281. this.zoomSpeed = 1.2;
  14282. this.panSpeed = 0.3;
  14283. this.noRotate = false;
  14284. this.noZoom = false;
  14285. this.noPan = false;
  14286. this.staticMoving = false;
  14287. this.dynamicDampingFactor = 0.2;
  14288. this.minDistance = 0;
  14289. this.maxDistance = Infinity;
  14290. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  14291. // internals
  14292. this.target = new THREE.Vector3();
  14293. var lastPosition = new THREE.Vector3();
  14294. var _keyPressed = false,
  14295. _state = STATE.NONE,
  14296. _eye = new THREE.Vector3(),
  14297. _rotateStart = new THREE.Vector3(),
  14298. _rotateEnd = new THREE.Vector3(),
  14299. _zoomStart = new THREE.Vector2(),
  14300. _zoomEnd = new THREE.Vector2(),
  14301. _panStart = new THREE.Vector2(),
  14302. _panEnd = new THREE.Vector2();
  14303. // events
  14304. var changeEvent = { type: 'change' };
  14305. // methods
  14306. this.handleEvent = function ( event ) {
  14307. if ( typeof this[ event.type ] == 'function' ) {
  14308. this[ event.type ]( event );
  14309. }
  14310. };
  14311. this.getMouseOnScreen = function ( clientX, clientY ) {
  14312. return new THREE.Vector2(
  14313. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  14314. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  14315. );
  14316. };
  14317. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  14318. var mouseOnBall = new THREE.Vector3(
  14319. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  14320. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  14321. 0.0
  14322. );
  14323. var length = mouseOnBall.length();
  14324. if ( length > 1.0 ) {
  14325. mouseOnBall.normalize();
  14326. } else {
  14327. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  14328. }
  14329. _eye.copy( _this.object.position ).subSelf( _this.target );
  14330. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  14331. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  14332. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  14333. return projection;
  14334. };
  14335. this.rotateCamera = function () {
  14336. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  14337. if ( angle ) {
  14338. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  14339. quaternion = new THREE.Quaternion();
  14340. angle *= _this.rotateSpeed;
  14341. quaternion.setFromAxisAngle( axis, -angle );
  14342. quaternion.multiplyVector3( _eye );
  14343. quaternion.multiplyVector3( _this.object.up );
  14344. quaternion.multiplyVector3( _rotateEnd );
  14345. if ( _this.staticMoving ) {
  14346. _rotateStart = _rotateEnd;
  14347. } else {
  14348. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  14349. quaternion.multiplyVector3( _rotateStart );
  14350. }
  14351. }
  14352. };
  14353. this.zoomCamera = function () {
  14354. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  14355. if ( factor !== 1.0 && factor > 0.0 ) {
  14356. _eye.multiplyScalar( factor );
  14357. if ( _this.staticMoving ) {
  14358. _zoomStart = _zoomEnd;
  14359. } else {
  14360. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  14361. }
  14362. }
  14363. };
  14364. this.panCamera = function () {
  14365. var mouseChange = _panEnd.clone().subSelf( _panStart );
  14366. if ( mouseChange.lengthSq() ) {
  14367. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  14368. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  14369. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  14370. _this.object.position.addSelf( pan );
  14371. _this.target.addSelf( pan );
  14372. if ( _this.staticMoving ) {
  14373. _panStart = _panEnd;
  14374. } else {
  14375. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  14376. }
  14377. }
  14378. };
  14379. this.checkDistances = function () {
  14380. if ( !_this.noZoom || !_this.noPan ) {
  14381. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  14382. _this.object.position.setLength( _this.maxDistance );
  14383. }
  14384. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  14385. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  14386. }
  14387. }
  14388. };
  14389. this.update = function () {
  14390. _eye.copy( _this.object.position ).subSelf( _this.target );
  14391. if ( !_this.noRotate ) {
  14392. _this.rotateCamera();
  14393. }
  14394. if ( !_this.noZoom ) {
  14395. _this.zoomCamera();
  14396. }
  14397. if ( !_this.noPan ) {
  14398. _this.panCamera();
  14399. }
  14400. _this.object.position.add( _this.target, _eye );
  14401. _this.checkDistances();
  14402. _this.object.lookAt( _this.target );
  14403. if ( lastPosition.distanceTo( _this.object.position ) > 0 ) {
  14404. _this.dispatchEvent( changeEvent );
  14405. lastPosition.copy( _this.object.position );
  14406. }
  14407. };
  14408. // listeners
  14409. function keydown( event ) {
  14410. if ( ! _this.enabled ) return;
  14411. if ( _state !== STATE.NONE ) {
  14412. return;
  14413. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  14414. _state = STATE.ROTATE;
  14415. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  14416. _state = STATE.ZOOM;
  14417. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  14418. _state = STATE.PAN;
  14419. }
  14420. if ( _state !== STATE.NONE ) {
  14421. _keyPressed = true;
  14422. }
  14423. };
  14424. function keyup( event ) {
  14425. if ( ! _this.enabled ) return;
  14426. if ( _state !== STATE.NONE ) {
  14427. _state = STATE.NONE;
  14428. }
  14429. };
  14430. function mousedown( event ) {
  14431. if ( ! _this.enabled ) return;
  14432. event.preventDefault();
  14433. event.stopPropagation();
  14434. if ( _state === STATE.NONE ) {
  14435. _state = event.button;
  14436. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14437. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14438. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14439. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14440. } else if ( !this.noPan ) {
  14441. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14442. }
  14443. }
  14444. };
  14445. function mousemove( event ) {
  14446. if ( ! _this.enabled ) return;
  14447. if ( _keyPressed ) {
  14448. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14449. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14450. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14451. _keyPressed = false;
  14452. }
  14453. if ( _state === STATE.NONE ) {
  14454. return;
  14455. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14456. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14457. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14458. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14459. } else if ( _state === STATE.PAN && !_this.noPan ) {
  14460. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14461. }
  14462. };
  14463. function mouseup( event ) {
  14464. if ( ! _this.enabled ) return;
  14465. event.preventDefault();
  14466. event.stopPropagation();
  14467. _state = STATE.NONE;
  14468. };
  14469. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14470. this.domElement.addEventListener( 'mousemove', mousemove, false );
  14471. this.domElement.addEventListener( 'mousedown', mousedown, false );
  14472. this.domElement.addEventListener( 'mouseup', mouseup, false );
  14473. window.addEventListener( 'keydown', keydown, false );
  14474. window.addEventListener( 'keyup', keyup, false );
  14475. };
  14476. /**
  14477. * @author mr.doob / http://mrdoob.com/
  14478. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  14479. */
  14480. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  14481. THREE.Geometry.call( this );
  14482. var scope = this,
  14483. width_half = width / 2,
  14484. height_half = height / 2,
  14485. depth_half = depth / 2;
  14486. var mpx, mpy, mpz, mnx, mny, mnz;
  14487. if ( materials !== undefined ) {
  14488. if ( materials instanceof Array ) {
  14489. this.materials = materials;
  14490. } else {
  14491. this.materials = [];
  14492. for ( var i = 0; i < 6; i ++ ) {
  14493. this.materials.push( materials );
  14494. }
  14495. }
  14496. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  14497. } else {
  14498. this.materials = [];
  14499. }
  14500. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  14501. if ( sides != undefined ) {
  14502. for ( var s in sides ) {
  14503. if ( this.sides[ s ] !== undefined ) {
  14504. this.sides[ s ] = sides[ s ];
  14505. }
  14506. }
  14507. }
  14508. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  14509. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  14510. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  14511. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  14512. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  14513. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  14514. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  14515. var w, ix, iy,
  14516. gridX = segmentsWidth || 1,
  14517. gridY = segmentsHeight || 1,
  14518. width_half = width / 2,
  14519. height_half = height / 2,
  14520. offset = scope.vertices.length;
  14521. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  14522. w = 'z';
  14523. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  14524. w = 'y';
  14525. gridY = segmentsDepth || 1;
  14526. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  14527. w = 'x';
  14528. gridX = segmentsDepth || 1;
  14529. }
  14530. var gridX1 = gridX + 1,
  14531. gridY1 = gridY + 1,
  14532. segment_width = width / gridX,
  14533. segment_height = height / gridY,
  14534. normal = new THREE.Vector3();
  14535. normal[ w ] = depth > 0 ? 1 : - 1;
  14536. for ( iy = 0; iy < gridY1; iy ++ ) {
  14537. for ( ix = 0; ix < gridX1; ix ++ ) {
  14538. var vector = new THREE.Vector3();
  14539. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  14540. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  14541. vector[ w ] = depth;
  14542. scope.vertices.push( new THREE.Vertex( vector ) );
  14543. }
  14544. }
  14545. for ( iy = 0; iy < gridY; iy++ ) {
  14546. for ( ix = 0; ix < gridX; ix++ ) {
  14547. var a = ix + gridX1 * iy;
  14548. var b = ix + gridX1 * ( iy + 1 );
  14549. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  14550. var d = ( ix + 1 ) + gridX1 * iy;
  14551. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  14552. face.normal.copy( normal );
  14553. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  14554. face.materialIndex = material;
  14555. scope.faces.push( face );
  14556. scope.faceVertexUvs[ 0 ].push( [
  14557. new THREE.UV( ix / gridX, iy / gridY ),
  14558. new THREE.UV( ix / gridX, ( iy + 1 ) / gridY ),
  14559. new THREE.UV( ( ix + 1 ) / gridX, ( iy + 1 ) / gridY ),
  14560. new THREE.UV( ( ix + 1 ) / gridX, iy / gridY )
  14561. ] );
  14562. }
  14563. }
  14564. }
  14565. this.computeCentroids();
  14566. this.mergeVertices();
  14567. };
  14568. THREE.CubeGeometry.prototype = new THREE.Geometry();
  14569. THREE.CubeGeometry.prototype.constructor = THREE.CubeGeometry;
  14570. /**
  14571. * @author mr.doob / http://mrdoob.com/
  14572. */
  14573. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  14574. THREE.Geometry.call( this );
  14575. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  14576. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  14577. height = height !== undefined ? height : 100;
  14578. var heightHalf = height / 2;
  14579. var segmentsX = segmentsRadius || 8;
  14580. var segmentsY = segmentsHeight || 1;
  14581. var x, y, vertices = [], uvs = [];
  14582. for ( y = 0; y <= segmentsY; y ++ ) {
  14583. var verticesRow = [];
  14584. var uvsRow = [];
  14585. var v = y / segmentsY;
  14586. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  14587. for ( x = 0; x <= segmentsX; x ++ ) {
  14588. var u = x / segmentsX;
  14589. var xpos = radius * Math.sin( u * Math.PI * 2 );
  14590. var ypos = - v * height + heightHalf;
  14591. var zpos = radius * Math.cos( u * Math.PI * 2 );
  14592. this.vertices.push( new THREE.Vertex( new THREE.Vector3( xpos, ypos, zpos ) ) );
  14593. verticesRow.push( this.vertices.length - 1 );
  14594. uvsRow.push( new THREE.UV( u, v ) );
  14595. }
  14596. vertices.push( verticesRow );
  14597. uvs.push( uvsRow );
  14598. }
  14599. for ( y = 0; y < segmentsY; y ++ ) {
  14600. for ( x = 0; x < segmentsX; x ++ ) {
  14601. var v1 = vertices[ y ][ x ];
  14602. var v2 = vertices[ y + 1 ][ x ];
  14603. var v3 = vertices[ y + 1 ][ x + 1 ];
  14604. var v4 = vertices[ y ][ x + 1 ];
  14605. // FIXME: These normals aren't right for cones.
  14606. var n1 = this.vertices[ v1 ].position.clone().setY( 0 ).normalize();
  14607. var n2 = this.vertices[ v2 ].position.clone().setY( 0 ).normalize();
  14608. var n3 = this.vertices[ v3 ].position.clone().setY( 0 ).normalize();
  14609. var n4 = this.vertices[ v4 ].position.clone().setY( 0 ).normalize();
  14610. var uv1 = uvs[ y ][ x ].clone();
  14611. var uv2 = uvs[ y + 1 ][ x ].clone();
  14612. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  14613. var uv4 = uvs[ y ][ x + 1 ].clone();
  14614. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  14615. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  14616. }
  14617. }
  14618. // top cap
  14619. if ( !openEnded && radiusTop > 0 ) {
  14620. this.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, heightHalf, 0 ) ) );
  14621. for ( x = 0; x < segmentsX; x ++ ) {
  14622. var v1 = vertices[ 0 ][ x ];
  14623. var v2 = vertices[ 0 ][ x + 1 ];
  14624. var v3 = this.vertices.length - 1;
  14625. var n1 = new THREE.Vector3( 0, 1, 0 );
  14626. var n2 = new THREE.Vector3( 0, 1, 0 );
  14627. var n3 = new THREE.Vector3( 0, 1, 0 );
  14628. var uv1 = uvs[ 0 ][ x ].clone();
  14629. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  14630. var uv3 = new THREE.UV( uv2.u, 0 );
  14631. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14632. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14633. }
  14634. }
  14635. // bottom cap
  14636. if ( !openEnded && radiusBottom > 0 ) {
  14637. this.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, - heightHalf, 0 ) ) );
  14638. for ( x = 0; x < segmentsX; x ++ ) {
  14639. var v1 = vertices[ y ][ x + 1 ];
  14640. var v2 = vertices[ y ][ x ];
  14641. var v3 = this.vertices.length - 1;
  14642. var n1 = new THREE.Vector3( 0, - 1, 0 );
  14643. var n2 = new THREE.Vector3( 0, - 1, 0 );
  14644. var n3 = new THREE.Vector3( 0, - 1, 0 );
  14645. var uv1 = uvs[ y ][ x + 1 ].clone();
  14646. var uv2 = uvs[ y ][ x ].clone();
  14647. var uv3 = new THREE.UV( uv2.u, 1 );
  14648. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14649. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14650. }
  14651. }
  14652. this.computeCentroids();
  14653. this.computeFaceNormals();
  14654. }
  14655. THREE.CylinderGeometry.prototype = new THREE.Geometry();
  14656. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  14657. /**
  14658. * @author zz85 / http://www.lab4games.net/zz85/blog
  14659. *
  14660. * Creates extruded geometry from a path shape.
  14661. *
  14662. * parameters = {
  14663. *
  14664. * size: <float>, // size of the text
  14665. * height: <float>, // thickness to extrude text
  14666. * curveSegments: <int>, // number of points on the curves
  14667. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  14668. amount: <int>, // Amount
  14669. *
  14670. * bevelEnabled: <bool>, // turn on bevel
  14671. * bevelThickness: <float>, // how deep into text bevel goes
  14672. * bevelSize: <float>, // how far from text outline is bevel
  14673. * bevelSegments: <int>, // number of bevel layers
  14674. *
  14675. * extrudePath: <THREE.CurvePath> // 2d/3d spline path to extrude shape orthogonality to
  14676. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  14677. *
  14678. * material: <int> // material index for front and back faces
  14679. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  14680. *
  14681. * }
  14682. **/
  14683. THREE.ExtrudeGeometry = function( shapes, options ) {
  14684. if ( typeof( shapes ) === "undefined" ) {
  14685. shapes = [];
  14686. return;
  14687. }
  14688. THREE.Geometry.call( this );
  14689. shapes = shapes instanceof Array ? shapes : [ shapes ];
  14690. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  14691. this.addShapeList( shapes, options );
  14692. this.computeCentroids();
  14693. this.computeFaceNormals();
  14694. // can't really use automatic vertex normals
  14695. // as then front and back sides get smoothed too
  14696. // should do separate smoothing just for sides
  14697. //this.computeVertexNormals();
  14698. //console.log( "took", ( Date.now() - startTime ) );
  14699. };
  14700. THREE.ExtrudeGeometry.prototype = new THREE.Geometry();
  14701. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  14702. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  14703. var sl = shapes.length;
  14704. for ( var s = 0; s < sl; s ++ ) {
  14705. var shape = shapes[ s ];
  14706. this.addShape( shape, options );
  14707. }
  14708. };
  14709. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  14710. var amount = options.amount !== undefined ? options.amount : 100;
  14711. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  14712. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  14713. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  14714. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  14715. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  14716. var steps = options.steps !== undefined ? options.steps : 1;
  14717. var bendPath = options.bendPath;
  14718. var extrudePath = options.extrudePath;
  14719. var extrudePts, extrudeByPath = false;
  14720. var material = options.material;
  14721. var extrudeMaterial = options.extrudeMaterial;
  14722. var shapebb = this.shapebb;
  14723. //shapebb = shape.getBoundingBox();
  14724. var splineTube, binormal, normal, position2;
  14725. if ( extrudePath ) {
  14726. extrudePts = extrudePath.getSpacedPoints( steps );
  14727. extrudeByPath = true;
  14728. bevelEnabled = false; // bevels not supported for path extrusion
  14729. // SETUP TNB variables
  14730. // Reuse TNB from TubeGeomtry for now.
  14731. // TODO1 - have a .isClosed in spline?
  14732. // TODO2 - have have TNBs calculation refactored from TubeGeometry?
  14733. splineTube = new THREE.TubeGeometry(extrudePath, steps, 1, 1, false, false);
  14734. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  14735. binormal = new THREE.Vector3();
  14736. normal = new THREE.Vector3();
  14737. position2 = new THREE.Vector3();
  14738. }
  14739. // Safeguards if bevels are not enabled
  14740. if ( ! bevelEnabled ) {
  14741. bevelSegments = 0;
  14742. bevelThickness = 0;
  14743. bevelSize = 0;
  14744. }
  14745. // Variables initalization
  14746. var ahole, h, hl; // looping of holes
  14747. var scope = this;
  14748. var bevelPoints = [];
  14749. var shapesOffset = this.vertices.length;
  14750. if ( bendPath ) {
  14751. shape.addWrapPath( bendPath );
  14752. }
  14753. var shapePoints = shape.extractPoints();
  14754. var vertices = shapePoints.shape;
  14755. var holes = shapePoints.holes;
  14756. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  14757. if ( reverse ) {
  14758. vertices = vertices.reverse();
  14759. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  14760. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14761. ahole = holes[ h ];
  14762. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  14763. holes[ h ] = ahole.reverse();
  14764. }
  14765. }
  14766. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  14767. }
  14768. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  14769. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  14770. // Would it be better to move points after triangulation?
  14771. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  14772. // vertices = shapePoints.shape;
  14773. // holes = shapePoints.holes;
  14774. //console.log(faces);
  14775. ////
  14776. /// Handle Vertices
  14777. ////
  14778. var contour = vertices; // vertices has all points but contour has only points of circumference
  14779. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14780. ahole = holes[ h ];
  14781. vertices = vertices.concat( ahole );
  14782. }
  14783. function scalePt2 ( pt, vec, size ) {
  14784. if ( !vec ) console.log( "die" );
  14785. return vec.clone().multiplyScalar( size ).addSelf( pt );
  14786. }
  14787. var b, bs, t, z,
  14788. vert, vlen = vertices.length,
  14789. face, flen = faces.length,
  14790. cont, clen = contour.length;
  14791. //------
  14792. // Find directions for point movement
  14793. //
  14794. var RAD_TO_DEGREES = 180 / Math.PI;
  14795. function getBevelVec( pt_i, pt_j, pt_k ) {
  14796. // Algorithm 2
  14797. return getBevelVec2( pt_i, pt_j, pt_k );
  14798. }
  14799. function getBevelVec1( pt_i, pt_j, pt_k ) {
  14800. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  14801. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  14802. if ( anglea > angleb ) {
  14803. angleb += Math.PI * 2;
  14804. }
  14805. var anglec = ( anglea + angleb ) / 2;
  14806. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  14807. var x = - Math.cos( anglec );
  14808. var y = - Math.sin( anglec );
  14809. var vec = new THREE.Vector2( x, y ); //.normalize();
  14810. return vec;
  14811. }
  14812. function getBevelVec2( pt_i, pt_j, pt_k ) {
  14813. var a = THREE.ExtrudeGeometry.__v1,
  14814. b = THREE.ExtrudeGeometry.__v2,
  14815. v_hat = THREE.ExtrudeGeometry.__v3,
  14816. w_hat = THREE.ExtrudeGeometry.__v4,
  14817. p = THREE.ExtrudeGeometry.__v5,
  14818. q = THREE.ExtrudeGeometry.__v6,
  14819. v, w,
  14820. v_dot_w_hat, q_sub_p_dot_w_hat,
  14821. s, intersection;
  14822. // good reading for line-line intersection
  14823. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  14824. // define a as vector j->i
  14825. // define b as vectot k->i
  14826. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  14827. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  14828. // get unit vectors
  14829. v = a.normalize();
  14830. w = b.normalize();
  14831. // normals from pt i
  14832. v_hat.set( -v.y, v.x );
  14833. w_hat.set( w.y, -w.x );
  14834. // pts from i
  14835. p.copy( pt_i ).addSelf( v_hat );
  14836. q.copy( pt_i ).addSelf( w_hat );
  14837. if ( p.equals( q ) ) {
  14838. //console.log("Warning: lines are straight");
  14839. return w_hat.clone();
  14840. }
  14841. // Points from j, k. helps prevents points cross overover most of the time
  14842. p.copy( pt_j ).addSelf( v_hat );
  14843. q.copy( pt_k ).addSelf( w_hat );
  14844. v_dot_w_hat = v.dot( w_hat );
  14845. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  14846. // We should not reach these conditions
  14847. if ( v_dot_w_hat === 0 ) {
  14848. console.log( "Either infinite or no solutions!" );
  14849. if ( q_sub_p_dot_w_hat === 0 ) {
  14850. console.log( "Its finite solutions." );
  14851. } else {
  14852. console.log( "Too bad, no solutions." );
  14853. }
  14854. }
  14855. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  14856. if ( s < 0 ) {
  14857. // in case of emergecy, revert to algorithm 1.
  14858. return getBevelVec1( pt_i, pt_j, pt_k );
  14859. }
  14860. intersection = v.multiplyScalar( s ).addSelf( p );
  14861. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  14862. }
  14863. var contourMovements = [];
  14864. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14865. if ( j === il ) j = 0;
  14866. if ( k === il ) k = 0;
  14867. // (j)---(i)---(k)
  14868. // console.log('i,j,k', i, j , k)
  14869. var pt_i = contour[ i ];
  14870. var pt_j = contour[ j ];
  14871. var pt_k = contour[ k ];
  14872. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  14873. }
  14874. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  14875. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14876. ahole = holes[ h ];
  14877. oneHoleMovements = [];
  14878. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14879. if ( j === il ) j = 0;
  14880. if ( k === il ) k = 0;
  14881. // (j)---(i)---(k)
  14882. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  14883. }
  14884. holesMovements.push( oneHoleMovements );
  14885. verticesMovements = verticesMovements.concat( oneHoleMovements );
  14886. }
  14887. // Loop bevelSegments, 1 for the front, 1 for the back
  14888. for ( b = 0; b < bevelSegments; b ++ ) {
  14889. //for ( b = bevelSegments; b > 0; b -- ) {
  14890. t = b / bevelSegments;
  14891. z = bevelThickness * ( 1 - t );
  14892. //z = bevelThickness * t;
  14893. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  14894. //bs = bevelSize * t ; // linear
  14895. // contract shape
  14896. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14897. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14898. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  14899. v( vert.x, vert.y, - z );
  14900. }
  14901. // expand holes
  14902. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  14903. ahole = holes[ h ];
  14904. oneHoleMovements = holesMovements[ h ];
  14905. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14906. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14907. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  14908. v( vert.x, vert.y, -z );
  14909. }
  14910. }
  14911. }
  14912. bs = bevelSize;
  14913. // Back facing vertices
  14914. for ( i = 0; i < vlen; i ++ ) {
  14915. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14916. if ( !extrudeByPath ) {
  14917. v( vert.x, vert.y, 0 );
  14918. } else {
  14919. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  14920. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  14921. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  14922. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  14923. v(position2.x, position2.y, position2.z);
  14924. }
  14925. }
  14926. // Add stepped vertices...
  14927. // Including front facing vertices
  14928. var s;
  14929. for ( s = 1; s <= steps; s ++ ) {
  14930. for ( i = 0; i < vlen; i ++ ) {
  14931. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14932. if ( !extrudeByPath ) {
  14933. v( vert.x, vert.y, amount / steps * s );
  14934. } else {
  14935. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  14936. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  14937. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  14938. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  14939. v(position2.x, position2.y, position2.z );
  14940. }
  14941. }
  14942. }
  14943. // Add bevel segments planes
  14944. //for ( b = 1; b <= bevelSegments; b ++ ) {
  14945. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  14946. t = b / bevelSegments;
  14947. z = bevelThickness * ( 1 - t );
  14948. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  14949. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  14950. // contract shape
  14951. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14952. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14953. v( vert.x, vert.y, amount + z );
  14954. }
  14955. // expand holes
  14956. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14957. ahole = holes[ h ];
  14958. oneHoleMovements = holesMovements[ h ];
  14959. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14960. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14961. if ( !extrudeByPath ) {
  14962. v( vert.x, vert.y, amount + z );
  14963. } else {
  14964. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  14965. }
  14966. }
  14967. }
  14968. }
  14969. // set UV generator
  14970. var uvgen = THREE.ExtrudeGeometry.WorldUVGenerator;
  14971. ////
  14972. /// Handle Faces
  14973. ////
  14974. // Top and bottom faces
  14975. buildLidFaces();
  14976. // Sides faces
  14977. buildSideFaces();
  14978. ///// Internal functions
  14979. function buildLidFaces() {
  14980. if ( bevelEnabled ) {
  14981. var layer = 0 ; // steps + 1
  14982. var offset = vlen * layer;
  14983. // Bottom faces
  14984. for ( i = 0; i < flen; i ++ ) {
  14985. face = faces[ i ];
  14986. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  14987. }
  14988. layer = steps + bevelSegments * 2;
  14989. offset = vlen * layer;
  14990. // Top faces
  14991. for ( i = 0; i < flen; i ++ ) {
  14992. face = faces[ i ];
  14993. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  14994. }
  14995. } else {
  14996. // Bottom faces
  14997. for ( i = 0; i < flen; i++ ) {
  14998. face = faces[ i ];
  14999. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  15000. }
  15001. // Top faces
  15002. for ( i = 0; i < flen; i ++ ) {
  15003. face = faces[ i ];
  15004. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  15005. }
  15006. }
  15007. }
  15008. // Create faces for the z-sides of the shape
  15009. function buildSideFaces() {
  15010. var layeroffset = 0;
  15011. sidewalls( contour, layeroffset );
  15012. layeroffset += contour.length;
  15013. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15014. ahole = holes[ h ];
  15015. sidewalls( ahole, layeroffset );
  15016. //, true
  15017. layeroffset += ahole.length;
  15018. }
  15019. }
  15020. function sidewalls( contour, layeroffset ) {
  15021. var j, k;
  15022. i = contour.length;
  15023. while ( --i >= 0 ) {
  15024. j = i;
  15025. k = i - 1;
  15026. if ( k < 0 ) k = contour.length - 1;
  15027. //console.log('b', i,j, i-1, k,vertices.length);
  15028. var s = 0, sl = steps + bevelSegments * 2;
  15029. for ( s = 0; s < sl; s ++ ) {
  15030. var slen1 = vlen * s;
  15031. var slen2 = vlen * ( s + 1 );
  15032. var a = layeroffset + j + slen1,
  15033. b = layeroffset + k + slen1,
  15034. c = layeroffset + k + slen2,
  15035. d = layeroffset + j + slen2;
  15036. f4( a, b, c, d, contour, s, sl );
  15037. }
  15038. }
  15039. }
  15040. function v( x, y, z ) {
  15041. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  15042. }
  15043. function f3( a, b, c, isBottom ) {
  15044. a += shapesOffset;
  15045. b += shapesOffset;
  15046. c += shapesOffset;
  15047. // normal, color, material
  15048. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  15049. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  15050. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  15051. scope.faceVertexUvs[ 0 ].push(uvs);
  15052. }
  15053. function f4( a, b, c, d, wallContour, stepIndex, stepsLength ) {
  15054. a += shapesOffset;
  15055. b += shapesOffset;
  15056. c += shapesOffset;
  15057. d += shapesOffset;
  15058. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  15059. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, stepIndex, stepsLength);
  15060. scope.faceVertexUvs[ 0 ].push(uvs);
  15061. }
  15062. };
  15063. THREE.ExtrudeGeometry.WorldUVGenerator = {
  15064. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15065. var ax = geometry.vertices[ indexA ].position.x,
  15066. ay = geometry.vertices[ indexA ].position.y,
  15067. bx = geometry.vertices[ indexB ].position.x,
  15068. by = geometry.vertices[ indexB ].position.y,
  15069. cx = geometry.vertices[ indexC ].position.x,
  15070. cy = geometry.vertices[ indexC ].position.y;
  15071. return [
  15072. new THREE.UV( ax, 1 - ay ),
  15073. new THREE.UV( bx, 1 - by ),
  15074. new THREE.UV( cx, 1 - cy )
  15075. ];
  15076. },
  15077. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15078. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  15079. },
  15080. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  15081. indexA, indexB, indexC, indexD, stepIndex, stepsLength) {
  15082. var ax = geometry.vertices[ indexA ].position.x,
  15083. ay = geometry.vertices[ indexA ].position.y,
  15084. az = geometry.vertices[ indexA ].position.z,
  15085. bx = geometry.vertices[ indexB ].position.x,
  15086. by = geometry.vertices[ indexB ].position.y,
  15087. bz = geometry.vertices[ indexB ].position.z,
  15088. cx = geometry.vertices[ indexC ].position.x,
  15089. cy = geometry.vertices[ indexC ].position.y,
  15090. cz = geometry.vertices[ indexC ].position.z,
  15091. dx = geometry.vertices[ indexD ].position.x,
  15092. dy = geometry.vertices[ indexD ].position.y,
  15093. dz = geometry.vertices[ indexD ].position.z;
  15094. if ( Math.abs( ay - by ) < 0.01 ) {
  15095. return [
  15096. new THREE.UV( ax, az ),
  15097. new THREE.UV( bx, bz ),
  15098. new THREE.UV( cx, cz ),
  15099. new THREE.UV( dx, dz )
  15100. ];
  15101. } else {
  15102. return [
  15103. new THREE.UV( ay, az ),
  15104. new THREE.UV( by, bz ),
  15105. new THREE.UV( cy, cz ),
  15106. new THREE.UV( dy, dz )
  15107. ];
  15108. }
  15109. }
  15110. };
  15111. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  15112. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  15113. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  15114. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  15115. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  15116. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  15117. /**
  15118. * @author astrodud / http://astrodud.isgreat.org/
  15119. */
  15120. THREE.LatheGeometry = function ( points, steps, angle ) {
  15121. THREE.Geometry.call( this );
  15122. this.steps = steps || 12;
  15123. this.angle = angle || 2 * Math.PI;
  15124. var stepSize = this.angle / this.steps,
  15125. newV = [], oldInds = [], newInds = [], startInds = [],
  15126. matrix = new THREE.Matrix4().makeRotationZ( stepSize );
  15127. for ( var j = 0; j < points.length; j ++ ) {
  15128. this.vertices.push( new THREE.Vertex( points[ j ] ) );
  15129. newV[ j ] = points[ j ].clone();
  15130. oldInds[ j ] = this.vertices.length - 1;
  15131. }
  15132. for ( var r = 0; r <= this.angle + 0.001; r += stepSize ) { // need the +0.001 for it go up to angle
  15133. for ( var j = 0; j < newV.length; j ++ ) {
  15134. if ( r < this.angle ) {
  15135. newV[ j ] = matrix.multiplyVector3( newV[ j ].clone() );
  15136. this.vertices.push( new THREE.Vertex( newV[ j ] ) );
  15137. newInds[ j ] = this.vertices.length - 1;
  15138. } else {
  15139. newInds = startInds; // wrap it up!
  15140. }
  15141. }
  15142. if ( r == 0 ) startInds = oldInds;
  15143. for ( var j = 0; j < oldInds.length - 1; j ++ ) {
  15144. this.faces.push( new THREE.Face4( newInds[ j ], newInds[ j + 1 ], oldInds[ j + 1 ], oldInds[ j ] ) );
  15145. this.faceVertexUvs[ 0 ].push( [
  15146. new THREE.UV( 1 - r / this.angle, j / points.length ),
  15147. new THREE.UV( 1 - r / this.angle, ( j + 1 ) / points.length ),
  15148. new THREE.UV( 1 - ( r - stepSize ) / this.angle, ( j + 1 ) / points.length ),
  15149. new THREE.UV( 1 - ( r - stepSize ) / this.angle, j / points.length )
  15150. ] );
  15151. }
  15152. oldInds = newInds;
  15153. newInds = [];
  15154. }
  15155. this.computeCentroids();
  15156. this.computeFaceNormals();
  15157. this.computeVertexNormals();
  15158. };
  15159. THREE.LatheGeometry.prototype = new THREE.Geometry();
  15160. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  15161. /**
  15162. * @author mr.doob / http://mrdoob.com/
  15163. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  15164. */
  15165. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  15166. THREE.Geometry.call( this );
  15167. var ix, iz,
  15168. width_half = width / 2,
  15169. depth_half = depth / 2,
  15170. gridX = segmentsWidth || 1,
  15171. gridZ = segmentsDepth || 1,
  15172. gridX1 = gridX + 1,
  15173. gridZ1 = gridZ + 1,
  15174. segment_width = width / gridX,
  15175. segment_depth = depth / gridZ,
  15176. normal = new THREE.Vector3( 0, 1, 0 );
  15177. for ( iz = 0; iz < gridZ1; iz ++ ) {
  15178. for ( ix = 0; ix < gridX1; ix ++ ) {
  15179. var x = ix * segment_width - width_half;
  15180. var z = iz * segment_depth - depth_half;
  15181. this.vertices.push( new THREE.Vertex( new THREE.Vector3( x, 0, z ) ) );
  15182. }
  15183. }
  15184. for ( iz = 0; iz < gridZ; iz ++ ) {
  15185. for ( ix = 0; ix < gridX; ix ++ ) {
  15186. var a = ix + gridX1 * iz;
  15187. var b = ix + gridX1 * ( iz + 1 );
  15188. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  15189. var d = ( ix + 1 ) + gridX1 * iz;
  15190. var face = new THREE.Face4( a, b, c, d );
  15191. face.normal.copy( normal );
  15192. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  15193. this.faces.push( face );
  15194. this.faceVertexUvs[ 0 ].push( [
  15195. new THREE.UV( ix / gridX, iz / gridZ ),
  15196. new THREE.UV( ix / gridX, ( iz + 1 ) / gridZ ),
  15197. new THREE.UV( ( ix + 1 ) / gridX, ( iz + 1 ) / gridZ ),
  15198. new THREE.UV( ( ix + 1 ) / gridX, iz / gridZ )
  15199. ] );
  15200. }
  15201. }
  15202. this.computeCentroids();
  15203. };
  15204. THREE.PlaneGeometry.prototype = new THREE.Geometry();
  15205. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  15206. /**
  15207. * @author mr.doob / http://mrdoob.com/
  15208. */
  15209. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  15210. THREE.Geometry.call( this );
  15211. radius = radius || 50;
  15212. phiStart = phiStart !== undefined ? phiStart : 0;
  15213. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  15214. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  15215. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  15216. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  15217. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  15218. var x, y, vertices = [], uvs = [];
  15219. for ( y = 0; y <= segmentsY; y ++ ) {
  15220. var verticesRow = [];
  15221. var uvsRow = [];
  15222. for ( x = 0; x <= segmentsX; x ++ ) {
  15223. var u = x / segmentsX;
  15224. var v = y / segmentsY;
  15225. var xpos = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15226. var ypos = radius * Math.cos( thetaStart + v * thetaLength );
  15227. var zpos = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15228. this.vertices.push( new THREE.Vertex( new THREE.Vector3( xpos, ypos, zpos ) ) );
  15229. verticesRow.push( this.vertices.length - 1 );
  15230. uvsRow.push( new THREE.UV( u, v ) );
  15231. }
  15232. vertices.push( verticesRow );
  15233. uvs.push( uvsRow );
  15234. }
  15235. for ( y = 0; y < segmentsY; y ++ ) {
  15236. for ( x = 0; x < segmentsX; x ++ ) {
  15237. var v1 = vertices[ y ][ x + 1 ];
  15238. var v2 = vertices[ y ][ x ];
  15239. var v3 = vertices[ y + 1 ][ x ];
  15240. var v4 = vertices[ y + 1 ][ x + 1 ];
  15241. var n1 = this.vertices[ v1 ].position.clone().normalize();
  15242. var n2 = this.vertices[ v2 ].position.clone().normalize();
  15243. var n3 = this.vertices[ v3 ].position.clone().normalize();
  15244. var n4 = this.vertices[ v4 ].position.clone().normalize();
  15245. var uv1 = uvs[ y ][ x + 1 ].clone();
  15246. var uv2 = uvs[ y ][ x ].clone();
  15247. var uv3 = uvs[ y + 1 ][ x ].clone();
  15248. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  15249. if ( Math.abs( this.vertices[ v1 ].position.y ) == radius ) {
  15250. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  15251. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  15252. } else if ( Math.abs( this.vertices[ v3 ].position.y ) == radius ) {
  15253. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  15254. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  15255. } else {
  15256. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  15257. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  15258. }
  15259. }
  15260. }
  15261. this.computeCentroids();
  15262. this.computeFaceNormals();
  15263. this.boundingSphere = { radius: radius };
  15264. };
  15265. THREE.SphereGeometry.prototype = new THREE.Geometry();
  15266. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  15267. /**
  15268. * @author zz85 / http://www.lab4games.net/zz85/blog
  15269. * @author alteredq / http://alteredqualia.com/
  15270. *
  15271. * For creating 3D text geometry in three.js
  15272. *
  15273. * Text = 3D Text
  15274. *
  15275. * parameters = {
  15276. * size: <float>, // size of the text
  15277. * height: <float>, // thickness to extrude text
  15278. * curveSegments: <int>, // number of points on the curves
  15279. *
  15280. * font: <string>, // font name
  15281. * weight: <string>, // font weight (normal, bold)
  15282. * style: <string>, // font style (normal, italics)
  15283. *
  15284. * bevelEnabled: <bool>, // turn on bevel
  15285. * bevelThickness: <float>, // how deep into text bevel goes
  15286. * bevelSize: <float>, // how far from text outline is bevel
  15287. *
  15288. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  15289. * bendPath: <curve> // wraps text according to bend Path
  15290. * }
  15291. *
  15292. * It uses techniques used in:
  15293. *
  15294. * typeface.js and canvastext
  15295. * For converting fonts and rendering with javascript
  15296. * http://typeface.neocracy.org
  15297. *
  15298. * Triangulation ported from AS3
  15299. * Simple Polygon Triangulation
  15300. * http://actionsnippet.com/?p=1462
  15301. *
  15302. * A Method to triangulate shapes with holes
  15303. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15304. *
  15305. */
  15306. /* Usage Examples
  15307. // TextGeometry wrapper
  15308. var text3d = new TextGeometry( text, options );
  15309. // Complete manner
  15310. var textPath = new THREE.TextPath( text, options );
  15311. var textShapes = textPath.toShapes();
  15312. var text3d = new ExtrudeGeometry( textShapes, options );
  15313. */
  15314. THREE.TextGeometry = function ( text, parameters ) {
  15315. var textPath = new THREE.TextPath( text, parameters );
  15316. var textShapes = textPath.toShapes();
  15317. // translate parameters to ExtrudeGeometry API
  15318. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15319. // defaults
  15320. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15321. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15322. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15323. if ( parameters.bend ) {
  15324. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  15325. var max = b.maxX;
  15326. parameters.bendPath = new THREE.QuadraticBezierCurve( new THREE.Vector2( 0, 0 ),
  15327. new THREE.Vector2( max / 2, 120 ),
  15328. new THREE.Vector2( max, 0 ) );
  15329. }
  15330. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  15331. };
  15332. THREE.TextGeometry.prototype = new THREE.ExtrudeGeometry();
  15333. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  15334. THREE.FontUtils = {
  15335. faces : {},
  15336. // Just for now. face[weight][style]
  15337. face : "helvetiker",
  15338. weight: "normal",
  15339. style : "normal",
  15340. size : 150,
  15341. divisions : 10,
  15342. getFace : function() {
  15343. return this.faces[ this.face ][ this.weight ][ this.style ];
  15344. },
  15345. loadFace : function( data ) {
  15346. var family = data.familyName.toLowerCase();
  15347. var ThreeFont = this;
  15348. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15349. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15350. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15351. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15352. return data;
  15353. },
  15354. drawText : function( text ) {
  15355. var characterPts = [], allPts = [];
  15356. // RenderText
  15357. var i, p,
  15358. face = this.getFace(),
  15359. scale = this.size / face.resolution,
  15360. offset = 0,
  15361. chars = String( text ).split( '' ),
  15362. length = chars.length;
  15363. var fontPaths = [];
  15364. for ( i = 0; i < length; i ++ ) {
  15365. var path = new THREE.Path();
  15366. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15367. offset += ret.offset;
  15368. //characterPts.push( ret.points );
  15369. //allPts = allPts.concat( ret.points );
  15370. fontPaths.push( ret.path );
  15371. }
  15372. // get the width
  15373. var width = offset / 2;
  15374. //
  15375. // for ( p = 0; p < allPts.length; p++ ) {
  15376. //
  15377. // allPts[ p ].x -= width;
  15378. //
  15379. // }
  15380. //var extract = this.extractPoints( allPts, characterPts );
  15381. //extract.contour = allPts;
  15382. //extract.paths = fontPaths;
  15383. //extract.offset = width;
  15384. return { paths : fontPaths, offset : width };
  15385. },
  15386. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15387. var pts = [];
  15388. var i, i2, divisions,
  15389. outline, action, length,
  15390. scaleX, scaleY,
  15391. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15392. laste,
  15393. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15394. if ( !glyph ) return;
  15395. if ( glyph.o ) {
  15396. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15397. length = outline.length;
  15398. scaleX = scale;
  15399. scaleY = scale;
  15400. for ( i = 0; i < length; ) {
  15401. action = outline[ i ++ ];
  15402. //console.log( action );
  15403. switch( action ) {
  15404. case 'm':
  15405. // Move To
  15406. x = outline[ i++ ] * scaleX + offset;
  15407. y = outline[ i++ ] * scaleY;
  15408. pts.push( new THREE.Vector2( x, y ) );
  15409. path.moveTo( x, y );
  15410. break;
  15411. case 'l':
  15412. // Line To
  15413. x = outline[ i++ ] * scaleX + offset;
  15414. y = outline[ i++ ] * scaleY;
  15415. pts.push( new THREE.Vector2( x, y ) );
  15416. path.lineTo(x,y);
  15417. break;
  15418. case 'q':
  15419. // QuadraticCurveTo
  15420. cpx = outline[ i++ ] * scaleX + offset;
  15421. cpy = outline[ i++ ] * scaleY;
  15422. cpx1 = outline[ i++ ] * scaleX + offset;
  15423. cpy1 = outline[ i++ ] * scaleY;
  15424. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15425. laste = pts[ pts.length - 1 ];
  15426. if ( laste ) {
  15427. cpx0 = laste.x;
  15428. cpy0 = laste.y;
  15429. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15430. var t = i2 / divisions;
  15431. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15432. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15433. pts.push( new THREE.Vector2( tx, ty ) );
  15434. }
  15435. }
  15436. break;
  15437. case 'b':
  15438. // Cubic Bezier Curve
  15439. cpx = outline[ i++ ] * scaleX + offset;
  15440. cpy = outline[ i++ ] * scaleY;
  15441. cpx1 = outline[ i++ ] * scaleX + offset;
  15442. cpy1 = outline[ i++ ] * -scaleY;
  15443. cpx2 = outline[ i++ ] * scaleX + offset;
  15444. cpy2 = outline[ i++ ] * -scaleY;
  15445. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15446. laste = pts[ pts.length - 1 ];
  15447. if ( laste ) {
  15448. cpx0 = laste.x;
  15449. cpy0 = laste.y;
  15450. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15451. var t = i2 / divisions;
  15452. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15453. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15454. pts.push( new THREE.Vector2( tx, ty ) );
  15455. }
  15456. }
  15457. break;
  15458. }
  15459. }
  15460. }
  15461. return { offset: glyph.ha*scale, points:pts, path:path};
  15462. }
  15463. };
  15464. /**
  15465. * This code is a quick port of code written in C++ which was submitted to
  15466. * flipcode.com by John W. Ratcliff // July 22, 2000
  15467. * See original code and more information here:
  15468. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15469. *
  15470. * ported to actionscript by Zevan Rosser
  15471. * www.actionsnippet.com
  15472. *
  15473. * ported to javascript by Joshua Koo
  15474. * http://www.lab4games.net/zz85/blog
  15475. *
  15476. */
  15477. ( function( namespace ) {
  15478. var EPSILON = 0.0000000001;
  15479. // takes in an contour array and returns
  15480. var process = function( contour, indices ) {
  15481. var n = contour.length;
  15482. if ( n < 3 ) return null;
  15483. var result = [],
  15484. verts = [],
  15485. vertIndices = [];
  15486. /* we want a counter-clockwise polygon in verts */
  15487. var u, v, w;
  15488. if ( area( contour ) > 0.0 ) {
  15489. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15490. } else {
  15491. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15492. }
  15493. var nv = n;
  15494. /* remove nv - 2 vertices, creating 1 triangle every time */
  15495. var count = 2 * nv; /* error detection */
  15496. for( v = nv - 1; nv > 2; ) {
  15497. /* if we loop, it is probably a non-simple polygon */
  15498. if ( ( count-- ) <= 0 ) {
  15499. //** Triangulate: ERROR - probable bad polygon!
  15500. //throw ( "Warning, unable to triangulate polygon!" );
  15501. //return null;
  15502. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15503. console.log( "Warning, unable to triangulate polygon!" );
  15504. if ( indices ) return vertIndices;
  15505. return result;
  15506. }
  15507. /* three consecutive vertices in current polygon, <u,v,w> */
  15508. u = v; if ( nv <= u ) u = 0; /* previous */
  15509. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15510. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15511. if ( snip( contour, u, v, w, nv, verts ) ) {
  15512. var a, b, c, s, t;
  15513. /* true names of the vertices */
  15514. a = verts[ u ];
  15515. b = verts[ v ];
  15516. c = verts[ w ];
  15517. /* output Triangle */
  15518. /*
  15519. result.push( contour[ a ] );
  15520. result.push( contour[ b ] );
  15521. result.push( contour[ c ] );
  15522. */
  15523. result.push( [ contour[ a ],
  15524. contour[ b ],
  15525. contour[ c ] ] );
  15526. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15527. /* remove v from the remaining polygon */
  15528. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15529. verts[ s ] = verts[ t ];
  15530. }
  15531. nv--;
  15532. /* reset error detection counter */
  15533. count = 2 * nv;
  15534. }
  15535. }
  15536. if ( indices ) return vertIndices;
  15537. return result;
  15538. };
  15539. // calculate area of the contour polygon
  15540. var area = function ( contour ) {
  15541. var n = contour.length;
  15542. var a = 0.0;
  15543. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15544. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15545. }
  15546. return a * 0.5;
  15547. };
  15548. // see if p is inside triangle abc
  15549. var insideTriangle = function( ax, ay,
  15550. bx, by,
  15551. cx, cy,
  15552. px, py ) {
  15553. var aX, aY, bX, bY;
  15554. var cX, cY, apx, apy;
  15555. var bpx, bpy, cpx, cpy;
  15556. var cCROSSap, bCROSScp, aCROSSbp;
  15557. aX = cx - bx; aY = cy - by;
  15558. bX = ax - cx; bY = ay - cy;
  15559. cX = bx - ax; cY = by - ay;
  15560. apx= px -ax; apy= py - ay;
  15561. bpx= px - bx; bpy= py - by;
  15562. cpx= px - cx; cpy= py - cy;
  15563. aCROSSbp = aX*bpy - aY*bpx;
  15564. cCROSSap = cX*apy - cY*apx;
  15565. bCROSScp = bX*cpy - bY*cpx;
  15566. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15567. };
  15568. var snip = function ( contour, u, v, w, n, verts ) {
  15569. var p;
  15570. var ax, ay, bx, by;
  15571. var cx, cy, px, py;
  15572. ax = contour[ verts[ u ] ].x;
  15573. ay = contour[ verts[ u ] ].y;
  15574. bx = contour[ verts[ v ] ].x;
  15575. by = contour[ verts[ v ] ].y;
  15576. cx = contour[ verts[ w ] ].x;
  15577. cy = contour[ verts[ w ] ].y;
  15578. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15579. for ( p = 0; p < n; p++ ) {
  15580. if( (p == u) || (p == v) || (p == w) ) continue;
  15581. px = contour[ verts[ p ] ].x
  15582. py = contour[ verts[ p ] ].y
  15583. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15584. }
  15585. return true;
  15586. };
  15587. namespace.Triangulate = process;
  15588. namespace.Triangulate.area = area;
  15589. return namespace;
  15590. })(THREE.FontUtils);
  15591. // To use the typeface.js face files, hook up the API
  15592. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15593. /**
  15594. * @author oosmoxiecode
  15595. * @author mr.doob / http://mrdoob.com/
  15596. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15597. */
  15598. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  15599. THREE.Geometry.call( this );
  15600. var scope = this;
  15601. this.radius = radius || 100;
  15602. this.tube = tube || 40;
  15603. this.segmentsR = segmentsR || 8;
  15604. this.segmentsT = segmentsT || 6;
  15605. this.arc = arc || Math.PI * 2;
  15606. var center = new THREE.Vector3(), uvs = [], normals = [];
  15607. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  15608. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  15609. var u = i / this.segmentsT * this.arc;
  15610. var v = j / this.segmentsR * Math.PI * 2;
  15611. center.x = this.radius * Math.cos( u );
  15612. center.y = this.radius * Math.sin( u );
  15613. var vector = new THREE.Vector3();
  15614. vector.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  15615. vector.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  15616. vector.z = this.tube * Math.sin( v );
  15617. this.vertices.push( new THREE.Vertex( vector ) );
  15618. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  15619. normals.push( vector.clone().subSelf( center ).normalize() );
  15620. }
  15621. }
  15622. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  15623. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  15624. var a = ( this.segmentsT + 1 ) * j + i - 1;
  15625. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  15626. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  15627. var d = ( this.segmentsT + 1 ) * j + i;
  15628. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  15629. face.normal.addSelf( normals[ a ] );
  15630. face.normal.addSelf( normals[ b ] );
  15631. face.normal.addSelf( normals[ c ] );
  15632. face.normal.addSelf( normals[ d ] );
  15633. face.normal.normalize();
  15634. this.faces.push( face );
  15635. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  15636. }
  15637. }
  15638. this.computeCentroids();
  15639. };
  15640. THREE.TorusGeometry.prototype = new THREE.Geometry();
  15641. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  15642. /**
  15643. * @author oosmoxiecode
  15644. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  15645. */
  15646. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  15647. THREE.Geometry.call( this );
  15648. var scope = this;
  15649. this.radius = radius || 200;
  15650. this.tube = tube || 40;
  15651. this.segmentsR = segmentsR || 64;
  15652. this.segmentsT = segmentsT || 8;
  15653. this.p = p || 2;
  15654. this.q = q || 3;
  15655. this.heightScale = heightScale || 1;
  15656. this.grid = new Array(this.segmentsR);
  15657. var tang = new THREE.Vector3();
  15658. var n = new THREE.Vector3();
  15659. var bitan = new THREE.Vector3();
  15660. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15661. this.grid[ i ] = new Array( this.segmentsT );
  15662. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15663. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  15664. var v = j / this.segmentsT * 2 * Math.PI;
  15665. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  15666. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  15667. var cx, cy;
  15668. tang.sub( p2, p1 );
  15669. n.add( p2, p1 );
  15670. bitan.cross( tang, n );
  15671. n.cross( bitan, tang );
  15672. bitan.normalize();
  15673. n.normalize();
  15674. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15675. cy = this.tube * Math.sin( v );
  15676. p1.x += cx * n.x + cy * bitan.x;
  15677. p1.y += cx * n.y + cy * bitan.y;
  15678. p1.z += cx * n.z + cy * bitan.z;
  15679. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  15680. }
  15681. }
  15682. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15683. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15684. var ip = ( i + 1 ) % this.segmentsR;
  15685. var jp = ( j + 1 ) % this.segmentsT;
  15686. var a = this.grid[ i ][ j ];
  15687. var b = this.grid[ ip ][ j ];
  15688. var c = this.grid[ ip ][ jp ];
  15689. var d = this.grid[ i ][ jp ];
  15690. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  15691. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  15692. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15693. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15694. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15695. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  15696. }
  15697. }
  15698. this.computeCentroids();
  15699. this.computeFaceNormals();
  15700. this.computeVertexNormals();
  15701. function vert( x, y, z ) {
  15702. return scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) ) - 1;
  15703. }
  15704. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  15705. var cu = Math.cos( u );
  15706. var cv = Math.cos( v );
  15707. var su = Math.sin( u );
  15708. var quOverP = in_q / in_p * u;
  15709. var cs = Math.cos( quOverP );
  15710. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  15711. var ty = radius * ( 2 + cs ) * su * 0.5;
  15712. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  15713. return new THREE.Vector3( tx, ty, tz );
  15714. }
  15715. };
  15716. THREE.TorusKnotGeometry.prototype = new THREE.Geometry();
  15717. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  15718. /**
  15719. * @author WestLangley / https://github.com/WestLangley
  15720. * @author zz85 / https://github.com/zz85
  15721. * @author miningold / https://github.com/miningold
  15722. *
  15723. * Modified from the TorusKnotGeometry by @oosmoxiecode
  15724. *
  15725. * Creates a tube which extrudes along a 3d spline
  15726. *
  15727. * Uses parallel transport frames as described in
  15728. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  15729. */
  15730. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  15731. THREE.Geometry.call( this );
  15732. this.path = path;
  15733. this.segments = segments || 64;
  15734. this.radius = radius || 1;
  15735. this.segmentsRadius = segmentsRadius || 8;
  15736. this.closed = closed || false;
  15737. if ( debug ) this.debug = new THREE.Object3D();
  15738. this.grid = [];
  15739. var scope = this,
  15740. tangent = new THREE.Vector3(),
  15741. normal = new THREE.Vector3(),
  15742. binormal = new THREE.Vector3(),
  15743. vec = new THREE.Vector3(),
  15744. mat = new THREE.Matrix4(),
  15745. tangents = [],
  15746. normals = [],
  15747. binormals = [],
  15748. numpoints = this.segments + 1,
  15749. theta,
  15750. epsilon = 0.0001,
  15751. smallest,
  15752. x, y, z,
  15753. tx, ty, tz,
  15754. u, v,
  15755. p1, p2,
  15756. cx, cy,
  15757. pos, pos2,
  15758. i, j,
  15759. ip, jp,
  15760. a, b, c, d,
  15761. uva, uvb, uvc, uvd;
  15762. // expose internals
  15763. this.tangents = tangents;
  15764. this.normals = normals;
  15765. this.binormals = binormals;
  15766. function vert( x, y, z ) {
  15767. return scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) ) - 1;
  15768. }
  15769. // compute the tangent vectors for each segment on the path
  15770. for ( i = 0; i < numpoints; i++ ) {
  15771. u = i / ( numpoints - 1 );
  15772. tangents[ i ] = this.path.getTangentAt( u );
  15773. tangents[ i ].normalize();
  15774. }
  15775. initialNormal3();
  15776. function initialNormal1() {
  15777. // fixed start binormal. Has dangers of 0 vectors
  15778. normals[ 0 ] = new THREE.Vector3();
  15779. binormals[ 0 ] = new THREE.Vector3();
  15780. var lastBinormal = new THREE.Vector3( 0, 0, 1 );
  15781. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  15782. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15783. }
  15784. function initialNormal2() {
  15785. // This uses the Frenet-Serret formula for deriving binormal
  15786. var t2 = path.getTangentAt( epsilon );
  15787. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize()
  15788. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  15789. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  15790. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15791. }
  15792. function initialNormal3() {
  15793. // select an initial normal vector perpenicular to the first tangent vector,
  15794. // and in the direction of the smallest tangent xyz component
  15795. normals[ 0 ] = new THREE.Vector3();
  15796. binormals[ 0 ] = new THREE.Vector3();
  15797. smallest = Number.MAX_VALUE;
  15798. tx = Math.abs( tangents[ 0 ].x );
  15799. ty = Math.abs( tangents[ 0 ].y );
  15800. tz = Math.abs( tangents[ 0 ].z );
  15801. if ( tx <= smallest ) {
  15802. smallest = tx;
  15803. vec.set( 1, 0, 0 );
  15804. }
  15805. if ( ty <= smallest ) {
  15806. smallest = ty;
  15807. vec.set( 0, 1, 0 );
  15808. }
  15809. if ( tz <= smallest ) {
  15810. vec.set( 0, 0, 1 );
  15811. }
  15812. // vec.cross( tangents[ 0 ], normal ).normalize();
  15813. normals[ 0 ].cross( tangents[ 0 ], vec );
  15814. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  15815. }
  15816. // compute the slowly-varying normal and binormal vectors for each segment on the path
  15817. for ( i = 1; i < numpoints; i++ ) {
  15818. normals[ i ] = normals[ i-1 ].clone();
  15819. binormals[ i ] = binormals[ i-1 ].clone();
  15820. vec.cross( tangents[ i-1 ], tangents[ i ] );
  15821. if ( vec.length() > epsilon ) {
  15822. vec.normalize();
  15823. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  15824. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  15825. }
  15826. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15827. }
  15828. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  15829. if ( this.closed ) {
  15830. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  15831. theta /= ( numpoints - 1 );
  15832. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  15833. theta = -theta;
  15834. }
  15835. for ( i = 1; i < numpoints; i++ ) {
  15836. // twist a little...
  15837. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  15838. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15839. }
  15840. }
  15841. // consruct the grid
  15842. for ( i = 0; i < numpoints; i++ ) {
  15843. this.grid[ i ] = [];
  15844. u = i / ( numpoints - 1 );
  15845. pos = this.path.getPointAt( u );
  15846. tangent = tangents[ i ];
  15847. normal = normals[ i ];
  15848. binormal = binormals[ i ];
  15849. if ( this.debug ) {
  15850. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  15851. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  15852. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  15853. }
  15854. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15855. v = j / this.segmentsRadius * 2 * Math.PI;
  15856. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15857. cy = this.radius * Math.sin( v );
  15858. pos2 = new THREE.Vector3().copy( pos );
  15859. pos2.x += cx * normal.x + cy * binormal.x;
  15860. pos2.y += cx * normal.y + cy * binormal.y;
  15861. pos2.z += cx * normal.z + cy * binormal.z;
  15862. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  15863. }
  15864. }
  15865. // construct the mesh
  15866. for ( i = 0; i < this.segments; i++ ) {
  15867. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15868. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  15869. jp = (j + 1) % this.segmentsRadius;
  15870. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  15871. b = this.grid[ ip ][ j ];
  15872. c = this.grid[ ip ][ jp ];
  15873. d = this.grid[ i ][ jp ];
  15874. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  15875. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  15876. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  15877. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  15878. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15879. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  15880. }
  15881. }
  15882. this.computeCentroids();
  15883. this.computeFaceNormals();
  15884. this.computeVertexNormals();
  15885. };
  15886. THREE.TubeGeometry.prototype = new THREE.Geometry();
  15887. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  15888. /**
  15889. * @author clockworkgeek / https://github.com/clockworkgeek
  15890. * @author timothypratley / https://github.com/timothypratley
  15891. */
  15892. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  15893. THREE.Geometry.call( this );
  15894. radius = radius || 1;
  15895. detail = detail || 0;
  15896. var that = this;
  15897. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  15898. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  15899. }
  15900. var midpoints = [], p = this.vertices;
  15901. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  15902. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  15903. }
  15904. this.mergeVertices();
  15905. // Apply radius
  15906. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  15907. this.vertices[ i ].position.multiplyScalar( radius );
  15908. }
  15909. /**
  15910. * Project vector onto sphere's surface
  15911. */
  15912. function prepare( vector ) {
  15913. var vertex = new THREE.Vertex( vector.normalize() );
  15914. vertex.index = that.vertices.push( vertex ) - 1;
  15915. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  15916. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  15917. var v = inclination( vector ) / Math.PI + 0.5;
  15918. vertex.uv = new THREE.UV( u, v );
  15919. return vertex;
  15920. }
  15921. /**
  15922. * Approximate a curved face with recursively sub-divided triangles.
  15923. */
  15924. function make( v1, v2, v3, detail ) {
  15925. if ( detail < 1 ) {
  15926. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.position.clone(), v2.position.clone(), v3.position.clone() ] );
  15927. face.centroid.addSelf( v1.position ).addSelf( v2.position ).addSelf( v3.position ).divideScalar( 3 );
  15928. face.normal = face.centroid.clone().normalize();
  15929. that.faces.push( face );
  15930. var azi = azimuth( face.centroid );
  15931. that.faceVertexUvs[ 0 ].push( [
  15932. correctUV( v1.uv, v1.position, azi ),
  15933. correctUV( v2.uv, v2.position, azi ),
  15934. correctUV( v3.uv, v3.position, azi )
  15935. ] );
  15936. }
  15937. else {
  15938. detail -= 1;
  15939. // split triangle into 4 smaller triangles
  15940. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  15941. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  15942. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  15943. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  15944. }
  15945. }
  15946. function midpoint( v1, v2 ) {
  15947. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  15948. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  15949. var mid = midpoints[ v1.index ][ v2.index ];
  15950. if ( mid === undefined ) {
  15951. // generate mean point and project to surface with prepare()
  15952. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  15953. new THREE.Vector3().add( v1.position, v2.position ).divideScalar( 2 )
  15954. );
  15955. }
  15956. return mid;
  15957. }
  15958. /**
  15959. * Angle around the Y axis, counter-clockwise when looking from above.
  15960. */
  15961. function azimuth( vector ) {
  15962. return Math.atan2( vector.z, -vector.x );
  15963. }
  15964. /**
  15965. * Angle above the XZ plane.
  15966. */
  15967. function inclination( vector ) {
  15968. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15969. }
  15970. /**
  15971. * Texture fixing helper. Spheres have some odd behaviours.
  15972. */
  15973. function correctUV( uv, vector, azimuth ) {
  15974. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  15975. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  15976. return uv;
  15977. }
  15978. this.computeCentroids();
  15979. this.boundingSphere = { radius: radius };
  15980. };
  15981. THREE.PolyhedronGeometry.prototype = new THREE.Geometry();
  15982. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  15983. /**
  15984. * @author timothypratley / https://github.com/timothypratley
  15985. */
  15986. THREE.IcosahedronGeometry = function ( radius, detail ) {
  15987. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15988. var vertices = [
  15989. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  15990. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  15991. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  15992. ];
  15993. var faces = [
  15994. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  15995. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  15996. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  15997. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  15998. ];
  15999. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16000. };
  16001. THREE.IcosahedronGeometry.prototype = new THREE.Geometry();
  16002. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  16003. /**
  16004. * @author timothypratley / https://github.com/timothypratley
  16005. */
  16006. THREE.OctahedronGeometry = function ( radius, detail ) {
  16007. var vertices = [
  16008. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  16009. ];
  16010. var faces = [
  16011. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  16012. ];
  16013. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16014. };
  16015. THREE.OctahedronGeometry.prototype = new THREE.Geometry();
  16016. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  16017. /**
  16018. * @author timothypratley / https://github.com/timothypratley
  16019. */
  16020. THREE.TetrahedronGeometry = function ( radius, detail ) {
  16021. var vertices = [
  16022. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  16023. ];
  16024. var faces = [
  16025. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  16026. ];
  16027. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16028. };
  16029. THREE.TetrahedronGeometry.prototype = new THREE.Geometry();
  16030. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  16031. /**
  16032. * @author sroucheray / http://sroucheray.org/
  16033. * @author mr.doob / http://mrdoob.com/
  16034. */
  16035. THREE.AxisHelper = function () {
  16036. THREE.Object3D.call( this );
  16037. var lineGeometry = new THREE.Geometry();
  16038. lineGeometry.vertices.push( new THREE.Vertex() );
  16039. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 100, 0 ) ) );
  16040. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  16041. var line, cone;
  16042. // x
  16043. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  16044. line.rotation.z = - Math.PI / 2;
  16045. this.add( line );
  16046. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  16047. cone.position.x = 100;
  16048. cone.rotation.z = - Math.PI / 2;
  16049. this.add( cone );
  16050. // y
  16051. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  16052. this.add( line );
  16053. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  16054. cone.position.y = 100;
  16055. this.add( cone );
  16056. // z
  16057. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  16058. line.rotation.x = Math.PI / 2;
  16059. this.add( line );
  16060. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  16061. cone.position.z = 100;
  16062. cone.rotation.x = Math.PI / 2;
  16063. this.add( cone );
  16064. };
  16065. THREE.AxisHelper.prototype = new THREE.Object3D();
  16066. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  16067. /**
  16068. * @author WestLangley / https://github.com/WestLangley
  16069. * @author zz85 / https://github.com/zz85
  16070. *
  16071. * Creates an arrow for visualizing directions
  16072. *
  16073. * Parameters:
  16074. * dir - Vector3
  16075. * origin - Vector3
  16076. * length - Number
  16077. * hex - color in hex value
  16078. */
  16079. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  16080. THREE.Object3D.call( this );
  16081. if ( hex === undefined ) hex = 0xffff00;
  16082. if ( length === undefined ) length = 20;
  16083. var lineGeometry = new THREE.Geometry();
  16084. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 0, 0 ) ) );
  16085. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 1, 0 ) ) );
  16086. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : hex } ) );
  16087. this.add( this.line );
  16088. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  16089. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : hex } ) );
  16090. this.cone.position.set( 0, 1, 0 );
  16091. this.add( this.cone );
  16092. if ( origin instanceof THREE.Vector3 ) {
  16093. this.position = origin;
  16094. }
  16095. this.setDirection( dir );
  16096. this.setLength( length );
  16097. };
  16098. THREE.ArrowHelper.prototype = new THREE.Object3D();
  16099. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  16100. THREE.ArrowHelper.prototype.setDirection = function( dir ) {
  16101. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  16102. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  16103. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  16104. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  16105. };
  16106. THREE.ArrowHelper.prototype.setLength = function( length ) {
  16107. this.scale.set( length, length, length );
  16108. };
  16109. THREE.ArrowHelper.prototype.setColor = function( hex ) {
  16110. this.line.material.color.setHex( hex );
  16111. this.cone.material.color.setHex( hex );
  16112. };
  16113. /**
  16114. * @author alteredq / http://alteredqualia.com/
  16115. *
  16116. * - shows frustum, line of sight and up of the camera
  16117. * - suitable for fast updates
  16118. * - based on frustum visualization in lightgl.js shadowmap example
  16119. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  16120. */
  16121. THREE.CameraHelper = function ( camera ) {
  16122. THREE.Object3D.call( this );
  16123. var _this = this;
  16124. this.lineGeometry = new THREE.Geometry();
  16125. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  16126. this.pointMap = {};
  16127. // colors
  16128. var hexFrustum = 0xffaa00,
  16129. hexCone = 0xff0000,
  16130. hexUp = 0x00aaff,
  16131. hexTarget = 0xffffff,
  16132. hexCross = 0x333333;
  16133. // near
  16134. addLine( "n1", "n2", hexFrustum );
  16135. addLine( "n2", "n4", hexFrustum );
  16136. addLine( "n4", "n3", hexFrustum );
  16137. addLine( "n3", "n1", hexFrustum );
  16138. // far
  16139. addLine( "f1", "f2", hexFrustum );
  16140. addLine( "f2", "f4", hexFrustum );
  16141. addLine( "f4", "f3", hexFrustum );
  16142. addLine( "f3", "f1", hexFrustum );
  16143. // sides
  16144. addLine( "n1", "f1", hexFrustum );
  16145. addLine( "n2", "f2", hexFrustum );
  16146. addLine( "n3", "f3", hexFrustum );
  16147. addLine( "n4", "f4", hexFrustum );
  16148. // cone
  16149. addLine( "p", "n1", hexCone );
  16150. addLine( "p", "n2", hexCone );
  16151. addLine( "p", "n3", hexCone );
  16152. addLine( "p", "n4", hexCone );
  16153. // up
  16154. addLine( "u1", "u2", hexUp );
  16155. addLine( "u2", "u3", hexUp );
  16156. addLine( "u3", "u1", hexUp );
  16157. // target
  16158. addLine( "c", "t", hexTarget );
  16159. addLine( "p", "c", hexCross );
  16160. // cross
  16161. addLine( "cn1", "cn2", hexCross );
  16162. addLine( "cn3", "cn4", hexCross );
  16163. addLine( "cf1", "cf2", hexCross );
  16164. addLine( "cf3", "cf4", hexCross );
  16165. this.camera = camera;
  16166. function addLine( a, b, hex ) {
  16167. addPoint( a, hex );
  16168. addPoint( b, hex );
  16169. }
  16170. function addPoint( id, hex ) {
  16171. _this.lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3() ) );
  16172. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  16173. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  16174. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  16175. }
  16176. this.update( camera );
  16177. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  16178. this.add( this.lines );
  16179. };
  16180. THREE.CameraHelper.prototype = new THREE.Object3D();
  16181. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  16182. THREE.CameraHelper.prototype.update = function () {
  16183. var camera = this.camera;
  16184. var w = 1;
  16185. var h = 1;
  16186. var _this = this;
  16187. // we need just camera projection matrix
  16188. // world matrix must be identity
  16189. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  16190. // center / target
  16191. setPoint( "c", 0, 0, -1 );
  16192. setPoint( "t", 0, 0, 1 );
  16193. // near
  16194. setPoint( "n1", -w, -h, -1 );
  16195. setPoint( "n2", w, -h, -1 );
  16196. setPoint( "n3", -w, h, -1 );
  16197. setPoint( "n4", w, h, -1 );
  16198. // far
  16199. setPoint( "f1", -w, -h, 1 );
  16200. setPoint( "f2", w, -h, 1 );
  16201. setPoint( "f3", -w, h, 1 );
  16202. setPoint( "f4", w, h, 1 );
  16203. // up
  16204. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  16205. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  16206. setPoint( "u3", 0, h * 2, -1 );
  16207. // cross
  16208. setPoint( "cf1", -w, 0, 1 );
  16209. setPoint( "cf2", w, 0, 1 );
  16210. setPoint( "cf3", 0, -h, 1 );
  16211. setPoint( "cf4", 0, h, 1 );
  16212. setPoint( "cn1", -w, 0, -1 );
  16213. setPoint( "cn2", w, 0, -1 );
  16214. setPoint( "cn3", 0, -h, -1 );
  16215. setPoint( "cn4", 0, h, -1 );
  16216. function setPoint( point, x, y, z ) {
  16217. THREE.CameraHelper.__v.set( x, y, z );
  16218. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  16219. var points = _this.pointMap[ point ];
  16220. if ( points !== undefined ) {
  16221. for ( var i = 0, il = points.length; i < il; i ++ ) {
  16222. var j = points[ i ];
  16223. _this.lineGeometry.vertices[ j ].position.copy( THREE.CameraHelper.__v );
  16224. }
  16225. }
  16226. }
  16227. this.lineGeometry.__dirtyVertices = true;
  16228. };
  16229. THREE.CameraHelper.__projector = new THREE.Projector();
  16230. THREE.CameraHelper.__v = new THREE.Vector3();
  16231. THREE.CameraHelper.__c = new THREE.Camera();
  16232. /*
  16233. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16234. *
  16235. * Subdivision Geometry Modifier
  16236. * using Catmull-Clark Subdivision Surfaces
  16237. * for creating smooth geometry meshes
  16238. *
  16239. * Note: a modifier modifies vertices and faces of geometry,
  16240. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  16241. *
  16242. * Readings:
  16243. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  16244. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  16245. * http://xrt.wikidot.com/blog:31
  16246. * "Subdivision Surfaces in Character Animation"
  16247. *
  16248. * Supports:
  16249. * Closed and Open geometries.
  16250. *
  16251. * TODO:
  16252. * crease vertex and "semi-sharp" features
  16253. * selective subdivision
  16254. */
  16255. THREE.SubdivisionModifier = function( subdivisions ) {
  16256. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  16257. // Settings
  16258. this.useOldVertexColors = false;
  16259. this.supportUVs = true;
  16260. };
  16261. //THREE.SubdivisionModifier.prototype = new THREE.Modifier();
  16262. THREE.SubdivisionModifier.prototype.constructor = THREE.SubdivisionModifier;
  16263. // Applies the "modify" pattern
  16264. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  16265. var repeats = this.subdivisions;
  16266. while ( repeats-- > 0 ) {
  16267. this.smooth( geometry );
  16268. }
  16269. };
  16270. // Performs an iteration of Catmull-Clark Subdivision
  16271. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  16272. //console.log( 'running smooth' );
  16273. // New set of vertices, faces and uvs
  16274. var newVertices = [], newFaces = [], newUVs = [];
  16275. function v( x, y, z ) {
  16276. newVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  16277. }
  16278. var scope = this;
  16279. function f4( a, b, c, d, oldFace, orders ) {
  16280. // TODO move vertex selection over here!
  16281. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.material );
  16282. if (scope.useOldVertexColors) {
  16283. newFace.vertexColors = [];
  16284. var color, tmpColor, order;
  16285. for (var i=0;i<4;i++) {
  16286. order = orders[i];
  16287. color = new THREE.Color(),
  16288. color.setRGB(0,0,0);
  16289. for (var j=0, jl=0; j<order.length;j++) {
  16290. tmpColor = oldFace.vertexColors[order[j]-1];
  16291. color.r += tmpColor.r;
  16292. color.g += tmpColor.g;
  16293. color.b += tmpColor.b;
  16294. }
  16295. color.r /= order.length;
  16296. color.g /= order.length;
  16297. color.b /= order.length;
  16298. newFace.vertexColors[i] = color;
  16299. }
  16300. }
  16301. newFaces.push( newFace );
  16302. if (!scope.supportUVs || uvForVertices.length!=0) {
  16303. newUVs.push( [
  16304. uvForVertices[a],
  16305. uvForVertices[b],
  16306. uvForVertices[c],
  16307. uvForVertices[d]
  16308. ] );
  16309. }
  16310. }
  16311. function edge_hash( a, b ) {
  16312. return Math.min( a, b ) + "_" + Math.max( a, b );
  16313. };
  16314. function computeEdgeFaces( geometry ) {
  16315. function addToMap( map, hash, i ) {
  16316. if ( map[ hash ] === undefined ) {
  16317. map[ hash ] = [];
  16318. }
  16319. map[ hash ].push( i );
  16320. };
  16321. var i, il, v1, v2, j, k,
  16322. face, faceIndices, faceIndex,
  16323. edge,
  16324. hash,
  16325. vfMap = {};
  16326. // construct vertex -> face map
  16327. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16328. face = geometry.faces[ i ];
  16329. if ( face instanceof THREE.Face3 ) {
  16330. hash = edge_hash( face.a, face.b );
  16331. addToMap( vfMap, hash, i );
  16332. hash = edge_hash( face.b, face.c );
  16333. addToMap( vfMap, hash, i );
  16334. hash = edge_hash( face.c, face.a );
  16335. addToMap( vfMap, hash, i );
  16336. } else if ( face instanceof THREE.Face4 ) {
  16337. hash = edge_hash( face.a, face.b );
  16338. addToMap( vfMap, hash, i );
  16339. hash = edge_hash( face.b, face.c );
  16340. addToMap( vfMap, hash, i );
  16341. hash = edge_hash( face.c, face.d );
  16342. addToMap( vfMap, hash, i );
  16343. hash = edge_hash( face.d, face.a );
  16344. addToMap( vfMap, hash, i );
  16345. }
  16346. }
  16347. // extract faces
  16348. // var edges = [];
  16349. //
  16350. // var numOfEdges = 0;
  16351. // for (i in vfMap) {
  16352. // numOfEdges++;
  16353. //
  16354. // edge = vfMap[i];
  16355. // edges.push(edge);
  16356. //
  16357. // }
  16358. //console.log('vfMap', vfMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  16359. return vfMap;
  16360. };
  16361. var originalPoints = oldGeometry.vertices;
  16362. var originalFaces = oldGeometry.faces;
  16363. var newPoints = originalPoints.concat(); // Vertices
  16364. var facePoints = [], edgePoints = {};
  16365. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  16366. var uvForVertices = [];
  16367. // Step 1
  16368. // For each face, add a face point
  16369. // Set each face point to be the centroid of all original points for the respective face.
  16370. var i, il, j, jl, face;
  16371. // For Uvs
  16372. var uvs = oldGeometry.faceVertexUvs[0];
  16373. var abcd = 'abcd', vertice;
  16374. for (i=0, il = uvs.length; i<il; i++ ) {
  16375. for (j=0,jl=uvs[i].length;j<jl;j++) {
  16376. vertice = originalFaces[i][abcd.charAt(j)];
  16377. if (!uvForVertices[vertice]) {
  16378. uvForVertices[vertice] = uvs[i][j];
  16379. } else {
  16380. //console.log('dup', uvForVertices[vertice]);
  16381. }
  16382. }
  16383. }
  16384. var avgUv ;
  16385. for (i=0, il = originalFaces.length; i<il ;i++) {
  16386. face = originalFaces[i];
  16387. facePoints.push(face.centroid);
  16388. newPoints.push( new THREE.Vertex(face.centroid) );
  16389. if (!scope.supportUVs || uvForVertices.length==0) continue;
  16390. // Prepare subdivided uv
  16391. avgUv = new THREE.UV();
  16392. if ( face instanceof THREE.Face3 ) {
  16393. avgUv.u = uvForVertices[face.a].u + uvForVertices[face.b].u + uvForVertices[face.c].u;
  16394. avgUv.v = uvForVertices[face.a].v + uvForVertices[face.b].v + uvForVertices[face.c].v;
  16395. avgUv.u /= 3;
  16396. avgUv.v /= 3;
  16397. } else if ( face instanceof THREE.Face4 ) {
  16398. avgUv.u = uvForVertices[face.a].u + uvForVertices[face.b].u + uvForVertices[face.c].u + uvForVertices[face.d].u;
  16399. avgUv.v = uvForVertices[face.a].v + uvForVertices[face.b].v + uvForVertices[face.c].v + uvForVertices[face.d].v;
  16400. avgUv.u /= 4;
  16401. avgUv.v /= 4;
  16402. }
  16403. uvForVertices.push(avgUv);
  16404. }
  16405. // Step 2
  16406. // For each edge, add an edge point.
  16407. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  16408. var vfMap = computeEdgeFaces ( oldGeometry );
  16409. var edge, faceIndexA, faceIndexB, avg;
  16410. //console.log('vfMap', vfMap);
  16411. var edgeCount = 0;
  16412. var originalVerticesLength = originalPoints.length;
  16413. var edgeVertex, edgeVertexA, edgeVertexB;
  16414. ////
  16415. var vertexEdgeMap = {};
  16416. var vertexFaceMap = {};
  16417. var addVertexEdgeMap = function(vertex, edge) {
  16418. if (vertexEdgeMap[vertex]===undefined) {
  16419. vertexEdgeMap[vertex] = [];
  16420. }
  16421. vertexEdgeMap[vertex].push(edge);
  16422. };
  16423. var addVertexFaceMap = function(vertex, face, edge) {
  16424. if (vertexFaceMap[vertex]===undefined) {
  16425. vertexFaceMap[vertex] = {};
  16426. }
  16427. //vertexFaceMap[vertex][face] = edge;
  16428. vertexFaceMap[vertex][face] = null;
  16429. };
  16430. // Prepares vertexEdgeMap and vertexFaceMap
  16431. for (i in vfMap) { // This is for every edge
  16432. edge = vfMap[i];
  16433. edgeVertex = i.split('_');
  16434. edgeVertexA = edgeVertex[0];
  16435. edgeVertexB = edgeVertex[1];
  16436. // Maps an edgeVertex to connecting edges
  16437. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  16438. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  16439. // faceIndexA = edge[0]; // face index a
  16440. // faceIndexB = edge[1]; // face index b
  16441. //
  16442. // // Add connecting faces for edge
  16443. // addVertexFaceMap(edgeVertexA, faceIndexA);
  16444. // addVertexFaceMap(edgeVertexB, faceIndexA);
  16445. //
  16446. //
  16447. // if (faceIndexB) {
  16448. // addVertexFaceMap(edgeVertexA, faceIndexB);
  16449. // addVertexFaceMap(edgeVertexB, faceIndexB);
  16450. // } else {
  16451. // addVertexFaceMap(edgeVertexA, faceIndexA);
  16452. // addVertexFaceMap(edgeVertexB, faceIndexA);
  16453. // }
  16454. for (j=0,jl=edge.length;j<jl;j++) {
  16455. face = edge[j];
  16456. addVertexFaceMap(edgeVertexA, face, i);
  16457. addVertexFaceMap(edgeVertexB, face, i);
  16458. }
  16459. if (edge.length < 2) {
  16460. // edge is "sharp";
  16461. sharpEdges[i] = true;
  16462. sharpVertices[edgeVertexA] = true;
  16463. sharpVertices[edgeVertexB] = true;
  16464. }
  16465. }
  16466. //console.log('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  16467. for (i in vfMap) {
  16468. edge = vfMap[i];
  16469. faceIndexA = edge[0]; // face index a
  16470. faceIndexB = edge[1]; // face index b
  16471. edgeVertex = i.split('_');
  16472. edgeVertexA = edgeVertex[0];
  16473. edgeVertexB = edgeVertex[1];
  16474. avg = new THREE.Vector3();
  16475. //console.log(i, faceIndexB,facePoints[faceIndexB]);
  16476. if (sharpEdges[i]) {
  16477. //console.log('warning, ', i, 'edge has only 1 connecting face', edge);
  16478. // For a sharp edge, average the edge end points.
  16479. avg.addSelf(originalPoints[edgeVertexA].position);
  16480. avg.addSelf(originalPoints[edgeVertexB].position);
  16481. avg.multiplyScalar(0.5);
  16482. sharpVertices[newPoints.length] = true;
  16483. } else {
  16484. avg.addSelf(facePoints[faceIndexA]);
  16485. avg.addSelf(facePoints[faceIndexB]);
  16486. avg.addSelf(originalPoints[edgeVertexA].position);
  16487. avg.addSelf(originalPoints[edgeVertexB].position);
  16488. avg.multiplyScalar(0.25);
  16489. }
  16490. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  16491. //console.log(edgePoints[i], newPoints.length);
  16492. newPoints.push( new THREE.Vertex(avg) );
  16493. edgeCount ++;
  16494. if (!scope.supportUVs || uvForVertices.length==0) continue;
  16495. // Prepare subdivided uv
  16496. avgUv = new THREE.UV();
  16497. avgUv.u = uvForVertices[edgeVertexA].u + uvForVertices[edgeVertexB].u;
  16498. avgUv.v = uvForVertices[edgeVertexA].v + uvForVertices[edgeVertexB].v;
  16499. avgUv.u /= 2;
  16500. avgUv.v /= 2;
  16501. uvForVertices.push(avgUv);
  16502. }
  16503. // Step 3
  16504. // For each face point, add an edge for every edge of the face,
  16505. // connecting the face point to each edge point for the face.
  16506. var facePt, currentVerticeIndex;
  16507. var hashAB, hashBC, hashCD, hashDA, hashCA;
  16508. var abc123 = ['123', '12', '2', '23'];
  16509. var bca123 = ['123', '23', '3', '31'];
  16510. var cab123 = ['123', '31', '1', '12'];
  16511. var abc1234 = ['1234', '12', '2', '23'];
  16512. var bcd1234 = ['1234', '23', '3', '34'];
  16513. var cda1234 = ['1234', '34', '4', '41'];
  16514. var dab1234 = ['1234', '41', '1', '12'];
  16515. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  16516. facePt = facePoints[i];
  16517. face = originalFaces[i];
  16518. currentVerticeIndex = originalVerticesLength+ i;
  16519. if ( face instanceof THREE.Face3 ) {
  16520. // create 3 face4s
  16521. hashAB = edge_hash( face.a, face.b );
  16522. hashBC = edge_hash( face.b, face.c );
  16523. hashCA = edge_hash( face.c, face.a );
  16524. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123 );
  16525. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123 );
  16526. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123 );
  16527. } else if ( face instanceof THREE.Face4 ) {
  16528. // create 4 face4s
  16529. hashAB = edge_hash( face.a, face.b );
  16530. hashBC = edge_hash( face.b, face.c );
  16531. hashCD = edge_hash( face.c, face.d );
  16532. hashDA = edge_hash( face.d, face.a );
  16533. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234 );
  16534. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234 );
  16535. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234 );
  16536. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234 );
  16537. } else {
  16538. console.log('face should be a face!', face);
  16539. }
  16540. }
  16541. newVertices = newPoints;
  16542. // console.log('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  16543. // console.log('new points', newPoints.length, 'faces', newFaces.length );
  16544. // Step 4
  16545. // For each original point P,
  16546. // take the average F of all n face points for faces touching P,
  16547. // and take the average R of all n edge midpoints for edges touching P,
  16548. // where each edge midpoint is the average of its two endpoint vertices.
  16549. // Move each original point to the point
  16550. var F = new THREE.Vector3();
  16551. var R = new THREE.Vector3();
  16552. var n;
  16553. for (i=0, il = originalPoints.length; i<il; i++) {
  16554. // (F + 2R + (n-3)P) / n
  16555. if (vertexEdgeMap[i]===undefined) continue;
  16556. F.set(0,0,0);
  16557. R.set(0,0,0);
  16558. var newPos = new THREE.Vector3(0,0,0);
  16559. var f =0;
  16560. for (j in vertexFaceMap[i]) {
  16561. F.addSelf(facePoints[j]);
  16562. f++;
  16563. }
  16564. var sharpEdgeCount = 0;
  16565. n = vertexEdgeMap[i].length;
  16566. for (j=0;j<n;j++) {
  16567. if (
  16568. sharpEdges[
  16569. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  16570. ]) {
  16571. sharpEdgeCount++;
  16572. }
  16573. }
  16574. if ( sharpEdgeCount==2 ) {
  16575. continue;
  16576. // Do not move vertex if there's 2 connecting sharp edges.
  16577. }
  16578. /*
  16579. if (sharpEdgeCount>2) {
  16580. // TODO
  16581. }
  16582. */
  16583. F.divideScalar(f);
  16584. for (j=0; j<n;j++) {
  16585. edge = vertexEdgeMap[i][j];
  16586. var midPt = originalPoints[edge[0]].position.clone().addSelf(originalPoints[edge[1]].position).divideScalar(2);
  16587. R.addSelf(midPt);
  16588. // R.addSelf(originalPoints[edge[0]].position);
  16589. // R.addSelf(originalPoints[edge[1]].position);
  16590. }
  16591. R.divideScalar(n)
  16592. newPos.addSelf(originalPoints[i].position);
  16593. newPos.multiplyScalar(n - 3);
  16594. newPos.addSelf(F);
  16595. newPos.addSelf(R.multiplyScalar(2));
  16596. newPos.divideScalar(n);
  16597. newVertices[i].position = newPos;
  16598. }
  16599. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  16600. newGeometry.vertices = newVertices;
  16601. newGeometry.faces = newFaces;
  16602. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  16603. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  16604. newGeometry.computeCentroids();
  16605. newGeometry.computeFaceNormals();
  16606. newGeometry.computeVertexNormals();
  16607. };
  16608. /**
  16609. * @author alteredq / http://alteredqualia.com/
  16610. */
  16611. THREE.Loader = function ( showStatus ) {
  16612. this.showStatus = showStatus;
  16613. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  16614. this.onLoadStart = function () {};
  16615. this.onLoadProgress = function() {};
  16616. this.onLoadComplete = function () {};
  16617. };
  16618. THREE.Loader.prototype = {
  16619. constructor: THREE.Loader,
  16620. crossOrigin: 'anonymous',
  16621. addStatusElement: function () {
  16622. var e = document.createElement( "div" );
  16623. e.style.position = "absolute";
  16624. e.style.right = "0px";
  16625. e.style.top = "0px";
  16626. e.style.fontSize = "0.8em";
  16627. e.style.textAlign = "left";
  16628. e.style.background = "rgba(0,0,0,0.25)";
  16629. e.style.color = "#fff";
  16630. e.style.width = "120px";
  16631. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  16632. e.style.zIndex = 1000;
  16633. e.innerHTML = "Loading ...";
  16634. return e;
  16635. },
  16636. updateProgress: function ( progress ) {
  16637. var message = "Loaded ";
  16638. if ( progress.total ) {
  16639. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  16640. } else {
  16641. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  16642. }
  16643. this.statusDomElement.innerHTML = message;
  16644. },
  16645. extractUrlBase: function ( url ) {
  16646. var parts = url.split( '/' );
  16647. parts.pop();
  16648. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  16649. },
  16650. initMaterials: function ( scope, materials, texturePath ) {
  16651. scope.materials = [];
  16652. for ( var i = 0; i < materials.length; ++ i ) {
  16653. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  16654. }
  16655. },
  16656. hasNormals: function ( scope ) {
  16657. var m, i, il = scope.materials.length;
  16658. for( i = 0; i < il; i ++ ) {
  16659. m = scope.materials[ i ];
  16660. if ( m instanceof THREE.ShaderMaterial ) return true;
  16661. }
  16662. return false;
  16663. },
  16664. createMaterial: function ( m, texturePath ) {
  16665. var _this = this;
  16666. function is_pow2( n ) {
  16667. var l = Math.log( n ) / Math.LN2;
  16668. return Math.floor( l ) == l;
  16669. }
  16670. function nearest_pow2( n ) {
  16671. var l = Math.log( n ) / Math.LN2;
  16672. return Math.pow( 2, Math.round( l ) );
  16673. }
  16674. function load_image( where, url ) {
  16675. var image = new Image();
  16676. image.onload = function () {
  16677. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  16678. var width = nearest_pow2( this.width );
  16679. var height = nearest_pow2( this.height );
  16680. where.image.width = width;
  16681. where.image.height = height;
  16682. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  16683. } else {
  16684. where.image = this;
  16685. }
  16686. where.needsUpdate = true;
  16687. };
  16688. image.crossOrigin = _this.crossOrigin;
  16689. image.src = url;
  16690. }
  16691. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  16692. var texture = document.createElement( 'canvas' );
  16693. where[ name ] = new THREE.Texture( texture );
  16694. where[ name ].sourceFile = sourceFile;
  16695. if( repeat ) {
  16696. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  16697. if ( repeat[ 0 ] != 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  16698. if ( repeat[ 1 ] != 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  16699. }
  16700. if ( offset ) {
  16701. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  16702. }
  16703. if ( wrap ) {
  16704. var wrapMap = {
  16705. "repeat" : THREE.RepeatWrapping,
  16706. "mirror" : THREE.MirroredRepeatWrapping
  16707. }
  16708. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  16709. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  16710. }
  16711. load_image( where[ name ], texturePath + "/" + sourceFile );
  16712. }
  16713. function rgb2hex( rgb ) {
  16714. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  16715. }
  16716. // defaults
  16717. var mtype = "MeshLambertMaterial";
  16718. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, wireframe: m.wireframe };
  16719. // parameters from model file
  16720. if ( m.shading ) {
  16721. var shading = m.shading.toLowerCase();
  16722. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  16723. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  16724. }
  16725. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  16726. mpars.blending = THREE[ m.blending ];
  16727. }
  16728. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  16729. mpars.transparent = m.transparent;
  16730. }
  16731. if ( m.depthTest !== undefined ) {
  16732. mpars.depthTest = m.depthTest;
  16733. }
  16734. if ( m.depthWrite !== undefined ) {
  16735. mpars.depthWrite = m.depthWrite;
  16736. }
  16737. if ( m.vertexColors !== undefined ) {
  16738. if ( m.vertexColors == "face" ) {
  16739. mpars.vertexColors = THREE.FaceColors;
  16740. } else if ( m.vertexColors ) {
  16741. mpars.vertexColors = THREE.VertexColors;
  16742. }
  16743. }
  16744. // colors
  16745. if ( m.colorDiffuse ) {
  16746. mpars.color = rgb2hex( m.colorDiffuse );
  16747. } else if ( m.DbgColor ) {
  16748. mpars.color = m.DbgColor;
  16749. }
  16750. if ( m.colorSpecular ) {
  16751. mpars.specular = rgb2hex( m.colorSpecular );
  16752. }
  16753. if ( m.colorAmbient ) {
  16754. mpars.ambient = rgb2hex( m.colorAmbient );
  16755. }
  16756. // modifiers
  16757. if ( m.transparency ) {
  16758. mpars.opacity = m.transparency;
  16759. }
  16760. if ( m.specularCoef ) {
  16761. mpars.shininess = m.specularCoef;
  16762. }
  16763. // textures
  16764. if ( m.mapDiffuse && texturePath ) {
  16765. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  16766. }
  16767. if ( m.mapLight && texturePath ) {
  16768. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  16769. }
  16770. if ( m.mapNormal && texturePath ) {
  16771. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  16772. }
  16773. if ( m.mapSpecular && texturePath ) {
  16774. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  16775. }
  16776. // special case for normal mapped material
  16777. if ( m.mapNormal ) {
  16778. var shader = THREE.ShaderUtils.lib[ "normal" ];
  16779. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  16780. uniforms[ "tNormal" ].texture = mpars.normalMap;
  16781. if ( m.mapNormalFactor ) {
  16782. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  16783. }
  16784. if ( mpars.map ) {
  16785. uniforms[ "tDiffuse" ].texture = mpars.map;
  16786. uniforms[ "enableDiffuse" ].value = true;
  16787. }
  16788. if ( mpars.specularMap ) {
  16789. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  16790. uniforms[ "enableSpecular" ].value = true;
  16791. }
  16792. if ( mpars.lightMap ) {
  16793. uniforms[ "tAO" ].texture = mpars.lightMap;
  16794. uniforms[ "enableAO" ].value = true;
  16795. }
  16796. // for the moment don't handle displacement texture
  16797. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  16798. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  16799. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  16800. uniforms[ "uShininess" ].value = mpars.shininess;
  16801. if ( mpars.opacity !== undefined ) {
  16802. uniforms[ "uOpacity" ].value = mpars.opacity;
  16803. }
  16804. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  16805. var material = new THREE.ShaderMaterial( parameters );
  16806. } else {
  16807. var material = new THREE[ mtype ]( mpars );
  16808. }
  16809. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  16810. return material;
  16811. }
  16812. };
  16813. /**
  16814. * @author alteredq / http://alteredqualia.com/
  16815. */
  16816. THREE.BinaryLoader = function ( showStatus ) {
  16817. THREE.Loader.call( this, showStatus );
  16818. };
  16819. THREE.BinaryLoader.prototype = new THREE.Loader();
  16820. THREE.BinaryLoader.prototype.constructor = THREE.BinaryLoader;
  16821. THREE.BinaryLoader.prototype.supr = THREE.Loader.prototype;
  16822. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  16823. // - binary models consist of two files: JS and BIN
  16824. // - parameters
  16825. // - url (required)
  16826. // - callback (required)
  16827. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  16828. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  16829. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  16830. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  16831. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  16832. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  16833. this.onLoadStart();
  16834. // #1 load JS part via web worker
  16835. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  16836. };
  16837. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  16838. var xhr = new XMLHttpRequest();
  16839. xhr.onreadystatechange = function () {
  16840. if ( xhr.readyState == 4 ) {
  16841. if ( xhr.status == 200 || xhr.status == 0 ) {
  16842. var json = JSON.parse( xhr.responseText );
  16843. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  16844. } else {
  16845. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16846. }
  16847. }
  16848. };
  16849. xhr.open( "GET", url, true );
  16850. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  16851. xhr.setRequestHeader( "Content-Type", "text/plain" );
  16852. xhr.send( null );
  16853. };
  16854. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  16855. var xhr = new XMLHttpRequest(),
  16856. url = binaryPath + "/" + json.buffers;
  16857. var length = 0;
  16858. xhr.onreadystatechange = function () {
  16859. if ( xhr.readyState == 4 ) {
  16860. if ( xhr.status == 200 || xhr.status == 0 ) {
  16861. THREE.BinaryLoader.prototype.createBinModel( xhr.response, callback, texturePath, json.materials );
  16862. } else {
  16863. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16864. }
  16865. } else if ( xhr.readyState == 3 ) {
  16866. if ( callbackProgress ) {
  16867. if ( length == 0 ) {
  16868. length = xhr.getResponseHeader( "Content-Length" );
  16869. }
  16870. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  16871. }
  16872. } else if ( xhr.readyState == 2 ) {
  16873. length = xhr.getResponseHeader( "Content-Length" );
  16874. }
  16875. };
  16876. xhr.open( "GET", url, true );
  16877. xhr.responseType = "arraybuffer";
  16878. xhr.send( null );
  16879. };
  16880. // Binary AJAX parser
  16881. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  16882. var Model = function ( texturePath ) {
  16883. var scope = this,
  16884. currentOffset = 0,
  16885. md,
  16886. normals = [],
  16887. uvs = [],
  16888. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  16889. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  16890. tri_size, quad_size,
  16891. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  16892. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  16893. THREE.Geometry.call( this );
  16894. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  16895. md = parseMetaData( data, currentOffset );
  16896. currentOffset += md.header_bytes;
  16897. /*
  16898. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16899. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  16900. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16901. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16902. */
  16903. // buffers sizes
  16904. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  16905. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  16906. len_tri_flat = md.ntri_flat * ( tri_size );
  16907. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  16908. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  16909. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  16910. len_quad_flat = md.nquad_flat * ( quad_size );
  16911. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  16912. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  16913. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  16914. // read buffers
  16915. currentOffset += init_vertices( currentOffset );
  16916. currentOffset += init_normals( currentOffset );
  16917. currentOffset += handlePadding( md.nnormals * 3 );
  16918. currentOffset += init_uvs( currentOffset );
  16919. start_tri_flat = currentOffset;
  16920. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  16921. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  16922. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  16923. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  16924. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  16925. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  16926. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  16927. // have to first process faces with uvs
  16928. // so that face and uv indices match
  16929. init_triangles_flat_uv( start_tri_flat_uv );
  16930. init_triangles_smooth_uv( start_tri_smooth_uv );
  16931. init_quads_flat_uv( start_quad_flat_uv );
  16932. init_quads_smooth_uv( start_quad_smooth_uv );
  16933. // now we can process untextured faces
  16934. init_triangles_flat( start_tri_flat );
  16935. init_triangles_smooth( start_tri_smooth );
  16936. init_quads_flat( start_quad_flat );
  16937. init_quads_smooth( start_quad_smooth );
  16938. this.computeCentroids();
  16939. this.computeFaceNormals();
  16940. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  16941. function handlePadding( n ) {
  16942. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  16943. };
  16944. function parseMetaData( data, offset ) {
  16945. var metaData = {
  16946. 'signature' :parseString( data, offset, 12 ),
  16947. 'header_bytes' :parseUChar8( data, offset + 12 ),
  16948. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  16949. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  16950. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  16951. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  16952. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  16953. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  16954. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  16955. 'nvertices' :parseUInt32( data, offset + 20 ),
  16956. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  16957. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  16958. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  16959. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  16960. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  16961. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  16962. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  16963. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  16964. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  16965. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  16966. };
  16967. /*
  16968. console.log( "signature: " + metaData.signature );
  16969. console.log( "header_bytes: " + metaData.header_bytes );
  16970. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  16971. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  16972. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  16973. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  16974. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  16975. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  16976. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  16977. console.log( "nvertices: " + metaData.nvertices );
  16978. console.log( "nnormals: " + metaData.nnormals );
  16979. console.log( "nuvs: " + metaData.nuvs );
  16980. console.log( "ntri_flat: " + metaData.ntri_flat );
  16981. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  16982. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  16983. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  16984. console.log( "nquad_flat: " + metaData.nquad_flat );
  16985. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  16986. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  16987. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  16988. var total = metaData.header_bytes
  16989. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  16990. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  16991. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  16992. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  16993. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  16994. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  16995. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  16996. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  16997. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  16998. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  16999. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  17000. console.log( "total bytes: " + total );
  17001. */
  17002. return metaData;
  17003. };
  17004. function parseString( data, offset, length ) {
  17005. var charArray = new Uint8Array( data, offset, length );
  17006. var text = "";
  17007. for ( var i = 0; i < length; i ++ ) {
  17008. text += String.fromCharCode( charArray[ offset + i ] );
  17009. }
  17010. return text;
  17011. };
  17012. function parseUChar8( data, offset ) {
  17013. var charArray = new Uint8Array( data, offset, 1 );
  17014. return charArray[ 0 ];
  17015. };
  17016. function parseUInt32( data, offset ) {
  17017. var intArray = new Uint32Array( data, offset, 1 );
  17018. return intArray[ 0 ];
  17019. };
  17020. function init_vertices( start ) {
  17021. var nElements = md.nvertices;
  17022. var coordArray = new Float32Array( data, start, nElements * 3 );
  17023. var i, x, y, z;
  17024. for( i = 0; i < nElements; i ++ ) {
  17025. x = coordArray[ i * 3 ];
  17026. y = coordArray[ i * 3 + 1 ];
  17027. z = coordArray[ i * 3 + 2 ];
  17028. vertex( scope, x, y, z );
  17029. }
  17030. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  17031. };
  17032. function init_normals( start ) {
  17033. var nElements = md.nnormals;
  17034. if ( nElements ) {
  17035. var normalArray = new Int8Array( data, start, nElements * 3 );
  17036. var i, x, y, z;
  17037. for( i = 0; i < nElements; i ++ ) {
  17038. x = normalArray[ i * 3 ];
  17039. y = normalArray[ i * 3 + 1 ];
  17040. z = normalArray[ i * 3 + 2 ];
  17041. normals.push( x/127, y/127, z/127 );
  17042. }
  17043. }
  17044. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  17045. };
  17046. function init_uvs( start ) {
  17047. var nElements = md.nuvs;
  17048. if ( nElements ) {
  17049. var uvArray = new Float32Array( data, start, nElements * 2 );
  17050. var i, u, v;
  17051. for( i = 0; i < nElements; i ++ ) {
  17052. u = uvArray[ i * 2 ];
  17053. v = uvArray[ i * 2 + 1 ];
  17054. uvs.push( u, v );
  17055. }
  17056. }
  17057. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  17058. };
  17059. function init_uvs3( nElements, offset ) {
  17060. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  17061. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  17062. for( i = 0; i < nElements; i ++ ) {
  17063. uva = uvIndexBuffer[ i * 3 ];
  17064. uvb = uvIndexBuffer[ i * 3 + 1 ];
  17065. uvc = uvIndexBuffer[ i * 3 + 2 ];
  17066. u1 = uvs[ uva*2 ];
  17067. v1 = uvs[ uva*2 + 1 ];
  17068. u2 = uvs[ uvb*2 ];
  17069. v2 = uvs[ uvb*2 + 1 ];
  17070. u3 = uvs[ uvc*2 ];
  17071. v3 = uvs[ uvc*2 + 1 ];
  17072. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  17073. }
  17074. };
  17075. function init_uvs4( nElements, offset ) {
  17076. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  17077. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  17078. for( i = 0; i < nElements; i ++ ) {
  17079. uva = uvIndexBuffer[ i * 4 ];
  17080. uvb = uvIndexBuffer[ i * 4 + 1 ];
  17081. uvc = uvIndexBuffer[ i * 4 + 2 ];
  17082. uvd = uvIndexBuffer[ i * 4 + 3 ];
  17083. u1 = uvs[ uva*2 ];
  17084. v1 = uvs[ uva*2 + 1 ];
  17085. u2 = uvs[ uvb*2 ];
  17086. v2 = uvs[ uvb*2 + 1 ];
  17087. u3 = uvs[ uvc*2 ];
  17088. v3 = uvs[ uvc*2 + 1 ];
  17089. u4 = uvs[ uvd*2 ];
  17090. v4 = uvs[ uvd*2 + 1 ];
  17091. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  17092. }
  17093. };
  17094. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  17095. var i, a, b, c, m;
  17096. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17097. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17098. for( i = 0; i < nElements; i ++ ) {
  17099. a = vertexIndexBuffer[ i * 3 ];
  17100. b = vertexIndexBuffer[ i * 3 + 1 ];
  17101. c = vertexIndexBuffer[ i * 3 + 2 ];
  17102. m = materialIndexBuffer[ i ];
  17103. f3( scope, a, b, c, m );
  17104. }
  17105. };
  17106. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  17107. var i, a, b, c, d, m;
  17108. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17109. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17110. for( i = 0; i < nElements; i ++ ) {
  17111. a = vertexIndexBuffer[ i * 4 ];
  17112. b = vertexIndexBuffer[ i * 4 + 1 ];
  17113. c = vertexIndexBuffer[ i * 4 + 2 ];
  17114. d = vertexIndexBuffer[ i * 4 + 3 ];
  17115. m = materialIndexBuffer[ i ];
  17116. f4( scope, a, b, c, d, m );
  17117. }
  17118. };
  17119. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17120. var i, a, b, c, m;
  17121. var na, nb, nc;
  17122. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17123. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  17124. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17125. for( i = 0; i < nElements; i ++ ) {
  17126. a = vertexIndexBuffer[ i * 3 ];
  17127. b = vertexIndexBuffer[ i * 3 + 1 ];
  17128. c = vertexIndexBuffer[ i * 3 + 2 ];
  17129. na = normalIndexBuffer[ i * 3 ];
  17130. nb = normalIndexBuffer[ i * 3 + 1 ];
  17131. nc = normalIndexBuffer[ i * 3 + 2 ];
  17132. m = materialIndexBuffer[ i ];
  17133. f3n( scope, normals, a, b, c, m, na, nb, nc );
  17134. }
  17135. };
  17136. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17137. var i, a, b, c, d, m;
  17138. var na, nb, nc, nd;
  17139. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17140. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  17141. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17142. for( i = 0; i < nElements; i ++ ) {
  17143. a = vertexIndexBuffer[ i * 4 ];
  17144. b = vertexIndexBuffer[ i * 4 + 1 ];
  17145. c = vertexIndexBuffer[ i * 4 + 2 ];
  17146. d = vertexIndexBuffer[ i * 4 + 3 ];
  17147. na = normalIndexBuffer[ i * 4 ];
  17148. nb = normalIndexBuffer[ i * 4 + 1 ];
  17149. nc = normalIndexBuffer[ i * 4 + 2 ];
  17150. nd = normalIndexBuffer[ i * 4 + 3 ];
  17151. m = materialIndexBuffer[ i ];
  17152. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  17153. }
  17154. };
  17155. function init_triangles_flat( start ) {
  17156. var nElements = md.ntri_flat;
  17157. if ( nElements ) {
  17158. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17159. init_faces3_flat( nElements, start, offsetMaterials );
  17160. }
  17161. };
  17162. function init_triangles_flat_uv( start ) {
  17163. var nElements = md.ntri_flat_uv;
  17164. if ( nElements ) {
  17165. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17166. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17167. init_faces3_flat( nElements, start, offsetMaterials );
  17168. init_uvs3( nElements, offsetUvs );
  17169. }
  17170. };
  17171. function init_triangles_smooth( start ) {
  17172. var nElements = md.ntri_smooth;
  17173. if ( nElements ) {
  17174. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17175. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17176. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17177. }
  17178. };
  17179. function init_triangles_smooth_uv( start ) {
  17180. var nElements = md.ntri_smooth_uv;
  17181. if ( nElements ) {
  17182. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17183. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17184. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17185. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17186. init_uvs3( nElements, offsetUvs );
  17187. }
  17188. };
  17189. function init_quads_flat( start ) {
  17190. var nElements = md.nquad_flat;
  17191. if ( nElements ) {
  17192. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17193. init_faces4_flat( nElements, start, offsetMaterials );
  17194. }
  17195. };
  17196. function init_quads_flat_uv( start ) {
  17197. var nElements = md.nquad_flat_uv;
  17198. if ( nElements ) {
  17199. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17200. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17201. init_faces4_flat( nElements, start, offsetMaterials );
  17202. init_uvs4( nElements, offsetUvs );
  17203. }
  17204. };
  17205. function init_quads_smooth( start ) {
  17206. var nElements = md.nquad_smooth;
  17207. if ( nElements ) {
  17208. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17209. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17210. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17211. }
  17212. };
  17213. function init_quads_smooth_uv( start ) {
  17214. var nElements = md.nquad_smooth_uv;
  17215. if ( nElements ) {
  17216. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17217. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17218. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17219. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17220. init_uvs4( nElements, offsetUvs );
  17221. }
  17222. };
  17223. };
  17224. function vertex ( scope, x, y, z ) {
  17225. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  17226. };
  17227. function f3 ( scope, a, b, c, mi ) {
  17228. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  17229. };
  17230. function f4 ( scope, a, b, c, d, mi ) {
  17231. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  17232. };
  17233. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  17234. var nax = normals[ na*3 ],
  17235. nay = normals[ na*3 + 1 ],
  17236. naz = normals[ na*3 + 2 ],
  17237. nbx = normals[ nb*3 ],
  17238. nby = normals[ nb*3 + 1 ],
  17239. nbz = normals[ nb*3 + 2 ],
  17240. ncx = normals[ nc*3 ],
  17241. ncy = normals[ nc*3 + 1 ],
  17242. ncz = normals[ nc*3 + 2 ];
  17243. scope.faces.push( new THREE.Face3( a, b, c,
  17244. [new THREE.Vector3( nax, nay, naz ),
  17245. new THREE.Vector3( nbx, nby, nbz ),
  17246. new THREE.Vector3( ncx, ncy, ncz )],
  17247. null,
  17248. mi ) );
  17249. };
  17250. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  17251. var nax = normals[ na*3 ],
  17252. nay = normals[ na*3 + 1 ],
  17253. naz = normals[ na*3 + 2 ],
  17254. nbx = normals[ nb*3 ],
  17255. nby = normals[ nb*3 + 1 ],
  17256. nbz = normals[ nb*3 + 2 ],
  17257. ncx = normals[ nc*3 ],
  17258. ncy = normals[ nc*3 + 1 ],
  17259. ncz = normals[ nc*3 + 2 ],
  17260. ndx = normals[ nd*3 ],
  17261. ndy = normals[ nd*3 + 1 ],
  17262. ndz = normals[ nd*3 + 2 ];
  17263. scope.faces.push( new THREE.Face4( a, b, c, d,
  17264. [new THREE.Vector3( nax, nay, naz ),
  17265. new THREE.Vector3( nbx, nby, nbz ),
  17266. new THREE.Vector3( ncx, ncy, ncz ),
  17267. new THREE.Vector3( ndx, ndy, ndz )],
  17268. null,
  17269. mi ) );
  17270. };
  17271. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  17272. var uv = [];
  17273. uv.push( new THREE.UV( u1, v1 ) );
  17274. uv.push( new THREE.UV( u2, v2 ) );
  17275. uv.push( new THREE.UV( u3, v3 ) );
  17276. where.push( uv );
  17277. };
  17278. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  17279. var uv = [];
  17280. uv.push( new THREE.UV( u1, v1 ) );
  17281. uv.push( new THREE.UV( u2, v2 ) );
  17282. uv.push( new THREE.UV( u3, v3 ) );
  17283. uv.push( new THREE.UV( u4, v4 ) );
  17284. where.push( uv );
  17285. };
  17286. Model.prototype = new THREE.Geometry();
  17287. Model.prototype.constructor = Model;
  17288. callback( new Model( texturePath ) );
  17289. };
  17290. /**
  17291. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  17292. */
  17293. THREE.ColladaLoader = function () {
  17294. var COLLADA = null;
  17295. var scene = null;
  17296. var daeScene;
  17297. var readyCallbackFunc = null;
  17298. var sources = {};
  17299. var images = {};
  17300. var animations = {};
  17301. var controllers = {};
  17302. var geometries = {};
  17303. var materials = {};
  17304. var effects = {};
  17305. var cameras = {};
  17306. var animData;
  17307. var visualScenes;
  17308. var baseUrl;
  17309. var morphs;
  17310. var skins;
  17311. var flip_uv = true;
  17312. var preferredShading = THREE.SmoothShading;
  17313. var options = {
  17314. // Force Geometry to always be centered at the local origin of the
  17315. // containing Mesh.
  17316. centerGeometry: false,
  17317. // Axis conversion is done for geometries, animations, and controllers.
  17318. // If we ever pull cameras or lights out of the COLLADA file, they'll
  17319. // need extra work.
  17320. convertUpAxis: false,
  17321. subdivideFaces: true,
  17322. upAxis: 'Y'
  17323. };
  17324. // TODO: support unit conversion as well
  17325. var colladaUnit = 1.0;
  17326. var colladaUp = 'Y';
  17327. var upConversion = null;
  17328. var TO_RADIANS = Math.PI / 180;
  17329. function load ( url, readyCallback, progressCallback ) {
  17330. var length = 0;
  17331. if ( document.implementation && document.implementation.createDocument ) {
  17332. var req = new XMLHttpRequest();
  17333. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  17334. req.onreadystatechange = function() {
  17335. if( req.readyState == 4 ) {
  17336. if( req.status == 0 || req.status == 200 ) {
  17337. if ( req.responseXML ) {
  17338. readyCallbackFunc = readyCallback;
  17339. parse( req.responseXML, undefined, url );
  17340. } else {
  17341. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  17342. }
  17343. }
  17344. } else if ( req.readyState == 3 ) {
  17345. if ( progressCallback ) {
  17346. if ( length == 0 ) {
  17347. length = req.getResponseHeader( "Content-Length" );
  17348. }
  17349. progressCallback( { total: length, loaded: req.responseText.length } );
  17350. }
  17351. }
  17352. }
  17353. req.open( "GET", url, true );
  17354. req.send( null );
  17355. } else {
  17356. alert( "Don't know how to parse XML!" );
  17357. }
  17358. };
  17359. function parse( doc, callBack, url ) {
  17360. COLLADA = doc;
  17361. callBack = callBack || readyCallbackFunc;
  17362. if ( url !== undefined ) {
  17363. var parts = url.split( '/' );
  17364. parts.pop();
  17365. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  17366. }
  17367. parseAsset();
  17368. setUpConversion();
  17369. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  17370. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  17371. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  17372. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  17373. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  17374. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  17375. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  17376. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  17377. morphs = [];
  17378. skins = [];
  17379. daeScene = parseScene();
  17380. scene = new THREE.Object3D();
  17381. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  17382. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  17383. }
  17384. createAnimations();
  17385. var result = {
  17386. scene: scene,
  17387. morphs: morphs,
  17388. skins: skins,
  17389. animations: animData,
  17390. dae: {
  17391. images: images,
  17392. materials: materials,
  17393. cameras: cameras,
  17394. effects: effects,
  17395. geometries: geometries,
  17396. controllers: controllers,
  17397. animations: animations,
  17398. visualScenes: visualScenes,
  17399. scene: daeScene
  17400. }
  17401. };
  17402. if ( callBack ) {
  17403. callBack( result );
  17404. }
  17405. return result;
  17406. };
  17407. function setPreferredShading ( shading ) {
  17408. preferredShading = shading;
  17409. };
  17410. function parseAsset () {
  17411. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  17412. var element = elements.iterateNext();
  17413. if ( element && element.childNodes ) {
  17414. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  17415. var child = element.childNodes[ i ];
  17416. switch ( child.nodeName ) {
  17417. case 'unit':
  17418. var meter = child.getAttribute( 'meter' );
  17419. if ( meter ) {
  17420. colladaUnit = parseFloat( meter );
  17421. }
  17422. break;
  17423. case 'up_axis':
  17424. colladaUp = child.textContent.charAt(0);
  17425. break;
  17426. }
  17427. }
  17428. }
  17429. };
  17430. function parseLib ( q, classSpec, prefix ) {
  17431. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  17432. var lib = {};
  17433. var element = elements.iterateNext();
  17434. var i = 0;
  17435. while ( element ) {
  17436. var daeElement = ( new classSpec() ).parse( element );
  17437. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  17438. lib[ daeElement.id ] = daeElement;
  17439. element = elements.iterateNext();
  17440. }
  17441. return lib;
  17442. };
  17443. function parseScene() {
  17444. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17445. if ( sceneElement ) {
  17446. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  17447. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  17448. } else {
  17449. return null;
  17450. }
  17451. };
  17452. function createAnimations() {
  17453. animData = [];
  17454. // fill in the keys
  17455. recurseHierarchy( scene );
  17456. };
  17457. function recurseHierarchy( node ) {
  17458. var n = daeScene.getChildById( node.name, true ),
  17459. newData = null;
  17460. if ( n && n.keys ) {
  17461. newData = {
  17462. fps: 60,
  17463. hierarchy: [ {
  17464. node: n,
  17465. keys: n.keys,
  17466. sids: n.sids
  17467. } ],
  17468. node: node,
  17469. name: 'animation_' + node.name,
  17470. length: 0
  17471. };
  17472. animData.push(newData);
  17473. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  17474. newData.length = Math.max( newData.length, n.keys[i].time );
  17475. }
  17476. } else {
  17477. newData = {
  17478. hierarchy: [ {
  17479. keys: [],
  17480. sids: []
  17481. } ]
  17482. }
  17483. }
  17484. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  17485. var d = recurseHierarchy( node.children[i] );
  17486. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  17487. newData.hierarchy.push( {
  17488. keys: [],
  17489. sids: []
  17490. } );
  17491. }
  17492. }
  17493. return newData;
  17494. };
  17495. function calcAnimationBounds () {
  17496. var start = 1000000;
  17497. var end = -start;
  17498. var frames = 0;
  17499. for ( var id in animations ) {
  17500. var animation = animations[ id ];
  17501. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  17502. var sampler = animation.sampler[ i ];
  17503. sampler.create();
  17504. start = Math.min( start, sampler.startTime );
  17505. end = Math.max( end, sampler.endTime );
  17506. frames = Math.max( frames, sampler.input.length );
  17507. }
  17508. }
  17509. return { start:start, end:end, frames:frames };
  17510. };
  17511. function createMorph ( geometry, ctrl ) {
  17512. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  17513. if ( !morphCtrl || !morphCtrl.morph ) {
  17514. console.log("could not find morph controller!");
  17515. return;
  17516. }
  17517. var morph = morphCtrl.morph;
  17518. for ( var i = 0; i < morph.targets.length; i ++ ) {
  17519. var target_id = morph.targets[ i ];
  17520. var daeGeometry = geometries[ target_id ];
  17521. if ( !daeGeometry.mesh ||
  17522. !daeGeometry.mesh.primitives ||
  17523. !daeGeometry.mesh.primitives.length ) {
  17524. continue;
  17525. }
  17526. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  17527. if ( target.vertices.length === geometry.vertices.length ) {
  17528. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  17529. }
  17530. }
  17531. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  17532. };
  17533. function createSkin ( geometry, ctrl, applyBindShape ) {
  17534. var skinCtrl = controllers[ ctrl.url ];
  17535. if ( !skinCtrl || !skinCtrl.skin ) {
  17536. console.log( "could not find skin controller!" );
  17537. return;
  17538. }
  17539. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  17540. console.log( "could not find the skeleton for the skin!" );
  17541. return;
  17542. }
  17543. var skin = skinCtrl.skin;
  17544. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  17545. var hierarchy = [];
  17546. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  17547. var bones = [];
  17548. geometry.skinWeights = [];
  17549. geometry.skinIndices = [];
  17550. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  17551. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  17552. /*
  17553. geometry.animation = {
  17554. name: 'take_001',
  17555. fps: 30,
  17556. length: 2,
  17557. JIT: true,
  17558. hierarchy: hierarchy
  17559. };
  17560. */
  17561. if ( applyBindShape ) {
  17562. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  17563. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ].position );
  17564. }
  17565. }
  17566. };
  17567. function setupSkeleton ( node, bones, frame, parent ) {
  17568. node.world = node.world || new THREE.Matrix4();
  17569. node.world.copy( node.matrix );
  17570. if ( node.channels && node.channels.length ) {
  17571. var channel = node.channels[ 0 ];
  17572. var m = channel.sampler.output[ frame ];
  17573. if ( m instanceof THREE.Matrix4 ) {
  17574. node.world.copy( m );
  17575. }
  17576. }
  17577. if ( parent ) {
  17578. node.world.multiply( parent, node.world );
  17579. }
  17580. bones.push( node );
  17581. for ( var i = 0; i < node.nodes.length; i ++ ) {
  17582. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  17583. }
  17584. };
  17585. function setupSkinningMatrices ( bones, skin ) {
  17586. // FIXME: this is dumb...
  17587. for ( var i = 0; i < bones.length; i ++ ) {
  17588. var bone = bones[ i ];
  17589. var found = -1;
  17590. if ( bone.type != 'JOINT' ) continue;
  17591. for ( var j = 0; j < skin.joints.length; j ++ ) {
  17592. if ( bone.sid == skin.joints[ j ] ) {
  17593. found = j;
  17594. break;
  17595. }
  17596. }
  17597. if ( found >= 0 ) {
  17598. var inv = skin.invBindMatrices[ found ];
  17599. bone.invBindMatrix = inv;
  17600. bone.skinningMatrix = new THREE.Matrix4();
  17601. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  17602. bone.weights = [];
  17603. for ( var j = 0; j < skin.weights.length; j ++ ) {
  17604. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  17605. var w = skin.weights[ j ][ k ];
  17606. if ( w.joint == found ) {
  17607. bone.weights.push( w );
  17608. }
  17609. }
  17610. }
  17611. } else {
  17612. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  17613. }
  17614. }
  17615. };
  17616. function applySkin ( geometry, instanceCtrl, frame ) {
  17617. var skinController = controllers[ instanceCtrl.url ];
  17618. frame = frame !== undefined ? frame : 40;
  17619. if ( !skinController || !skinController.skin ) {
  17620. console.log( 'ColladaLoader: Could not find skin controller.' );
  17621. return;
  17622. }
  17623. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  17624. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  17625. return;
  17626. }
  17627. var animationBounds = calcAnimationBounds();
  17628. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  17629. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  17630. var i, j, w, vidx, weight;
  17631. var v = new THREE.Vector3(), o, s;
  17632. // move vertices to bind shape
  17633. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  17634. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i].position );
  17635. }
  17636. // process animation, or simply pose the rig if no animation
  17637. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  17638. var bones = [];
  17639. var skinned = [];
  17640. // zero skinned vertices
  17641. for ( i = 0; i < geometry.vertices.length; i++ ) {
  17642. skinned.push( new THREE.Vertex( new THREE.Vector3() ) );
  17643. }
  17644. // process the frame and setup the rig with a fresh
  17645. // transform, possibly from the bone's animation channel(s)
  17646. setupSkeleton( skeleton, bones, frame );
  17647. setupSkinningMatrices( bones, skinController.skin );
  17648. // skin 'm
  17649. for ( i = 0; i < bones.length; i ++ ) {
  17650. if ( bones[ i ].type != 'JOINT' ) continue;
  17651. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  17652. w = bones[ i ].weights[ j ];
  17653. vidx = w.index;
  17654. weight = w.weight;
  17655. o = geometry.vertices[vidx];
  17656. s = skinned[vidx];
  17657. v.x = o.position.x;
  17658. v.y = o.position.y;
  17659. v.z = o.position.z;
  17660. bones[i].skinningMatrix.multiplyVector3(v);
  17661. s.position.x += (v.x * weight);
  17662. s.position.y += (v.y * weight);
  17663. s.position.z += (v.z * weight);
  17664. }
  17665. }
  17666. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  17667. }
  17668. };
  17669. function createSceneGraph ( node, parent ) {
  17670. var obj = new THREE.Object3D();
  17671. var skinned = false;
  17672. var skinController;
  17673. var morphController;
  17674. var i, j;
  17675. // FIXME: controllers
  17676. for ( i = 0; i < node.controllers.length; i ++ ) {
  17677. var controller = controllers[ node.controllers[ i ].url ];
  17678. switch ( controller.type ) {
  17679. case 'skin':
  17680. if ( geometries[ controller.skin.source ] ) {
  17681. var inst_geom = new InstanceGeometry();
  17682. inst_geom.url = controller.skin.source;
  17683. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17684. node.geometries.push( inst_geom );
  17685. skinned = true;
  17686. skinController = node.controllers[ i ];
  17687. } else if ( controllers[ controller.skin.source ] ) {
  17688. // urgh: controller can be chained
  17689. // handle the most basic case...
  17690. var second = controllers[ controller.skin.source ];
  17691. morphController = second;
  17692. // skinController = node.controllers[i];
  17693. if ( second.morph && geometries[ second.morph.source ] ) {
  17694. var inst_geom = new InstanceGeometry();
  17695. inst_geom.url = second.morph.source;
  17696. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17697. node.geometries.push( inst_geom );
  17698. }
  17699. }
  17700. break;
  17701. case 'morph':
  17702. if ( geometries[ controller.morph.source ] ) {
  17703. var inst_geom = new InstanceGeometry();
  17704. inst_geom.url = controller.morph.source;
  17705. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17706. node.geometries.push( inst_geom );
  17707. morphController = node.controllers[ i ];
  17708. }
  17709. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  17710. default:
  17711. break;
  17712. }
  17713. }
  17714. // FIXME: multi-material mesh?
  17715. // geometries
  17716. for ( i = 0; i < node.geometries.length; i ++ ) {
  17717. var instance_geometry = node.geometries[i];
  17718. var instance_materials = instance_geometry.instance_material;
  17719. var geometry = geometries[instance_geometry.url];
  17720. var used_materials = {};
  17721. var used_materials_array = [];
  17722. var num_materials = 0;
  17723. var first_material;
  17724. if ( geometry ) {
  17725. if ( !geometry.mesh || !geometry.mesh.primitives )
  17726. continue;
  17727. if ( obj.name.length == 0 ) {
  17728. obj.name = geometry.id;
  17729. }
  17730. // collect used fx for this geometry-instance
  17731. if ( instance_materials ) {
  17732. for ( j = 0; j < instance_materials.length; j ++ ) {
  17733. var instance_material = instance_materials[ j ];
  17734. var mat = materials[ instance_material.target ];
  17735. var effect_id = mat.instance_effect.url;
  17736. var shader = effects[ effect_id ].shader;
  17737. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  17738. used_materials[ instance_material.symbol ] = num_materials;
  17739. used_materials_array.push( shader.material )
  17740. first_material = shader.material;
  17741. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  17742. num_materials ++;
  17743. }
  17744. }
  17745. var mesh;
  17746. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  17747. var geom = geometry.mesh.geometry3js;
  17748. if ( num_materials > 1 ) {
  17749. material = new THREE.MeshFaceMaterial();
  17750. geom.materials = used_materials_array;
  17751. for ( j = 0; j < geom.faces.length; j ++ ) {
  17752. var face = geom.faces[ j ];
  17753. face.materialIndex = used_materials[ face.daeMaterial ]
  17754. }
  17755. }
  17756. if ( skinController !== undefined) {
  17757. applySkin( geom, skinController );
  17758. material.morphTargets = true;
  17759. mesh = new THREE.SkinnedMesh( geom, material );
  17760. mesh.skeleton = skinController.skeleton;
  17761. mesh.skinController = controllers[ skinController.url ];
  17762. mesh.skinInstanceController = skinController;
  17763. mesh.name = 'skin_' + skins.length;
  17764. skins.push( mesh );
  17765. } else if ( morphController !== undefined ) {
  17766. createMorph( geom, morphController );
  17767. material.morphTargets = true;
  17768. mesh = new THREE.Mesh( geom, material );
  17769. mesh.name = 'morph_' + morphs.length;
  17770. morphs.push( mesh );
  17771. } else {
  17772. mesh = new THREE.Mesh( geom, material );
  17773. // mesh.geom.name = geometry.id;
  17774. }
  17775. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  17776. }
  17777. }
  17778. for ( i = 0; i < node.cameras.length; i ++ ) {
  17779. var instance_camera = node.cameras[i];
  17780. var cparams = cameras[instance_camera.url];
  17781. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  17782. }
  17783. obj.name = node.id || "";
  17784. obj.matrix = node.matrix;
  17785. var props = node.matrix.decompose();
  17786. obj.position = props[ 0 ];
  17787. obj.quaternion = props[ 1 ];
  17788. obj.useQuaternion = true;
  17789. obj.scale = props[ 2 ];
  17790. if ( options.centerGeometry && obj.geometry ) {
  17791. var delta = THREE.GeometryUtils.center( obj.geometry );
  17792. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  17793. obj.position.subSelf( delta );
  17794. }
  17795. for ( i = 0; i < node.nodes.length; i ++ ) {
  17796. obj.add( createSceneGraph( node.nodes[i], node ) );
  17797. }
  17798. return obj;
  17799. };
  17800. function getJointId( skin, id ) {
  17801. for ( var i = 0; i < skin.joints.length; i ++ ) {
  17802. if ( skin.joints[ i ] == id ) {
  17803. return i;
  17804. }
  17805. }
  17806. };
  17807. function getLibraryNode( id ) {
  17808. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17809. };
  17810. function getChannelsForNode (node ) {
  17811. var channels = [];
  17812. var startTime = 1000000;
  17813. var endTime = -1000000;
  17814. for ( var id in animations ) {
  17815. var animation = animations[id];
  17816. for ( var i = 0; i < animation.channel.length; i ++ ) {
  17817. var channel = animation.channel[i];
  17818. var sampler = animation.sampler[i];
  17819. var id = channel.target.split('/')[0];
  17820. if ( id == node.id ) {
  17821. sampler.create();
  17822. channel.sampler = sampler;
  17823. startTime = Math.min(startTime, sampler.startTime);
  17824. endTime = Math.max(endTime, sampler.endTime);
  17825. channels.push(channel);
  17826. }
  17827. }
  17828. }
  17829. if ( channels.length ) {
  17830. node.startTime = startTime;
  17831. node.endTime = endTime;
  17832. }
  17833. return channels;
  17834. };
  17835. function calcFrameDuration( node ) {
  17836. var minT = 10000000;
  17837. for ( var i = 0; i < node.channels.length; i ++ ) {
  17838. var sampler = node.channels[i].sampler;
  17839. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  17840. var t0 = sampler.input[ j ];
  17841. var t1 = sampler.input[ j + 1 ];
  17842. minT = Math.min( minT, t1 - t0 );
  17843. }
  17844. }
  17845. return minT;
  17846. };
  17847. function calcMatrixAt( node, t ) {
  17848. var animated = {};
  17849. var i, j;
  17850. for ( i = 0; i < node.channels.length; i ++ ) {
  17851. var channel = node.channels[ i ];
  17852. animated[ channel.sid ] = channel;
  17853. }
  17854. var matrix = new THREE.Matrix4();
  17855. for ( i = 0; i < node.transforms.length; i ++ ) {
  17856. var transform = node.transforms[ i ];
  17857. var channel = animated[ transform.sid ];
  17858. if ( channel !== undefined ) {
  17859. var sampler = channel.sampler;
  17860. var value;
  17861. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  17862. if ( sampler.input[ j + 1 ] > t ) {
  17863. value = sampler.output[ j ];
  17864. //console.log(value.flatten)
  17865. break;
  17866. }
  17867. }
  17868. if ( value !== undefined ) {
  17869. if ( value instanceof THREE.Matrix4 ) {
  17870. matrix = matrix.multiply( matrix, value );
  17871. } else {
  17872. // FIXME: handle other types
  17873. matrix = matrix.multiply( matrix, transform.matrix );
  17874. }
  17875. } else {
  17876. matrix = matrix.multiply( matrix, transform.matrix );
  17877. }
  17878. } else {
  17879. matrix = matrix.multiply( matrix, transform.matrix );
  17880. }
  17881. }
  17882. return matrix;
  17883. };
  17884. function bakeAnimations ( node ) {
  17885. if ( node.channels && node.channels.length ) {
  17886. var keys = [],
  17887. sids = [];
  17888. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  17889. var channel = node.channels[i],
  17890. fullSid = channel.fullSid,
  17891. member = getConvertedMember( channel.member ),
  17892. sampler = channel.sampler,
  17893. input = sampler.input,
  17894. transform = node.getTransformBySid( channel.sid );
  17895. if ( transform ) {
  17896. if ( sids.indexOf( fullSid ) === -1 ) {
  17897. sids.push( fullSid );
  17898. }
  17899. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  17900. var time = input[j],
  17901. data = sampler.getData( transform.type, j ),
  17902. key = findKey( keys, time );
  17903. if ( !key ) {
  17904. key = new Key( time );
  17905. var timeNdx = findTimeNdx( keys, time );
  17906. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  17907. }
  17908. key.addTarget( fullSid, transform, member, data );
  17909. }
  17910. } else {
  17911. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  17912. }
  17913. }
  17914. // post process
  17915. for ( var i = 0; i < sids.length; i++ ) {
  17916. var sid = sids[ i ];
  17917. for ( var j = 0; j < keys.length; j++ ) {
  17918. var key = keys[ j ];
  17919. if ( !key.hasTarget( sid ) ) {
  17920. interpolateKeys( keys, key, j, sid );
  17921. }
  17922. }
  17923. }
  17924. node.keys = keys;
  17925. node.sids = sids;
  17926. }
  17927. };
  17928. function findKey ( keys, time) {
  17929. var retVal = null;
  17930. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  17931. var key = keys[i];
  17932. if ( key.time === time ) {
  17933. retVal = key;
  17934. } else if ( key.time > time ) {
  17935. break;
  17936. }
  17937. }
  17938. return retVal;
  17939. };
  17940. function findTimeNdx ( keys, time) {
  17941. var ndx = -1;
  17942. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  17943. var key = keys[i];
  17944. if ( key.time >= time ) {
  17945. ndx = i;
  17946. }
  17947. }
  17948. return ndx;
  17949. };
  17950. function interpolateKeys ( keys, key, ndx, fullSid ) {
  17951. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  17952. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  17953. if ( prevKey && nextKey ) {
  17954. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  17955. prevTarget = prevKey.getTarget( fullSid ),
  17956. nextData = nextKey.getTarget( fullSid ).data,
  17957. prevData = prevTarget.data,
  17958. data;
  17959. if ( prevData.length ) {
  17960. data = [];
  17961. for ( var i = 0; i < prevData.length; ++i ) {
  17962. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  17963. }
  17964. } else {
  17965. data = prevData + ( nextData - prevData ) * scale;
  17966. }
  17967. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  17968. }
  17969. };
  17970. // Get next key with given sid
  17971. function getNextKeyWith( keys, fullSid, ndx ) {
  17972. for ( ; ndx < keys.length; ndx++ ) {
  17973. var key = keys[ ndx ];
  17974. if ( key.hasTarget( fullSid ) ) {
  17975. return key;
  17976. }
  17977. }
  17978. return null;
  17979. };
  17980. // Get previous key with given sid
  17981. function getPrevKeyWith( keys, fullSid, ndx ) {
  17982. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  17983. for ( ; ndx >= 0; ndx-- ) {
  17984. var key = keys[ ndx ];
  17985. if ( key.hasTarget( fullSid ) ) {
  17986. return key;
  17987. }
  17988. }
  17989. return null;
  17990. };
  17991. function _Image() {
  17992. this.id = "";
  17993. this.init_from = "";
  17994. };
  17995. _Image.prototype.parse = function(element) {
  17996. this.id = element.getAttribute('id');
  17997. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  17998. var child = element.childNodes[ i ];
  17999. if ( child.nodeName == 'init_from' ) {
  18000. this.init_from = child.textContent;
  18001. }
  18002. }
  18003. return this;
  18004. };
  18005. function Controller() {
  18006. this.id = "";
  18007. this.name = "";
  18008. this.type = "";
  18009. this.skin = null;
  18010. this.morph = null;
  18011. };
  18012. Controller.prototype.parse = function( element ) {
  18013. this.id = element.getAttribute('id');
  18014. this.name = element.getAttribute('name');
  18015. this.type = "none";
  18016. for ( var i = 0; i < element.childNodes.length; i++ ) {
  18017. var child = element.childNodes[ i ];
  18018. switch ( child.nodeName ) {
  18019. case 'skin':
  18020. this.skin = (new Skin()).parse(child);
  18021. this.type = child.nodeName;
  18022. break;
  18023. case 'morph':
  18024. this.morph = (new Morph()).parse(child);
  18025. this.type = child.nodeName;
  18026. break;
  18027. default:
  18028. break;
  18029. }
  18030. }
  18031. return this;
  18032. };
  18033. function Morph() {
  18034. this.method = null;
  18035. this.source = null;
  18036. this.targets = null;
  18037. this.weights = null;
  18038. };
  18039. Morph.prototype.parse = function( element ) {
  18040. var sources = {};
  18041. var inputs = [];
  18042. var i;
  18043. this.method = element.getAttribute( 'method' );
  18044. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18045. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18046. var child = element.childNodes[ i ];
  18047. if ( child.nodeType != 1 ) continue;
  18048. switch ( child.nodeName ) {
  18049. case 'source':
  18050. var source = ( new Source() ).parse( child );
  18051. sources[ source.id ] = source;
  18052. break;
  18053. case 'targets':
  18054. inputs = this.parseInputs( child );
  18055. break;
  18056. default:
  18057. console.log( child.nodeName );
  18058. break;
  18059. }
  18060. }
  18061. for ( i = 0; i < inputs.length; i ++ ) {
  18062. var input = inputs[ i ];
  18063. var source = sources[ input.source ];
  18064. switch ( input.semantic ) {
  18065. case 'MORPH_TARGET':
  18066. this.targets = source.read();
  18067. break;
  18068. case 'MORPH_WEIGHT':
  18069. this.weights = source.read();
  18070. break;
  18071. default:
  18072. break;
  18073. }
  18074. }
  18075. return this;
  18076. };
  18077. Morph.prototype.parseInputs = function(element) {
  18078. var inputs = [];
  18079. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18080. var child = element.childNodes[i];
  18081. if ( child.nodeType != 1) continue;
  18082. switch ( child.nodeName ) {
  18083. case 'input':
  18084. inputs.push( (new Input()).parse(child) );
  18085. break;
  18086. default:
  18087. break;
  18088. }
  18089. }
  18090. return inputs;
  18091. };
  18092. function Skin() {
  18093. this.source = "";
  18094. this.bindShapeMatrix = null;
  18095. this.invBindMatrices = [];
  18096. this.joints = [];
  18097. this.weights = [];
  18098. };
  18099. Skin.prototype.parse = function( element ) {
  18100. var sources = {};
  18101. var joints, weights;
  18102. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18103. this.invBindMatrices = [];
  18104. this.joints = [];
  18105. this.weights = [];
  18106. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18107. var child = element.childNodes[i];
  18108. if ( child.nodeType != 1 ) continue;
  18109. switch ( child.nodeName ) {
  18110. case 'bind_shape_matrix':
  18111. var f = _floats(child.textContent);
  18112. this.bindShapeMatrix = getConvertedMat4( f );
  18113. break;
  18114. case 'source':
  18115. var src = new Source().parse(child);
  18116. sources[ src.id ] = src;
  18117. break;
  18118. case 'joints':
  18119. joints = child;
  18120. break;
  18121. case 'vertex_weights':
  18122. weights = child;
  18123. break;
  18124. default:
  18125. console.log( child.nodeName );
  18126. break;
  18127. }
  18128. }
  18129. this.parseJoints( joints, sources );
  18130. this.parseWeights( weights, sources );
  18131. return this;
  18132. };
  18133. Skin.prototype.parseJoints = function ( element, sources ) {
  18134. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18135. var child = element.childNodes[ i ];
  18136. if ( child.nodeType != 1 ) continue;
  18137. switch ( child.nodeName ) {
  18138. case 'input':
  18139. var input = ( new Input() ).parse( child );
  18140. var source = sources[ input.source ];
  18141. if ( input.semantic == 'JOINT' ) {
  18142. this.joints = source.read();
  18143. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  18144. this.invBindMatrices = source.read();
  18145. }
  18146. break;
  18147. default:
  18148. break;
  18149. }
  18150. }
  18151. };
  18152. Skin.prototype.parseWeights = function ( element, sources ) {
  18153. var v, vcount, inputs = [];
  18154. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18155. var child = element.childNodes[ i ];
  18156. if ( child.nodeType != 1 ) continue;
  18157. switch ( child.nodeName ) {
  18158. case 'input':
  18159. inputs.push( ( new Input() ).parse( child ) );
  18160. break;
  18161. case 'v':
  18162. v = _ints( child.textContent );
  18163. break;
  18164. case 'vcount':
  18165. vcount = _ints( child.textContent );
  18166. break;
  18167. default:
  18168. break;
  18169. }
  18170. }
  18171. var index = 0;
  18172. for ( var i = 0; i < vcount.length; i ++ ) {
  18173. var numBones = vcount[i];
  18174. var vertex_weights = [];
  18175. for ( var j = 0; j < numBones; j++ ) {
  18176. var influence = {};
  18177. for ( var k = 0; k < inputs.length; k ++ ) {
  18178. var input = inputs[ k ];
  18179. var value = v[ index + input.offset ];
  18180. switch ( input.semantic ) {
  18181. case 'JOINT':
  18182. influence.joint = value;//this.joints[value];
  18183. break;
  18184. case 'WEIGHT':
  18185. influence.weight = sources[ input.source ].data[ value ];
  18186. break;
  18187. default:
  18188. break;
  18189. }
  18190. }
  18191. vertex_weights.push( influence );
  18192. index += inputs.length;
  18193. }
  18194. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  18195. vertex_weights[ j ].index = i;
  18196. }
  18197. this.weights.push( vertex_weights );
  18198. }
  18199. };
  18200. function VisualScene () {
  18201. this.id = "";
  18202. this.name = "";
  18203. this.nodes = [];
  18204. this.scene = new THREE.Object3D();
  18205. };
  18206. VisualScene.prototype.getChildById = function( id, recursive ) {
  18207. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18208. var node = this.nodes[ i ].getChildById( id, recursive );
  18209. if ( node ) {
  18210. return node;
  18211. }
  18212. }
  18213. return null;
  18214. };
  18215. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  18216. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18217. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  18218. if ( node ) {
  18219. return node;
  18220. }
  18221. }
  18222. return null;
  18223. };
  18224. VisualScene.prototype.parse = function( element ) {
  18225. this.id = element.getAttribute( 'id' );
  18226. this.name = element.getAttribute( 'name' );
  18227. this.nodes = [];
  18228. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18229. var child = element.childNodes[ i ];
  18230. if ( child.nodeType != 1 ) continue;
  18231. switch ( child.nodeName ) {
  18232. case 'node':
  18233. this.nodes.push( ( new Node() ).parse( child ) );
  18234. break;
  18235. default:
  18236. break;
  18237. }
  18238. }
  18239. return this;
  18240. };
  18241. function Node() {
  18242. this.id = "";
  18243. this.name = "";
  18244. this.sid = "";
  18245. this.nodes = [];
  18246. this.controllers = [];
  18247. this.transforms = [];
  18248. this.geometries = [];
  18249. this.channels = [];
  18250. this.matrix = new THREE.Matrix4();
  18251. };
  18252. Node.prototype.getChannelForTransform = function( transformSid ) {
  18253. for ( var i = 0; i < this.channels.length; i ++ ) {
  18254. var channel = this.channels[i];
  18255. var parts = channel.target.split('/');
  18256. var id = parts.shift();
  18257. var sid = parts.shift();
  18258. var dotSyntax = (sid.indexOf(".") >= 0);
  18259. var arrSyntax = (sid.indexOf("(") >= 0);
  18260. var arrIndices;
  18261. var member;
  18262. if ( dotSyntax ) {
  18263. parts = sid.split(".");
  18264. sid = parts.shift();
  18265. member = parts.shift();
  18266. } else if ( arrSyntax ) {
  18267. arrIndices = sid.split("(");
  18268. sid = arrIndices.shift();
  18269. for ( var j = 0; j < arrIndices.length; j ++ ) {
  18270. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  18271. }
  18272. }
  18273. if ( sid == transformSid ) {
  18274. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  18275. return channel;
  18276. }
  18277. }
  18278. return null;
  18279. };
  18280. Node.prototype.getChildById = function ( id, recursive ) {
  18281. if ( this.id == id ) {
  18282. return this;
  18283. }
  18284. if ( recursive ) {
  18285. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18286. var n = this.nodes[ i ].getChildById( id, recursive );
  18287. if ( n ) {
  18288. return n;
  18289. }
  18290. }
  18291. }
  18292. return null;
  18293. };
  18294. Node.prototype.getChildBySid = function ( sid, recursive ) {
  18295. if ( this.sid == sid ) {
  18296. return this;
  18297. }
  18298. if ( recursive ) {
  18299. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18300. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  18301. if ( n ) {
  18302. return n;
  18303. }
  18304. }
  18305. }
  18306. return null;
  18307. };
  18308. Node.prototype.getTransformBySid = function ( sid ) {
  18309. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18310. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  18311. }
  18312. return null;
  18313. };
  18314. Node.prototype.parse = function( element ) {
  18315. var url;
  18316. this.id = element.getAttribute('id');
  18317. this.sid = element.getAttribute('sid');
  18318. this.name = element.getAttribute('name');
  18319. this.type = element.getAttribute('type');
  18320. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  18321. this.nodes = [];
  18322. this.transforms = [];
  18323. this.geometries = [];
  18324. this.cameras = [];
  18325. this.controllers = [];
  18326. this.matrix = new THREE.Matrix4();
  18327. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18328. var child = element.childNodes[ i ];
  18329. if ( child.nodeType != 1 ) continue;
  18330. switch ( child.nodeName ) {
  18331. case 'node':
  18332. this.nodes.push( ( new Node() ).parse( child ) );
  18333. break;
  18334. case 'instance_camera':
  18335. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  18336. break;
  18337. case 'instance_controller':
  18338. this.controllers.push( ( new InstanceController() ).parse( child ) );
  18339. break;
  18340. case 'instance_geometry':
  18341. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  18342. break;
  18343. case 'instance_light':
  18344. break;
  18345. case 'instance_node':
  18346. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  18347. var iNode = getLibraryNode( url );
  18348. if ( iNode ) {
  18349. this.nodes.push( ( new Node() ).parse( iNode )) ;
  18350. }
  18351. break;
  18352. case 'rotate':
  18353. case 'translate':
  18354. case 'scale':
  18355. case 'matrix':
  18356. case 'lookat':
  18357. case 'skew':
  18358. this.transforms.push( ( new Transform() ).parse( child ) );
  18359. break;
  18360. case 'extra':
  18361. break;
  18362. default:
  18363. console.log( child.nodeName );
  18364. break;
  18365. }
  18366. }
  18367. this.channels = getChannelsForNode( this );
  18368. bakeAnimations( this );
  18369. this.updateMatrix();
  18370. return this;
  18371. };
  18372. Node.prototype.updateMatrix = function () {
  18373. this.matrix.identity();
  18374. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18375. this.transforms[ i ].apply( this.matrix );
  18376. }
  18377. };
  18378. function Transform () {
  18379. this.sid = "";
  18380. this.type = "";
  18381. this.data = [];
  18382. this.obj = null;
  18383. };
  18384. Transform.prototype.parse = function ( element ) {
  18385. this.sid = element.getAttribute( 'sid' );
  18386. this.type = element.nodeName;
  18387. this.data = _floats( element.textContent );
  18388. this.convert();
  18389. return this;
  18390. };
  18391. Transform.prototype.convert = function () {
  18392. switch ( this.type ) {
  18393. case 'matrix':
  18394. this.obj = getConvertedMat4( this.data );
  18395. break;
  18396. case 'rotate':
  18397. this.angle = this.data[3] * TO_RADIANS;
  18398. case 'translate':
  18399. fixCoords( this.data, -1 );
  18400. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18401. break;
  18402. case 'scale':
  18403. fixCoords( this.data, 1 );
  18404. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18405. break;
  18406. default:
  18407. console.log( 'Can not convert Transform of type ' + this.type );
  18408. break;
  18409. }
  18410. };
  18411. Transform.prototype.apply = function ( matrix ) {
  18412. switch ( this.type ) {
  18413. case 'matrix':
  18414. matrix.multiplySelf( this.obj );
  18415. break;
  18416. case 'translate':
  18417. matrix.translate( this.obj );
  18418. break;
  18419. case 'rotate':
  18420. matrix.rotateByAxis( this.obj, this.angle );
  18421. break;
  18422. case 'scale':
  18423. matrix.scale( this.obj );
  18424. break;
  18425. }
  18426. };
  18427. Transform.prototype.update = function ( data, member ) {
  18428. switch ( this.type ) {
  18429. case 'matrix':
  18430. console.log( 'Currently not handling matrix transform updates' );
  18431. break;
  18432. case 'translate':
  18433. case 'scale':
  18434. switch ( member ) {
  18435. case 'X':
  18436. this.obj.x = data;
  18437. break;
  18438. case 'Y':
  18439. this.obj.y = data;
  18440. break;
  18441. case 'Z':
  18442. this.obj.z = data;
  18443. break;
  18444. default:
  18445. this.obj.x = data[ 0 ];
  18446. this.obj.y = data[ 1 ];
  18447. this.obj.z = data[ 2 ];
  18448. break;
  18449. }
  18450. break;
  18451. case 'rotate':
  18452. switch ( member ) {
  18453. case 'X':
  18454. this.obj.x = data;
  18455. break;
  18456. case 'Y':
  18457. this.obj.y = data;
  18458. break;
  18459. case 'Z':
  18460. this.obj.z = data;
  18461. break;
  18462. case 'ANGLE':
  18463. this.angle = data * TO_RADIANS;
  18464. break;
  18465. default:
  18466. this.obj.x = data[ 0 ];
  18467. this.obj.y = data[ 1 ];
  18468. this.obj.z = data[ 2 ];
  18469. this.angle = data[ 3 ] * TO_RADIANS;
  18470. break;
  18471. }
  18472. break;
  18473. }
  18474. };
  18475. function InstanceController() {
  18476. this.url = "";
  18477. this.skeleton = [];
  18478. this.instance_material = [];
  18479. };
  18480. InstanceController.prototype.parse = function ( element ) {
  18481. this.url = element.getAttribute('url').replace(/^#/, '');
  18482. this.skeleton = [];
  18483. this.instance_material = [];
  18484. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18485. var child = element.childNodes[i];
  18486. if (child.nodeType != 1) continue;
  18487. switch ( child.nodeName ) {
  18488. case 'skeleton':
  18489. this.skeleton.push( child.textContent.replace(/^#/, '') );
  18490. break;
  18491. case 'bind_material':
  18492. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18493. if ( instances ) {
  18494. var instance = instances.iterateNext();
  18495. while ( instance ) {
  18496. this.instance_material.push((new InstanceMaterial()).parse(instance));
  18497. instance = instances.iterateNext();
  18498. }
  18499. }
  18500. break;
  18501. case 'extra':
  18502. break;
  18503. default:
  18504. break;
  18505. }
  18506. }
  18507. return this;
  18508. };
  18509. function InstanceMaterial () {
  18510. this.symbol = "";
  18511. this.target = "";
  18512. };
  18513. InstanceMaterial.prototype.parse = function ( element ) {
  18514. this.symbol = element.getAttribute('symbol');
  18515. this.target = element.getAttribute('target').replace(/^#/, '');
  18516. return this;
  18517. };
  18518. function InstanceGeometry() {
  18519. this.url = "";
  18520. this.instance_material = [];
  18521. };
  18522. InstanceGeometry.prototype.parse = function ( element ) {
  18523. this.url = element.getAttribute('url').replace(/^#/, '');
  18524. this.instance_material = [];
  18525. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18526. var child = element.childNodes[i];
  18527. if ( child.nodeType != 1 ) continue;
  18528. if ( child.nodeName == 'bind_material' ) {
  18529. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18530. if ( instances ) {
  18531. var instance = instances.iterateNext();
  18532. while ( instance ) {
  18533. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  18534. instance = instances.iterateNext();
  18535. }
  18536. }
  18537. break;
  18538. }
  18539. }
  18540. return this;
  18541. };
  18542. function Geometry() {
  18543. this.id = "";
  18544. this.mesh = null;
  18545. };
  18546. Geometry.prototype.parse = function ( element ) {
  18547. this.id = element.getAttribute('id');
  18548. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18549. var child = element.childNodes[i];
  18550. switch ( child.nodeName ) {
  18551. case 'mesh':
  18552. this.mesh = (new Mesh(this)).parse(child);
  18553. break;
  18554. case 'extra':
  18555. // console.log( child );
  18556. break;
  18557. default:
  18558. break;
  18559. }
  18560. }
  18561. return this;
  18562. };
  18563. function Mesh( geometry ) {
  18564. this.geometry = geometry.id;
  18565. this.primitives = [];
  18566. this.vertices = null;
  18567. this.geometry3js = null;
  18568. };
  18569. Mesh.prototype.parse = function( element ) {
  18570. this.primitives = [];
  18571. var i, j;
  18572. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18573. var child = element.childNodes[ i ];
  18574. switch ( child.nodeName ) {
  18575. case 'source':
  18576. _source( child );
  18577. break;
  18578. case 'vertices':
  18579. this.vertices = ( new Vertices() ).parse( child );
  18580. break;
  18581. case 'triangles':
  18582. this.primitives.push( ( new Triangles().parse( child ) ) );
  18583. break;
  18584. case 'polygons':
  18585. this.primitives.push( ( new Polygons().parse( child ) ) );
  18586. break;
  18587. case 'polylist':
  18588. this.primitives.push( ( new Polylist().parse( child ) ) );
  18589. break;
  18590. default:
  18591. break;
  18592. }
  18593. }
  18594. this.geometry3js = new THREE.Geometry();
  18595. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  18596. for ( i = 0; i < vertexData.length; i += 3 ) {
  18597. var v = new THREE.Vertex( getConvertedVec3( vertexData, i ) );
  18598. this.geometry3js.vertices.push( v );
  18599. }
  18600. for ( i = 0; i < this.primitives.length; i ++ ) {
  18601. var primitive = this.primitives[ i ];
  18602. primitive.setVertices( this.vertices );
  18603. this.handlePrimitive( primitive, this.geometry3js );
  18604. }
  18605. this.geometry3js.computeCentroids();
  18606. this.geometry3js.computeFaceNormals();
  18607. if ( this.geometry3js.calcNormals ) {
  18608. this.geometry3js.computeVertexNormals();
  18609. delete this.geometry3js.calcNormals;
  18610. }
  18611. this.geometry3js.computeBoundingBox();
  18612. return this;
  18613. };
  18614. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  18615. var j, k, pList = primitive.p, inputs = primitive.inputs;
  18616. var input, index, idx32;
  18617. var source, numParams;
  18618. var vcIndex = 0, vcount = 3, maxOffset = 0;
  18619. var texture_sets = [];
  18620. for ( j = 0; j < inputs.length; j ++ ) {
  18621. input = inputs[ j ];
  18622. var offset = input.offset + 1;
  18623. maxOffset = (maxOffset < offset)? offset : maxOffset;
  18624. switch ( input.semantic ) {
  18625. case 'TEXCOORD':
  18626. texture_sets.push( input.set );
  18627. break;
  18628. }
  18629. }
  18630. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  18631. var p = pList[pCount], i = 0;
  18632. while ( i < p.length ) {
  18633. var vs = [];
  18634. var ns = [];
  18635. var ts = {};
  18636. var cs = [];
  18637. if ( primitive.vcount ) {
  18638. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  18639. } else {
  18640. vcount = p.length / maxOffset;
  18641. }
  18642. for ( j = 0; j < vcount; j ++ ) {
  18643. for ( k = 0; k < inputs.length; k ++ ) {
  18644. input = inputs[ k ];
  18645. source = sources[ input.source ];
  18646. index = p[ i + ( j * maxOffset ) + input.offset ];
  18647. numParams = source.accessor.params.length;
  18648. idx32 = index * numParams;
  18649. switch ( input.semantic ) {
  18650. case 'VERTEX':
  18651. vs.push( index );
  18652. break;
  18653. case 'NORMAL':
  18654. ns.push( getConvertedVec3( source.data, idx32 ) );
  18655. break;
  18656. case 'TEXCOORD':
  18657. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  18658. // invert the V
  18659. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  18660. break;
  18661. case 'COLOR':
  18662. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  18663. break;
  18664. default:
  18665. break;
  18666. }
  18667. }
  18668. }
  18669. var face = null, faces = [], uv, uvArr;
  18670. if ( ns.length == 0 ) {
  18671. // check the vertices source
  18672. input = this.vertices.input.NORMAL;
  18673. if ( input ) {
  18674. source = sources[ input.source ];
  18675. numParams = source.accessor.params.length;
  18676. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  18677. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  18678. }
  18679. }
  18680. else {
  18681. geom.calcNormals = true;
  18682. }
  18683. }
  18684. if ( vcount === 3 ) {
  18685. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  18686. } else if ( vcount === 4 ) {
  18687. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  18688. } else if ( vcount > 4 && options.subdivideFaces ) {
  18689. var clr = cs.length ? cs : new THREE.Color(),
  18690. vec1, vec2, vec3, v1, v2, norm;
  18691. // subdivide into multiple Face3s
  18692. for ( k = 1; k < vcount-1; ) {
  18693. // FIXME: normals don't seem to be quite right
  18694. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  18695. }
  18696. }
  18697. if ( faces.length ) {
  18698. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  18699. face = faces[ndx];
  18700. face.daeMaterial = primitive.material;
  18701. geom.faces.push( face );
  18702. for ( k = 0; k < texture_sets.length; k++ ) {
  18703. uv = ts[ texture_sets[k] ];
  18704. if ( vcount > 4 ) {
  18705. // Grab the right UVs for the vertices in this face
  18706. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  18707. } else if ( vcount === 4 ) {
  18708. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  18709. } else {
  18710. uvArr = [ uv[0], uv[1], uv[2] ];
  18711. }
  18712. if ( !geom.faceVertexUvs[k] ) {
  18713. geom.faceVertexUvs[k] = [];
  18714. }
  18715. geom.faceVertexUvs[k].push( uvArr );
  18716. }
  18717. }
  18718. } else {
  18719. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  18720. }
  18721. i += maxOffset * vcount;
  18722. }
  18723. }
  18724. };
  18725. function Polygons () {
  18726. this.material = "";
  18727. this.count = 0;
  18728. this.inputs = [];
  18729. this.vcount = null;
  18730. this.p = [];
  18731. this.geometry = new THREE.Geometry();
  18732. };
  18733. Polygons.prototype.setVertices = function ( vertices ) {
  18734. for ( var i = 0; i < this.inputs.length; i ++ ) {
  18735. if ( this.inputs[ i ].source == vertices.id ) {
  18736. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  18737. }
  18738. }
  18739. };
  18740. Polygons.prototype.parse = function ( element ) {
  18741. this.material = element.getAttribute( 'material' );
  18742. this.count = _attr_as_int( element, 'count', 0 );
  18743. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18744. var child = element.childNodes[ i ];
  18745. switch ( child.nodeName ) {
  18746. case 'input':
  18747. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  18748. break;
  18749. case 'vcount':
  18750. this.vcount = _ints( child.textContent );
  18751. break;
  18752. case 'p':
  18753. this.p.push( _ints( child.textContent ) );
  18754. break;
  18755. case 'ph':
  18756. console.warn( 'polygon holes not yet supported!' );
  18757. break;
  18758. default:
  18759. break;
  18760. }
  18761. }
  18762. return this;
  18763. };
  18764. function Polylist () {
  18765. Polygons.call( this );
  18766. this.vcount = [];
  18767. };
  18768. Polylist.prototype = new Polygons();
  18769. Polylist.prototype.constructor = Polylist;
  18770. function Triangles () {
  18771. Polygons.call( this );
  18772. this.vcount = 3;
  18773. };
  18774. Triangles.prototype = new Polygons();
  18775. Triangles.prototype.constructor = Triangles;
  18776. function Accessor() {
  18777. this.source = "";
  18778. this.count = 0;
  18779. this.stride = 0;
  18780. this.params = [];
  18781. };
  18782. Accessor.prototype.parse = function ( element ) {
  18783. this.params = [];
  18784. this.source = element.getAttribute( 'source' );
  18785. this.count = _attr_as_int( element, 'count', 0 );
  18786. this.stride = _attr_as_int( element, 'stride', 0 );
  18787. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18788. var child = element.childNodes[ i ];
  18789. if ( child.nodeName == 'param' ) {
  18790. var param = {};
  18791. param[ 'name' ] = child.getAttribute( 'name' );
  18792. param[ 'type' ] = child.getAttribute( 'type' );
  18793. this.params.push( param );
  18794. }
  18795. }
  18796. return this;
  18797. };
  18798. function Vertices() {
  18799. this.input = {};
  18800. };
  18801. Vertices.prototype.parse = function ( element ) {
  18802. this.id = element.getAttribute('id');
  18803. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18804. if ( element.childNodes[i].nodeName == 'input' ) {
  18805. var input = ( new Input() ).parse( element.childNodes[ i ] );
  18806. this.input[ input.semantic ] = input;
  18807. }
  18808. }
  18809. return this;
  18810. };
  18811. function Input () {
  18812. this.semantic = "";
  18813. this.offset = 0;
  18814. this.source = "";
  18815. this.set = 0;
  18816. };
  18817. Input.prototype.parse = function ( element ) {
  18818. this.semantic = element.getAttribute('semantic');
  18819. this.source = element.getAttribute('source').replace(/^#/, '');
  18820. this.set = _attr_as_int(element, 'set', -1);
  18821. this.offset = _attr_as_int(element, 'offset', 0);
  18822. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  18823. this.set = 0;
  18824. }
  18825. return this;
  18826. };
  18827. function Source ( id ) {
  18828. this.id = id;
  18829. this.type = null;
  18830. };
  18831. Source.prototype.parse = function ( element ) {
  18832. this.id = element.getAttribute( 'id' );
  18833. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18834. var child = element.childNodes[i];
  18835. switch ( child.nodeName ) {
  18836. case 'bool_array':
  18837. this.data = _bools( child.textContent );
  18838. this.type = child.nodeName;
  18839. break;
  18840. case 'float_array':
  18841. this.data = _floats( child.textContent );
  18842. this.type = child.nodeName;
  18843. break;
  18844. case 'int_array':
  18845. this.data = _ints( child.textContent );
  18846. this.type = child.nodeName;
  18847. break;
  18848. case 'IDREF_array':
  18849. case 'Name_array':
  18850. this.data = _strings( child.textContent );
  18851. this.type = child.nodeName;
  18852. break;
  18853. case 'technique_common':
  18854. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  18855. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  18856. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  18857. break;
  18858. }
  18859. }
  18860. break;
  18861. default:
  18862. // console.log(child.nodeName);
  18863. break;
  18864. }
  18865. }
  18866. return this;
  18867. };
  18868. Source.prototype.read = function () {
  18869. var result = [];
  18870. //for (var i = 0; i < this.accessor.params.length; i++) {
  18871. var param = this.accessor.params[ 0 ];
  18872. //console.log(param.name + " " + param.type);
  18873. switch ( param.type ) {
  18874. case 'IDREF':
  18875. case 'Name': case 'name':
  18876. case 'float':
  18877. return this.data;
  18878. case 'float4x4':
  18879. for ( var j = 0; j < this.data.length; j += 16 ) {
  18880. var s = this.data.slice( j, j + 16 );
  18881. var m = getConvertedMat4( s );
  18882. result.push( m );
  18883. }
  18884. break;
  18885. default:
  18886. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  18887. break;
  18888. }
  18889. //}
  18890. return result;
  18891. };
  18892. function Material () {
  18893. this.id = "";
  18894. this.name = "";
  18895. this.instance_effect = null;
  18896. };
  18897. Material.prototype.parse = function ( element ) {
  18898. this.id = element.getAttribute( 'id' );
  18899. this.name = element.getAttribute( 'name' );
  18900. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18901. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  18902. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  18903. break;
  18904. }
  18905. }
  18906. return this;
  18907. };
  18908. function ColorOrTexture () {
  18909. this.color = new THREE.Color( 0 );
  18910. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  18911. this.color.a = 1.0;
  18912. this.texture = null;
  18913. this.texcoord = null;
  18914. this.texOpts = null;
  18915. };
  18916. ColorOrTexture.prototype.isColor = function () {
  18917. return ( this.texture == null );
  18918. };
  18919. ColorOrTexture.prototype.isTexture = function () {
  18920. return ( this.texture != null );
  18921. };
  18922. ColorOrTexture.prototype.parse = function ( element ) {
  18923. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18924. var child = element.childNodes[ i ];
  18925. if ( child.nodeType != 1 ) continue;
  18926. switch ( child.nodeName ) {
  18927. case 'color':
  18928. var rgba = _floats( child.textContent );
  18929. this.color = new THREE.Color(0);
  18930. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  18931. this.color.a = rgba[3];
  18932. break;
  18933. case 'texture':
  18934. this.texture = child.getAttribute('texture');
  18935. this.texcoord = child.getAttribute('texcoord');
  18936. // Defaults from:
  18937. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  18938. this.texOpts = {
  18939. offsetU: 0,
  18940. offsetV: 0,
  18941. repeatU: 1,
  18942. repeatV: 1,
  18943. wrapU: 1,
  18944. wrapV: 1,
  18945. };
  18946. this.parseTexture( child );
  18947. break;
  18948. default:
  18949. break;
  18950. }
  18951. }
  18952. return this;
  18953. };
  18954. ColorOrTexture.prototype.parseTexture = function ( element ) {
  18955. if ( ! element.childNodes ) return this;
  18956. // This should be supported by Maya, 3dsMax, and MotionBuilder
  18957. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  18958. element = element.childNodes[1];
  18959. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  18960. element = element.childNodes[1];
  18961. }
  18962. }
  18963. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18964. var child = element.childNodes[ i ];
  18965. switch ( child.nodeName ) {
  18966. case 'offsetU':
  18967. case 'offsetV':
  18968. case 'repeatU':
  18969. case 'repeatV':
  18970. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  18971. break;
  18972. case 'wrapU':
  18973. case 'wrapV':
  18974. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  18975. break;
  18976. default:
  18977. this.texOpts[ child.nodeName ] = child.textContent;
  18978. break;
  18979. }
  18980. }
  18981. return this;
  18982. };
  18983. function Shader ( type, effect ) {
  18984. this.type = type;
  18985. this.effect = effect;
  18986. this.material = null;
  18987. };
  18988. Shader.prototype.parse = function ( element ) {
  18989. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18990. var child = element.childNodes[ i ];
  18991. if ( child.nodeType != 1 ) continue;
  18992. switch ( child.nodeName ) {
  18993. case 'ambient':
  18994. case 'emission':
  18995. case 'diffuse':
  18996. case 'specular':
  18997. case 'transparent':
  18998. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  18999. break;
  19000. case 'shininess':
  19001. case 'reflectivity':
  19002. case 'transparency':
  19003. var f = evaluateXPath( child, './/dae:float' );
  19004. if ( f.length > 0 )
  19005. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  19006. break;
  19007. default:
  19008. break;
  19009. }
  19010. }
  19011. this.create();
  19012. return this;
  19013. };
  19014. Shader.prototype.create = function() {
  19015. var props = {};
  19016. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  19017. for ( var prop in this ) {
  19018. switch ( prop ) {
  19019. case 'ambient':
  19020. case 'emission':
  19021. case 'diffuse':
  19022. case 'specular':
  19023. var cot = this[prop];
  19024. if ( cot instanceof ColorOrTexture ) {
  19025. if ( cot.isTexture() ) {
  19026. if ( this.effect.sampler && this.effect.surface ) {
  19027. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  19028. var image = images[this.effect.surface.init_from];
  19029. if ( image ) {
  19030. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  19031. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19032. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19033. texture.offset.x = cot.texOpts.offsetU;
  19034. texture.offset.y = cot.texOpts.offsetV;
  19035. texture.repeat.x = cot.texOpts.repeatU;
  19036. texture.repeat.y = cot.texOpts.repeatV;
  19037. props['map'] = texture;
  19038. }
  19039. }
  19040. }
  19041. } else if ( prop == 'diffuse' || !transparent ) {
  19042. props[ prop ] = cot.color.getHex();
  19043. }
  19044. }
  19045. break;
  19046. case 'shininess':
  19047. case 'reflectivity':
  19048. props[ prop ] = this[ prop ];
  19049. break;
  19050. case 'transparency':
  19051. if ( transparent ) {
  19052. props[ 'transparent' ] = true;
  19053. props[ 'opacity' ] = this[ prop ];
  19054. transparent = true;
  19055. }
  19056. break;
  19057. default:
  19058. break;
  19059. }
  19060. }
  19061. props[ 'shading' ] = preferredShading;
  19062. switch ( this.type ) {
  19063. case 'constant':
  19064. props.color = props.emission;
  19065. this.material = new THREE.MeshBasicMaterial( props );
  19066. break;
  19067. case 'phong':
  19068. case 'blinn':
  19069. props.color = props.diffuse;
  19070. this.material = new THREE.MeshPhongMaterial( props );
  19071. break;
  19072. case 'lambert':
  19073. default:
  19074. props.color = props.diffuse;
  19075. this.material = new THREE.MeshLambertMaterial( props );
  19076. break;
  19077. }
  19078. return this.material;
  19079. };
  19080. function Surface ( effect ) {
  19081. this.effect = effect;
  19082. this.init_from = null;
  19083. this.format = null;
  19084. };
  19085. Surface.prototype.parse = function ( element ) {
  19086. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19087. var child = element.childNodes[ i ];
  19088. if ( child.nodeType != 1 ) continue;
  19089. switch ( child.nodeName ) {
  19090. case 'init_from':
  19091. this.init_from = child.textContent;
  19092. break;
  19093. case 'format':
  19094. this.format = child.textContent;
  19095. break;
  19096. default:
  19097. console.log( "unhandled Surface prop: " + child.nodeName );
  19098. break;
  19099. }
  19100. }
  19101. return this;
  19102. };
  19103. function Sampler2D ( effect ) {
  19104. this.effect = effect;
  19105. this.source = null;
  19106. this.wrap_s = null;
  19107. this.wrap_t = null;
  19108. this.minfilter = null;
  19109. this.magfilter = null;
  19110. this.mipfilter = null;
  19111. };
  19112. Sampler2D.prototype.parse = function ( element ) {
  19113. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19114. var child = element.childNodes[ i ];
  19115. if ( child.nodeType != 1 ) continue;
  19116. switch ( child.nodeName ) {
  19117. case 'source':
  19118. this.source = child.textContent;
  19119. break;
  19120. case 'minfilter':
  19121. this.minfilter = child.textContent;
  19122. break;
  19123. case 'magfilter':
  19124. this.magfilter = child.textContent;
  19125. break;
  19126. case 'mipfilter':
  19127. this.mipfilter = child.textContent;
  19128. break;
  19129. case 'wrap_s':
  19130. this.wrap_s = child.textContent;
  19131. break;
  19132. case 'wrap_t':
  19133. this.wrap_t = child.textContent;
  19134. break;
  19135. default:
  19136. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  19137. break;
  19138. }
  19139. }
  19140. return this;
  19141. };
  19142. function Effect () {
  19143. this.id = "";
  19144. this.name = "";
  19145. this.shader = null;
  19146. this.surface = null;
  19147. this.sampler = null;
  19148. };
  19149. Effect.prototype.create = function () {
  19150. if ( this.shader == null ) {
  19151. return null;
  19152. }
  19153. };
  19154. Effect.prototype.parse = function ( element ) {
  19155. this.id = element.getAttribute( 'id' );
  19156. this.name = element.getAttribute( 'name' );
  19157. this.shader = null;
  19158. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19159. var child = element.childNodes[ i ];
  19160. if ( child.nodeType != 1 ) continue;
  19161. switch ( child.nodeName ) {
  19162. case 'profile_COMMON':
  19163. this.parseTechnique( this.parseProfileCOMMON( child ) );
  19164. break;
  19165. default:
  19166. break;
  19167. }
  19168. }
  19169. return this;
  19170. };
  19171. Effect.prototype.parseNewparam = function ( element ) {
  19172. var sid = element.getAttribute( 'sid' );
  19173. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19174. var child = element.childNodes[ i ];
  19175. if ( child.nodeType != 1 ) continue;
  19176. switch ( child.nodeName ) {
  19177. case 'surface':
  19178. this.surface = ( new Surface( this ) ).parse( child );
  19179. this.surface.sid = sid;
  19180. break;
  19181. case 'sampler2D':
  19182. this.sampler = ( new Sampler2D( this ) ).parse( child );
  19183. this.sampler.sid = sid;
  19184. break;
  19185. case 'extra':
  19186. break;
  19187. default:
  19188. console.log( child.nodeName );
  19189. break;
  19190. }
  19191. }
  19192. };
  19193. Effect.prototype.parseProfileCOMMON = function ( element ) {
  19194. var technique;
  19195. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19196. var child = element.childNodes[ i ];
  19197. if ( child.nodeType != 1 ) continue;
  19198. switch ( child.nodeName ) {
  19199. case 'profile_COMMON':
  19200. this.parseProfileCOMMON( child );
  19201. break;
  19202. case 'technique':
  19203. technique = child;
  19204. break;
  19205. case 'newparam':
  19206. this.parseNewparam( child );
  19207. break;
  19208. case 'image':
  19209. var _image = ( new _Image() ).parse( child );
  19210. images[ _image.id ] = _image;
  19211. break;
  19212. case 'extra':
  19213. break;
  19214. default:
  19215. console.log( child.nodeName );
  19216. break;
  19217. }
  19218. }
  19219. return technique;
  19220. };
  19221. Effect.prototype.parseTechnique= function ( element ) {
  19222. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19223. var child = element.childNodes[i];
  19224. if ( child.nodeType != 1 ) continue;
  19225. switch ( child.nodeName ) {
  19226. case 'constant':
  19227. case 'lambert':
  19228. case 'blinn':
  19229. case 'phong':
  19230. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  19231. break;
  19232. default:
  19233. break;
  19234. }
  19235. }
  19236. };
  19237. function InstanceEffect () {
  19238. this.url = "";
  19239. };
  19240. InstanceEffect.prototype.parse = function ( element ) {
  19241. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  19242. return this;
  19243. };
  19244. function Animation() {
  19245. this.id = "";
  19246. this.name = "";
  19247. this.source = {};
  19248. this.sampler = [];
  19249. this.channel = [];
  19250. };
  19251. Animation.prototype.parse = function ( element ) {
  19252. this.id = element.getAttribute( 'id' );
  19253. this.name = element.getAttribute( 'name' );
  19254. this.source = {};
  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 'source':
  19260. var src = ( new Source() ).parse( child );
  19261. this.source[ src.id ] = src;
  19262. break;
  19263. case 'sampler':
  19264. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  19265. break;
  19266. case 'channel':
  19267. this.channel.push( ( new Channel( this ) ).parse( child ) );
  19268. break;
  19269. default:
  19270. break;
  19271. }
  19272. }
  19273. return this;
  19274. };
  19275. function Channel( animation ) {
  19276. this.animation = animation;
  19277. this.source = "";
  19278. this.target = "";
  19279. this.fullSid = null;
  19280. this.sid = null;
  19281. this.dotSyntax = null;
  19282. this.arrSyntax = null;
  19283. this.arrIndices = null;
  19284. this.member = null;
  19285. };
  19286. Channel.prototype.parse = function ( element ) {
  19287. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  19288. this.target = element.getAttribute( 'target' );
  19289. var parts = this.target.split( '/' );
  19290. var id = parts.shift();
  19291. var sid = parts.shift();
  19292. var dotSyntax = ( sid.indexOf(".") >= 0 );
  19293. var arrSyntax = ( sid.indexOf("(") >= 0 );
  19294. if ( dotSyntax ) {
  19295. parts = sid.split(".");
  19296. this.sid = parts.shift();
  19297. this.member = parts.shift();
  19298. } else if ( arrSyntax ) {
  19299. var arrIndices = sid.split("(");
  19300. this.sid = arrIndices.shift();
  19301. for (var j = 0; j < arrIndices.length; j ++ ) {
  19302. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  19303. }
  19304. this.arrIndices = arrIndices;
  19305. } else {
  19306. this.sid = sid;
  19307. }
  19308. this.fullSid = sid;
  19309. this.dotSyntax = dotSyntax;
  19310. this.arrSyntax = arrSyntax;
  19311. return this;
  19312. };
  19313. function Sampler ( animation ) {
  19314. this.id = "";
  19315. this.animation = animation;
  19316. this.inputs = [];
  19317. this.input = null;
  19318. this.output = null;
  19319. this.strideOut = null;
  19320. this.interpolation = null;
  19321. this.startTime = null;
  19322. this.endTime = null;
  19323. this.duration = 0;
  19324. };
  19325. Sampler.prototype.parse = function ( element ) {
  19326. this.id = element.getAttribute( 'id' );
  19327. this.inputs = [];
  19328. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19329. var child = element.childNodes[ i ];
  19330. if ( child.nodeType != 1 ) continue;
  19331. switch ( child.nodeName ) {
  19332. case 'input':
  19333. this.inputs.push( (new Input()).parse( child ) );
  19334. break;
  19335. default:
  19336. break;
  19337. }
  19338. }
  19339. return this;
  19340. };
  19341. Sampler.prototype.create = function () {
  19342. for ( var i = 0; i < this.inputs.length; i ++ ) {
  19343. var input = this.inputs[ i ];
  19344. var source = this.animation.source[ input.source ];
  19345. switch ( input.semantic ) {
  19346. case 'INPUT':
  19347. this.input = source.read();
  19348. break;
  19349. case 'OUTPUT':
  19350. this.output = source.read();
  19351. this.strideOut = source.accessor.stride;
  19352. break;
  19353. case 'INTERPOLATION':
  19354. this.interpolation = source.read();
  19355. break;
  19356. case 'IN_TANGENT':
  19357. break;
  19358. case 'OUT_TANGENT':
  19359. break;
  19360. default:
  19361. console.log(input.semantic);
  19362. break;
  19363. }
  19364. }
  19365. this.startTime = 0;
  19366. this.endTime = 0;
  19367. this.duration = 0;
  19368. if ( this.input.length ) {
  19369. this.startTime = 100000000;
  19370. this.endTime = -100000000;
  19371. for ( var i = 0; i < this.input.length; i ++ ) {
  19372. this.startTime = Math.min( this.startTime, this.input[ i ] );
  19373. this.endTime = Math.max( this.endTime, this.input[ i ] );
  19374. }
  19375. this.duration = this.endTime - this.startTime;
  19376. }
  19377. };
  19378. Sampler.prototype.getData = function ( type, ndx ) {
  19379. var data;
  19380. if ( this.strideOut > 1 ) {
  19381. data = [];
  19382. ndx *= this.strideOut;
  19383. for ( var i = 0; i < this.strideOut; ++i ) {
  19384. data[ i ] = this.output[ ndx + i ];
  19385. }
  19386. if ( this.strideOut === 3 ) {
  19387. switch ( type ) {
  19388. case 'rotate':
  19389. case 'translate':
  19390. fixCoords( data, -1 );
  19391. break;
  19392. case 'scale':
  19393. fixCoords( data, 1 );
  19394. break;
  19395. }
  19396. }
  19397. } else {
  19398. data = this.output[ ndx ];
  19399. }
  19400. return data;
  19401. };
  19402. function Key ( time ) {
  19403. this.targets = [];
  19404. this.time = time;
  19405. };
  19406. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  19407. this.targets.push( {
  19408. sid: fullSid,
  19409. member: member,
  19410. transform: transform,
  19411. data: data
  19412. } );
  19413. };
  19414. Key.prototype.apply = function ( opt_sid ) {
  19415. for ( var i = 0; i < this.targets.length; ++i ) {
  19416. var target = this.targets[ i ];
  19417. if ( !opt_sid || target.sid === opt_sid ) {
  19418. target.transform.update( target.data, target.member );
  19419. }
  19420. }
  19421. };
  19422. Key.prototype.getTarget = function ( fullSid ) {
  19423. for ( var i = 0; i < this.targets.length; ++i ) {
  19424. if ( this.targets[ i ].sid === fullSid ) {
  19425. return this.targets[ i ];
  19426. }
  19427. }
  19428. return null;
  19429. };
  19430. Key.prototype.hasTarget = function ( fullSid ) {
  19431. for ( var i = 0; i < this.targets.length; ++i ) {
  19432. if ( this.targets[ i ].sid === fullSid ) {
  19433. return true;
  19434. }
  19435. }
  19436. return false;
  19437. };
  19438. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  19439. Key.prototype.interpolate = function ( nextKey, time ) {
  19440. for ( var i = 0; i < this.targets.length; ++i ) {
  19441. var target = this.targets[ i ],
  19442. nextTarget = nextKey.getTarget( target.sid ),
  19443. data;
  19444. if ( nextTarget ) {
  19445. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  19446. nextData = nextTarget.data,
  19447. prevData = target.data;
  19448. // check scale error
  19449. if ( scale < 0 || scale > 1 ) {
  19450. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  19451. scale = scale < 0 ? 0 : 1;
  19452. }
  19453. if ( prevData.length ) {
  19454. data = [];
  19455. for ( var j = 0; j < prevData.length; ++j ) {
  19456. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  19457. }
  19458. } else {
  19459. data = prevData + ( nextData - prevData ) * scale;
  19460. }
  19461. } else {
  19462. data = target.data;
  19463. }
  19464. target.transform.update( data, target.member );
  19465. }
  19466. };
  19467. function Camera() {
  19468. this.id = "";
  19469. this.name = "";
  19470. this.technique = "";
  19471. };
  19472. Camera.prototype.parse = function ( element ) {
  19473. this.id = element.getAttribute( 'id' );
  19474. this.name = element.getAttribute( 'name' );
  19475. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19476. var child = element.childNodes[ i ];
  19477. if ( child.nodeType != 1 ) continue;
  19478. switch ( child.nodeName ) {
  19479. case 'optics':
  19480. this.parseOptics( child );
  19481. break;
  19482. default:
  19483. break;
  19484. }
  19485. }
  19486. return this;
  19487. };
  19488. Camera.prototype.parseOptics = function ( element ) {
  19489. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19490. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  19491. var technique = element.childNodes[ i ];
  19492. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  19493. this.technique = technique.childNodes[ j ].nodeName;
  19494. if ( this.technique == 'perspective' ) {
  19495. var perspective = technique.childNodes[ j ];
  19496. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  19497. var param = perspective.childNodes[ k ];
  19498. switch ( param.nodeName ) {
  19499. case 'yfov':
  19500. this.yfov = param.textContent;
  19501. break;
  19502. case 'xfov':
  19503. this.xfov = param.textContent;
  19504. break;
  19505. case 'znear':
  19506. this.znear = param.textContent;
  19507. break;
  19508. case 'zfar':
  19509. this.zfar = param.textContent;
  19510. break;
  19511. case 'aspect_ratio':
  19512. this.aspect_ratio = param.textContent;
  19513. break;
  19514. }
  19515. }
  19516. } else if ( this.technique == 'orthographic' ) {
  19517. var orthographic = technique.childNodes[ j ];
  19518. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  19519. var param = orthographic.childNodes[ k ];
  19520. switch ( param.nodeName ) {
  19521. case 'xmag':
  19522. this.xmag = param.textContent;
  19523. break;
  19524. case 'ymag':
  19525. this.ymag = param.textContent;
  19526. break;
  19527. case 'znear':
  19528. this.znear = param.textContent;
  19529. break;
  19530. case 'zfar':
  19531. this.zfar = param.textContent;
  19532. break;
  19533. case 'aspect_ratio':
  19534. this.aspect_ratio = param.textContent;
  19535. break;
  19536. }
  19537. }
  19538. }
  19539. }
  19540. }
  19541. }
  19542. return this;
  19543. };
  19544. function InstanceCamera() {
  19545. this.url = "";
  19546. };
  19547. InstanceCamera.prototype.parse = function ( element ) {
  19548. this.url = element.getAttribute('url').replace(/^#/, '');
  19549. return this;
  19550. };
  19551. function _source( element ) {
  19552. var id = element.getAttribute( 'id' );
  19553. if ( sources[ id ] != undefined ) {
  19554. return sources[ id ];
  19555. }
  19556. sources[ id ] = ( new Source(id )).parse( element );
  19557. return sources[ id ];
  19558. };
  19559. function _nsResolver( nsPrefix ) {
  19560. if ( nsPrefix == "dae" ) {
  19561. return "http://www.collada.org/2005/11/COLLADASchema";
  19562. }
  19563. return null;
  19564. };
  19565. function _bools( str ) {
  19566. var raw = _strings( str );
  19567. var data = [];
  19568. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19569. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  19570. }
  19571. return data;
  19572. };
  19573. function _floats( str ) {
  19574. var raw = _strings(str);
  19575. var data = [];
  19576. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19577. data.push( parseFloat( raw[ i ] ) );
  19578. }
  19579. return data;
  19580. };
  19581. function _ints( str ) {
  19582. var raw = _strings( str );
  19583. var data = [];
  19584. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19585. data.push( parseInt( raw[ i ], 10 ) );
  19586. }
  19587. return data;
  19588. };
  19589. function _strings( str ) {
  19590. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  19591. };
  19592. function _trimString( str ) {
  19593. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  19594. };
  19595. function _attr_as_float( element, name, defaultValue ) {
  19596. if ( element.hasAttribute( name ) ) {
  19597. return parseFloat( element.getAttribute( name ) );
  19598. } else {
  19599. return defaultValue;
  19600. }
  19601. };
  19602. function _attr_as_int( element, name, defaultValue ) {
  19603. if ( element.hasAttribute( name ) ) {
  19604. return parseInt( element.getAttribute( name ), 10) ;
  19605. } else {
  19606. return defaultValue;
  19607. }
  19608. };
  19609. function _attr_as_string( element, name, defaultValue ) {
  19610. if ( element.hasAttribute( name ) ) {
  19611. return element.getAttribute( name );
  19612. } else {
  19613. return defaultValue;
  19614. }
  19615. };
  19616. function _format_float( f, num ) {
  19617. if ( f === undefined ) {
  19618. var s = '0.';
  19619. while ( s.length < num + 2 ) {
  19620. s += '0';
  19621. }
  19622. return s;
  19623. }
  19624. num = num || 2;
  19625. var parts = f.toString().split( '.' );
  19626. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  19627. while( parts[ 1 ].length < num ) {
  19628. parts[ 1 ] += '0';
  19629. }
  19630. return parts.join( '.' );
  19631. };
  19632. function evaluateXPath( node, query ) {
  19633. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  19634. var inst = instances.iterateNext();
  19635. var result = [];
  19636. while ( inst ) {
  19637. result.push( inst );
  19638. inst = instances.iterateNext();
  19639. }
  19640. return result;
  19641. };
  19642. // Up axis conversion
  19643. function setUpConversion() {
  19644. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19645. upConversion = null;
  19646. } else {
  19647. switch ( colladaUp ) {
  19648. case 'X':
  19649. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  19650. break;
  19651. case 'Y':
  19652. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  19653. break;
  19654. case 'Z':
  19655. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  19656. break;
  19657. }
  19658. }
  19659. };
  19660. function fixCoords( data, sign ) {
  19661. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19662. return;
  19663. }
  19664. switch ( upConversion ) {
  19665. case 'XtoY':
  19666. var tmp = data[ 0 ];
  19667. data[ 0 ] = sign * data[ 1 ];
  19668. data[ 1 ] = tmp;
  19669. break;
  19670. case 'XtoZ':
  19671. var tmp = data[ 2 ];
  19672. data[ 2 ] = data[ 1 ];
  19673. data[ 1 ] = data[ 0 ];
  19674. data[ 0 ] = tmp;
  19675. break;
  19676. case 'YtoX':
  19677. var tmp = data[ 0 ];
  19678. data[ 0 ] = data[ 1 ];
  19679. data[ 1 ] = sign * tmp;
  19680. break;
  19681. case 'YtoZ':
  19682. var tmp = data[ 1 ];
  19683. data[ 1 ] = sign * data[ 2 ];
  19684. data[ 2 ] = tmp;
  19685. break;
  19686. case 'ZtoX':
  19687. var tmp = data[ 0 ];
  19688. data[ 0 ] = data[ 1 ];
  19689. data[ 1 ] = data[ 2 ];
  19690. data[ 2 ] = tmp;
  19691. break;
  19692. case 'ZtoY':
  19693. var tmp = data[ 1 ];
  19694. data[ 1 ] = data[ 2 ];
  19695. data[ 2 ] = sign * tmp;
  19696. break;
  19697. }
  19698. };
  19699. function getConvertedVec3( data, offset ) {
  19700. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  19701. fixCoords( arr, -1 );
  19702. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  19703. };
  19704. function getConvertedMat4( data ) {
  19705. if ( options.convertUpAxis ) {
  19706. // First fix rotation and scale
  19707. // Columns first
  19708. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  19709. fixCoords( arr, -1 );
  19710. data[ 0 ] = arr[ 0 ];
  19711. data[ 4 ] = arr[ 1 ];
  19712. data[ 8 ] = arr[ 2 ];
  19713. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  19714. fixCoords( arr, -1 );
  19715. data[ 1 ] = arr[ 0 ];
  19716. data[ 5 ] = arr[ 1 ];
  19717. data[ 9 ] = arr[ 2 ];
  19718. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  19719. fixCoords( arr, -1 );
  19720. data[ 2 ] = arr[ 0 ];
  19721. data[ 6 ] = arr[ 1 ];
  19722. data[ 10 ] = arr[ 2 ];
  19723. // Rows second
  19724. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  19725. fixCoords( arr, -1 );
  19726. data[ 0 ] = arr[ 0 ];
  19727. data[ 1 ] = arr[ 1 ];
  19728. data[ 2 ] = arr[ 2 ];
  19729. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  19730. fixCoords( arr, -1 );
  19731. data[ 4 ] = arr[ 0 ];
  19732. data[ 5 ] = arr[ 1 ];
  19733. data[ 6 ] = arr[ 2 ];
  19734. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  19735. fixCoords( arr, -1 );
  19736. data[ 8 ] = arr[ 0 ];
  19737. data[ 9 ] = arr[ 1 ];
  19738. data[ 10 ] = arr[ 2 ];
  19739. // Now fix translation
  19740. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  19741. fixCoords( arr, -1 );
  19742. data[ 3 ] = arr[ 0 ];
  19743. data[ 7 ] = arr[ 1 ];
  19744. data[ 11 ] = arr[ 2 ];
  19745. }
  19746. return new THREE.Matrix4(
  19747. data[0], data[1], data[2], data[3],
  19748. data[4], data[5], data[6], data[7],
  19749. data[8], data[9], data[10], data[11],
  19750. data[12], data[13], data[14], data[15]
  19751. );
  19752. };
  19753. function getConvertedMember( member ) {
  19754. if ( options.convertUpAxis ) {
  19755. switch ( member ) {
  19756. case 'X':
  19757. switch ( upConversion ) {
  19758. case 'XtoY':
  19759. case 'XtoZ':
  19760. case 'YtoX':
  19761. member = 'Y';
  19762. break;
  19763. case 'ZtoX':
  19764. member = 'Z';
  19765. break;
  19766. }
  19767. break;
  19768. case 'Y':
  19769. switch ( upConversion ) {
  19770. case 'XtoY':
  19771. case 'YtoX':
  19772. case 'ZtoX':
  19773. member = 'X';
  19774. break;
  19775. case 'XtoZ':
  19776. case 'YtoZ':
  19777. case 'ZtoY':
  19778. member = 'Z';
  19779. break;
  19780. }
  19781. break;
  19782. case 'Z':
  19783. switch ( upConversion ) {
  19784. case 'XtoZ':
  19785. member = 'X';
  19786. break;
  19787. case 'YtoZ':
  19788. case 'ZtoX':
  19789. case 'ZtoY':
  19790. member = 'Y';
  19791. break;
  19792. }
  19793. break;
  19794. }
  19795. }
  19796. return member;
  19797. };
  19798. return {
  19799. load: load,
  19800. parse: parse,
  19801. setPreferredShading: setPreferredShading,
  19802. applySkin: applySkin,
  19803. geometries : geometries,
  19804. options: options
  19805. };
  19806. };
  19807. /**
  19808. * @author mrdoob / http://mrdoob.com/
  19809. * @author alteredq / http://alteredqualia.com/
  19810. */
  19811. THREE.JSONLoader = function ( showStatus ) {
  19812. THREE.Loader.call( this, showStatus );
  19813. };
  19814. THREE.JSONLoader.prototype = new THREE.Loader();
  19815. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  19816. THREE.JSONLoader.prototype.supr = THREE.Loader.prototype;
  19817. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  19818. var worker, scope = this;
  19819. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  19820. this.onLoadStart();
  19821. this.loadAjaxJSON( this, url, callback, texturePath );
  19822. };
  19823. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  19824. var xhr = new XMLHttpRequest();
  19825. var length = 0;
  19826. xhr.onreadystatechange = function () {
  19827. if ( xhr.readyState === xhr.DONE ) {
  19828. if ( xhr.status === 200 || xhr.status === 0 ) {
  19829. if ( xhr.responseText ) {
  19830. var json = JSON.parse( xhr.responseText );
  19831. context.createModel( json, callback, texturePath );
  19832. } else {
  19833. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  19834. }
  19835. // in context of more complex asset initialization
  19836. // do not block on single failed file
  19837. // maybe should go even one more level up
  19838. context.onLoadComplete();
  19839. } else {
  19840. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  19841. }
  19842. } else if ( xhr.readyState === xhr.LOADING ) {
  19843. if ( callbackProgress ) {
  19844. if ( length === 0 ) {
  19845. length = xhr.getResponseHeader( "Content-Length" );
  19846. }
  19847. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  19848. }
  19849. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  19850. length = xhr.getResponseHeader( "Content-Length" );
  19851. }
  19852. };
  19853. xhr.open( "GET", url, true );
  19854. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  19855. xhr.setRequestHeader( "Content-Type", "text/plain" );
  19856. xhr.send( null );
  19857. };
  19858. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  19859. var scope = this,
  19860. geometry = new THREE.Geometry(),
  19861. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19862. this.initMaterials( geometry, json.materials, texturePath );
  19863. parseModel( scale );
  19864. parseSkin();
  19865. parseMorphing( scale );
  19866. geometry.computeCentroids();
  19867. geometry.computeFaceNormals();
  19868. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  19869. function parseModel( scale ) {
  19870. function isBitSet( value, position ) {
  19871. return value & ( 1 << position );
  19872. }
  19873. var i, j, fi,
  19874. offset, zLength, nVertices,
  19875. colorIndex, normalIndex, uvIndex, materialIndex,
  19876. type,
  19877. isQuad,
  19878. hasMaterial,
  19879. hasFaceUv, hasFaceVertexUv,
  19880. hasFaceNormal, hasFaceVertexNormal,
  19881. hasFaceColor, hasFaceVertexColor,
  19882. vertex, face, color, normal,
  19883. uvLayer, uvs, u, v,
  19884. faces = json.faces,
  19885. vertices = json.vertices,
  19886. normals = json.normals,
  19887. colors = json.colors,
  19888. nUvLayers = 0;
  19889. // disregard empty arrays
  19890. for ( i = 0; i < json.uvs.length; i++ ) {
  19891. if ( json.uvs[ i ].length ) nUvLayers ++;
  19892. }
  19893. for ( i = 0; i < nUvLayers; i++ ) {
  19894. geometry.faceUvs[ i ] = [];
  19895. geometry.faceVertexUvs[ i ] = [];
  19896. }
  19897. offset = 0;
  19898. zLength = vertices.length;
  19899. while ( offset < zLength ) {
  19900. vertex = new THREE.Vertex();
  19901. vertex.position.x = vertices[ offset ++ ] * scale;
  19902. vertex.position.y = vertices[ offset ++ ] * scale;
  19903. vertex.position.z = vertices[ offset ++ ] * scale;
  19904. geometry.vertices.push( vertex );
  19905. }
  19906. offset = 0;
  19907. zLength = faces.length;
  19908. while ( offset < zLength ) {
  19909. type = faces[ offset ++ ];
  19910. isQuad = isBitSet( type, 0 );
  19911. hasMaterial = isBitSet( type, 1 );
  19912. hasFaceUv = isBitSet( type, 2 );
  19913. hasFaceVertexUv = isBitSet( type, 3 );
  19914. hasFaceNormal = isBitSet( type, 4 );
  19915. hasFaceVertexNormal = isBitSet( type, 5 );
  19916. hasFaceColor = isBitSet( type, 6 );
  19917. hasFaceVertexColor = isBitSet( type, 7 );
  19918. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19919. if ( isQuad ) {
  19920. face = new THREE.Face4();
  19921. face.a = faces[ offset ++ ];
  19922. face.b = faces[ offset ++ ];
  19923. face.c = faces[ offset ++ ];
  19924. face.d = faces[ offset ++ ];
  19925. nVertices = 4;
  19926. } else {
  19927. face = new THREE.Face3();
  19928. face.a = faces[ offset ++ ];
  19929. face.b = faces[ offset ++ ];
  19930. face.c = faces[ offset ++ ];
  19931. nVertices = 3;
  19932. }
  19933. if ( hasMaterial ) {
  19934. materialIndex = faces[ offset ++ ];
  19935. face.materialIndex = materialIndex;
  19936. }
  19937. // to get face <=> uv index correspondence
  19938. fi = geometry.faces.length;
  19939. if ( hasFaceUv ) {
  19940. for ( i = 0; i < nUvLayers; i++ ) {
  19941. uvLayer = json.uvs[ i ];
  19942. uvIndex = faces[ offset ++ ];
  19943. u = uvLayer[ uvIndex * 2 ];
  19944. v = uvLayer[ uvIndex * 2 + 1 ];
  19945. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  19946. }
  19947. }
  19948. if ( hasFaceVertexUv ) {
  19949. for ( i = 0; i < nUvLayers; i++ ) {
  19950. uvLayer = json.uvs[ i ];
  19951. uvs = [];
  19952. for ( j = 0; j < nVertices; j ++ ) {
  19953. uvIndex = faces[ offset ++ ];
  19954. u = uvLayer[ uvIndex * 2 ];
  19955. v = uvLayer[ uvIndex * 2 + 1 ];
  19956. uvs[ j ] = new THREE.UV( u, v );
  19957. }
  19958. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  19959. }
  19960. }
  19961. if ( hasFaceNormal ) {
  19962. normalIndex = faces[ offset ++ ] * 3;
  19963. normal = new THREE.Vector3();
  19964. normal.x = normals[ normalIndex ++ ];
  19965. normal.y = normals[ normalIndex ++ ];
  19966. normal.z = normals[ normalIndex ];
  19967. face.normal = normal;
  19968. }
  19969. if ( hasFaceVertexNormal ) {
  19970. for ( i = 0; i < nVertices; i++ ) {
  19971. normalIndex = faces[ offset ++ ] * 3;
  19972. normal = new THREE.Vector3();
  19973. normal.x = normals[ normalIndex ++ ];
  19974. normal.y = normals[ normalIndex ++ ];
  19975. normal.z = normals[ normalIndex ];
  19976. face.vertexNormals.push( normal );
  19977. }
  19978. }
  19979. if ( hasFaceColor ) {
  19980. colorIndex = faces[ offset ++ ];
  19981. color = new THREE.Color( colors[ colorIndex ] );
  19982. face.color = color;
  19983. }
  19984. if ( hasFaceVertexColor ) {
  19985. for ( i = 0; i < nVertices; i++ ) {
  19986. colorIndex = faces[ offset ++ ];
  19987. color = new THREE.Color( colors[ colorIndex ] );
  19988. face.vertexColors.push( color );
  19989. }
  19990. }
  19991. geometry.faces.push( face );
  19992. }
  19993. };
  19994. function parseSkin() {
  19995. var i, l, x, y, z, w, a, b, c, d;
  19996. if ( json.skinWeights ) {
  19997. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  19998. x = json.skinWeights[ i ];
  19999. y = json.skinWeights[ i + 1 ];
  20000. z = 0;
  20001. w = 0;
  20002. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  20003. }
  20004. }
  20005. if ( json.skinIndices ) {
  20006. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  20007. a = json.skinIndices[ i ];
  20008. b = json.skinIndices[ i + 1 ];
  20009. c = 0;
  20010. d = 0;
  20011. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  20012. }
  20013. }
  20014. geometry.bones = json.bones;
  20015. geometry.animation = json.animation;
  20016. };
  20017. function parseMorphing( scale ) {
  20018. if ( json.morphTargets !== undefined ) {
  20019. var i, l, v, vl, x, y, z, dstVertices, srcVertices;
  20020. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20021. geometry.morphTargets[ i ] = {};
  20022. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20023. geometry.morphTargets[ i ].vertices = [];
  20024. dstVertices = geometry.morphTargets[ i ].vertices;
  20025. srcVertices = json.morphTargets [ i ].vertices;
  20026. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20027. x = srcVertices[ v ] * scale;
  20028. y = srcVertices[ v + 1 ] * scale;
  20029. z = srcVertices[ v + 2 ] * scale;
  20030. dstVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  20031. }
  20032. }
  20033. }
  20034. if ( json.morphColors !== undefined ) {
  20035. var i, l, c, cl, dstColors, srcColors, color;
  20036. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  20037. geometry.morphColors[ i ] = {};
  20038. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  20039. geometry.morphColors[ i ].colors = [];
  20040. dstColors = geometry.morphColors[ i ].colors;
  20041. srcColors = json.morphColors [ i ].colors;
  20042. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  20043. color = new THREE.Color( 0xffaa00 );
  20044. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  20045. dstColors.push( color );
  20046. }
  20047. }
  20048. }
  20049. };
  20050. callback( geometry );
  20051. };
  20052. /**
  20053. * @author alteredq / http://alteredqualia.com/
  20054. */
  20055. THREE.SceneLoader = function () {
  20056. this.onLoadStart = function () {};
  20057. this.onLoadProgress = function() {};
  20058. this.onLoadComplete = function () {};
  20059. this.callbackSync = function () {};
  20060. this.callbackProgress = function () {};
  20061. };
  20062. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  20063. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  20064. var context = this;
  20065. var xhr = new XMLHttpRequest();
  20066. xhr.onreadystatechange = function () {
  20067. if ( xhr.readyState == 4 ) {
  20068. if ( xhr.status == 200 || xhr.status == 0 ) {
  20069. var json = JSON.parse( xhr.responseText );
  20070. context.createScene( json, callbackFinished, url );
  20071. } else {
  20072. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20073. }
  20074. }
  20075. };
  20076. xhr.open( "GET", url, true );
  20077. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  20078. xhr.setRequestHeader( "Content-Type", "text/plain" );
  20079. xhr.send( null );
  20080. };
  20081. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  20082. var scope = this;
  20083. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  20084. var dg, dm, dd, dl, dc, df, dt,
  20085. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  20086. geometry, material, camera, fog,
  20087. texture, images,
  20088. light,
  20089. data, binLoader, jsonLoader,
  20090. counter_models, counter_textures,
  20091. total_models, total_textures,
  20092. result;
  20093. data = json;
  20094. binLoader = new THREE.BinaryLoader();
  20095. jsonLoader = new THREE.JSONLoader();
  20096. counter_models = 0;
  20097. counter_textures = 0;
  20098. result = {
  20099. scene: new THREE.Scene(),
  20100. geometries: {},
  20101. materials: {},
  20102. textures: {},
  20103. objects: {},
  20104. cameras: {},
  20105. lights: {},
  20106. fogs: {},
  20107. empties: {}
  20108. };
  20109. if ( data.transform ) {
  20110. var position = data.transform.position,
  20111. rotation = data.transform.rotation,
  20112. scale = data.transform.scale;
  20113. if ( position )
  20114. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  20115. if ( rotation )
  20116. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  20117. if ( scale )
  20118. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  20119. if ( position || rotation || scale ) {
  20120. result.scene.updateMatrix();
  20121. result.scene.updateMatrixWorld();
  20122. }
  20123. }
  20124. function get_url( source_url, url_type ) {
  20125. if ( url_type == "relativeToHTML" ) {
  20126. return source_url;
  20127. } else {
  20128. return urlBase + "/" + source_url;
  20129. }
  20130. };
  20131. function handle_objects() {
  20132. var object;
  20133. for( dd in data.objects ) {
  20134. if ( !result.objects[ dd ] ) {
  20135. o = data.objects[ dd ];
  20136. if ( o.geometry !== undefined ) {
  20137. geometry = result.geometries[ o.geometry ];
  20138. // geometry already loaded
  20139. if ( geometry ) {
  20140. var hasNormals = false;
  20141. // not anymore support for multiple materials
  20142. // shouldn't really be array
  20143. material = result.materials[ o.materials[ 0 ] ];
  20144. hasNormals = material instanceof THREE.ShaderMaterial;
  20145. if ( hasNormals ) {
  20146. geometry.computeTangents();
  20147. }
  20148. p = o.position;
  20149. r = o.rotation;
  20150. q = o.quaternion;
  20151. s = o.scale;
  20152. // turn off quaternions, for the moment
  20153. q = 0;
  20154. if ( o.materials.length == 0 ) {
  20155. material = new THREE.MeshFaceMaterial();
  20156. }
  20157. // dirty hack to handle meshes with multiple materials
  20158. // just use face materials defined in model
  20159. if ( o.materials.length > 1 ) {
  20160. material = new THREE.MeshFaceMaterial();
  20161. }
  20162. object = new THREE.Mesh( geometry, material );
  20163. object.name = dd;
  20164. object.position.set( p[0], p[1], p[2] );
  20165. if ( q ) {
  20166. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20167. object.useQuaternion = true;
  20168. } else {
  20169. object.rotation.set( r[0], r[1], r[2] );
  20170. }
  20171. object.scale.set( s[0], s[1], s[2] );
  20172. object.visible = o.visible;
  20173. object.doubleSided = o.doubleSided;
  20174. object.castShadow = o.castShadow;
  20175. object.receiveShadow = o.receiveShadow;
  20176. result.scene.add( object );
  20177. result.objects[ dd ] = object;
  20178. }
  20179. // pure Object3D
  20180. } else {
  20181. p = o.position;
  20182. r = o.rotation;
  20183. q = o.quaternion;
  20184. s = o.scale;
  20185. // turn off quaternions, for the moment
  20186. q = 0;
  20187. object = new THREE.Object3D();
  20188. object.name = dd;
  20189. object.position.set( p[0], p[1], p[2] );
  20190. if ( q ) {
  20191. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20192. object.useQuaternion = true;
  20193. } else {
  20194. object.rotation.set( r[0], r[1], r[2] );
  20195. }
  20196. object.scale.set( s[0], s[1], s[2] );
  20197. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  20198. result.scene.add( object );
  20199. result.objects[ dd ] = object;
  20200. result.empties[ dd ] = object;
  20201. }
  20202. }
  20203. }
  20204. };
  20205. function handle_mesh( geo, id ) {
  20206. result.geometries[ id ] = geo;
  20207. handle_objects();
  20208. };
  20209. function create_callback( id ) {
  20210. return function( geo ) {
  20211. handle_mesh( geo, id );
  20212. counter_models -= 1;
  20213. scope.onLoadComplete();
  20214. async_callback_gate();
  20215. }
  20216. };
  20217. function create_callback_embed( id ) {
  20218. return function( geo ) {
  20219. result.geometries[ id ] = geo;
  20220. }
  20221. };
  20222. function async_callback_gate() {
  20223. var progress = {
  20224. totalModels : total_models,
  20225. totalTextures : total_textures,
  20226. loadedModels : total_models - counter_models,
  20227. loadedTextures : total_textures - counter_textures
  20228. };
  20229. scope.callbackProgress( progress, result );
  20230. scope.onLoadProgress();
  20231. if( counter_models == 0 && counter_textures == 0 ) {
  20232. callbackFinished( result );
  20233. }
  20234. };
  20235. var callbackTexture = function( images ) {
  20236. counter_textures -= 1;
  20237. async_callback_gate();
  20238. scope.onLoadComplete();
  20239. };
  20240. // first go synchronous elements
  20241. // cameras
  20242. for( dc in data.cameras ) {
  20243. c = data.cameras[ dc ];
  20244. if ( c.type == "perspective" ) {
  20245. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  20246. } else if ( c.type == "ortho" ) {
  20247. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  20248. }
  20249. p = c.position;
  20250. t = c.target;
  20251. u = c.up;
  20252. camera.position.set( p[0], p[1], p[2] );
  20253. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  20254. if ( u ) camera.up.set( u[0], u[1], u[2] );
  20255. result.cameras[ dc ] = camera;
  20256. }
  20257. // lights
  20258. var hex, intensity;
  20259. for ( dl in data.lights ) {
  20260. l = data.lights[ dl ];
  20261. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  20262. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  20263. if ( l.type == "directional" ) {
  20264. p = l.direction;
  20265. light = new THREE.DirectionalLight( hex, intensity );
  20266. light.position.set( p[0], p[1], p[2] );
  20267. light.position.normalize();
  20268. } else if ( l.type == "point" ) {
  20269. p = l.position;
  20270. d = l.distance;
  20271. light = new THREE.PointLight( hex, intensity, d );
  20272. light.position.set( p[0], p[1], p[2] );
  20273. } else if ( l.type == "ambient" ) {
  20274. light = new THREE.AmbientLight( hex );
  20275. }
  20276. result.scene.add( light );
  20277. result.lights[ dl ] = light;
  20278. }
  20279. // fogs
  20280. for( df in data.fogs ) {
  20281. f = data.fogs[ df ];
  20282. if ( f.type == "linear" ) {
  20283. fog = new THREE.Fog( 0x000000, f.near, f.far );
  20284. } else if ( f.type == "exp2" ) {
  20285. fog = new THREE.FogExp2( 0x000000, f.density );
  20286. }
  20287. c = f.color;
  20288. fog.color.setRGB( c[0], c[1], c[2] );
  20289. result.fogs[ df ] = fog;
  20290. }
  20291. // defaults
  20292. if ( result.cameras && data.defaults.camera ) {
  20293. result.currentCamera = result.cameras[ data.defaults.camera ];
  20294. }
  20295. if ( result.fogs && data.defaults.fog ) {
  20296. result.scene.fog = result.fogs[ data.defaults.fog ];
  20297. }
  20298. c = data.defaults.bgcolor;
  20299. result.bgColor = new THREE.Color();
  20300. result.bgColor.setRGB( c[0], c[1], c[2] );
  20301. result.bgColorAlpha = data.defaults.bgalpha;
  20302. // now come potentially asynchronous elements
  20303. // geometries
  20304. // count how many models will be loaded asynchronously
  20305. for( dg in data.geometries ) {
  20306. g = data.geometries[ dg ];
  20307. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  20308. counter_models += 1;
  20309. scope.onLoadStart();
  20310. }
  20311. }
  20312. total_models = counter_models;
  20313. for ( dg in data.geometries ) {
  20314. g = data.geometries[ dg ];
  20315. if ( g.type == "cube" ) {
  20316. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  20317. result.geometries[ dg ] = geometry;
  20318. } else if ( g.type == "plane" ) {
  20319. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  20320. result.geometries[ dg ] = geometry;
  20321. } else if ( g.type == "sphere" ) {
  20322. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  20323. result.geometries[ dg ] = geometry;
  20324. } else if ( g.type == "cylinder" ) {
  20325. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  20326. result.geometries[ dg ] = geometry;
  20327. } else if ( g.type == "torus" ) {
  20328. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  20329. result.geometries[ dg ] = geometry;
  20330. } else if ( g.type == "icosahedron" ) {
  20331. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  20332. result.geometries[ dg ] = geometry;
  20333. } else if ( g.type == "bin_mesh" ) {
  20334. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20335. } else if ( g.type == "ascii_mesh" ) {
  20336. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20337. } else if ( g.type == "embedded_mesh" ) {
  20338. var modelJson = data.embeds[ g.id ],
  20339. texture_path = "";
  20340. // Pass metadata along to jsonLoader so it knows the format version.
  20341. modelJson.metadata = data.metadata;
  20342. if ( modelJson ) {
  20343. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  20344. }
  20345. }
  20346. }
  20347. // textures
  20348. // count how many textures will be loaded asynchronously
  20349. for( dt in data.textures ) {
  20350. tt = data.textures[ dt ];
  20351. if( tt.url instanceof Array ) {
  20352. counter_textures += tt.url.length;
  20353. for( var n = 0; n < tt.url.length; n ++ ) {
  20354. scope.onLoadStart();
  20355. }
  20356. } else {
  20357. counter_textures += 1;
  20358. scope.onLoadStart();
  20359. }
  20360. }
  20361. total_textures = counter_textures;
  20362. for( dt in data.textures ) {
  20363. tt = data.textures[ dt ];
  20364. if ( tt.mapping != undefined && THREE[ tt.mapping ] != undefined ) {
  20365. tt.mapping = new THREE[ tt.mapping ]();
  20366. }
  20367. if( tt.url instanceof Array ) {
  20368. var url_array = [];
  20369. for( var i = 0; i < tt.url.length; i ++ ) {
  20370. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  20371. }
  20372. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, callbackTexture );
  20373. } else {
  20374. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, callbackTexture );
  20375. if ( THREE[ tt.minFilter ] != undefined )
  20376. texture.minFilter = THREE[ tt.minFilter ];
  20377. if ( THREE[ tt.magFilter ] != undefined )
  20378. texture.magFilter = THREE[ tt.magFilter ];
  20379. if ( tt.repeat ) {
  20380. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  20381. if ( tt.repeat[ 0 ] != 1 ) texture.wrapS = THREE.RepeatWrapping;
  20382. if ( tt.repeat[ 1 ] != 1 ) texture.wrapT = THREE.RepeatWrapping;
  20383. }
  20384. if ( tt.offset ) {
  20385. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  20386. }
  20387. // handle wrap after repeat so that default repeat can be overriden
  20388. if ( tt.wrap ) {
  20389. var wrapMap = {
  20390. "repeat" : THREE.RepeatWrapping,
  20391. "mirror" : THREE.MirroredRepeatWrapping
  20392. }
  20393. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  20394. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  20395. }
  20396. }
  20397. result.textures[ dt ] = texture;
  20398. }
  20399. // materials
  20400. for ( dm in data.materials ) {
  20401. m = data.materials[ dm ];
  20402. for ( pp in m.parameters ) {
  20403. if ( pp == "envMap" || pp == "map" || pp == "lightMap" ) {
  20404. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  20405. } else if ( pp == "shading" ) {
  20406. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  20407. } else if ( pp == "blending" ) {
  20408. m.parameters[ pp ] = THREE[ m.parameters[ pp ] ] ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  20409. } else if ( pp == "combine" ) {
  20410. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  20411. } else if ( pp == "vertexColors" ) {
  20412. if ( m.parameters[ pp ] == "face" ) {
  20413. m.parameters[ pp ] = THREE.FaceColors;
  20414. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  20415. } else if ( m.parameters[ pp ] ) {
  20416. m.parameters[ pp ] = THREE.VertexColors;
  20417. }
  20418. }
  20419. }
  20420. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  20421. m.parameters.transparent = true;
  20422. }
  20423. if ( m.parameters.normalMap ) {
  20424. var shader = THREE.ShaderUtils.lib[ "normal" ];
  20425. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  20426. var diffuse = m.parameters.color;
  20427. var specular = m.parameters.specular;
  20428. var ambient = m.parameters.ambient;
  20429. var shininess = m.parameters.shininess;
  20430. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  20431. if ( m.parameters.normalMapFactor ) {
  20432. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  20433. }
  20434. if ( m.parameters.map ) {
  20435. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  20436. uniforms[ "enableDiffuse" ].value = true;
  20437. }
  20438. if ( m.parameters.lightMap ) {
  20439. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  20440. uniforms[ "enableAO" ].value = true;
  20441. }
  20442. if ( m.parameters.specularMap ) {
  20443. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  20444. uniforms[ "enableSpecular" ].value = true;
  20445. }
  20446. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  20447. uniforms[ "uSpecularColor" ].value.setHex( specular );
  20448. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  20449. uniforms[ "uShininess" ].value = shininess;
  20450. if ( m.parameters.opacity ) {
  20451. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  20452. }
  20453. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  20454. material = new THREE.ShaderMaterial( parameters );
  20455. } else {
  20456. material = new THREE[ m.type ]( m.parameters );
  20457. }
  20458. result.materials[ dm ] = material;
  20459. }
  20460. // objects ( synchronous init of procedural primitives )
  20461. handle_objects();
  20462. // synchronous callback
  20463. scope.callbackSync( result );
  20464. // just in case there are no async elements:
  20465. async_callback_gate();
  20466. };
  20467. /**
  20468. * Loader for UTF8 encoded models generated by:
  20469. * http://code.google.com/p/webgl-loader/
  20470. *
  20471. * Limitations:
  20472. * - number of vertices < 65536 (this is after optimizations in compressor, input OBJ may have even less)
  20473. * - models must have normals and texture coordinates
  20474. * - texture coordinates must be only from <0,1>
  20475. * - no materials support yet
  20476. * - models are scaled and offset (copy numbers from compressor and use them as parameters in UTF8Loader.load() )
  20477. *
  20478. * @author alteredq / http://alteredqualia.com/
  20479. * @author won3d / http://twitter.com/won3d
  20480. */
  20481. THREE.UTF8Loader = function () {};
  20482. THREE.UTF8Loader.prototype.load = function ( url, callback, metadata ) {
  20483. var xhr = new XMLHttpRequest(),
  20484. callbackProgress = null,
  20485. scale = metadata.scale !== undefined ? metadata.scale : 1,
  20486. offsetX = metadata.offsetX !== undefined ? metadata.offsetX : 0,
  20487. offsetY = metadata.offsetY !== undefined ? metadata.offsetY : 0,
  20488. offsetZ = metadata.offsetZ !== undefined ? metadata.offsetZ : 0;
  20489. var length = 0;
  20490. xhr.onreadystatechange = function() {
  20491. if ( xhr.readyState == 4 ) {
  20492. if ( xhr.status == 200 || xhr.status == 0 ) {
  20493. THREE.UTF8Loader.prototype.createModel( xhr.responseText, callback, scale, offsetX, offsetY, offsetZ );
  20494. } else {
  20495. console.error( "THREE.UTF8Loader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20496. }
  20497. } else if ( xhr.readyState == 3 ) {
  20498. if ( callbackProgress ) {
  20499. if ( length == 0 ) {
  20500. length = xhr.getResponseHeader( "Content-Length" );
  20501. }
  20502. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  20503. }
  20504. } else if ( xhr.readyState == 2 ) {
  20505. length = xhr.getResponseHeader( "Content-Length" );
  20506. }
  20507. }
  20508. xhr.open( "GET", url, true );
  20509. xhr.send( null );
  20510. };
  20511. // UTF-8 decoder from webgl-loader
  20512. // http://code.google.com/p/webgl-loader/
  20513. // Copyright 2011 Google Inc. All Rights Reserved.
  20514. //
  20515. // Licensed under the Apache License, Version 2.0 (the "License"); you
  20516. // may not use this file except in compliance with the License. You
  20517. // may obtain a copy of the License at
  20518. //
  20519. // http://www.apache.org/licenses/LICENSE-2.0
  20520. //
  20521. // Unless required by applicable law or agreed to in writing, software
  20522. // distributed under the License is distributed on an "AS IS" BASIS,
  20523. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  20524. // implied. See the License for the specific language governing
  20525. // permissions and limitations under the License.
  20526. THREE.UTF8Loader.prototype.decompressMesh = function ( str ) {
  20527. var num_verts = str.charCodeAt( 0 );
  20528. if ( num_verts >= 0xE000 ) {
  20529. num_verts -= 0x0800;
  20530. }
  20531. num_verts ++;
  20532. var attribs_out = new Float32Array( 8 * num_verts );
  20533. var offset = 1;
  20534. for ( var i = 0; i < 8; i ++ ) {
  20535. var prev_attrib = 0;
  20536. for ( var j = 0; j < num_verts; ++ j ) {
  20537. var code = str.charCodeAt( j + offset );
  20538. prev_attrib += ( code >> 1 ) ^ ( - ( code & 1 ) );
  20539. attribs_out[ 8 * j + i ] = prev_attrib;
  20540. }
  20541. offset += num_verts;
  20542. }
  20543. var num_indices = str.length - offset;
  20544. var indices_out = new Uint16Array( num_indices );
  20545. var index_high_water_mark = 0;
  20546. for ( var i = 0; i < num_indices; i ++ ) {
  20547. var code = str.charCodeAt( i + offset );
  20548. indices_out[ i ] = index_high_water_mark - code;
  20549. if ( code == 0 ) {
  20550. index_high_water_mark ++;
  20551. }
  20552. }
  20553. return [ attribs_out, indices_out ];
  20554. };
  20555. THREE.UTF8Loader.prototype.createModel = function ( data, callback, scale, offsetX, offsetY, offsetZ ) {
  20556. var Model = function ( texture_path ) {
  20557. //var s = (new Date).getTime();
  20558. var scope = this;
  20559. scope.materials = [];
  20560. THREE.Geometry.call( this );
  20561. var buffers = THREE.UTF8Loader.prototype.decompressMesh( data );
  20562. var normals = [],
  20563. uvs = [];
  20564. init_vertices( buffers[ 0 ], 8, 0 );
  20565. init_uvs( buffers[ 0 ], 8, 3 );
  20566. init_normals( buffers[ 0 ], 8, 5 );
  20567. init_faces( buffers[ 1 ] );
  20568. this.computeCentroids();
  20569. this.computeFaceNormals();
  20570. //this.computeTangents();
  20571. //var e = (new Date).getTime();
  20572. //console.log( "utf8 data parse time: " + (e-s) + " ms" );
  20573. function init_vertices( data, stride, offset ) {
  20574. var i, x, y, z,
  20575. end = data.length;
  20576. for( i = offset; i < end; i += stride ) {
  20577. x = data[ i ];
  20578. y = data[ i + 1 ];
  20579. z = data[ i + 2 ];
  20580. // fix scale and offsets
  20581. x = ( x / 16383 ) * scale;
  20582. y = ( y / 16383 ) * scale;
  20583. z = ( z / 16383 ) * scale;
  20584. x += offsetX;
  20585. y += offsetY;
  20586. z += offsetZ;
  20587. vertex( scope, x, y, z );
  20588. }
  20589. };
  20590. function init_normals( data, stride, offset ) {
  20591. var i, x, y, z,
  20592. end = data.length;
  20593. for( i = offset; i < end; i += stride ) {
  20594. x = data[ i ];
  20595. y = data[ i + 1 ];
  20596. z = data[ i + 2 ];
  20597. // normalize to <-1,1>
  20598. x = ( x - 512 ) / 511;
  20599. y = ( y - 512 ) / 511;
  20600. z = ( z - 512 ) / 511;
  20601. normals.push( x, y, z );
  20602. }
  20603. };
  20604. function init_uvs( data, stride, offset ) {
  20605. var i, u, v,
  20606. end = data.length;
  20607. for( i = offset; i < end; i += stride ) {
  20608. u = data[ i ];
  20609. v = data[ i + 1 ];
  20610. // normalize to <0,1>
  20611. u /= 1023;
  20612. v /= 1023;
  20613. uvs.push( u, 1 - v );
  20614. }
  20615. };
  20616. function init_faces( indices ) {
  20617. var i,
  20618. a, b, c,
  20619. u1, v1, u2, v2, u3, v3,
  20620. m,
  20621. end = indices.length;
  20622. m = 0; // all faces defaulting to material 0
  20623. for( i = 0; i < end; i += 3 ) {
  20624. a = indices[ i ];
  20625. b = indices[ i + 1 ];
  20626. c = indices[ i + 2 ];
  20627. f3n( scope, normals, a, b, c, m, a, b, c );
  20628. u1 = uvs[ a * 2 ];
  20629. v1 = uvs[ a * 2 + 1 ];
  20630. u2 = uvs[ b * 2 ];
  20631. v2 = uvs[ b * 2 + 1 ];
  20632. u3 = uvs[ c * 2 ];
  20633. v3 = uvs[ c * 2 + 1 ];
  20634. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  20635. }
  20636. }
  20637. };
  20638. function vertex ( scope, x, y, z ) {
  20639. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  20640. };
  20641. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  20642. var nax = normals[ nai * 3 ],
  20643. nay = normals[ nai * 3 + 1 ],
  20644. naz = normals[ nai * 3 + 2 ],
  20645. nbx = normals[ nbi * 3 ],
  20646. nby = normals[ nbi * 3 + 1 ],
  20647. nbz = normals[ nbi * 3 + 2 ],
  20648. ncx = normals[ nci * 3 ],
  20649. ncy = normals[ nci * 3 + 1 ],
  20650. ncz = normals[ nci * 3 + 2 ];
  20651. var na = new THREE.Vector3( nax, nay, naz ),
  20652. nb = new THREE.Vector3( nbx, nby, nbz ),
  20653. nc = new THREE.Vector3( ncx, ncy, ncz );
  20654. scope.faces.push( new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi ) );
  20655. };
  20656. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  20657. var uv = [];
  20658. uv.push( new THREE.UV( u1, v1 ) );
  20659. uv.push( new THREE.UV( u2, v2 ) );
  20660. uv.push( new THREE.UV( u3, v3 ) );
  20661. where.push( uv );
  20662. };
  20663. Model.prototype = new THREE.Geometry();
  20664. Model.prototype.constructor = Model;
  20665. callback( new Model() );
  20666. };
  20667. /**
  20668. * @author alteredq / http://alteredqualia.com/
  20669. */
  20670. THREE.ImmediateRenderObject = function ( ) {
  20671. THREE.Object3D.call( this );
  20672. this.render = function( renderCallback ) {
  20673. };
  20674. };
  20675. THREE.ImmediateRenderObject.prototype = new THREE.Object3D();
  20676. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20677. /**
  20678. * @author mikael emtinger / http://gomo.se/
  20679. * @author alteredq / http://alteredqualia.com/
  20680. */
  20681. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20682. THREE.Object3D.call( this );
  20683. this.lensFlares = [];
  20684. this.positionScreen = new THREE.Vector3();
  20685. this.customUpdateCallback = undefined;
  20686. if( texture !== undefined ) {
  20687. this.add( texture, size, distance, blending, color );
  20688. }
  20689. };
  20690. THREE.LensFlare.prototype = new THREE.Object3D();
  20691. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  20692. THREE.LensFlare.prototype.supr = THREE.Object3D.prototype;
  20693. /*
  20694. * Add: adds another flare
  20695. */
  20696. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20697. if( size === undefined ) size = -1;
  20698. if( distance === undefined ) distance = 0;
  20699. if( opacity === undefined ) opacity = 1;
  20700. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20701. if( blending === undefined ) blending = THREE.NormalBlending;
  20702. distance = Math.min( distance, Math.max( 0, distance ) );
  20703. this.lensFlares.push( { texture: texture, // THREE.Texture
  20704. size: size, // size in pixels (-1 = use texture.width)
  20705. distance: distance, // distance (0-1) from light source (0=at light source)
  20706. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20707. scale: 1, // scale
  20708. rotation: 1, // rotation
  20709. opacity: opacity, // opacity
  20710. color: color, // color
  20711. blending: blending } ); // blending
  20712. };
  20713. /*
  20714. * Update lens flares update positions on all flares based on the screen position
  20715. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20716. */
  20717. THREE.LensFlare.prototype.updateLensFlares = function () {
  20718. var f, fl = this.lensFlares.length;
  20719. var flare;
  20720. var vecX = -this.positionScreen.x * 2;
  20721. var vecY = -this.positionScreen.y * 2;
  20722. for( f = 0; f < fl; f ++ ) {
  20723. flare = this.lensFlares[ f ];
  20724. flare.x = this.positionScreen.x + vecX * flare.distance;
  20725. flare.y = this.positionScreen.y + vecY * flare.distance;
  20726. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20727. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20728. }
  20729. };
  20730. /**
  20731. * @author alteredq / http://alteredqualia.com/
  20732. */
  20733. THREE.MorphBlendMesh = function( geometry, material ) {
  20734. THREE.Mesh.call( this, geometry, material );
  20735. this.animationsMap = {};
  20736. this.animationsList = [];
  20737. // prepare default animation
  20738. // (all frames played together in 1 second)
  20739. var numFrames = this.geometry.morphTargets.length;
  20740. var name = "__default";
  20741. var startFrame = 0;
  20742. var endFrame = numFrames - 1;
  20743. var fps = numFrames / 1;
  20744. this.createAnimation( name, startFrame, endFrame, fps );
  20745. this.setAnimationWeight( name, 1 );
  20746. };
  20747. THREE.MorphBlendMesh.prototype = new THREE.Mesh();
  20748. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20749. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20750. var animation = {
  20751. startFrame: start,
  20752. endFrame: end,
  20753. length: end - start + 1,
  20754. fps: fps,
  20755. duration: ( end - start ) / fps,
  20756. lastFrame: 0,
  20757. currentFrame: 0,
  20758. active: false,
  20759. time: 0,
  20760. direction: 1,
  20761. weight: 1,
  20762. directionBackwards: false,
  20763. mirroredLoop: false
  20764. };
  20765. this.animationsMap[ name ] = animation;
  20766. this.animationsList.push( animation );
  20767. };
  20768. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20769. var pattern = /([a-z]+)(\d+)/;
  20770. var firstAnimation, frameRanges = {};
  20771. var geometry = this.geometry;
  20772. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20773. var morph = geometry.morphTargets[ i ];
  20774. var chunks = morph.name.match( pattern );
  20775. if ( chunks && chunks.length > 1 ) {
  20776. var name = chunks[ 1 ];
  20777. var num = chunks[ 2 ];
  20778. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20779. var range = frameRanges[ name ];
  20780. if ( i < range.start ) range.start = i;
  20781. if ( i > range.end ) range.end = i;
  20782. if ( ! firstAnimation ) firstAnimation = name;
  20783. }
  20784. }
  20785. for ( var name in frameRanges ) {
  20786. var range = frameRanges[ name ];
  20787. this.createAnimation( name, range.start, range.end, fps );
  20788. }
  20789. this.firstAnimation = firstAnimation;
  20790. };
  20791. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20792. var animation = this.animationsMap[ name ];
  20793. if ( animation ) {
  20794. animation.direction = 1;
  20795. animation.directionBackwards = false;
  20796. }
  20797. };
  20798. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20799. var animation = this.animationsMap[ name ];
  20800. if ( animation ) {
  20801. animation.direction = -1;
  20802. animation.directionBackwards = true;
  20803. }
  20804. };
  20805. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20806. var animation = this.animationsMap[ name ];
  20807. if ( animation ) {
  20808. animation.fps = fps;
  20809. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20810. }
  20811. };
  20812. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20813. var animation = this.animationsMap[ name ];
  20814. if ( animation ) {
  20815. animation.duration = duration;
  20816. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20817. }
  20818. };
  20819. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20820. var animation = this.animationsMap[ name ];
  20821. if ( animation ) {
  20822. animation.weight = weight;
  20823. }
  20824. };
  20825. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20826. var animation = this.animationsMap[ name ];
  20827. if ( animation ) {
  20828. animation.time = time;
  20829. }
  20830. };
  20831. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20832. var time = 0;
  20833. var animation = this.animationsMap[ name ];
  20834. if ( animation ) {
  20835. time = animation.time;
  20836. }
  20837. return time;
  20838. };
  20839. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20840. var duration = -1;
  20841. var animation = this.animationsMap[ name ];
  20842. if ( animation ) {
  20843. duration = animation.duration;
  20844. }
  20845. return duration;
  20846. };
  20847. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20848. var animation = this.animationsMap[ name ];
  20849. if ( animation ) {
  20850. animation.time = 0;
  20851. animation.active = true;
  20852. } else {
  20853. console.warn( "animation[" + name + "] undefined" );
  20854. }
  20855. };
  20856. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20857. var animation = this.animationsMap[ name ];
  20858. if ( animation ) {
  20859. animation.active = false;
  20860. }
  20861. };
  20862. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20863. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20864. var animation = this.animationsList[ i ];
  20865. if ( ! animation.active ) continue;
  20866. var frameTime = animation.duration / animation.length;
  20867. animation.time += animation.direction * delta;
  20868. if ( animation.mirroredLoop ) {
  20869. if ( animation.time > animation.duration || animation.time < 0 ) {
  20870. animation.direction *= -1;
  20871. if ( animation.time > animation.duration ) {
  20872. animation.time = animation.duration;
  20873. animation.directionBackwards = true;
  20874. }
  20875. if ( animation.time < 0 ) {
  20876. animation.time = 0;
  20877. animation.directionBackwards = false;
  20878. }
  20879. }
  20880. } else {
  20881. animation.time = animation.time % animation.duration;
  20882. if ( animation.time < 0 ) animation.time += animation.duration;
  20883. }
  20884. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20885. var weight = animation.weight;
  20886. if ( keyframe !== animation.currentFrame ) {
  20887. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20888. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20889. this.morphTargetInfluences[ keyframe ] = 0;
  20890. animation.lastFrame = animation.currentFrame;
  20891. animation.currentFrame = keyframe;
  20892. }
  20893. var mix = ( animation.time % frameTime ) / frameTime;
  20894. if ( animation.directionBackwards ) mix = 1 - mix;
  20895. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20896. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20897. }
  20898. };
  20899. /**
  20900. * @author mikael emtinger / http://gomo.se/
  20901. * @author alteredq / http://alteredqualia.com/
  20902. */
  20903. THREE.LensFlarePlugin = function ( ) {
  20904. var _gl, _renderer, _lensFlare = {};
  20905. this.init = function ( renderer ) {
  20906. _gl = renderer.context;
  20907. _renderer = renderer;
  20908. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20909. _lensFlare.faces = new Uint16Array( 6 );
  20910. var i = 0;
  20911. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20912. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20913. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20914. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20915. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20916. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20917. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20918. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20919. i = 0;
  20920. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20921. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20922. // buffers
  20923. _lensFlare.vertexBuffer = _gl.createBuffer();
  20924. _lensFlare.elementBuffer = _gl.createBuffer();
  20925. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20926. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20927. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20928. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20929. // textures
  20930. _lensFlare.tempTexture = _gl.createTexture();
  20931. _lensFlare.occlusionTexture = _gl.createTexture();
  20932. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20933. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20934. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20935. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20936. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20937. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20938. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20939. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20940. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20941. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20942. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20943. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20944. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20945. _lensFlare.hasVertexTexture = false;
  20946. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20947. } else {
  20948. _lensFlare.hasVertexTexture = true;
  20949. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20950. }
  20951. _lensFlare.attributes = {};
  20952. _lensFlare.uniforms = {};
  20953. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20954. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20955. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20956. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20957. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20958. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20959. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20960. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20961. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20962. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20963. _lensFlare.attributesEnabled = false;
  20964. };
  20965. /*
  20966. * Render lens flares
  20967. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20968. * reads these back and calculates occlusion.
  20969. * Then _lensFlare.update_lensFlares() is called to re-position and
  20970. * update transparency of flares. Then they are rendered.
  20971. *
  20972. */
  20973. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20974. var flares = scene.__webglFlares,
  20975. nFlares = flares.length;
  20976. if ( ! nFlares ) return;
  20977. var tempPosition = new THREE.Vector3();
  20978. var invAspect = viewportHeight / viewportWidth,
  20979. halfViewportWidth = viewportWidth * 0.5,
  20980. halfViewportHeight = viewportHeight * 0.5;
  20981. var size = 16 / viewportHeight,
  20982. scale = new THREE.Vector2( size * invAspect, size );
  20983. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20984. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20985. var uniforms = _lensFlare.uniforms,
  20986. attributes = _lensFlare.attributes;
  20987. // set _lensFlare program and reset blending
  20988. _gl.useProgram( _lensFlare.program );
  20989. if ( ! _lensFlare.attributesEnabled ) {
  20990. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20991. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20992. _lensFlare.attributesEnabled = true;
  20993. }
  20994. // loop through all lens flares to update their occlusion and positions
  20995. // setup gl and common used attribs/unforms
  20996. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20997. _gl.uniform1i( uniforms.map, 1 );
  20998. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20999. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21000. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21001. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21002. _gl.disable( _gl.CULL_FACE );
  21003. _gl.depthMask( false );
  21004. var i, j, jl, flare, sprite;
  21005. for ( i = 0; i < nFlares; i ++ ) {
  21006. size = 16 / viewportHeight;
  21007. scale.set( size * invAspect, size );
  21008. // calc object screen position
  21009. flare = flares[ i ];
  21010. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21011. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21012. camera.projectionMatrix.multiplyVector3( tempPosition );
  21013. // setup arrays for gl programs
  21014. screenPosition.copy( tempPosition )
  21015. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21016. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21017. // screen cull
  21018. if ( _lensFlare.hasVertexTexture || (
  21019. screenPositionPixels.x > 0 &&
  21020. screenPositionPixels.x < viewportWidth &&
  21021. screenPositionPixels.y > 0 &&
  21022. screenPositionPixels.y < viewportHeight ) ) {
  21023. // save current RGB to temp texture
  21024. _gl.activeTexture( _gl.TEXTURE1 );
  21025. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21026. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21027. // render pink quad
  21028. _gl.uniform1i( uniforms.renderType, 0 );
  21029. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21030. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21031. _gl.disable( _gl.BLEND );
  21032. _gl.enable( _gl.DEPTH_TEST );
  21033. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21034. // copy result to occlusionMap
  21035. _gl.activeTexture( _gl.TEXTURE0 );
  21036. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21037. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21038. // restore graphics
  21039. _gl.uniform1i( uniforms.renderType, 1 );
  21040. _gl.disable( _gl.DEPTH_TEST );
  21041. _gl.activeTexture( _gl.TEXTURE1 );
  21042. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21043. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21044. // update object positions
  21045. flare.positionScreen.copy( screenPosition )
  21046. if ( flare.customUpdateCallback ) {
  21047. flare.customUpdateCallback( flare );
  21048. } else {
  21049. flare.updateLensFlares();
  21050. }
  21051. // render flares
  21052. _gl.uniform1i( uniforms.renderType, 2 );
  21053. _gl.enable( _gl.BLEND );
  21054. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21055. sprite = flare.lensFlares[ j ];
  21056. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21057. screenPosition.x = sprite.x;
  21058. screenPosition.y = sprite.y;
  21059. screenPosition.z = sprite.z;
  21060. size = sprite.size * sprite.scale / viewportHeight;
  21061. scale.x = size * invAspect;
  21062. scale.y = size;
  21063. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21064. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21065. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21066. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21067. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21068. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21069. _renderer.setTexture( sprite.texture, 1 );
  21070. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21071. }
  21072. }
  21073. }
  21074. }
  21075. // restore gl
  21076. _gl.enable( _gl.CULL_FACE );
  21077. _gl.enable( _gl.DEPTH_TEST );
  21078. _gl.depthMask( true );
  21079. };
  21080. function createProgram ( shader ) {
  21081. var program = _gl.createProgram();
  21082. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21083. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21084. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21085. _gl.shaderSource( vertexShader, shader.vertexShader );
  21086. _gl.compileShader( fragmentShader );
  21087. _gl.compileShader( vertexShader );
  21088. _gl.attachShader( program, fragmentShader );
  21089. _gl.attachShader( program, vertexShader );
  21090. _gl.linkProgram( program );
  21091. return program;
  21092. };
  21093. };/**
  21094. * @author alteredq / http://alteredqualia.com/
  21095. */
  21096. THREE.ShadowMapPlugin = function ( ) {
  21097. var _gl,
  21098. _renderer,
  21099. _depthMaterial, _depthMaterialMorph,
  21100. _frustum = new THREE.Frustum(),
  21101. _projScreenMatrix = new THREE.Matrix4(),
  21102. _min = new THREE.Vector3(),
  21103. _max = new THREE.Vector3();
  21104. this.init = function ( renderer ) {
  21105. _gl = renderer.context;
  21106. _renderer = renderer;
  21107. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21108. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21109. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21110. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21111. _depthMaterial._shadowPass = true;
  21112. _depthMaterialMorph._shadowPass = true;
  21113. };
  21114. this.render = function ( scene, camera ) {
  21115. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21116. this.update( scene, camera );
  21117. };
  21118. this.update = function ( scene, camera ) {
  21119. var i, il, j, jl, n,
  21120. shadowMap, shadowMatrix, shadowCamera,
  21121. program, buffer, material,
  21122. webglObject, object, light,
  21123. renderList,
  21124. lights = [],
  21125. k = 0,
  21126. fog = null;
  21127. // set GL state for depth map
  21128. _gl.clearColor( 1, 1, 1, 1 );
  21129. _gl.disable( _gl.BLEND );
  21130. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.FRONT );
  21131. _renderer.setDepthTest( true );
  21132. // preprocess lights
  21133. // - skip lights that are not casting shadows
  21134. // - create virtual lights for cascaded shadow maps
  21135. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21136. light = scene.__lights[ i ];
  21137. if ( ! light.castShadow ) continue;
  21138. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21139. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21140. var virtualLight;
  21141. if ( ! light.shadowCascadeArray[ n ] ) {
  21142. virtualLight = createVirtualLight( light, n );
  21143. virtualLight.originalCamera = camera;
  21144. var gyro = new THREE.Gyroscope();
  21145. gyro.position = light.shadowCascadeOffset;
  21146. gyro.add( virtualLight );
  21147. gyro.add( virtualLight.target );
  21148. camera.add( gyro );
  21149. light.shadowCascadeArray[ n ] = virtualLight;
  21150. console.log( "Created virtualLight", virtualLight );
  21151. } else {
  21152. virtualLight = light.shadowCascadeArray[ n ];
  21153. }
  21154. updateVirtualLight( light, n );
  21155. lights[ k ] = virtualLight;
  21156. k ++;
  21157. }
  21158. } else {
  21159. lights[ k ] = light;
  21160. k ++;
  21161. }
  21162. }
  21163. // render depth map
  21164. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21165. light = lights[ i ];
  21166. if ( ! light.shadowMap ) {
  21167. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21168. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21169. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21170. light.shadowMatrix = new THREE.Matrix4();
  21171. }
  21172. if ( ! light.shadowCamera ) {
  21173. if ( light instanceof THREE.SpotLight ) {
  21174. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21175. } else if ( light instanceof THREE.DirectionalLight ) {
  21176. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21177. } else {
  21178. console.error( "Unsupported light type for shadow" );
  21179. continue;
  21180. }
  21181. scene.add( light.shadowCamera );
  21182. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21183. }
  21184. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21185. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21186. light.shadowCamera.add( light.cameraHelper );
  21187. }
  21188. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21189. updateShadowCamera( camera, light );
  21190. }
  21191. shadowMap = light.shadowMap;
  21192. shadowMatrix = light.shadowMatrix;
  21193. shadowCamera = light.shadowCamera;
  21194. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21195. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21196. shadowCamera.updateMatrixWorld();
  21197. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21198. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  21199. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21200. // compute shadow matrix
  21201. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21202. 0.0, 0.5, 0.0, 0.5,
  21203. 0.0, 0.0, 0.5, 0.5,
  21204. 0.0, 0.0, 0.0, 1.0 );
  21205. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21206. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21207. // update camera matrices and frustum
  21208. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  21209. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  21210. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  21211. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  21212. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21213. _frustum.setFromMatrix( _projScreenMatrix );
  21214. // render shadow map
  21215. _renderer.setRenderTarget( shadowMap );
  21216. _renderer.clear();
  21217. // set object matrices & frustum culling
  21218. renderList = scene.__webglObjects;
  21219. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21220. webglObject = renderList[ j ];
  21221. object = webglObject.object;
  21222. webglObject.render = false;
  21223. if ( object.visible && object.castShadow ) {
  21224. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21225. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21226. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  21227. webglObject.render = true;
  21228. }
  21229. }
  21230. }
  21231. // render regular objects
  21232. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21233. webglObject = renderList[ j ];
  21234. if ( webglObject.render ) {
  21235. object = webglObject.object;
  21236. buffer = webglObject.buffer;
  21237. _renderer.setObjectFaces( object );
  21238. if ( object.customDepthMaterial ) {
  21239. material = object.customDepthMaterial;
  21240. } else if ( object.geometry.morphTargets.length ) {
  21241. material = _depthMaterialMorph;
  21242. } else {
  21243. material = _depthMaterial;
  21244. }
  21245. if ( buffer instanceof THREE.BufferGeometry ) {
  21246. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21247. } else {
  21248. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21249. }
  21250. }
  21251. }
  21252. // set matrices and render immediate objects
  21253. renderList = scene.__webglObjectsImmediate;
  21254. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21255. webglObject = renderList[ j ];
  21256. object = webglObject.object;
  21257. if ( object.visible && object.castShadow ) {
  21258. if( object.matrixAutoUpdate ) {
  21259. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21260. }
  21261. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  21262. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21263. }
  21264. }
  21265. }
  21266. // restore GL state
  21267. var clearColor = _renderer.getClearColor(),
  21268. clearAlpha = _renderer.getClearAlpha();
  21269. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21270. _gl.enable( _gl.BLEND );
  21271. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.BACK );
  21272. };
  21273. function createVirtualLight( light, cascade ) {
  21274. var virtualLight = new THREE.DirectionalLight();
  21275. virtualLight.isVirtual = true;
  21276. virtualLight.onlyShadow = true;
  21277. virtualLight.castShadow = true;
  21278. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21279. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21280. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21281. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21282. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21283. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21284. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21285. virtualLight.shadowDarkness = light.shadowDarkness;
  21286. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21287. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21288. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21289. virtualLight.pointsWorld = [];
  21290. virtualLight.pointsFrustum = [];
  21291. var pointsWorld = virtualLight.pointsWorld,
  21292. pointsFrustum = virtualLight.pointsFrustum;
  21293. for ( var i = 0; i < 8; i ++ ) {
  21294. pointsWorld[ i ] = new THREE.Vector3();
  21295. pointsFrustum[ i ] = new THREE.Vector3();
  21296. }
  21297. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21298. var farZ = light.shadowCascadeFarZ[ cascade ];
  21299. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21300. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21301. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21302. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21303. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21304. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21305. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21306. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21307. return virtualLight;
  21308. }
  21309. // Synchronize virtual light with the original light
  21310. function updateVirtualLight( light, cascade ) {
  21311. var virtualLight = light.shadowCascadeArray[ cascade ];
  21312. virtualLight.position.copy( light.position );
  21313. virtualLight.target.position.copy( light.target.position );
  21314. virtualLight.lookAt( virtualLight.target );
  21315. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21316. virtualLight.shadowDarkness = light.shadowDarkness;
  21317. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21318. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21319. var farZ = light.shadowCascadeFarZ[ cascade ];
  21320. var pointsFrustum = virtualLight.pointsFrustum;
  21321. pointsFrustum[ 0 ].z = nearZ;
  21322. pointsFrustum[ 1 ].z = nearZ;
  21323. pointsFrustum[ 2 ].z = nearZ;
  21324. pointsFrustum[ 3 ].z = nearZ;
  21325. pointsFrustum[ 4 ].z = farZ;
  21326. pointsFrustum[ 5 ].z = farZ;
  21327. pointsFrustum[ 6 ].z = farZ;
  21328. pointsFrustum[ 7 ].z = farZ;
  21329. }
  21330. // Fit shadow camera's ortho frustum to camera frustum
  21331. function updateShadowCamera( camera, light ) {
  21332. var shadowCamera = light.shadowCamera,
  21333. pointsFrustum = light.pointsFrustum,
  21334. pointsWorld = light.pointsWorld;
  21335. _min.set( Infinity, Infinity, Infinity );
  21336. _max.set( -Infinity, -Infinity, -Infinity );
  21337. for ( var i = 0; i < 8; i ++ ) {
  21338. var p = pointsWorld[ i ];
  21339. p.copy( pointsFrustum[ i ] );
  21340. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21341. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21342. if ( p.x < _min.x ) _min.x = p.x;
  21343. if ( p.x > _max.x ) _max.x = p.x;
  21344. if ( p.y < _min.y ) _min.y = p.y;
  21345. if ( p.y > _max.y ) _max.y = p.y;
  21346. if ( p.z < _min.z ) _min.z = p.z;
  21347. if ( p.z > _max.z ) _max.z = p.z;
  21348. }
  21349. shadowCamera.left = _min.x;
  21350. shadowCamera.right = _max.x;
  21351. shadowCamera.top = _max.y;
  21352. shadowCamera.bottom = _min.y;
  21353. // can't really fit near/far
  21354. //shadowCamera.near = _min.z;
  21355. //shadowCamera.far = _max.z;
  21356. shadowCamera.updateProjectionMatrix();
  21357. }
  21358. };
  21359. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21360. /**
  21361. * @author mikael emtinger / http://gomo.se/
  21362. * @author alteredq / http://alteredqualia.com/
  21363. */
  21364. THREE.SpritePlugin = function ( ) {
  21365. var _gl, _renderer, _sprite = {};
  21366. this.init = function ( renderer ) {
  21367. _gl = renderer.context;
  21368. _renderer = renderer;
  21369. _sprite.vertices = new Float32Array( 8 + 8 );
  21370. _sprite.faces = new Uint16Array( 6 );
  21371. var i = 0;
  21372. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21373. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 0
  21374. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21375. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 1
  21376. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21377. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 2
  21378. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21379. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 3
  21380. i = 0;
  21381. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21382. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21383. _sprite.vertexBuffer = _gl.createBuffer();
  21384. _sprite.elementBuffer = _gl.createBuffer();
  21385. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21386. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21387. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21388. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21389. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21390. _sprite.attributes = {};
  21391. _sprite.uniforms = {};
  21392. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21393. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21394. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21395. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21396. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21397. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21398. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21399. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21400. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21401. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21402. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21403. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  21404. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21405. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21406. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21407. _sprite.attributesEnabled = false;
  21408. };
  21409. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21410. var sprites = scene.__webglSprites,
  21411. nSprites = sprites.length;
  21412. if ( ! nSprites ) return;
  21413. var attributes = _sprite.attributes,
  21414. uniforms = _sprite.uniforms;
  21415. var invAspect = viewportHeight / viewportWidth;
  21416. var halfViewportWidth = viewportWidth * 0.5,
  21417. halfViewportHeight = viewportHeight * 0.5;
  21418. var mergeWith3D = true;
  21419. // setup gl
  21420. _gl.useProgram( _sprite.program );
  21421. if ( ! _sprite.attributesEnabled ) {
  21422. _gl.enableVertexAttribArray( attributes.position );
  21423. _gl.enableVertexAttribArray( attributes.uv );
  21424. _sprite.attributesEnabled = true;
  21425. }
  21426. _gl.disable( _gl.CULL_FACE );
  21427. _gl.enable( _gl.BLEND );
  21428. _gl.depthMask( true );
  21429. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21430. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21431. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21432. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21433. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  21434. _gl.activeTexture( _gl.TEXTURE0 );
  21435. _gl.uniform1i( uniforms.map, 0 );
  21436. // update positions and sort
  21437. var i, sprite, screenPosition, size, scale = [];
  21438. for( i = 0; i < nSprites; i ++ ) {
  21439. sprite = sprites[ i ];
  21440. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21441. if( ! sprite.useScreenCoordinates ) {
  21442. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld);
  21443. sprite.z = - sprite._modelViewMatrix.elements[14];
  21444. } else {
  21445. sprite.z = - sprite.position.z;
  21446. }
  21447. }
  21448. sprites.sort( painterSort );
  21449. // render all sprites
  21450. for( i = 0; i < nSprites; i ++ ) {
  21451. sprite = sprites[ i ];
  21452. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21453. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  21454. if ( sprite.useScreenCoordinates ) {
  21455. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21456. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21457. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21458. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  21459. } else {
  21460. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21461. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  21462. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements);
  21463. }
  21464. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  21465. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21466. scale[ 1 ] = size * sprite.scale.y;
  21467. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  21468. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  21469. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  21470. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21471. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21472. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21473. _gl.uniform2fv( uniforms.scale, scale );
  21474. if ( sprite.mergeWith3D && !mergeWith3D ) {
  21475. _gl.enable( _gl.DEPTH_TEST );
  21476. mergeWith3D = true;
  21477. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  21478. _gl.disable( _gl.DEPTH_TEST );
  21479. mergeWith3D = false;
  21480. }
  21481. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21482. _renderer.setTexture( sprite.map, 0 );
  21483. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21484. }
  21485. }
  21486. // restore gl
  21487. _gl.enable( _gl.CULL_FACE );
  21488. _gl.enable( _gl.DEPTH_TEST );
  21489. _gl.depthMask( true );
  21490. };
  21491. function createProgram ( shader ) {
  21492. var program = _gl.createProgram();
  21493. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21494. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21495. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21496. _gl.shaderSource( vertexShader, shader.vertexShader );
  21497. _gl.compileShader( fragmentShader );
  21498. _gl.compileShader( vertexShader );
  21499. _gl.attachShader( program, fragmentShader );
  21500. _gl.attachShader( program, vertexShader );
  21501. _gl.linkProgram( program );
  21502. return program;
  21503. };
  21504. function painterSort ( a, b ) {
  21505. return b.z - a.z;
  21506. };
  21507. };/**
  21508. * @author alteredq / http://alteredqualia.com/
  21509. */
  21510. THREE.DepthPassPlugin = function ( ) {
  21511. this.enabled = false;
  21512. this.renderTarget = null;
  21513. var _gl,
  21514. _renderer,
  21515. _depthMaterial, _depthMaterialMorph,
  21516. _frustum = new THREE.Frustum(),
  21517. _projScreenMatrix = new THREE.Matrix4();
  21518. this.init = function ( renderer ) {
  21519. _gl = renderer.context;
  21520. _renderer = renderer;
  21521. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21522. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21523. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21524. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21525. _depthMaterial._shadowPass = true;
  21526. _depthMaterialMorph._shadowPass = true;
  21527. };
  21528. this.render = function ( scene, camera ) {
  21529. if ( ! this.enabled ) return;
  21530. this.update( scene, camera );
  21531. };
  21532. this.update = function ( scene, camera ) {
  21533. var i, il, j, jl, n,
  21534. program, buffer, material,
  21535. webglObject, object, light,
  21536. renderList,
  21537. fog = null;
  21538. // set GL state for depth map
  21539. _gl.clearColor( 1, 1, 1, 1 );
  21540. _gl.disable( _gl.BLEND );
  21541. _renderer.setDepthTest( true );
  21542. // update scene
  21543. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21544. // update camera matrices and frustum
  21545. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21546. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21547. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21548. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21549. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21550. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21551. _frustum.setFromMatrix( _projScreenMatrix );
  21552. // render depth map
  21553. _renderer.setRenderTarget( this.renderTarget );
  21554. _renderer.clear();
  21555. // set object matrices & frustum culling
  21556. renderList = scene.__webglObjects;
  21557. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21558. webglObject = renderList[ j ];
  21559. object = webglObject.object;
  21560. webglObject.render = false;
  21561. if ( object.visible ) {
  21562. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21563. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21564. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21565. webglObject.render = true;
  21566. }
  21567. }
  21568. }
  21569. // render regular objects
  21570. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21571. webglObject = renderList[ j ];
  21572. if ( webglObject.render ) {
  21573. object = webglObject.object;
  21574. buffer = webglObject.buffer;
  21575. _renderer.setObjectFaces( object );
  21576. if ( object.customDepthMaterial ) {
  21577. material = object.customDepthMaterial;
  21578. } else if ( object.geometry.morphTargets.length ) {
  21579. material = _depthMaterialMorph;
  21580. } else {
  21581. material = _depthMaterial;
  21582. }
  21583. if ( buffer instanceof THREE.BufferGeometry ) {
  21584. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21585. } else {
  21586. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21587. }
  21588. }
  21589. }
  21590. // set matrices and render immediate objects
  21591. renderList = scene.__webglObjectsImmediate;
  21592. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21593. webglObject = renderList[ j ];
  21594. object = webglObject.object;
  21595. if ( object.visible && object.castShadow ) {
  21596. if( object.matrixAutoUpdate ) {
  21597. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21598. }
  21599. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21600. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21601. }
  21602. }
  21603. // restore GL state
  21604. var clearColor = _renderer.getClearColor(),
  21605. clearAlpha = _renderer.getClearAlpha();
  21606. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21607. _gl.enable( _gl.BLEND );
  21608. };
  21609. };
  21610. /**
  21611. * @author mrdoob / http://mrdoob.com/
  21612. * @author marklundin / http://mark-lundin.com/
  21613. * @author alteredq / http://alteredqualia.com/
  21614. */
  21615. if ( THREE.WebGLRenderer ) {
  21616. THREE.AnaglyphWebGLRenderer = function ( parameters ) {
  21617. THREE.WebGLRenderer.call( this, parameters );
  21618. this.autoUpdateScene = false;
  21619. var _this = this, _setSize = this.setSize, _render = this.render;
  21620. var _cameraL = new THREE.PerspectiveCamera(),
  21621. _cameraR = new THREE.PerspectiveCamera();
  21622. var eyeRight = new THREE.Matrix4(),
  21623. eyeLeft = new THREE.Matrix4(),
  21624. focalLength = 125,
  21625. _aspect, _near, _far, _fov;
  21626. _cameraL.matrixAutoUpdate = _cameraR.matrixAutoUpdate = false;
  21627. var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  21628. var _renderTargetL = new THREE.WebGLRenderTarget( 512, 512, _params ),
  21629. _renderTargetR = new THREE.WebGLRenderTarget( 512, 512, _params );
  21630. var _camera = new THREE.PerspectiveCamera( 53, 1, 1, 10000 );
  21631. _camera.position.z = 2;
  21632. var _material = new THREE.ShaderMaterial( {
  21633. uniforms: {
  21634. "mapLeft": { type: "t", value: 0, texture: _renderTargetL },
  21635. "mapRight": { type: "t", value: 1, texture: _renderTargetR }
  21636. },
  21637. vertexShader: [
  21638. "varying vec2 vUv;",
  21639. "void main() {",
  21640. "vUv = vec2( uv.x, 1.0 - uv.y );",
  21641. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  21642. "}"
  21643. ].join("\n"),
  21644. fragmentShader: [
  21645. "uniform sampler2D mapLeft;",
  21646. "uniform sampler2D mapRight;",
  21647. "varying vec2 vUv;",
  21648. "void main() {",
  21649. "vec4 colorL, colorR;",
  21650. "vec2 uv = vUv;",
  21651. "colorL = texture2D( mapLeft, uv );",
  21652. "colorR = texture2D( mapRight, uv );",
  21653. // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
  21654. "gl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;",
  21655. "}"
  21656. ].join("\n")
  21657. } );
  21658. var _scene = new THREE.Scene();
  21659. var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _material );
  21660. mesh.rotation.x = Math.PI / 2;
  21661. _scene.add( mesh );
  21662. _scene.add( _camera );
  21663. this.setSize = function ( width, height ) {
  21664. _setSize.call( _this, width, height );
  21665. _renderTargetL.width = width;
  21666. _renderTargetL.height = height;
  21667. _renderTargetR.width = width;
  21668. _renderTargetR.height = height;
  21669. };
  21670. /*
  21671. * Renderer now uses an asymmetric perspective projection (http://paulbourke.net/miscellaneous/stereographics/stereorender/).
  21672. * Each camera is offset by the eye seperation and its projection matrix is also skewed asymetrically back to converge on the same
  21673. * projection plane. Added a focal length parameter to, this is where the parallax is equal to 0.
  21674. */
  21675. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21676. scene.updateMatrixWorld();
  21677. var hasCameraChanged = ( _aspect !== camera.aspect ) || ( _near !== camera.near ) || ( _far !== camera.far ) || ( _fov !== camera.fov );
  21678. if( hasCameraChanged ) {
  21679. _aspect = camera.aspect;
  21680. _near = camera.near;
  21681. _far = camera.far;
  21682. _fov = camera.fov;
  21683. var projectionMatrix = camera.projectionMatrix.clone(),
  21684. eyeSep = focalLength / 30 * 0.5,
  21685. eyeSepOnProjection = eyeSep * _near / focalLength,
  21686. ymax = _near * Math.tan( _fov * Math.PI / 360 ),
  21687. xmin, xmax;
  21688. // translate xOffset
  21689. eyeRight.elements[12] = eyeSep;
  21690. eyeLeft.elements[12] = -eyeSep;
  21691. // for left eye
  21692. xmin = -ymax * _aspect + eyeSepOnProjection;
  21693. xmax = ymax * _aspect + eyeSepOnProjection;
  21694. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21695. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21696. _cameraL.projectionMatrix.copy( projectionMatrix );
  21697. // for right eye
  21698. xmin = -ymax * _aspect - eyeSepOnProjection;
  21699. xmax = ymax * _aspect - eyeSepOnProjection;
  21700. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21701. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21702. _cameraR.projectionMatrix.copy( projectionMatrix );
  21703. }
  21704. _cameraL.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeLeft );
  21705. _cameraL.position.copy( camera.position );
  21706. _cameraL.near = camera.near;
  21707. _cameraL.far = camera.far;
  21708. _render.call( _this, scene, _cameraL, _renderTargetL, true );
  21709. _cameraR.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeRight );
  21710. _cameraR.position.copy( camera.position );
  21711. _cameraR.near = camera.near;
  21712. _cameraR.far = camera.far;
  21713. _render.call( _this, scene, _cameraR, _renderTargetR, true );
  21714. _scene.updateMatrixWorld();
  21715. _render.call( _this, _scene, _camera );
  21716. };
  21717. };
  21718. };
  21719. /**
  21720. * @author alteredq / http://alteredqualia.com/
  21721. */
  21722. if ( THREE.WebGLRenderer ) {
  21723. THREE.CrosseyedWebGLRenderer = function ( parameters ) {
  21724. THREE.WebGLRenderer.call( this, parameters );
  21725. this.autoClear = false;
  21726. var _this = this, _setSize = this.setSize, _render = this.render;
  21727. var _width, _height;
  21728. var _cameraL = new THREE.PerspectiveCamera();
  21729. _cameraL.target = new THREE.Vector3( 0, 0, 0 );
  21730. var _cameraR = new THREE.PerspectiveCamera();
  21731. _cameraR.target = new THREE.Vector3( 0, 0, 0 );
  21732. _this.separation = 10;
  21733. if ( parameters && parameters.separation !== undefined ) _this.separation = parameters.separation;
  21734. var SCREEN_WIDTH = window.innerWidth;
  21735. var SCREEN_HEIGHT = window.innerHeight;
  21736. var HALF_WIDTH = SCREEN_WIDTH / 2;
  21737. this.setSize = function ( width, height ) {
  21738. _setSize.call( _this, width, height );
  21739. _width = width/2;
  21740. _height = height;
  21741. };
  21742. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21743. this.clear();
  21744. _cameraL.fov = camera.fov;
  21745. _cameraL.aspect = 0.5 * camera.aspect;
  21746. _cameraL.near = camera.near;
  21747. _cameraL.far = camera.far;
  21748. _cameraL.updateProjectionMatrix();
  21749. _cameraL.position.copy( camera.position );
  21750. _cameraL.target.copy( camera.target );
  21751. _cameraL.translateX( _this.separation );
  21752. _cameraL.lookAt( _cameraL.target );
  21753. _cameraR.projectionMatrix = _cameraL.projectionMatrix;
  21754. _cameraR.position.copy( camera.position );
  21755. _cameraR.target.copy( camera.target );
  21756. _cameraR.translateX( - _this.separation );
  21757. _cameraR.lookAt( _cameraR.target );
  21758. this.setViewport( 0, 0, _width, _height );
  21759. _render.call( _this, scene, _cameraL );
  21760. this.setViewport( _width, 0, _width, _height );
  21761. _render.call( _this, scene, _cameraR, false );
  21762. };
  21763. };
  21764. }
  21765. /**
  21766. * @author mikael emtinger / http://gomo.se/
  21767. *
  21768. */
  21769. THREE.ShaderFlares = {
  21770. 'lensFlareVertexTexture': {
  21771. vertexShader: [
  21772. "uniform vec3 screenPosition;",
  21773. "uniform vec2 scale;",
  21774. "uniform float rotation;",
  21775. "uniform int renderType;",
  21776. "uniform sampler2D occlusionMap;",
  21777. "attribute vec2 position;",
  21778. "attribute vec2 uv;",
  21779. "varying vec2 vUV;",
  21780. "varying float vVisibility;",
  21781. "void main() {",
  21782. "vUV = uv;",
  21783. "vec2 pos = position;",
  21784. "if( renderType == 2 ) {",
  21785. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21786. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21787. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21788. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21789. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21790. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21791. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21792. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21793. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21794. "vVisibility = ( visibility.r / 9.0 ) *",
  21795. "( 1.0 - visibility.g / 9.0 ) *",
  21796. "( visibility.b / 9.0 ) *",
  21797. "( 1.0 - visibility.a / 9.0 );",
  21798. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21799. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21800. "}",
  21801. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21802. "}"
  21803. ].join( "\n" ),
  21804. fragmentShader: [
  21805. "precision mediump float;",
  21806. "uniform sampler2D map;",
  21807. "uniform float opacity;",
  21808. "uniform int renderType;",
  21809. "uniform vec3 color;",
  21810. "varying vec2 vUV;",
  21811. "varying float vVisibility;",
  21812. "void main() {",
  21813. // pink square
  21814. "if( renderType == 0 ) {",
  21815. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21816. // restore
  21817. "} else if( renderType == 1 ) {",
  21818. "gl_FragColor = texture2D( map, vUV );",
  21819. // flare
  21820. "} else {",
  21821. "vec4 texture = texture2D( map, vUV );",
  21822. "texture.a *= opacity * vVisibility;",
  21823. "gl_FragColor = texture;",
  21824. "gl_FragColor.rgb *= color;",
  21825. "}",
  21826. "}"
  21827. ].join( "\n" )
  21828. },
  21829. 'lensFlare': {
  21830. vertexShader: [
  21831. "uniform vec3 screenPosition;",
  21832. "uniform vec2 scale;",
  21833. "uniform float rotation;",
  21834. "uniform int renderType;",
  21835. "attribute vec2 position;",
  21836. "attribute vec2 uv;",
  21837. "varying vec2 vUV;",
  21838. "void main() {",
  21839. "vUV = uv;",
  21840. "vec2 pos = position;",
  21841. "if( renderType == 2 ) {",
  21842. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21843. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21844. "}",
  21845. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21846. "}"
  21847. ].join( "\n" ),
  21848. fragmentShader: [
  21849. "precision mediump float;",
  21850. "uniform sampler2D map;",
  21851. "uniform sampler2D occlusionMap;",
  21852. "uniform float opacity;",
  21853. "uniform int renderType;",
  21854. "uniform vec3 color;",
  21855. "varying vec2 vUV;",
  21856. "void main() {",
  21857. // pink square
  21858. "if( renderType == 0 ) {",
  21859. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21860. // restore
  21861. "} else if( renderType == 1 ) {",
  21862. "gl_FragColor = texture2D( map, vUV );",
  21863. // flare
  21864. "} else {",
  21865. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21866. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21867. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21868. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21869. "visibility = ( 1.0 - visibility / 4.0 );",
  21870. "vec4 texture = texture2D( map, vUV );",
  21871. "texture.a *= opacity * visibility;",
  21872. "gl_FragColor = texture;",
  21873. "gl_FragColor.rgb *= color;",
  21874. "}",
  21875. "}"
  21876. ].join( "\n" )
  21877. }
  21878. };
  21879. /**
  21880. * @author mikael emtinger / http://gomo.se/
  21881. *
  21882. */
  21883. THREE.ShaderSprite = {
  21884. 'sprite': {
  21885. vertexShader: [
  21886. "uniform int useScreenCoordinates;",
  21887. "uniform int affectedByDistance;",
  21888. "uniform vec3 screenPosition;",
  21889. "uniform mat4 modelViewMatrix;",
  21890. "uniform mat4 projectionMatrix;",
  21891. "uniform float rotation;",
  21892. "uniform vec2 scale;",
  21893. "uniform vec2 alignment;",
  21894. "uniform vec2 uvOffset;",
  21895. "uniform vec2 uvScale;",
  21896. "attribute vec2 position;",
  21897. "attribute vec2 uv;",
  21898. "varying vec2 vUV;",
  21899. "void main() {",
  21900. "vUV = uvOffset + uv * uvScale;",
  21901. "vec2 alignedPosition = position + alignment;",
  21902. "vec2 rotatedPosition;",
  21903. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21904. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21905. "vec4 finalPosition;",
  21906. "if( useScreenCoordinates != 0 ) {",
  21907. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21908. "} else {",
  21909. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21910. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21911. "}",
  21912. "gl_Position = finalPosition;",
  21913. "}"
  21914. ].join( "\n" ),
  21915. fragmentShader: [
  21916. "precision mediump float;",
  21917. "uniform vec3 color;",
  21918. "uniform sampler2D map;",
  21919. "uniform float opacity;",
  21920. "varying vec2 vUV;",
  21921. "void main() {",
  21922. "vec4 texture = texture2D( map, vUV );",
  21923. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21924. "}"
  21925. ].join( "\n" )
  21926. }
  21927. };
粤ICP备19079148号