three.module.js 976 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954
  1. // Polyfills
  2. if ( Number.EPSILON === undefined ) {
  3. Number.EPSILON = Math.pow( 2, - 52 );
  4. }
  5. //
  6. if ( Math.sign === undefined ) {
  7. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  8. Math.sign = function ( x ) {
  9. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  10. };
  11. }
  12. if ( Function.prototype.name === undefined ) {
  13. // Missing in IE9-11.
  14. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  15. Object.defineProperty( Function.prototype, 'name', {
  16. get: function () {
  17. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  18. }
  19. } );
  20. }
  21. if ( Object.assign === undefined ) {
  22. // Missing in IE.
  23. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  24. ( function () {
  25. Object.assign = function ( target ) {
  26. 'use strict';
  27. if ( target === undefined || target === null ) {
  28. throw new TypeError( 'Cannot convert undefined or null to object' );
  29. }
  30. var output = Object( target );
  31. for ( var index = 1; index < arguments.length; index ++ ) {
  32. var source = arguments[ index ];
  33. if ( source !== undefined && source !== null ) {
  34. for ( var nextKey in source ) {
  35. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  36. output[ nextKey ] = source[ nextKey ];
  37. }
  38. }
  39. }
  40. }
  41. return output;
  42. };
  43. } )();
  44. }
  45. /**
  46. * https://github.com/mrdoob/eventdispatcher.js/
  47. */
  48. function EventDispatcher() {}
  49. Object.assign( EventDispatcher.prototype, {
  50. addEventListener: function ( type, listener ) {
  51. if ( this._listeners === undefined ) this._listeners = {};
  52. var listeners = this._listeners;
  53. if ( listeners[ type ] === undefined ) {
  54. listeners[ type ] = [];
  55. }
  56. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  57. listeners[ type ].push( listener );
  58. }
  59. },
  60. hasEventListener: function ( type, listener ) {
  61. if ( this._listeners === undefined ) return false;
  62. var listeners = this._listeners;
  63. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  64. },
  65. removeEventListener: function ( type, listener ) {
  66. if ( this._listeners === undefined ) return;
  67. var listeners = this._listeners;
  68. var listenerArray = listeners[ type ];
  69. if ( listenerArray !== undefined ) {
  70. var index = listenerArray.indexOf( listener );
  71. if ( index !== - 1 ) {
  72. listenerArray.splice( index, 1 );
  73. }
  74. }
  75. },
  76. dispatchEvent: function ( event ) {
  77. if ( this._listeners === undefined ) return;
  78. var listeners = this._listeners;
  79. var listenerArray = listeners[ event.type ];
  80. if ( listenerArray !== undefined ) {
  81. event.target = this;
  82. var array = [], i = 0;
  83. var length = listenerArray.length;
  84. for ( i = 0; i < length; i ++ ) {
  85. array[ i ] = listenerArray[ i ];
  86. }
  87. for ( i = 0; i < length; i ++ ) {
  88. array[ i ].call( this, event );
  89. }
  90. }
  91. }
  92. } );
  93. var REVISION = '83';
  94. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  95. var CullFaceNone = 0;
  96. var CullFaceBack = 1;
  97. var CullFaceFront = 2;
  98. var CullFaceFrontBack = 3;
  99. var FrontFaceDirectionCW = 0;
  100. var FrontFaceDirectionCCW = 1;
  101. var BasicShadowMap = 0;
  102. var PCFShadowMap = 1;
  103. var PCFSoftShadowMap = 2;
  104. var FrontSide = 0;
  105. var BackSide = 1;
  106. var DoubleSide = 2;
  107. var FlatShading = 1;
  108. var SmoothShading = 2;
  109. var NoColors = 0;
  110. var FaceColors = 1;
  111. var VertexColors = 2;
  112. var NoBlending = 0;
  113. var NormalBlending = 1;
  114. var AdditiveBlending = 2;
  115. var SubtractiveBlending = 3;
  116. var MultiplyBlending = 4;
  117. var CustomBlending = 5;
  118. var BlendingMode = {
  119. NoBlending: NoBlending,
  120. NormalBlending: NormalBlending,
  121. AdditiveBlending: AdditiveBlending,
  122. SubtractiveBlending: SubtractiveBlending,
  123. MultiplyBlending: MultiplyBlending,
  124. CustomBlending: CustomBlending
  125. };
  126. var AddEquation = 100;
  127. var SubtractEquation = 101;
  128. var ReverseSubtractEquation = 102;
  129. var MinEquation = 103;
  130. var MaxEquation = 104;
  131. var ZeroFactor = 200;
  132. var OneFactor = 201;
  133. var SrcColorFactor = 202;
  134. var OneMinusSrcColorFactor = 203;
  135. var SrcAlphaFactor = 204;
  136. var OneMinusSrcAlphaFactor = 205;
  137. var DstAlphaFactor = 206;
  138. var OneMinusDstAlphaFactor = 207;
  139. var DstColorFactor = 208;
  140. var OneMinusDstColorFactor = 209;
  141. var SrcAlphaSaturateFactor = 210;
  142. var NeverDepth = 0;
  143. var AlwaysDepth = 1;
  144. var LessDepth = 2;
  145. var LessEqualDepth = 3;
  146. var EqualDepth = 4;
  147. var GreaterEqualDepth = 5;
  148. var GreaterDepth = 6;
  149. var NotEqualDepth = 7;
  150. var MultiplyOperation = 0;
  151. var MixOperation = 1;
  152. var AddOperation = 2;
  153. var NoToneMapping = 0;
  154. var LinearToneMapping = 1;
  155. var ReinhardToneMapping = 2;
  156. var Uncharted2ToneMapping = 3;
  157. var CineonToneMapping = 4;
  158. var UVMapping = 300;
  159. var CubeReflectionMapping = 301;
  160. var CubeRefractionMapping = 302;
  161. var EquirectangularReflectionMapping = 303;
  162. var EquirectangularRefractionMapping = 304;
  163. var SphericalReflectionMapping = 305;
  164. var CubeUVReflectionMapping = 306;
  165. var CubeUVRefractionMapping = 307;
  166. var TextureMapping = {
  167. UVMapping: UVMapping,
  168. CubeReflectionMapping: CubeReflectionMapping,
  169. CubeRefractionMapping: CubeRefractionMapping,
  170. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  171. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  172. SphericalReflectionMapping: SphericalReflectionMapping,
  173. CubeUVReflectionMapping: CubeUVReflectionMapping,
  174. CubeUVRefractionMapping: CubeUVRefractionMapping
  175. };
  176. var RepeatWrapping = 1000;
  177. var ClampToEdgeWrapping = 1001;
  178. var MirroredRepeatWrapping = 1002;
  179. var TextureWrapping = {
  180. RepeatWrapping: RepeatWrapping,
  181. ClampToEdgeWrapping: ClampToEdgeWrapping,
  182. MirroredRepeatWrapping: MirroredRepeatWrapping
  183. };
  184. var NearestFilter = 1003;
  185. var NearestMipMapNearestFilter = 1004;
  186. var NearestMipMapLinearFilter = 1005;
  187. var LinearFilter = 1006;
  188. var LinearMipMapNearestFilter = 1007;
  189. var LinearMipMapLinearFilter = 1008;
  190. var TextureFilter = {
  191. NearestFilter: NearestFilter,
  192. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  193. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  194. LinearFilter: LinearFilter,
  195. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  196. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  197. };
  198. var UnsignedByteType = 1009;
  199. var ByteType = 1010;
  200. var ShortType = 1011;
  201. var UnsignedShortType = 1012;
  202. var IntType = 1013;
  203. var UnsignedIntType = 1014;
  204. var FloatType = 1015;
  205. var HalfFloatType = 1016;
  206. var UnsignedShort4444Type = 1017;
  207. var UnsignedShort5551Type = 1018;
  208. var UnsignedShort565Type = 1019;
  209. var UnsignedInt248Type = 1020;
  210. var AlphaFormat = 1021;
  211. var RGBFormat = 1022;
  212. var RGBAFormat = 1023;
  213. var LuminanceFormat = 1024;
  214. var LuminanceAlphaFormat = 1025;
  215. var RGBEFormat = RGBAFormat;
  216. var DepthFormat = 1026;
  217. var DepthStencilFormat = 1027;
  218. var RGB_S3TC_DXT1_Format = 2001;
  219. var RGBA_S3TC_DXT1_Format = 2002;
  220. var RGBA_S3TC_DXT3_Format = 2003;
  221. var RGBA_S3TC_DXT5_Format = 2004;
  222. var RGB_PVRTC_4BPPV1_Format = 2100;
  223. var RGB_PVRTC_2BPPV1_Format = 2101;
  224. var RGBA_PVRTC_4BPPV1_Format = 2102;
  225. var RGBA_PVRTC_2BPPV1_Format = 2103;
  226. var RGB_ETC1_Format = 2151;
  227. var LoopOnce = 2200;
  228. var LoopRepeat = 2201;
  229. var LoopPingPong = 2202;
  230. var InterpolateDiscrete = 2300;
  231. var InterpolateLinear = 2301;
  232. var InterpolateSmooth = 2302;
  233. var ZeroCurvatureEnding = 2400;
  234. var ZeroSlopeEnding = 2401;
  235. var WrapAroundEnding = 2402;
  236. var TrianglesDrawMode = 0;
  237. var TriangleStripDrawMode = 1;
  238. var TriangleFanDrawMode = 2;
  239. var LinearEncoding = 3000;
  240. var sRGBEncoding = 3001;
  241. var GammaEncoding = 3007;
  242. var RGBEEncoding = 3002;
  243. var LogLuvEncoding = 3003;
  244. var RGBM7Encoding = 3004;
  245. var RGBM16Encoding = 3005;
  246. var RGBDEncoding = 3006;
  247. var BasicDepthPacking = 3200;
  248. var RGBADepthPacking = 3201;
  249. /**
  250. * @author alteredq / http://alteredqualia.com/
  251. * @author mrdoob / http://mrdoob.com/
  252. */
  253. var _Math = {
  254. DEG2RAD: Math.PI / 180,
  255. RAD2DEG: 180 / Math.PI,
  256. generateUUID: function () {
  257. // http://www.broofa.com/Tools/Math.uuid.htm
  258. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  259. var uuid = new Array( 36 );
  260. var rnd = 0, r;
  261. return function generateUUID() {
  262. for ( var i = 0; i < 36; i ++ ) {
  263. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  264. uuid[ i ] = '-';
  265. } else if ( i === 14 ) {
  266. uuid[ i ] = '4';
  267. } else {
  268. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  269. r = rnd & 0xf;
  270. rnd = rnd >> 4;
  271. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  272. }
  273. }
  274. return uuid.join( '' );
  275. };
  276. }(),
  277. clamp: function ( value, min, max ) {
  278. return Math.max( min, Math.min( max, value ) );
  279. },
  280. // compute euclidian modulo of m % n
  281. // https://en.wikipedia.org/wiki/Modulo_operation
  282. euclideanModulo: function ( n, m ) {
  283. return ( ( n % m ) + m ) % m;
  284. },
  285. // Linear mapping from range <a1, a2> to range <b1, b2>
  286. mapLinear: function ( x, a1, a2, b1, b2 ) {
  287. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  288. },
  289. // https://en.wikipedia.org/wiki/Linear_interpolation
  290. lerp: function ( x, y, t ) {
  291. return ( 1 - t ) * x + t * y;
  292. },
  293. // http://en.wikipedia.org/wiki/Smoothstep
  294. smoothstep: function ( x, min, max ) {
  295. if ( x <= min ) return 0;
  296. if ( x >= max ) return 1;
  297. x = ( x - min ) / ( max - min );
  298. return x * x * ( 3 - 2 * x );
  299. },
  300. smootherstep: function ( x, min, max ) {
  301. if ( x <= min ) return 0;
  302. if ( x >= max ) return 1;
  303. x = ( x - min ) / ( max - min );
  304. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  305. },
  306. // Random integer from <low, high> interval
  307. randInt: function ( low, high ) {
  308. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  309. },
  310. // Random float from <low, high> interval
  311. randFloat: function ( low, high ) {
  312. return low + Math.random() * ( high - low );
  313. },
  314. // Random float from <-range/2, range/2> interval
  315. randFloatSpread: function ( range ) {
  316. return range * ( 0.5 - Math.random() );
  317. },
  318. degToRad: function ( degrees ) {
  319. return degrees * _Math.DEG2RAD;
  320. },
  321. radToDeg: function ( radians ) {
  322. return radians * _Math.RAD2DEG;
  323. },
  324. isPowerOfTwo: function ( value ) {
  325. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  326. },
  327. nearestPowerOfTwo: function ( value ) {
  328. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  329. },
  330. nextPowerOfTwo: function ( value ) {
  331. value --;
  332. value |= value >> 1;
  333. value |= value >> 2;
  334. value |= value >> 4;
  335. value |= value >> 8;
  336. value |= value >> 16;
  337. value ++;
  338. return value;
  339. }
  340. };
  341. /**
  342. * @author mrdoob / http://mrdoob.com/
  343. * @author philogb / http://blog.thejit.org/
  344. * @author egraether / http://egraether.com/
  345. * @author zz85 / http://www.lab4games.net/zz85/blog
  346. */
  347. function Vector2( x, y ) {
  348. this.x = x || 0;
  349. this.y = y || 0;
  350. }
  351. Vector2.prototype = {
  352. constructor: Vector2,
  353. isVector2: true,
  354. get width() {
  355. return this.x;
  356. },
  357. set width( value ) {
  358. this.x = value;
  359. },
  360. get height() {
  361. return this.y;
  362. },
  363. set height( value ) {
  364. this.y = value;
  365. },
  366. //
  367. set: function ( x, y ) {
  368. this.x = x;
  369. this.y = y;
  370. return this;
  371. },
  372. setScalar: function ( scalar ) {
  373. this.x = scalar;
  374. this.y = scalar;
  375. return this;
  376. },
  377. setX: function ( x ) {
  378. this.x = x;
  379. return this;
  380. },
  381. setY: function ( y ) {
  382. this.y = y;
  383. return this;
  384. },
  385. setComponent: function ( index, value ) {
  386. switch ( index ) {
  387. case 0: this.x = value; break;
  388. case 1: this.y = value; break;
  389. default: throw new Error( 'index is out of range: ' + index );
  390. }
  391. return this;
  392. },
  393. getComponent: function ( index ) {
  394. switch ( index ) {
  395. case 0: return this.x;
  396. case 1: return this.y;
  397. default: throw new Error( 'index is out of range: ' + index );
  398. }
  399. },
  400. clone: function () {
  401. return new this.constructor( this.x, this.y );
  402. },
  403. copy: function ( v ) {
  404. this.x = v.x;
  405. this.y = v.y;
  406. return this;
  407. },
  408. add: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  411. return this.addVectors( v, w );
  412. }
  413. this.x += v.x;
  414. this.y += v.y;
  415. return this;
  416. },
  417. addScalar: function ( s ) {
  418. this.x += s;
  419. this.y += s;
  420. return this;
  421. },
  422. addVectors: function ( a, b ) {
  423. this.x = a.x + b.x;
  424. this.y = a.y + b.y;
  425. return this;
  426. },
  427. addScaledVector: function ( v, s ) {
  428. this.x += v.x * s;
  429. this.y += v.y * s;
  430. return this;
  431. },
  432. sub: function ( v, w ) {
  433. if ( w !== undefined ) {
  434. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  435. return this.subVectors( v, w );
  436. }
  437. this.x -= v.x;
  438. this.y -= v.y;
  439. return this;
  440. },
  441. subScalar: function ( s ) {
  442. this.x -= s;
  443. this.y -= s;
  444. return this;
  445. },
  446. subVectors: function ( a, b ) {
  447. this.x = a.x - b.x;
  448. this.y = a.y - b.y;
  449. return this;
  450. },
  451. multiply: function ( v ) {
  452. this.x *= v.x;
  453. this.y *= v.y;
  454. return this;
  455. },
  456. multiplyScalar: function ( scalar ) {
  457. if ( isFinite( scalar ) ) {
  458. this.x *= scalar;
  459. this.y *= scalar;
  460. } else {
  461. this.x = 0;
  462. this.y = 0;
  463. }
  464. return this;
  465. },
  466. divide: function ( v ) {
  467. this.x /= v.x;
  468. this.y /= v.y;
  469. return this;
  470. },
  471. divideScalar: function ( scalar ) {
  472. return this.multiplyScalar( 1 / scalar );
  473. },
  474. min: function ( v ) {
  475. this.x = Math.min( this.x, v.x );
  476. this.y = Math.min( this.y, v.y );
  477. return this;
  478. },
  479. max: function ( v ) {
  480. this.x = Math.max( this.x, v.x );
  481. this.y = Math.max( this.y, v.y );
  482. return this;
  483. },
  484. clamp: function ( min, max ) {
  485. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  486. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  487. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  488. return this;
  489. },
  490. clampScalar: function () {
  491. var min, max;
  492. return function clampScalar( minVal, maxVal ) {
  493. if ( min === undefined ) {
  494. min = new Vector2();
  495. max = new Vector2();
  496. }
  497. min.set( minVal, minVal );
  498. max.set( maxVal, maxVal );
  499. return this.clamp( min, max );
  500. };
  501. }(),
  502. clampLength: function ( min, max ) {
  503. var length = this.length();
  504. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  505. },
  506. floor: function () {
  507. this.x = Math.floor( this.x );
  508. this.y = Math.floor( this.y );
  509. return this;
  510. },
  511. ceil: function () {
  512. this.x = Math.ceil( this.x );
  513. this.y = Math.ceil( this.y );
  514. return this;
  515. },
  516. round: function () {
  517. this.x = Math.round( this.x );
  518. this.y = Math.round( this.y );
  519. return this;
  520. },
  521. roundToZero: function () {
  522. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  523. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  524. return this;
  525. },
  526. negate: function () {
  527. this.x = - this.x;
  528. this.y = - this.y;
  529. return this;
  530. },
  531. dot: function ( v ) {
  532. return this.x * v.x + this.y * v.y;
  533. },
  534. lengthSq: function () {
  535. return this.x * this.x + this.y * this.y;
  536. },
  537. length: function () {
  538. return Math.sqrt( this.x * this.x + this.y * this.y );
  539. },
  540. lengthManhattan: function() {
  541. return Math.abs( this.x ) + Math.abs( this.y );
  542. },
  543. normalize: function () {
  544. return this.divideScalar( this.length() );
  545. },
  546. angle: function () {
  547. // computes the angle in radians with respect to the positive x-axis
  548. var angle = Math.atan2( this.y, this.x );
  549. if ( angle < 0 ) angle += 2 * Math.PI;
  550. return angle;
  551. },
  552. distanceTo: function ( v ) {
  553. return Math.sqrt( this.distanceToSquared( v ) );
  554. },
  555. distanceToSquared: function ( v ) {
  556. var dx = this.x - v.x, dy = this.y - v.y;
  557. return dx * dx + dy * dy;
  558. },
  559. distanceToManhattan: function ( v ) {
  560. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  561. },
  562. setLength: function ( length ) {
  563. return this.multiplyScalar( length / this.length() );
  564. },
  565. lerp: function ( v, alpha ) {
  566. this.x += ( v.x - this.x ) * alpha;
  567. this.y += ( v.y - this.y ) * alpha;
  568. return this;
  569. },
  570. lerpVectors: function ( v1, v2, alpha ) {
  571. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  572. },
  573. equals: function ( v ) {
  574. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  575. },
  576. fromArray: function ( array, offset ) {
  577. if ( offset === undefined ) offset = 0;
  578. this.x = array[ offset ];
  579. this.y = array[ offset + 1 ];
  580. return this;
  581. },
  582. toArray: function ( array, offset ) {
  583. if ( array === undefined ) array = [];
  584. if ( offset === undefined ) offset = 0;
  585. array[ offset ] = this.x;
  586. array[ offset + 1 ] = this.y;
  587. return array;
  588. },
  589. fromAttribute: function ( attribute, index, offset ) {
  590. if ( offset !== undefined ) {
  591. console.warn( 'THREE.Vector2: offset has been removed from .fromAttribute().' );
  592. }
  593. this.x = attribute.getX( index );
  594. this.y = attribute.getY( index );
  595. return this;
  596. },
  597. rotateAround: function ( center, angle ) {
  598. var c = Math.cos( angle ), s = Math.sin( angle );
  599. var x = this.x - center.x;
  600. var y = this.y - center.y;
  601. this.x = x * c - y * s + center.x;
  602. this.y = x * s + y * c + center.y;
  603. return this;
  604. }
  605. };
  606. /**
  607. * @author mrdoob / http://mrdoob.com/
  608. * @author alteredq / http://alteredqualia.com/
  609. * @author szimek / https://github.com/szimek/
  610. */
  611. var textureId = 0;
  612. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  613. Object.defineProperty( this, 'id', { value: textureId ++ } );
  614. this.uuid = _Math.generateUUID();
  615. this.name = '';
  616. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  617. this.mipmaps = [];
  618. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  619. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  620. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  621. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  622. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  623. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  624. this.format = format !== undefined ? format : RGBAFormat;
  625. this.type = type !== undefined ? type : UnsignedByteType;
  626. this.offset = new Vector2( 0, 0 );
  627. this.repeat = new Vector2( 1, 1 );
  628. this.generateMipmaps = true;
  629. this.premultiplyAlpha = false;
  630. this.flipY = true;
  631. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  632. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  633. //
  634. // Also changing the encoding after already used by a Material will not automatically make the Material
  635. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  636. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  637. this.version = 0;
  638. this.onUpdate = null;
  639. }
  640. Texture.DEFAULT_IMAGE = undefined;
  641. Texture.DEFAULT_MAPPING = UVMapping;
  642. Texture.prototype = {
  643. constructor: Texture,
  644. isTexture: true,
  645. set needsUpdate( value ) {
  646. if ( value === true ) this.version ++;
  647. },
  648. clone: function () {
  649. return new this.constructor().copy( this );
  650. },
  651. copy: function ( source ) {
  652. this.image = source.image;
  653. this.mipmaps = source.mipmaps.slice( 0 );
  654. this.mapping = source.mapping;
  655. this.wrapS = source.wrapS;
  656. this.wrapT = source.wrapT;
  657. this.magFilter = source.magFilter;
  658. this.minFilter = source.minFilter;
  659. this.anisotropy = source.anisotropy;
  660. this.format = source.format;
  661. this.type = source.type;
  662. this.offset.copy( source.offset );
  663. this.repeat.copy( source.repeat );
  664. this.generateMipmaps = source.generateMipmaps;
  665. this.premultiplyAlpha = source.premultiplyAlpha;
  666. this.flipY = source.flipY;
  667. this.unpackAlignment = source.unpackAlignment;
  668. this.encoding = source.encoding;
  669. return this;
  670. },
  671. toJSON: function ( meta ) {
  672. if ( meta.textures[ this.uuid ] !== undefined ) {
  673. return meta.textures[ this.uuid ];
  674. }
  675. function getDataURL( image ) {
  676. var canvas;
  677. if ( image.toDataURL !== undefined ) {
  678. canvas = image;
  679. } else {
  680. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  681. canvas.width = image.width;
  682. canvas.height = image.height;
  683. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  684. }
  685. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  686. return canvas.toDataURL( 'image/jpeg', 0.6 );
  687. } else {
  688. return canvas.toDataURL( 'image/png' );
  689. }
  690. }
  691. var output = {
  692. metadata: {
  693. version: 4.4,
  694. type: 'Texture',
  695. generator: 'Texture.toJSON'
  696. },
  697. uuid: this.uuid,
  698. name: this.name,
  699. mapping: this.mapping,
  700. repeat: [ this.repeat.x, this.repeat.y ],
  701. offset: [ this.offset.x, this.offset.y ],
  702. wrap: [ this.wrapS, this.wrapT ],
  703. minFilter: this.minFilter,
  704. magFilter: this.magFilter,
  705. anisotropy: this.anisotropy,
  706. flipY: this.flipY
  707. };
  708. if ( this.image !== undefined ) {
  709. // TODO: Move to THREE.Image
  710. var image = this.image;
  711. if ( image.uuid === undefined ) {
  712. image.uuid = _Math.generateUUID(); // UGH
  713. }
  714. if ( meta.images[ image.uuid ] === undefined ) {
  715. meta.images[ image.uuid ] = {
  716. uuid: image.uuid,
  717. url: getDataURL( image )
  718. };
  719. }
  720. output.image = image.uuid;
  721. }
  722. meta.textures[ this.uuid ] = output;
  723. return output;
  724. },
  725. dispose: function () {
  726. this.dispatchEvent( { type: 'dispose' } );
  727. },
  728. transformUv: function ( uv ) {
  729. if ( this.mapping !== UVMapping ) return;
  730. uv.multiply( this.repeat );
  731. uv.add( this.offset );
  732. if ( uv.x < 0 || uv.x > 1 ) {
  733. switch ( this.wrapS ) {
  734. case RepeatWrapping:
  735. uv.x = uv.x - Math.floor( uv.x );
  736. break;
  737. case ClampToEdgeWrapping:
  738. uv.x = uv.x < 0 ? 0 : 1;
  739. break;
  740. case MirroredRepeatWrapping:
  741. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  742. uv.x = Math.ceil( uv.x ) - uv.x;
  743. } else {
  744. uv.x = uv.x - Math.floor( uv.x );
  745. }
  746. break;
  747. }
  748. }
  749. if ( uv.y < 0 || uv.y > 1 ) {
  750. switch ( this.wrapT ) {
  751. case RepeatWrapping:
  752. uv.y = uv.y - Math.floor( uv.y );
  753. break;
  754. case ClampToEdgeWrapping:
  755. uv.y = uv.y < 0 ? 0 : 1;
  756. break;
  757. case MirroredRepeatWrapping:
  758. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  759. uv.y = Math.ceil( uv.y ) - uv.y;
  760. } else {
  761. uv.y = uv.y - Math.floor( uv.y );
  762. }
  763. break;
  764. }
  765. }
  766. if ( this.flipY ) {
  767. uv.y = 1 - uv.y;
  768. }
  769. }
  770. };
  771. Object.assign( Texture.prototype, EventDispatcher.prototype );
  772. /**
  773. * @author supereggbert / http://www.paulbrunt.co.uk/
  774. * @author philogb / http://blog.thejit.org/
  775. * @author mikael emtinger / http://gomo.se/
  776. * @author egraether / http://egraether.com/
  777. * @author WestLangley / http://github.com/WestLangley
  778. */
  779. function Vector4( x, y, z, w ) {
  780. this.x = x || 0;
  781. this.y = y || 0;
  782. this.z = z || 0;
  783. this.w = ( w !== undefined ) ? w : 1;
  784. }
  785. Vector4.prototype = {
  786. constructor: Vector4,
  787. isVector4: true,
  788. set: function ( x, y, z, w ) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. this.w = w;
  793. return this;
  794. },
  795. setScalar: function ( scalar ) {
  796. this.x = scalar;
  797. this.y = scalar;
  798. this.z = scalar;
  799. this.w = scalar;
  800. return this;
  801. },
  802. setX: function ( x ) {
  803. this.x = x;
  804. return this;
  805. },
  806. setY: function ( y ) {
  807. this.y = y;
  808. return this;
  809. },
  810. setZ: function ( z ) {
  811. this.z = z;
  812. return this;
  813. },
  814. setW: function ( w ) {
  815. this.w = w;
  816. return this;
  817. },
  818. setComponent: function ( index, value ) {
  819. switch ( index ) {
  820. case 0: this.x = value; break;
  821. case 1: this.y = value; break;
  822. case 2: this.z = value; break;
  823. case 3: this.w = value; break;
  824. default: throw new Error( 'index is out of range: ' + index );
  825. }
  826. return this;
  827. },
  828. getComponent: function ( index ) {
  829. switch ( index ) {
  830. case 0: return this.x;
  831. case 1: return this.y;
  832. case 2: return this.z;
  833. case 3: return this.w;
  834. default: throw new Error( 'index is out of range: ' + index );
  835. }
  836. },
  837. clone: function () {
  838. return new this.constructor( this.x, this.y, this.z, this.w );
  839. },
  840. copy: function ( v ) {
  841. this.x = v.x;
  842. this.y = v.y;
  843. this.z = v.z;
  844. this.w = ( v.w !== undefined ) ? v.w : 1;
  845. return this;
  846. },
  847. add: function ( v, w ) {
  848. if ( w !== undefined ) {
  849. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  850. return this.addVectors( v, w );
  851. }
  852. this.x += v.x;
  853. this.y += v.y;
  854. this.z += v.z;
  855. this.w += v.w;
  856. return this;
  857. },
  858. addScalar: function ( s ) {
  859. this.x += s;
  860. this.y += s;
  861. this.z += s;
  862. this.w += s;
  863. return this;
  864. },
  865. addVectors: function ( a, b ) {
  866. this.x = a.x + b.x;
  867. this.y = a.y + b.y;
  868. this.z = a.z + b.z;
  869. this.w = a.w + b.w;
  870. return this;
  871. },
  872. addScaledVector: function ( v, s ) {
  873. this.x += v.x * s;
  874. this.y += v.y * s;
  875. this.z += v.z * s;
  876. this.w += v.w * s;
  877. return this;
  878. },
  879. sub: function ( v, w ) {
  880. if ( w !== undefined ) {
  881. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  882. return this.subVectors( v, w );
  883. }
  884. this.x -= v.x;
  885. this.y -= v.y;
  886. this.z -= v.z;
  887. this.w -= v.w;
  888. return this;
  889. },
  890. subScalar: function ( s ) {
  891. this.x -= s;
  892. this.y -= s;
  893. this.z -= s;
  894. this.w -= s;
  895. return this;
  896. },
  897. subVectors: function ( a, b ) {
  898. this.x = a.x - b.x;
  899. this.y = a.y - b.y;
  900. this.z = a.z - b.z;
  901. this.w = a.w - b.w;
  902. return this;
  903. },
  904. multiplyScalar: function ( scalar ) {
  905. if ( isFinite( scalar ) ) {
  906. this.x *= scalar;
  907. this.y *= scalar;
  908. this.z *= scalar;
  909. this.w *= scalar;
  910. } else {
  911. this.x = 0;
  912. this.y = 0;
  913. this.z = 0;
  914. this.w = 0;
  915. }
  916. return this;
  917. },
  918. applyMatrix4: function ( m ) {
  919. var x = this.x, y = this.y, z = this.z, w = this.w;
  920. var e = m.elements;
  921. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  922. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  923. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  924. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  925. return this;
  926. },
  927. divideScalar: function ( scalar ) {
  928. return this.multiplyScalar( 1 / scalar );
  929. },
  930. setAxisAngleFromQuaternion: function ( q ) {
  931. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  932. // q is assumed to be normalized
  933. this.w = 2 * Math.acos( q.w );
  934. var s = Math.sqrt( 1 - q.w * q.w );
  935. if ( s < 0.0001 ) {
  936. this.x = 1;
  937. this.y = 0;
  938. this.z = 0;
  939. } else {
  940. this.x = q.x / s;
  941. this.y = q.y / s;
  942. this.z = q.z / s;
  943. }
  944. return this;
  945. },
  946. setAxisAngleFromRotationMatrix: function ( m ) {
  947. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  948. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  949. var angle, x, y, z, // variables for result
  950. epsilon = 0.01, // margin to allow for rounding errors
  951. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  952. te = m.elements,
  953. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  954. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  955. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  956. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  957. ( Math.abs( m13 - m31 ) < epsilon ) &&
  958. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  959. // singularity found
  960. // first check for identity matrix which must have +1 for all terms
  961. // in leading diagonal and zero in other terms
  962. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  963. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  964. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  965. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  966. // this singularity is identity matrix so angle = 0
  967. this.set( 1, 0, 0, 0 );
  968. return this; // zero angle, arbitrary axis
  969. }
  970. // otherwise this singularity is angle = 180
  971. angle = Math.PI;
  972. var xx = ( m11 + 1 ) / 2;
  973. var yy = ( m22 + 1 ) / 2;
  974. var zz = ( m33 + 1 ) / 2;
  975. var xy = ( m12 + m21 ) / 4;
  976. var xz = ( m13 + m31 ) / 4;
  977. var yz = ( m23 + m32 ) / 4;
  978. if ( ( xx > yy ) && ( xx > zz ) ) {
  979. // m11 is the largest diagonal term
  980. if ( xx < epsilon ) {
  981. x = 0;
  982. y = 0.707106781;
  983. z = 0.707106781;
  984. } else {
  985. x = Math.sqrt( xx );
  986. y = xy / x;
  987. z = xz / x;
  988. }
  989. } else if ( yy > zz ) {
  990. // m22 is the largest diagonal term
  991. if ( yy < epsilon ) {
  992. x = 0.707106781;
  993. y = 0;
  994. z = 0.707106781;
  995. } else {
  996. y = Math.sqrt( yy );
  997. x = xy / y;
  998. z = yz / y;
  999. }
  1000. } else {
  1001. // m33 is the largest diagonal term so base result on this
  1002. if ( zz < epsilon ) {
  1003. x = 0.707106781;
  1004. y = 0.707106781;
  1005. z = 0;
  1006. } else {
  1007. z = Math.sqrt( zz );
  1008. x = xz / z;
  1009. y = yz / z;
  1010. }
  1011. }
  1012. this.set( x, y, z, angle );
  1013. return this; // return 180 deg rotation
  1014. }
  1015. // as we have reached here there are no singularities so we can handle normally
  1016. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1017. ( m13 - m31 ) * ( m13 - m31 ) +
  1018. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1019. if ( Math.abs( s ) < 0.001 ) s = 1;
  1020. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1021. // caught by singularity test above, but I've left it in just in case
  1022. this.x = ( m32 - m23 ) / s;
  1023. this.y = ( m13 - m31 ) / s;
  1024. this.z = ( m21 - m12 ) / s;
  1025. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1026. return this;
  1027. },
  1028. min: function ( v ) {
  1029. this.x = Math.min( this.x, v.x );
  1030. this.y = Math.min( this.y, v.y );
  1031. this.z = Math.min( this.z, v.z );
  1032. this.w = Math.min( this.w, v.w );
  1033. return this;
  1034. },
  1035. max: function ( v ) {
  1036. this.x = Math.max( this.x, v.x );
  1037. this.y = Math.max( this.y, v.y );
  1038. this.z = Math.max( this.z, v.z );
  1039. this.w = Math.max( this.w, v.w );
  1040. return this;
  1041. },
  1042. clamp: function ( min, max ) {
  1043. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1044. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1045. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1046. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1047. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1048. return this;
  1049. },
  1050. clampScalar: function () {
  1051. var min, max;
  1052. return function clampScalar( minVal, maxVal ) {
  1053. if ( min === undefined ) {
  1054. min = new Vector4();
  1055. max = new Vector4();
  1056. }
  1057. min.set( minVal, minVal, minVal, minVal );
  1058. max.set( maxVal, maxVal, maxVal, maxVal );
  1059. return this.clamp( min, max );
  1060. };
  1061. }(),
  1062. floor: function () {
  1063. this.x = Math.floor( this.x );
  1064. this.y = Math.floor( this.y );
  1065. this.z = Math.floor( this.z );
  1066. this.w = Math.floor( this.w );
  1067. return this;
  1068. },
  1069. ceil: function () {
  1070. this.x = Math.ceil( this.x );
  1071. this.y = Math.ceil( this.y );
  1072. this.z = Math.ceil( this.z );
  1073. this.w = Math.ceil( this.w );
  1074. return this;
  1075. },
  1076. round: function () {
  1077. this.x = Math.round( this.x );
  1078. this.y = Math.round( this.y );
  1079. this.z = Math.round( this.z );
  1080. this.w = Math.round( this.w );
  1081. return this;
  1082. },
  1083. roundToZero: function () {
  1084. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1085. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1086. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1087. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1088. return this;
  1089. },
  1090. negate: function () {
  1091. this.x = - this.x;
  1092. this.y = - this.y;
  1093. this.z = - this.z;
  1094. this.w = - this.w;
  1095. return this;
  1096. },
  1097. dot: function ( v ) {
  1098. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1099. },
  1100. lengthSq: function () {
  1101. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1102. },
  1103. length: function () {
  1104. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1105. },
  1106. lengthManhattan: function () {
  1107. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1108. },
  1109. normalize: function () {
  1110. return this.divideScalar( this.length() );
  1111. },
  1112. setLength: function ( length ) {
  1113. return this.multiplyScalar( length / this.length() );
  1114. },
  1115. lerp: function ( v, alpha ) {
  1116. this.x += ( v.x - this.x ) * alpha;
  1117. this.y += ( v.y - this.y ) * alpha;
  1118. this.z += ( v.z - this.z ) * alpha;
  1119. this.w += ( v.w - this.w ) * alpha;
  1120. return this;
  1121. },
  1122. lerpVectors: function ( v1, v2, alpha ) {
  1123. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1124. },
  1125. equals: function ( v ) {
  1126. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1127. },
  1128. fromArray: function ( array, offset ) {
  1129. if ( offset === undefined ) offset = 0;
  1130. this.x = array[ offset ];
  1131. this.y = array[ offset + 1 ];
  1132. this.z = array[ offset + 2 ];
  1133. this.w = array[ offset + 3 ];
  1134. return this;
  1135. },
  1136. toArray: function ( array, offset ) {
  1137. if ( array === undefined ) array = [];
  1138. if ( offset === undefined ) offset = 0;
  1139. array[ offset ] = this.x;
  1140. array[ offset + 1 ] = this.y;
  1141. array[ offset + 2 ] = this.z;
  1142. array[ offset + 3 ] = this.w;
  1143. return array;
  1144. },
  1145. fromAttribute: function ( attribute, index, offset ) {
  1146. if ( offset !== undefined ) {
  1147. console.warn( 'THREE.Vector4: offset has been removed from .fromAttribute().' );
  1148. }
  1149. this.x = attribute.getX( index );
  1150. this.y = attribute.getY( index );
  1151. this.z = attribute.getZ( index );
  1152. this.w = attribute.getW( index );
  1153. return this;
  1154. }
  1155. };
  1156. /**
  1157. * @author szimek / https://github.com/szimek/
  1158. * @author alteredq / http://alteredqualia.com/
  1159. * @author Marius Kintel / https://github.com/kintel
  1160. */
  1161. /*
  1162. In options, we can specify:
  1163. * Texture parameters for an auto-generated target texture
  1164. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1165. */
  1166. function WebGLRenderTarget( width, height, options ) {
  1167. this.uuid = _Math.generateUUID();
  1168. this.width = width;
  1169. this.height = height;
  1170. this.scissor = new Vector4( 0, 0, width, height );
  1171. this.scissorTest = false;
  1172. this.viewport = new Vector4( 0, 0, width, height );
  1173. options = options || {};
  1174. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1175. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1176. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1177. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1178. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1179. }
  1180. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1181. isWebGLRenderTarget: true,
  1182. setSize: function ( width, height ) {
  1183. if ( this.width !== width || this.height !== height ) {
  1184. this.width = width;
  1185. this.height = height;
  1186. this.dispose();
  1187. }
  1188. this.viewport.set( 0, 0, width, height );
  1189. this.scissor.set( 0, 0, width, height );
  1190. },
  1191. clone: function () {
  1192. return new this.constructor().copy( this );
  1193. },
  1194. copy: function ( source ) {
  1195. this.width = source.width;
  1196. this.height = source.height;
  1197. this.viewport.copy( source.viewport );
  1198. this.texture = source.texture.clone();
  1199. this.depthBuffer = source.depthBuffer;
  1200. this.stencilBuffer = source.stencilBuffer;
  1201. this.depthTexture = source.depthTexture;
  1202. return this;
  1203. },
  1204. dispose: function () {
  1205. this.dispatchEvent( { type: 'dispose' } );
  1206. }
  1207. } );
  1208. /**
  1209. * @author alteredq / http://alteredqualia.com
  1210. */
  1211. function WebGLRenderTargetCube( width, height, options ) {
  1212. WebGLRenderTarget.call( this, width, height, options );
  1213. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1214. this.activeMipMapLevel = 0;
  1215. }
  1216. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1217. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1218. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1219. /**
  1220. * @author mikael emtinger / http://gomo.se/
  1221. * @author alteredq / http://alteredqualia.com/
  1222. * @author WestLangley / http://github.com/WestLangley
  1223. * @author bhouston / http://clara.io
  1224. */
  1225. function Quaternion( x, y, z, w ) {
  1226. this._x = x || 0;
  1227. this._y = y || 0;
  1228. this._z = z || 0;
  1229. this._w = ( w !== undefined ) ? w : 1;
  1230. }
  1231. Quaternion.prototype = {
  1232. constructor: Quaternion,
  1233. get x () {
  1234. return this._x;
  1235. },
  1236. set x ( value ) {
  1237. this._x = value;
  1238. this.onChangeCallback();
  1239. },
  1240. get y () {
  1241. return this._y;
  1242. },
  1243. set y ( value ) {
  1244. this._y = value;
  1245. this.onChangeCallback();
  1246. },
  1247. get z () {
  1248. return this._z;
  1249. },
  1250. set z ( value ) {
  1251. this._z = value;
  1252. this.onChangeCallback();
  1253. },
  1254. get w () {
  1255. return this._w;
  1256. },
  1257. set w ( value ) {
  1258. this._w = value;
  1259. this.onChangeCallback();
  1260. },
  1261. set: function ( x, y, z, w ) {
  1262. this._x = x;
  1263. this._y = y;
  1264. this._z = z;
  1265. this._w = w;
  1266. this.onChangeCallback();
  1267. return this;
  1268. },
  1269. clone: function () {
  1270. return new this.constructor( this._x, this._y, this._z, this._w );
  1271. },
  1272. copy: function ( quaternion ) {
  1273. this._x = quaternion.x;
  1274. this._y = quaternion.y;
  1275. this._z = quaternion.z;
  1276. this._w = quaternion.w;
  1277. this.onChangeCallback();
  1278. return this;
  1279. },
  1280. setFromEuler: function ( euler, update ) {
  1281. if ( (euler && euler.isEuler) === false ) {
  1282. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1283. }
  1284. // http://www.mathworks.com/matlabcentral/fileexchange/
  1285. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1286. // content/SpinCalc.m
  1287. var c1 = Math.cos( euler._x / 2 );
  1288. var c2 = Math.cos( euler._y / 2 );
  1289. var c3 = Math.cos( euler._z / 2 );
  1290. var s1 = Math.sin( euler._x / 2 );
  1291. var s2 = Math.sin( euler._y / 2 );
  1292. var s3 = Math.sin( euler._z / 2 );
  1293. var order = euler.order;
  1294. if ( order === 'XYZ' ) {
  1295. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1296. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1297. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1298. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1299. } else if ( order === 'YXZ' ) {
  1300. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1301. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1302. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1303. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1304. } else if ( order === 'ZXY' ) {
  1305. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1306. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1307. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1308. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1309. } else if ( order === 'ZYX' ) {
  1310. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1311. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1312. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1313. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1314. } else if ( order === 'YZX' ) {
  1315. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1316. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1317. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1318. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1319. } else if ( order === 'XZY' ) {
  1320. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1321. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1322. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1323. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1324. }
  1325. if ( update !== false ) this.onChangeCallback();
  1326. return this;
  1327. },
  1328. setFromAxisAngle: function ( axis, angle ) {
  1329. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1330. // assumes axis is normalized
  1331. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1332. this._x = axis.x * s;
  1333. this._y = axis.y * s;
  1334. this._z = axis.z * s;
  1335. this._w = Math.cos( halfAngle );
  1336. this.onChangeCallback();
  1337. return this;
  1338. },
  1339. setFromRotationMatrix: function ( m ) {
  1340. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1341. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1342. var te = m.elements,
  1343. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1344. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1345. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1346. trace = m11 + m22 + m33,
  1347. s;
  1348. if ( trace > 0 ) {
  1349. s = 0.5 / Math.sqrt( trace + 1.0 );
  1350. this._w = 0.25 / s;
  1351. this._x = ( m32 - m23 ) * s;
  1352. this._y = ( m13 - m31 ) * s;
  1353. this._z = ( m21 - m12 ) * s;
  1354. } else if ( m11 > m22 && m11 > m33 ) {
  1355. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1356. this._w = ( m32 - m23 ) / s;
  1357. this._x = 0.25 * s;
  1358. this._y = ( m12 + m21 ) / s;
  1359. this._z = ( m13 + m31 ) / s;
  1360. } else if ( m22 > m33 ) {
  1361. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1362. this._w = ( m13 - m31 ) / s;
  1363. this._x = ( m12 + m21 ) / s;
  1364. this._y = 0.25 * s;
  1365. this._z = ( m23 + m32 ) / s;
  1366. } else {
  1367. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1368. this._w = ( m21 - m12 ) / s;
  1369. this._x = ( m13 + m31 ) / s;
  1370. this._y = ( m23 + m32 ) / s;
  1371. this._z = 0.25 * s;
  1372. }
  1373. this.onChangeCallback();
  1374. return this;
  1375. },
  1376. setFromUnitVectors: function () {
  1377. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1378. // assumes direction vectors vFrom and vTo are normalized
  1379. var v1, r;
  1380. var EPS = 0.000001;
  1381. return function setFromUnitVectors( vFrom, vTo ) {
  1382. if ( v1 === undefined ) v1 = new Vector3();
  1383. r = vFrom.dot( vTo ) + 1;
  1384. if ( r < EPS ) {
  1385. r = 0;
  1386. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1387. v1.set( - vFrom.y, vFrom.x, 0 );
  1388. } else {
  1389. v1.set( 0, - vFrom.z, vFrom.y );
  1390. }
  1391. } else {
  1392. v1.crossVectors( vFrom, vTo );
  1393. }
  1394. this._x = v1.x;
  1395. this._y = v1.y;
  1396. this._z = v1.z;
  1397. this._w = r;
  1398. return this.normalize();
  1399. };
  1400. }(),
  1401. inverse: function () {
  1402. return this.conjugate().normalize();
  1403. },
  1404. conjugate: function () {
  1405. this._x *= - 1;
  1406. this._y *= - 1;
  1407. this._z *= - 1;
  1408. this.onChangeCallback();
  1409. return this;
  1410. },
  1411. dot: function ( v ) {
  1412. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1413. },
  1414. lengthSq: function () {
  1415. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1416. },
  1417. length: function () {
  1418. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1419. },
  1420. normalize: function () {
  1421. var l = this.length();
  1422. if ( l === 0 ) {
  1423. this._x = 0;
  1424. this._y = 0;
  1425. this._z = 0;
  1426. this._w = 1;
  1427. } else {
  1428. l = 1 / l;
  1429. this._x = this._x * l;
  1430. this._y = this._y * l;
  1431. this._z = this._z * l;
  1432. this._w = this._w * l;
  1433. }
  1434. this.onChangeCallback();
  1435. return this;
  1436. },
  1437. multiply: function ( q, p ) {
  1438. if ( p !== undefined ) {
  1439. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1440. return this.multiplyQuaternions( q, p );
  1441. }
  1442. return this.multiplyQuaternions( this, q );
  1443. },
  1444. premultiply: function ( q ) {
  1445. return this.multiplyQuaternions( q, this );
  1446. },
  1447. multiplyQuaternions: function ( a, b ) {
  1448. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1449. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1450. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1451. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1452. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1453. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1454. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1455. this.onChangeCallback();
  1456. return this;
  1457. },
  1458. slerp: function ( qb, t ) {
  1459. if ( t === 0 ) return this;
  1460. if ( t === 1 ) return this.copy( qb );
  1461. var x = this._x, y = this._y, z = this._z, w = this._w;
  1462. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1463. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1464. if ( cosHalfTheta < 0 ) {
  1465. this._w = - qb._w;
  1466. this._x = - qb._x;
  1467. this._y = - qb._y;
  1468. this._z = - qb._z;
  1469. cosHalfTheta = - cosHalfTheta;
  1470. } else {
  1471. this.copy( qb );
  1472. }
  1473. if ( cosHalfTheta >= 1.0 ) {
  1474. this._w = w;
  1475. this._x = x;
  1476. this._y = y;
  1477. this._z = z;
  1478. return this;
  1479. }
  1480. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1481. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1482. this._w = 0.5 * ( w + this._w );
  1483. this._x = 0.5 * ( x + this._x );
  1484. this._y = 0.5 * ( y + this._y );
  1485. this._z = 0.5 * ( z + this._z );
  1486. return this;
  1487. }
  1488. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1489. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1490. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1491. this._w = ( w * ratioA + this._w * ratioB );
  1492. this._x = ( x * ratioA + this._x * ratioB );
  1493. this._y = ( y * ratioA + this._y * ratioB );
  1494. this._z = ( z * ratioA + this._z * ratioB );
  1495. this.onChangeCallback();
  1496. return this;
  1497. },
  1498. equals: function ( quaternion ) {
  1499. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1500. },
  1501. fromArray: function ( array, offset ) {
  1502. if ( offset === undefined ) offset = 0;
  1503. this._x = array[ offset ];
  1504. this._y = array[ offset + 1 ];
  1505. this._z = array[ offset + 2 ];
  1506. this._w = array[ offset + 3 ];
  1507. this.onChangeCallback();
  1508. return this;
  1509. },
  1510. toArray: function ( array, offset ) {
  1511. if ( array === undefined ) array = [];
  1512. if ( offset === undefined ) offset = 0;
  1513. array[ offset ] = this._x;
  1514. array[ offset + 1 ] = this._y;
  1515. array[ offset + 2 ] = this._z;
  1516. array[ offset + 3 ] = this._w;
  1517. return array;
  1518. },
  1519. onChange: function ( callback ) {
  1520. this.onChangeCallback = callback;
  1521. return this;
  1522. },
  1523. onChangeCallback: function () {}
  1524. };
  1525. Object.assign( Quaternion, {
  1526. slerp: function( qa, qb, qm, t ) {
  1527. return qm.copy( qa ).slerp( qb, t );
  1528. },
  1529. slerpFlat: function(
  1530. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1531. // fuzz-free, array-based Quaternion SLERP operation
  1532. var x0 = src0[ srcOffset0 + 0 ],
  1533. y0 = src0[ srcOffset0 + 1 ],
  1534. z0 = src0[ srcOffset0 + 2 ],
  1535. w0 = src0[ srcOffset0 + 3 ],
  1536. x1 = src1[ srcOffset1 + 0 ],
  1537. y1 = src1[ srcOffset1 + 1 ],
  1538. z1 = src1[ srcOffset1 + 2 ],
  1539. w1 = src1[ srcOffset1 + 3 ];
  1540. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1541. var s = 1 - t,
  1542. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1543. dir = ( cos >= 0 ? 1 : - 1 ),
  1544. sqrSin = 1 - cos * cos;
  1545. // Skip the Slerp for tiny steps to avoid numeric problems:
  1546. if ( sqrSin > Number.EPSILON ) {
  1547. var sin = Math.sqrt( sqrSin ),
  1548. len = Math.atan2( sin, cos * dir );
  1549. s = Math.sin( s * len ) / sin;
  1550. t = Math.sin( t * len ) / sin;
  1551. }
  1552. var tDir = t * dir;
  1553. x0 = x0 * s + x1 * tDir;
  1554. y0 = y0 * s + y1 * tDir;
  1555. z0 = z0 * s + z1 * tDir;
  1556. w0 = w0 * s + w1 * tDir;
  1557. // Normalize in case we just did a lerp:
  1558. if ( s === 1 - t ) {
  1559. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1560. x0 *= f;
  1561. y0 *= f;
  1562. z0 *= f;
  1563. w0 *= f;
  1564. }
  1565. }
  1566. dst[ dstOffset ] = x0;
  1567. dst[ dstOffset + 1 ] = y0;
  1568. dst[ dstOffset + 2 ] = z0;
  1569. dst[ dstOffset + 3 ] = w0;
  1570. }
  1571. } );
  1572. /**
  1573. * @author mrdoob / http://mrdoob.com/
  1574. * @author *kile / http://kile.stravaganza.org/
  1575. * @author philogb / http://blog.thejit.org/
  1576. * @author mikael emtinger / http://gomo.se/
  1577. * @author egraether / http://egraether.com/
  1578. * @author WestLangley / http://github.com/WestLangley
  1579. */
  1580. function Vector3( x, y, z ) {
  1581. this.x = x || 0;
  1582. this.y = y || 0;
  1583. this.z = z || 0;
  1584. }
  1585. Vector3.prototype = {
  1586. constructor: Vector3,
  1587. isVector3: true,
  1588. set: function ( x, y, z ) {
  1589. this.x = x;
  1590. this.y = y;
  1591. this.z = z;
  1592. return this;
  1593. },
  1594. setScalar: function ( scalar ) {
  1595. this.x = scalar;
  1596. this.y = scalar;
  1597. this.z = scalar;
  1598. return this;
  1599. },
  1600. setX: function ( x ) {
  1601. this.x = x;
  1602. return this;
  1603. },
  1604. setY: function ( y ) {
  1605. this.y = y;
  1606. return this;
  1607. },
  1608. setZ: function ( z ) {
  1609. this.z = z;
  1610. return this;
  1611. },
  1612. setComponent: function ( index, value ) {
  1613. switch ( index ) {
  1614. case 0: this.x = value; break;
  1615. case 1: this.y = value; break;
  1616. case 2: this.z = value; break;
  1617. default: throw new Error( 'index is out of range: ' + index );
  1618. }
  1619. return this;
  1620. },
  1621. getComponent: function ( index ) {
  1622. switch ( index ) {
  1623. case 0: return this.x;
  1624. case 1: return this.y;
  1625. case 2: return this.z;
  1626. default: throw new Error( 'index is out of range: ' + index );
  1627. }
  1628. },
  1629. clone: function () {
  1630. return new this.constructor( this.x, this.y, this.z );
  1631. },
  1632. copy: function ( v ) {
  1633. this.x = v.x;
  1634. this.y = v.y;
  1635. this.z = v.z;
  1636. return this;
  1637. },
  1638. add: function ( v, w ) {
  1639. if ( w !== undefined ) {
  1640. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1641. return this.addVectors( v, w );
  1642. }
  1643. this.x += v.x;
  1644. this.y += v.y;
  1645. this.z += v.z;
  1646. return this;
  1647. },
  1648. addScalar: function ( s ) {
  1649. this.x += s;
  1650. this.y += s;
  1651. this.z += s;
  1652. return this;
  1653. },
  1654. addVectors: function ( a, b ) {
  1655. this.x = a.x + b.x;
  1656. this.y = a.y + b.y;
  1657. this.z = a.z + b.z;
  1658. return this;
  1659. },
  1660. addScaledVector: function ( v, s ) {
  1661. this.x += v.x * s;
  1662. this.y += v.y * s;
  1663. this.z += v.z * s;
  1664. return this;
  1665. },
  1666. sub: function ( v, w ) {
  1667. if ( w !== undefined ) {
  1668. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1669. return this.subVectors( v, w );
  1670. }
  1671. this.x -= v.x;
  1672. this.y -= v.y;
  1673. this.z -= v.z;
  1674. return this;
  1675. },
  1676. subScalar: function ( s ) {
  1677. this.x -= s;
  1678. this.y -= s;
  1679. this.z -= s;
  1680. return this;
  1681. },
  1682. subVectors: function ( a, b ) {
  1683. this.x = a.x - b.x;
  1684. this.y = a.y - b.y;
  1685. this.z = a.z - b.z;
  1686. return this;
  1687. },
  1688. multiply: function ( v, w ) {
  1689. if ( w !== undefined ) {
  1690. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1691. return this.multiplyVectors( v, w );
  1692. }
  1693. this.x *= v.x;
  1694. this.y *= v.y;
  1695. this.z *= v.z;
  1696. return this;
  1697. },
  1698. multiplyScalar: function ( scalar ) {
  1699. if ( isFinite( scalar ) ) {
  1700. this.x *= scalar;
  1701. this.y *= scalar;
  1702. this.z *= scalar;
  1703. } else {
  1704. this.x = 0;
  1705. this.y = 0;
  1706. this.z = 0;
  1707. }
  1708. return this;
  1709. },
  1710. multiplyVectors: function ( a, b ) {
  1711. this.x = a.x * b.x;
  1712. this.y = a.y * b.y;
  1713. this.z = a.z * b.z;
  1714. return this;
  1715. },
  1716. applyEuler: function () {
  1717. var quaternion;
  1718. return function applyEuler( euler ) {
  1719. if ( (euler && euler.isEuler) === false ) {
  1720. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1721. }
  1722. if ( quaternion === undefined ) quaternion = new Quaternion();
  1723. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1724. };
  1725. }(),
  1726. applyAxisAngle: function () {
  1727. var quaternion;
  1728. return function applyAxisAngle( axis, angle ) {
  1729. if ( quaternion === undefined ) quaternion = new Quaternion();
  1730. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1731. };
  1732. }(),
  1733. applyMatrix3: function ( m ) {
  1734. var x = this.x, y = this.y, z = this.z;
  1735. var e = m.elements;
  1736. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1737. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1738. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1739. return this;
  1740. },
  1741. applyMatrix4: function ( m ) {
  1742. // input: THREE.Matrix4 affine matrix
  1743. var x = this.x, y = this.y, z = this.z;
  1744. var e = m.elements;
  1745. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1746. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1747. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1748. return this;
  1749. },
  1750. applyProjection: function ( m ) {
  1751. // input: THREE.Matrix4 projection matrix
  1752. var x = this.x, y = this.y, z = this.z;
  1753. var e = m.elements;
  1754. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1755. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1756. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1757. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1758. return this;
  1759. },
  1760. applyQuaternion: function ( q ) {
  1761. var x = this.x, y = this.y, z = this.z;
  1762. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1763. // calculate quat * vector
  1764. var ix = qw * x + qy * z - qz * y;
  1765. var iy = qw * y + qz * x - qx * z;
  1766. var iz = qw * z + qx * y - qy * x;
  1767. var iw = - qx * x - qy * y - qz * z;
  1768. // calculate result * inverse quat
  1769. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1770. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1771. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1772. return this;
  1773. },
  1774. project: function () {
  1775. var matrix;
  1776. return function project( camera ) {
  1777. if ( matrix === undefined ) matrix = new Matrix4();
  1778. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1779. return this.applyProjection( matrix );
  1780. };
  1781. }(),
  1782. unproject: function () {
  1783. var matrix;
  1784. return function unproject( camera ) {
  1785. if ( matrix === undefined ) matrix = new Matrix4();
  1786. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1787. return this.applyProjection( matrix );
  1788. };
  1789. }(),
  1790. transformDirection: function ( m ) {
  1791. // input: THREE.Matrix4 affine matrix
  1792. // vector interpreted as a direction
  1793. var x = this.x, y = this.y, z = this.z;
  1794. var e = m.elements;
  1795. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1796. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1797. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1798. return this.normalize();
  1799. },
  1800. divide: function ( v ) {
  1801. this.x /= v.x;
  1802. this.y /= v.y;
  1803. this.z /= v.z;
  1804. return this;
  1805. },
  1806. divideScalar: function ( scalar ) {
  1807. return this.multiplyScalar( 1 / scalar );
  1808. },
  1809. min: function ( v ) {
  1810. this.x = Math.min( this.x, v.x );
  1811. this.y = Math.min( this.y, v.y );
  1812. this.z = Math.min( this.z, v.z );
  1813. return this;
  1814. },
  1815. max: function ( v ) {
  1816. this.x = Math.max( this.x, v.x );
  1817. this.y = Math.max( this.y, v.y );
  1818. this.z = Math.max( this.z, v.z );
  1819. return this;
  1820. },
  1821. clamp: function ( min, max ) {
  1822. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1823. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1824. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1825. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1826. return this;
  1827. },
  1828. clampScalar: function () {
  1829. var min, max;
  1830. return function clampScalar( minVal, maxVal ) {
  1831. if ( min === undefined ) {
  1832. min = new Vector3();
  1833. max = new Vector3();
  1834. }
  1835. min.set( minVal, minVal, minVal );
  1836. max.set( maxVal, maxVal, maxVal );
  1837. return this.clamp( min, max );
  1838. };
  1839. }(),
  1840. clampLength: function ( min, max ) {
  1841. var length = this.length();
  1842. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1843. },
  1844. floor: function () {
  1845. this.x = Math.floor( this.x );
  1846. this.y = Math.floor( this.y );
  1847. this.z = Math.floor( this.z );
  1848. return this;
  1849. },
  1850. ceil: function () {
  1851. this.x = Math.ceil( this.x );
  1852. this.y = Math.ceil( this.y );
  1853. this.z = Math.ceil( this.z );
  1854. return this;
  1855. },
  1856. round: function () {
  1857. this.x = Math.round( this.x );
  1858. this.y = Math.round( this.y );
  1859. this.z = Math.round( this.z );
  1860. return this;
  1861. },
  1862. roundToZero: function () {
  1863. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1864. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1865. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1866. return this;
  1867. },
  1868. negate: function () {
  1869. this.x = - this.x;
  1870. this.y = - this.y;
  1871. this.z = - this.z;
  1872. return this;
  1873. },
  1874. dot: function ( v ) {
  1875. return this.x * v.x + this.y * v.y + this.z * v.z;
  1876. },
  1877. lengthSq: function () {
  1878. return this.x * this.x + this.y * this.y + this.z * this.z;
  1879. },
  1880. length: function () {
  1881. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1882. },
  1883. lengthManhattan: function () {
  1884. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1885. },
  1886. normalize: function () {
  1887. return this.divideScalar( this.length() );
  1888. },
  1889. setLength: function ( length ) {
  1890. return this.multiplyScalar( length / this.length() );
  1891. },
  1892. lerp: function ( v, alpha ) {
  1893. this.x += ( v.x - this.x ) * alpha;
  1894. this.y += ( v.y - this.y ) * alpha;
  1895. this.z += ( v.z - this.z ) * alpha;
  1896. return this;
  1897. },
  1898. lerpVectors: function ( v1, v2, alpha ) {
  1899. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1900. },
  1901. cross: function ( v, w ) {
  1902. if ( w !== undefined ) {
  1903. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1904. return this.crossVectors( v, w );
  1905. }
  1906. var x = this.x, y = this.y, z = this.z;
  1907. this.x = y * v.z - z * v.y;
  1908. this.y = z * v.x - x * v.z;
  1909. this.z = x * v.y - y * v.x;
  1910. return this;
  1911. },
  1912. crossVectors: function ( a, b ) {
  1913. var ax = a.x, ay = a.y, az = a.z;
  1914. var bx = b.x, by = b.y, bz = b.z;
  1915. this.x = ay * bz - az * by;
  1916. this.y = az * bx - ax * bz;
  1917. this.z = ax * by - ay * bx;
  1918. return this;
  1919. },
  1920. projectOnVector: function ( vector ) {
  1921. var scalar = vector.dot( this ) / vector.lengthSq();
  1922. return this.copy( vector ).multiplyScalar( scalar );
  1923. },
  1924. projectOnPlane: function () {
  1925. var v1;
  1926. return function projectOnPlane( planeNormal ) {
  1927. if ( v1 === undefined ) v1 = new Vector3();
  1928. v1.copy( this ).projectOnVector( planeNormal );
  1929. return this.sub( v1 );
  1930. };
  1931. }(),
  1932. reflect: function () {
  1933. // reflect incident vector off plane orthogonal to normal
  1934. // normal is assumed to have unit length
  1935. var v1;
  1936. return function reflect( normal ) {
  1937. if ( v1 === undefined ) v1 = new Vector3();
  1938. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1939. };
  1940. }(),
  1941. angleTo: function ( v ) {
  1942. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1943. // clamp, to handle numerical problems
  1944. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1945. },
  1946. distanceTo: function ( v ) {
  1947. return Math.sqrt( this.distanceToSquared( v ) );
  1948. },
  1949. distanceToSquared: function ( v ) {
  1950. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1951. return dx * dx + dy * dy + dz * dz;
  1952. },
  1953. distanceToManhattan: function ( v ) {
  1954. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1955. },
  1956. setFromSpherical: function( s ) {
  1957. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1958. this.x = sinPhiRadius * Math.sin( s.theta );
  1959. this.y = Math.cos( s.phi ) * s.radius;
  1960. this.z = sinPhiRadius * Math.cos( s.theta );
  1961. return this;
  1962. },
  1963. setFromCylindrical: function( c ) {
  1964. this.x = c.radius * Math.sin( c.theta );
  1965. this.y = c.y;
  1966. this.z = c.radius * Math.cos( c.theta );
  1967. return this;
  1968. },
  1969. setFromMatrixPosition: function ( m ) {
  1970. return this.setFromMatrixColumn( m, 3 );
  1971. },
  1972. setFromMatrixScale: function ( m ) {
  1973. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1974. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1975. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1976. this.x = sx;
  1977. this.y = sy;
  1978. this.z = sz;
  1979. return this;
  1980. },
  1981. setFromMatrixColumn: function ( m, index ) {
  1982. if ( typeof m === 'number' ) {
  1983. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1984. var temp = m;
  1985. m = index;
  1986. index = temp;
  1987. }
  1988. return this.fromArray( m.elements, index * 4 );
  1989. },
  1990. equals: function ( v ) {
  1991. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1992. },
  1993. fromArray: function ( array, offset ) {
  1994. if ( offset === undefined ) offset = 0;
  1995. this.x = array[ offset ];
  1996. this.y = array[ offset + 1 ];
  1997. this.z = array[ offset + 2 ];
  1998. return this;
  1999. },
  2000. toArray: function ( array, offset ) {
  2001. if ( array === undefined ) array = [];
  2002. if ( offset === undefined ) offset = 0;
  2003. array[ offset ] = this.x;
  2004. array[ offset + 1 ] = this.y;
  2005. array[ offset + 2 ] = this.z;
  2006. return array;
  2007. },
  2008. fromAttribute: function ( attribute, index, offset ) {
  2009. if ( offset !== undefined ) {
  2010. console.warn( 'THREE.Vector3: offset has been removed from .fromAttribute().' );
  2011. }
  2012. this.x = attribute.getX( index );
  2013. this.y = attribute.getY( index );
  2014. this.z = attribute.getZ( index );
  2015. return this;
  2016. }
  2017. };
  2018. /**
  2019. * @author mrdoob / http://mrdoob.com/
  2020. * @author supereggbert / http://www.paulbrunt.co.uk/
  2021. * @author philogb / http://blog.thejit.org/
  2022. * @author jordi_ros / http://plattsoft.com
  2023. * @author D1plo1d / http://github.com/D1plo1d
  2024. * @author alteredq / http://alteredqualia.com/
  2025. * @author mikael emtinger / http://gomo.se/
  2026. * @author timknip / http://www.floorplanner.com/
  2027. * @author bhouston / http://clara.io
  2028. * @author WestLangley / http://github.com/WestLangley
  2029. */
  2030. function Matrix4() {
  2031. this.elements = new Float32Array( [
  2032. 1, 0, 0, 0,
  2033. 0, 1, 0, 0,
  2034. 0, 0, 1, 0,
  2035. 0, 0, 0, 1
  2036. ] );
  2037. if ( arguments.length > 0 ) {
  2038. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2039. }
  2040. }
  2041. Matrix4.prototype = {
  2042. constructor: Matrix4,
  2043. isMatrix4: true,
  2044. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2045. var te = this.elements;
  2046. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2047. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2048. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2049. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2050. return this;
  2051. },
  2052. identity: function () {
  2053. this.set(
  2054. 1, 0, 0, 0,
  2055. 0, 1, 0, 0,
  2056. 0, 0, 1, 0,
  2057. 0, 0, 0, 1
  2058. );
  2059. return this;
  2060. },
  2061. clone: function () {
  2062. return new Matrix4().fromArray( this.elements );
  2063. },
  2064. copy: function ( m ) {
  2065. this.elements.set( m.elements );
  2066. return this;
  2067. },
  2068. copyPosition: function ( m ) {
  2069. var te = this.elements;
  2070. var me = m.elements;
  2071. te[ 12 ] = me[ 12 ];
  2072. te[ 13 ] = me[ 13 ];
  2073. te[ 14 ] = me[ 14 ];
  2074. return this;
  2075. },
  2076. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2077. xAxis.setFromMatrixColumn( this, 0 );
  2078. yAxis.setFromMatrixColumn( this, 1 );
  2079. zAxis.setFromMatrixColumn( this, 2 );
  2080. return this;
  2081. },
  2082. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2083. this.set(
  2084. xAxis.x, yAxis.x, zAxis.x, 0,
  2085. xAxis.y, yAxis.y, zAxis.y, 0,
  2086. xAxis.z, yAxis.z, zAxis.z, 0,
  2087. 0, 0, 0, 1
  2088. );
  2089. return this;
  2090. },
  2091. extractRotation: function () {
  2092. var v1;
  2093. return function extractRotation( m ) {
  2094. if ( v1 === undefined ) v1 = new Vector3();
  2095. var te = this.elements;
  2096. var me = m.elements;
  2097. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2098. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2099. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2100. te[ 0 ] = me[ 0 ] * scaleX;
  2101. te[ 1 ] = me[ 1 ] * scaleX;
  2102. te[ 2 ] = me[ 2 ] * scaleX;
  2103. te[ 4 ] = me[ 4 ] * scaleY;
  2104. te[ 5 ] = me[ 5 ] * scaleY;
  2105. te[ 6 ] = me[ 6 ] * scaleY;
  2106. te[ 8 ] = me[ 8 ] * scaleZ;
  2107. te[ 9 ] = me[ 9 ] * scaleZ;
  2108. te[ 10 ] = me[ 10 ] * scaleZ;
  2109. return this;
  2110. };
  2111. }(),
  2112. makeRotationFromEuler: function ( euler ) {
  2113. if ( (euler && euler.isEuler) === false ) {
  2114. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2115. }
  2116. var te = this.elements;
  2117. var x = euler.x, y = euler.y, z = euler.z;
  2118. var a = Math.cos( x ), b = Math.sin( x );
  2119. var c = Math.cos( y ), d = Math.sin( y );
  2120. var e = Math.cos( z ), f = Math.sin( z );
  2121. if ( euler.order === 'XYZ' ) {
  2122. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2123. te[ 0 ] = c * e;
  2124. te[ 4 ] = - c * f;
  2125. te[ 8 ] = d;
  2126. te[ 1 ] = af + be * d;
  2127. te[ 5 ] = ae - bf * d;
  2128. te[ 9 ] = - b * c;
  2129. te[ 2 ] = bf - ae * d;
  2130. te[ 6 ] = be + af * d;
  2131. te[ 10 ] = a * c;
  2132. } else if ( euler.order === 'YXZ' ) {
  2133. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2134. te[ 0 ] = ce + df * b;
  2135. te[ 4 ] = de * b - cf;
  2136. te[ 8 ] = a * d;
  2137. te[ 1 ] = a * f;
  2138. te[ 5 ] = a * e;
  2139. te[ 9 ] = - b;
  2140. te[ 2 ] = cf * b - de;
  2141. te[ 6 ] = df + ce * b;
  2142. te[ 10 ] = a * c;
  2143. } else if ( euler.order === 'ZXY' ) {
  2144. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2145. te[ 0 ] = ce - df * b;
  2146. te[ 4 ] = - a * f;
  2147. te[ 8 ] = de + cf * b;
  2148. te[ 1 ] = cf + de * b;
  2149. te[ 5 ] = a * e;
  2150. te[ 9 ] = df - ce * b;
  2151. te[ 2 ] = - a * d;
  2152. te[ 6 ] = b;
  2153. te[ 10 ] = a * c;
  2154. } else if ( euler.order === 'ZYX' ) {
  2155. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2156. te[ 0 ] = c * e;
  2157. te[ 4 ] = be * d - af;
  2158. te[ 8 ] = ae * d + bf;
  2159. te[ 1 ] = c * f;
  2160. te[ 5 ] = bf * d + ae;
  2161. te[ 9 ] = af * d - be;
  2162. te[ 2 ] = - d;
  2163. te[ 6 ] = b * c;
  2164. te[ 10 ] = a * c;
  2165. } else if ( euler.order === 'YZX' ) {
  2166. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2167. te[ 0 ] = c * e;
  2168. te[ 4 ] = bd - ac * f;
  2169. te[ 8 ] = bc * f + ad;
  2170. te[ 1 ] = f;
  2171. te[ 5 ] = a * e;
  2172. te[ 9 ] = - b * e;
  2173. te[ 2 ] = - d * e;
  2174. te[ 6 ] = ad * f + bc;
  2175. te[ 10 ] = ac - bd * f;
  2176. } else if ( euler.order === 'XZY' ) {
  2177. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2178. te[ 0 ] = c * e;
  2179. te[ 4 ] = - f;
  2180. te[ 8 ] = d * e;
  2181. te[ 1 ] = ac * f + bd;
  2182. te[ 5 ] = a * e;
  2183. te[ 9 ] = ad * f - bc;
  2184. te[ 2 ] = bc * f - ad;
  2185. te[ 6 ] = b * e;
  2186. te[ 10 ] = bd * f + ac;
  2187. }
  2188. // last column
  2189. te[ 3 ] = 0;
  2190. te[ 7 ] = 0;
  2191. te[ 11 ] = 0;
  2192. // bottom row
  2193. te[ 12 ] = 0;
  2194. te[ 13 ] = 0;
  2195. te[ 14 ] = 0;
  2196. te[ 15 ] = 1;
  2197. return this;
  2198. },
  2199. makeRotationFromQuaternion: function ( q ) {
  2200. var te = this.elements;
  2201. var x = q.x, y = q.y, z = q.z, w = q.w;
  2202. var x2 = x + x, y2 = y + y, z2 = z + z;
  2203. var xx = x * x2, xy = x * y2, xz = x * z2;
  2204. var yy = y * y2, yz = y * z2, zz = z * z2;
  2205. var wx = w * x2, wy = w * y2, wz = w * z2;
  2206. te[ 0 ] = 1 - ( yy + zz );
  2207. te[ 4 ] = xy - wz;
  2208. te[ 8 ] = xz + wy;
  2209. te[ 1 ] = xy + wz;
  2210. te[ 5 ] = 1 - ( xx + zz );
  2211. te[ 9 ] = yz - wx;
  2212. te[ 2 ] = xz - wy;
  2213. te[ 6 ] = yz + wx;
  2214. te[ 10 ] = 1 - ( xx + yy );
  2215. // last column
  2216. te[ 3 ] = 0;
  2217. te[ 7 ] = 0;
  2218. te[ 11 ] = 0;
  2219. // bottom row
  2220. te[ 12 ] = 0;
  2221. te[ 13 ] = 0;
  2222. te[ 14 ] = 0;
  2223. te[ 15 ] = 1;
  2224. return this;
  2225. },
  2226. lookAt: function () {
  2227. var x, y, z;
  2228. return function lookAt( eye, target, up ) {
  2229. if ( x === undefined ) {
  2230. x = new Vector3();
  2231. y = new Vector3();
  2232. z = new Vector3();
  2233. }
  2234. var te = this.elements;
  2235. z.subVectors( eye, target ).normalize();
  2236. if ( z.lengthSq() === 0 ) {
  2237. z.z = 1;
  2238. }
  2239. x.crossVectors( up, z ).normalize();
  2240. if ( x.lengthSq() === 0 ) {
  2241. z.z += 0.0001;
  2242. x.crossVectors( up, z ).normalize();
  2243. }
  2244. y.crossVectors( z, x );
  2245. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2246. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2247. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2248. return this;
  2249. };
  2250. }(),
  2251. multiply: function ( m, n ) {
  2252. if ( n !== undefined ) {
  2253. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2254. return this.multiplyMatrices( m, n );
  2255. }
  2256. return this.multiplyMatrices( this, m );
  2257. },
  2258. premultiply: function ( m ) {
  2259. return this.multiplyMatrices( m, this );
  2260. },
  2261. multiplyMatrices: function ( a, b ) {
  2262. var ae = a.elements;
  2263. var be = b.elements;
  2264. var te = this.elements;
  2265. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2266. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2267. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2268. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2269. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2270. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2271. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2272. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2273. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2274. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2275. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2276. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2277. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2278. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2279. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2280. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2281. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2282. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2283. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2284. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2285. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2286. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2287. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2288. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2289. return this;
  2290. },
  2291. multiplyToArray: function ( a, b, r ) {
  2292. var te = this.elements;
  2293. this.multiplyMatrices( a, b );
  2294. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2295. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2296. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2297. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2298. return this;
  2299. },
  2300. multiplyScalar: function ( s ) {
  2301. var te = this.elements;
  2302. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2303. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2304. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2305. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2306. return this;
  2307. },
  2308. applyToVector3Array: function () {
  2309. var v1;
  2310. return function applyToVector3Array( array, offset, length ) {
  2311. if ( v1 === undefined ) v1 = new Vector3();
  2312. if ( offset === undefined ) offset = 0;
  2313. if ( length === undefined ) length = array.length;
  2314. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2315. v1.fromArray( array, j );
  2316. v1.applyMatrix4( this );
  2317. v1.toArray( array, j );
  2318. }
  2319. return array;
  2320. };
  2321. }(),
  2322. applyToBufferAttribute: function () {
  2323. var v1;
  2324. return function applyToBufferAttribute( attribute ) {
  2325. if ( v1 === undefined ) v1 = new Vector3();
  2326. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2327. v1.x = attribute.getX( i );
  2328. v1.y = attribute.getY( i );
  2329. v1.z = attribute.getZ( i );
  2330. v1.applyMatrix4( this );
  2331. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2332. }
  2333. return attribute;
  2334. };
  2335. }(),
  2336. determinant: function () {
  2337. var te = this.elements;
  2338. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2339. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2340. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2341. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2342. //TODO: make this more efficient
  2343. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2344. return (
  2345. n41 * (
  2346. + n14 * n23 * n32
  2347. - n13 * n24 * n32
  2348. - n14 * n22 * n33
  2349. + n12 * n24 * n33
  2350. + n13 * n22 * n34
  2351. - n12 * n23 * n34
  2352. ) +
  2353. n42 * (
  2354. + n11 * n23 * n34
  2355. - n11 * n24 * n33
  2356. + n14 * n21 * n33
  2357. - n13 * n21 * n34
  2358. + n13 * n24 * n31
  2359. - n14 * n23 * n31
  2360. ) +
  2361. n43 * (
  2362. + n11 * n24 * n32
  2363. - n11 * n22 * n34
  2364. - n14 * n21 * n32
  2365. + n12 * n21 * n34
  2366. + n14 * n22 * n31
  2367. - n12 * n24 * n31
  2368. ) +
  2369. n44 * (
  2370. - n13 * n22 * n31
  2371. - n11 * n23 * n32
  2372. + n11 * n22 * n33
  2373. + n13 * n21 * n32
  2374. - n12 * n21 * n33
  2375. + n12 * n23 * n31
  2376. )
  2377. );
  2378. },
  2379. transpose: function () {
  2380. var te = this.elements;
  2381. var tmp;
  2382. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2383. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2384. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2385. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2386. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2387. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2388. return this;
  2389. },
  2390. setPosition: function ( v ) {
  2391. var te = this.elements;
  2392. te[ 12 ] = v.x;
  2393. te[ 13 ] = v.y;
  2394. te[ 14 ] = v.z;
  2395. return this;
  2396. },
  2397. getInverse: function ( m, throwOnDegenerate ) {
  2398. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2399. var te = this.elements,
  2400. me = m.elements,
  2401. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2402. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2403. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2404. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2405. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2406. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2407. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2408. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2409. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2410. if ( det === 0 ) {
  2411. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2412. if ( throwOnDegenerate === true ) {
  2413. throw new Error( msg );
  2414. } else {
  2415. console.warn( msg );
  2416. }
  2417. return this.identity();
  2418. }
  2419. var detInv = 1 / det;
  2420. te[ 0 ] = t11 * detInv;
  2421. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2422. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2423. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2424. te[ 4 ] = t12 * detInv;
  2425. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2426. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2427. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2428. te[ 8 ] = t13 * detInv;
  2429. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2430. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2431. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2432. te[ 12 ] = t14 * detInv;
  2433. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2434. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2435. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2436. return this;
  2437. },
  2438. scale: function ( v ) {
  2439. var te = this.elements;
  2440. var x = v.x, y = v.y, z = v.z;
  2441. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2442. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2443. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2444. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2445. return this;
  2446. },
  2447. getMaxScaleOnAxis: function () {
  2448. var te = this.elements;
  2449. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2450. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2451. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2452. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2453. },
  2454. makeTranslation: function ( x, y, z ) {
  2455. this.set(
  2456. 1, 0, 0, x,
  2457. 0, 1, 0, y,
  2458. 0, 0, 1, z,
  2459. 0, 0, 0, 1
  2460. );
  2461. return this;
  2462. },
  2463. makeRotationX: function ( theta ) {
  2464. var c = Math.cos( theta ), s = Math.sin( theta );
  2465. this.set(
  2466. 1, 0, 0, 0,
  2467. 0, c, - s, 0,
  2468. 0, s, c, 0,
  2469. 0, 0, 0, 1
  2470. );
  2471. return this;
  2472. },
  2473. makeRotationY: function ( theta ) {
  2474. var c = Math.cos( theta ), s = Math.sin( theta );
  2475. this.set(
  2476. c, 0, s, 0,
  2477. 0, 1, 0, 0,
  2478. - s, 0, c, 0,
  2479. 0, 0, 0, 1
  2480. );
  2481. return this;
  2482. },
  2483. makeRotationZ: function ( theta ) {
  2484. var c = Math.cos( theta ), s = Math.sin( theta );
  2485. this.set(
  2486. c, - s, 0, 0,
  2487. s, c, 0, 0,
  2488. 0, 0, 1, 0,
  2489. 0, 0, 0, 1
  2490. );
  2491. return this;
  2492. },
  2493. makeRotationAxis: function ( axis, angle ) {
  2494. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2495. var c = Math.cos( angle );
  2496. var s = Math.sin( angle );
  2497. var t = 1 - c;
  2498. var x = axis.x, y = axis.y, z = axis.z;
  2499. var tx = t * x, ty = t * y;
  2500. this.set(
  2501. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2502. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2503. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2504. 0, 0, 0, 1
  2505. );
  2506. return this;
  2507. },
  2508. makeScale: function ( x, y, z ) {
  2509. this.set(
  2510. x, 0, 0, 0,
  2511. 0, y, 0, 0,
  2512. 0, 0, z, 0,
  2513. 0, 0, 0, 1
  2514. );
  2515. return this;
  2516. },
  2517. makeShear: function ( x, y, z ) {
  2518. this.set(
  2519. 1, y, z, 0,
  2520. x, 1, z, 0,
  2521. x, y, 1, 0,
  2522. 0, 0, 0, 1
  2523. );
  2524. return this;
  2525. },
  2526. compose: function ( position, quaternion, scale ) {
  2527. this.makeRotationFromQuaternion( quaternion );
  2528. this.scale( scale );
  2529. this.setPosition( position );
  2530. return this;
  2531. },
  2532. decompose: function () {
  2533. var vector, matrix;
  2534. return function decompose( position, quaternion, scale ) {
  2535. if ( vector === undefined ) {
  2536. vector = new Vector3();
  2537. matrix = new Matrix4();
  2538. }
  2539. var te = this.elements;
  2540. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2541. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2542. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2543. // if determine is negative, we need to invert one scale
  2544. var det = this.determinant();
  2545. if ( det < 0 ) {
  2546. sx = - sx;
  2547. }
  2548. position.x = te[ 12 ];
  2549. position.y = te[ 13 ];
  2550. position.z = te[ 14 ];
  2551. // scale the rotation part
  2552. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2553. var invSX = 1 / sx;
  2554. var invSY = 1 / sy;
  2555. var invSZ = 1 / sz;
  2556. matrix.elements[ 0 ] *= invSX;
  2557. matrix.elements[ 1 ] *= invSX;
  2558. matrix.elements[ 2 ] *= invSX;
  2559. matrix.elements[ 4 ] *= invSY;
  2560. matrix.elements[ 5 ] *= invSY;
  2561. matrix.elements[ 6 ] *= invSY;
  2562. matrix.elements[ 8 ] *= invSZ;
  2563. matrix.elements[ 9 ] *= invSZ;
  2564. matrix.elements[ 10 ] *= invSZ;
  2565. quaternion.setFromRotationMatrix( matrix );
  2566. scale.x = sx;
  2567. scale.y = sy;
  2568. scale.z = sz;
  2569. return this;
  2570. };
  2571. }(),
  2572. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2573. var te = this.elements;
  2574. var x = 2 * near / ( right - left );
  2575. var y = 2 * near / ( top - bottom );
  2576. var a = ( right + left ) / ( right - left );
  2577. var b = ( top + bottom ) / ( top - bottom );
  2578. var c = - ( far + near ) / ( far - near );
  2579. var d = - 2 * far * near / ( far - near );
  2580. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2581. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2582. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2583. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2584. return this;
  2585. },
  2586. makePerspective: function ( fov, aspect, near, far ) {
  2587. var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 );
  2588. var ymin = - ymax;
  2589. var xmin = ymin * aspect;
  2590. var xmax = ymax * aspect;
  2591. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2592. },
  2593. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2594. var te = this.elements;
  2595. var w = 1.0 / ( right - left );
  2596. var h = 1.0 / ( top - bottom );
  2597. var p = 1.0 / ( far - near );
  2598. var x = ( right + left ) * w;
  2599. var y = ( top + bottom ) * h;
  2600. var z = ( far + near ) * p;
  2601. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2602. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2603. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2604. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2605. return this;
  2606. },
  2607. equals: function ( matrix ) {
  2608. var te = this.elements;
  2609. var me = matrix.elements;
  2610. for ( var i = 0; i < 16; i ++ ) {
  2611. if ( te[ i ] !== me[ i ] ) return false;
  2612. }
  2613. return true;
  2614. },
  2615. fromArray: function ( array, offset ) {
  2616. if ( offset === undefined ) offset = 0;
  2617. for( var i = 0; i < 16; i ++ ) {
  2618. this.elements[ i ] = array[ i + offset ];
  2619. }
  2620. return this;
  2621. },
  2622. toArray: function ( array, offset ) {
  2623. if ( array === undefined ) array = [];
  2624. if ( offset === undefined ) offset = 0;
  2625. var te = this.elements;
  2626. array[ offset ] = te[ 0 ];
  2627. array[ offset + 1 ] = te[ 1 ];
  2628. array[ offset + 2 ] = te[ 2 ];
  2629. array[ offset + 3 ] = te[ 3 ];
  2630. array[ offset + 4 ] = te[ 4 ];
  2631. array[ offset + 5 ] = te[ 5 ];
  2632. array[ offset + 6 ] = te[ 6 ];
  2633. array[ offset + 7 ] = te[ 7 ];
  2634. array[ offset + 8 ] = te[ 8 ];
  2635. array[ offset + 9 ] = te[ 9 ];
  2636. array[ offset + 10 ] = te[ 10 ];
  2637. array[ offset + 11 ] = te[ 11 ];
  2638. array[ offset + 12 ] = te[ 12 ];
  2639. array[ offset + 13 ] = te[ 13 ];
  2640. array[ offset + 14 ] = te[ 14 ];
  2641. array[ offset + 15 ] = te[ 15 ];
  2642. return array;
  2643. }
  2644. };
  2645. /**
  2646. * @author mrdoob / http://mrdoob.com/
  2647. */
  2648. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2649. images = images !== undefined ? images : [];
  2650. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2651. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2652. this.flipY = false;
  2653. }
  2654. CubeTexture.prototype = Object.create( Texture.prototype );
  2655. CubeTexture.prototype.constructor = CubeTexture;
  2656. CubeTexture.prototype.isCubeTexture = true;
  2657. Object.defineProperty( CubeTexture.prototype, 'images', {
  2658. get: function () {
  2659. return this.image;
  2660. },
  2661. set: function ( value ) {
  2662. this.image = value;
  2663. }
  2664. } );
  2665. /**
  2666. * @author tschw
  2667. *
  2668. * Uniforms of a program.
  2669. * Those form a tree structure with a special top-level container for the root,
  2670. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2671. *
  2672. *
  2673. * Properties of inner nodes including the top-level container:
  2674. *
  2675. * .seq - array of nested uniforms
  2676. * .map - nested uniforms by name
  2677. *
  2678. *
  2679. * Methods of all nodes except the top-level container:
  2680. *
  2681. * .setValue( gl, value, [renderer] )
  2682. *
  2683. * uploads a uniform value(s)
  2684. * the 'renderer' parameter is needed for sampler uniforms
  2685. *
  2686. *
  2687. * Static methods of the top-level container (renderer factorizations):
  2688. *
  2689. * .upload( gl, seq, values, renderer )
  2690. *
  2691. * sets uniforms in 'seq' to 'values[id].value'
  2692. *
  2693. * .seqWithValue( seq, values ) : filteredSeq
  2694. *
  2695. * filters 'seq' entries with corresponding entry in values
  2696. *
  2697. *
  2698. * Methods of the top-level container (renderer factorizations):
  2699. *
  2700. * .setValue( gl, name, value )
  2701. *
  2702. * sets uniform with name 'name' to 'value'
  2703. *
  2704. * .set( gl, obj, prop )
  2705. *
  2706. * sets uniform from object and property with same name than uniform
  2707. *
  2708. * .setOptional( gl, obj, prop )
  2709. *
  2710. * like .set for an optional property of the object
  2711. *
  2712. */
  2713. var emptyTexture = new Texture();
  2714. var emptyCubeTexture = new CubeTexture();
  2715. // --- Base for inner nodes (including the root) ---
  2716. function UniformContainer() {
  2717. this.seq = [];
  2718. this.map = {};
  2719. }
  2720. // --- Utilities ---
  2721. // Array Caches (provide typed arrays for temporary by size)
  2722. var arrayCacheF32 = [];
  2723. var arrayCacheI32 = [];
  2724. // Flattening for arrays of vectors and matrices
  2725. function flatten( array, nBlocks, blockSize ) {
  2726. var firstElem = array[ 0 ];
  2727. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2728. // unoptimized: ! isNaN( firstElem )
  2729. // see http://jacksondunstan.com/articles/983
  2730. var n = nBlocks * blockSize,
  2731. r = arrayCacheF32[ n ];
  2732. if ( r === undefined ) {
  2733. r = new Float32Array( n );
  2734. arrayCacheF32[ n ] = r;
  2735. }
  2736. if ( nBlocks !== 0 ) {
  2737. firstElem.toArray( r, 0 );
  2738. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2739. offset += blockSize;
  2740. array[ i ].toArray( r, offset );
  2741. }
  2742. }
  2743. return r;
  2744. }
  2745. // Texture unit allocation
  2746. function allocTexUnits( renderer, n ) {
  2747. var r = arrayCacheI32[ n ];
  2748. if ( r === undefined ) {
  2749. r = new Int32Array( n );
  2750. arrayCacheI32[ n ] = r;
  2751. }
  2752. for ( var i = 0; i !== n; ++ i )
  2753. r[ i ] = renderer.allocTextureUnit();
  2754. return r;
  2755. }
  2756. // --- Setters ---
  2757. // Note: Defining these methods externally, because they come in a bunch
  2758. // and this way their names minify.
  2759. // Single scalar
  2760. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2761. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2762. // Single float vector (from flat array or THREE.VectorN)
  2763. function setValue2fv( gl, v ) {
  2764. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2765. else gl.uniform2f( this.addr, v.x, v.y );
  2766. }
  2767. function setValue3fv( gl, v ) {
  2768. if ( v.x !== undefined )
  2769. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2770. else if ( v.r !== undefined )
  2771. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2772. else
  2773. gl.uniform3fv( this.addr, v );
  2774. }
  2775. function setValue4fv( gl, v ) {
  2776. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2777. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2778. }
  2779. // Single matrix (from flat array or MatrixN)
  2780. function setValue2fm( gl, v ) {
  2781. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2782. }
  2783. function setValue3fm( gl, v ) {
  2784. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2785. }
  2786. function setValue4fm( gl, v ) {
  2787. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2788. }
  2789. // Single texture (2D / Cube)
  2790. function setValueT1( gl, v, renderer ) {
  2791. var unit = renderer.allocTextureUnit();
  2792. gl.uniform1i( this.addr, unit );
  2793. renderer.setTexture2D( v || emptyTexture, unit );
  2794. }
  2795. function setValueT6( gl, v, renderer ) {
  2796. var unit = renderer.allocTextureUnit();
  2797. gl.uniform1i( this.addr, unit );
  2798. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2799. }
  2800. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2801. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2802. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2803. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2804. // Helper to pick the right setter for the singular case
  2805. function getSingularSetter( type ) {
  2806. switch ( type ) {
  2807. case 0x1406: return setValue1f; // FLOAT
  2808. case 0x8b50: return setValue2fv; // _VEC2
  2809. case 0x8b51: return setValue3fv; // _VEC3
  2810. case 0x8b52: return setValue4fv; // _VEC4
  2811. case 0x8b5a: return setValue2fm; // _MAT2
  2812. case 0x8b5b: return setValue3fm; // _MAT3
  2813. case 0x8b5c: return setValue4fm; // _MAT4
  2814. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2815. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2816. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2817. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2818. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2819. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2820. }
  2821. }
  2822. // Array of scalars
  2823. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2824. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2825. // Array of vectors (flat or from THREE classes)
  2826. function setValueV2a( gl, v ) {
  2827. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2828. }
  2829. function setValueV3a( gl, v ) {
  2830. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2831. }
  2832. function setValueV4a( gl, v ) {
  2833. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2834. }
  2835. // Array of matrices (flat or from THREE clases)
  2836. function setValueM2a( gl, v ) {
  2837. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2838. }
  2839. function setValueM3a( gl, v ) {
  2840. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2841. }
  2842. function setValueM4a( gl, v ) {
  2843. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2844. }
  2845. // Array of textures (2D / Cube)
  2846. function setValueT1a( gl, v, renderer ) {
  2847. var n = v.length,
  2848. units = allocTexUnits( renderer, n );
  2849. gl.uniform1iv( this.addr, units );
  2850. for ( var i = 0; i !== n; ++ i ) {
  2851. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2852. }
  2853. }
  2854. function setValueT6a( gl, v, renderer ) {
  2855. var n = v.length,
  2856. units = allocTexUnits( renderer, n );
  2857. gl.uniform1iv( this.addr, units );
  2858. for ( var i = 0; i !== n; ++ i ) {
  2859. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2860. }
  2861. }
  2862. // Helper to pick the right setter for a pure (bottom-level) array
  2863. function getPureArraySetter( type ) {
  2864. switch ( type ) {
  2865. case 0x1406: return setValue1fv; // FLOAT
  2866. case 0x8b50: return setValueV2a; // _VEC2
  2867. case 0x8b51: return setValueV3a; // _VEC3
  2868. case 0x8b52: return setValueV4a; // _VEC4
  2869. case 0x8b5a: return setValueM2a; // _MAT2
  2870. case 0x8b5b: return setValueM3a; // _MAT3
  2871. case 0x8b5c: return setValueM4a; // _MAT4
  2872. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2873. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2874. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2875. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2876. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2877. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2878. }
  2879. }
  2880. // --- Uniform Classes ---
  2881. function SingleUniform( id, activeInfo, addr ) {
  2882. this.id = id;
  2883. this.addr = addr;
  2884. this.setValue = getSingularSetter( activeInfo.type );
  2885. // this.path = activeInfo.name; // DEBUG
  2886. }
  2887. function PureArrayUniform( id, activeInfo, addr ) {
  2888. this.id = id;
  2889. this.addr = addr;
  2890. this.size = activeInfo.size;
  2891. this.setValue = getPureArraySetter( activeInfo.type );
  2892. // this.path = activeInfo.name; // DEBUG
  2893. }
  2894. function StructuredUniform( id ) {
  2895. this.id = id;
  2896. UniformContainer.call( this ); // mix-in
  2897. }
  2898. StructuredUniform.prototype.setValue = function( gl, value ) {
  2899. // Note: Don't need an extra 'renderer' parameter, since samplers
  2900. // are not allowed in structured uniforms.
  2901. var seq = this.seq;
  2902. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2903. var u = seq[ i ];
  2904. u.setValue( gl, value[ u.id ] );
  2905. }
  2906. };
  2907. // --- Top-level ---
  2908. // Parser - builds up the property tree from the path strings
  2909. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2910. // extracts
  2911. // - the identifier (member name or array index)
  2912. // - followed by an optional right bracket (found when array index)
  2913. // - followed by an optional left bracket or dot (type of subscript)
  2914. //
  2915. // Note: These portions can be read in a non-overlapping fashion and
  2916. // allow straightforward parsing of the hierarchy that WebGL encodes
  2917. // in the uniform names.
  2918. function addUniform( container, uniformObject ) {
  2919. container.seq.push( uniformObject );
  2920. container.map[ uniformObject.id ] = uniformObject;
  2921. }
  2922. function parseUniform( activeInfo, addr, container ) {
  2923. var path = activeInfo.name,
  2924. pathLength = path.length;
  2925. // reset RegExp object, because of the early exit of a previous run
  2926. RePathPart.lastIndex = 0;
  2927. for (; ;) {
  2928. var match = RePathPart.exec( path ),
  2929. matchEnd = RePathPart.lastIndex,
  2930. id = match[ 1 ],
  2931. idIsIndex = match[ 2 ] === ']',
  2932. subscript = match[ 3 ];
  2933. if ( idIsIndex ) id = id | 0; // convert to integer
  2934. if ( subscript === undefined ||
  2935. subscript === '[' && matchEnd + 2 === pathLength ) {
  2936. // bare name or "pure" bottom-level array "[0]" suffix
  2937. addUniform( container, subscript === undefined ?
  2938. new SingleUniform( id, activeInfo, addr ) :
  2939. new PureArrayUniform( id, activeInfo, addr ) );
  2940. break;
  2941. } else {
  2942. // step into inner node / create it in case it doesn't exist
  2943. var map = container.map,
  2944. next = map[ id ];
  2945. if ( next === undefined ) {
  2946. next = new StructuredUniform( id );
  2947. addUniform( container, next );
  2948. }
  2949. container = next;
  2950. }
  2951. }
  2952. }
  2953. // Root Container
  2954. function WebGLUniforms( gl, program, renderer ) {
  2955. UniformContainer.call( this );
  2956. this.renderer = renderer;
  2957. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2958. for ( var i = 0; i !== n; ++ i ) {
  2959. var info = gl.getActiveUniform( program, i ),
  2960. path = info.name,
  2961. addr = gl.getUniformLocation( program, path );
  2962. parseUniform( info, addr, this );
  2963. }
  2964. }
  2965. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  2966. var u = this.map[ name ];
  2967. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2968. };
  2969. WebGLUniforms.prototype.set = function( gl, object, name ) {
  2970. var u = this.map[ name ];
  2971. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  2972. };
  2973. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  2974. var v = object[ name ];
  2975. if ( v !== undefined ) this.setValue( gl, name, v );
  2976. };
  2977. // Static interface
  2978. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  2979. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2980. var u = seq[ i ],
  2981. v = values[ u.id ];
  2982. if ( v.needsUpdate !== false ) {
  2983. // note: always updating when .needsUpdate is undefined
  2984. u.setValue( gl, v.value, renderer );
  2985. }
  2986. }
  2987. };
  2988. WebGLUniforms.seqWithValue = function( seq, values ) {
  2989. var r = [];
  2990. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2991. var u = seq[ i ];
  2992. if ( u.id in values ) r.push( u );
  2993. }
  2994. return r;
  2995. };
  2996. /**
  2997. * Uniform Utilities
  2998. */
  2999. var UniformsUtils = {
  3000. merge: function ( uniforms ) {
  3001. var merged = {};
  3002. for ( var u = 0; u < uniforms.length; u ++ ) {
  3003. var tmp = this.clone( uniforms[ u ] );
  3004. for ( var p in tmp ) {
  3005. merged[ p ] = tmp[ p ];
  3006. }
  3007. }
  3008. return merged;
  3009. },
  3010. clone: function ( uniforms_src ) {
  3011. var uniforms_dst = {};
  3012. for ( var u in uniforms_src ) {
  3013. uniforms_dst[ u ] = {};
  3014. for ( var p in uniforms_src[ u ] ) {
  3015. var parameter_src = uniforms_src[ u ][ p ];
  3016. if ( parameter_src && ( parameter_src.isColor ||
  3017. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3018. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3019. parameter_src.isTexture ) ) {
  3020. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3021. } else if ( Array.isArray( parameter_src ) ) {
  3022. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3023. } else {
  3024. uniforms_dst[ u ][ p ] = parameter_src;
  3025. }
  3026. }
  3027. }
  3028. return uniforms_dst;
  3029. }
  3030. };
  3031. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3032. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3033. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3034. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  3035. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3036. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3037. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3038. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 ltcTextureCoords( const in GeometricContext geometry, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = (LUT_SIZE - 1.0)/LUT_SIZE;\n\tconst float LUT_BIAS = 0.5/LUT_SIZE;\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  3039. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  3040. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";
  3041. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  3042. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3043. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3044. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3045. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3046. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3047. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3048. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";
  3049. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  3050. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3051. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3052. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3053. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  3054. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3055. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3056. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3057. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  3058. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  3059. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  3060. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  3061. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3062. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  3063. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n";
  3064. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3065. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3066. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  3067. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  3068. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3069. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n }\n#endif\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3070. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  3071. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.specularRoughness;\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff;\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  3072. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3073. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3074. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  3075. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  3076. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  3077. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3078. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3079. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  3080. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3081. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  3082. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3083. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  3084. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  3085. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  3086. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  3087. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  3088. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3089. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3090. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3091. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  3092. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  3093. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3094. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3095. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  3096. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  3097. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3098. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  3099. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  3100. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  3101. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  3102. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  3103. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3104. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3105. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3106. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  3107. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  3108. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  3109. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3110. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3111. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3112. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  3113. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  3114. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3115. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  3116. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3117. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  3118. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  3119. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  3120. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  3121. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3122. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3123. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3124. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n}\n";
  3125. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3126. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3127. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3128. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3129. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3130. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3131. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#include <premultiplied_alpha_fragment>\n\t#include <encodings_fragment>\n}\n";
  3132. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3133. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3134. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3135. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  3136. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3137. var ShaderChunk = {
  3138. alphamap_fragment: alphamap_fragment,
  3139. alphamap_pars_fragment: alphamap_pars_fragment,
  3140. alphatest_fragment: alphatest_fragment,
  3141. aomap_fragment: aomap_fragment,
  3142. aomap_pars_fragment: aomap_pars_fragment,
  3143. begin_vertex: begin_vertex,
  3144. beginnormal_vertex: beginnormal_vertex,
  3145. bsdfs: bsdfs,
  3146. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3147. clipping_planes_fragment: clipping_planes_fragment,
  3148. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3149. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3150. clipping_planes_vertex: clipping_planes_vertex,
  3151. color_fragment: color_fragment,
  3152. color_pars_fragment: color_pars_fragment,
  3153. color_pars_vertex: color_pars_vertex,
  3154. color_vertex: color_vertex,
  3155. common: common,
  3156. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3157. defaultnormal_vertex: defaultnormal_vertex,
  3158. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3159. displacementmap_vertex: displacementmap_vertex,
  3160. emissivemap_fragment: emissivemap_fragment,
  3161. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3162. encodings_fragment: encodings_fragment,
  3163. encodings_pars_fragment: encodings_pars_fragment,
  3164. envmap_fragment: envmap_fragment,
  3165. envmap_pars_fragment: envmap_pars_fragment,
  3166. envmap_pars_vertex: envmap_pars_vertex,
  3167. envmap_vertex: envmap_vertex,
  3168. fog_fragment: fog_fragment,
  3169. fog_pars_fragment: fog_pars_fragment,
  3170. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3171. lightmap_fragment: lightmap_fragment,
  3172. lightmap_pars_fragment: lightmap_pars_fragment,
  3173. lights_lambert_vertex: lights_lambert_vertex,
  3174. lights_pars: lights_pars,
  3175. lights_phong_fragment: lights_phong_fragment,
  3176. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3177. lights_physical_fragment: lights_physical_fragment,
  3178. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3179. lights_template: lights_template,
  3180. logdepthbuf_fragment: logdepthbuf_fragment,
  3181. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3182. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3183. logdepthbuf_vertex: logdepthbuf_vertex,
  3184. map_fragment: map_fragment,
  3185. map_pars_fragment: map_pars_fragment,
  3186. map_particle_fragment: map_particle_fragment,
  3187. map_particle_pars_fragment: map_particle_pars_fragment,
  3188. metalnessmap_fragment: metalnessmap_fragment,
  3189. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3190. morphnormal_vertex: morphnormal_vertex,
  3191. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3192. morphtarget_vertex: morphtarget_vertex,
  3193. normal_flip: normal_flip,
  3194. normal_fragment: normal_fragment,
  3195. normalmap_pars_fragment: normalmap_pars_fragment,
  3196. packing: packing,
  3197. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3198. project_vertex: project_vertex,
  3199. roughnessmap_fragment: roughnessmap_fragment,
  3200. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3201. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3202. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3203. shadowmap_vertex: shadowmap_vertex,
  3204. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3205. skinbase_vertex: skinbase_vertex,
  3206. skinning_pars_vertex: skinning_pars_vertex,
  3207. skinning_vertex: skinning_vertex,
  3208. skinnormal_vertex: skinnormal_vertex,
  3209. specularmap_fragment: specularmap_fragment,
  3210. specularmap_pars_fragment: specularmap_pars_fragment,
  3211. tonemapping_fragment: tonemapping_fragment,
  3212. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3213. uv_pars_fragment: uv_pars_fragment,
  3214. uv_pars_vertex: uv_pars_vertex,
  3215. uv_vertex: uv_vertex,
  3216. uv2_pars_fragment: uv2_pars_fragment,
  3217. uv2_pars_vertex: uv2_pars_vertex,
  3218. uv2_vertex: uv2_vertex,
  3219. worldpos_vertex: worldpos_vertex,
  3220. cube_frag: cube_frag,
  3221. cube_vert: cube_vert,
  3222. depth_frag: depth_frag,
  3223. depth_vert: depth_vert,
  3224. distanceRGBA_frag: distanceRGBA_frag,
  3225. distanceRGBA_vert: distanceRGBA_vert,
  3226. equirect_frag: equirect_frag,
  3227. equirect_vert: equirect_vert,
  3228. linedashed_frag: linedashed_frag,
  3229. linedashed_vert: linedashed_vert,
  3230. meshbasic_frag: meshbasic_frag,
  3231. meshbasic_vert: meshbasic_vert,
  3232. meshlambert_frag: meshlambert_frag,
  3233. meshlambert_vert: meshlambert_vert,
  3234. meshphong_frag: meshphong_frag,
  3235. meshphong_vert: meshphong_vert,
  3236. meshphysical_frag: meshphysical_frag,
  3237. meshphysical_vert: meshphysical_vert,
  3238. normal_frag: normal_frag,
  3239. normal_vert: normal_vert,
  3240. points_frag: points_frag,
  3241. points_vert: points_vert,
  3242. shadow_frag: shadow_frag,
  3243. shadow_vert: shadow_vert
  3244. };
  3245. /**
  3246. * @author mrdoob / http://mrdoob.com/
  3247. */
  3248. function Color( r, g, b ) {
  3249. if ( g === undefined && b === undefined ) {
  3250. // r is THREE.Color, hex or string
  3251. return this.set( r );
  3252. }
  3253. return this.setRGB( r, g, b );
  3254. }
  3255. Color.prototype = {
  3256. constructor: Color,
  3257. isColor: true,
  3258. r: 1, g: 1, b: 1,
  3259. set: function ( value ) {
  3260. if ( value && value.isColor ) {
  3261. this.copy( value );
  3262. } else if ( typeof value === 'number' ) {
  3263. this.setHex( value );
  3264. } else if ( typeof value === 'string' ) {
  3265. this.setStyle( value );
  3266. }
  3267. return this;
  3268. },
  3269. setScalar: function ( scalar ) {
  3270. this.r = scalar;
  3271. this.g = scalar;
  3272. this.b = scalar;
  3273. return this;
  3274. },
  3275. setHex: function ( hex ) {
  3276. hex = Math.floor( hex );
  3277. this.r = ( hex >> 16 & 255 ) / 255;
  3278. this.g = ( hex >> 8 & 255 ) / 255;
  3279. this.b = ( hex & 255 ) / 255;
  3280. return this;
  3281. },
  3282. setRGB: function ( r, g, b ) {
  3283. this.r = r;
  3284. this.g = g;
  3285. this.b = b;
  3286. return this;
  3287. },
  3288. setHSL: function () {
  3289. function hue2rgb( p, q, t ) {
  3290. if ( t < 0 ) t += 1;
  3291. if ( t > 1 ) t -= 1;
  3292. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3293. if ( t < 1 / 2 ) return q;
  3294. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3295. return p;
  3296. }
  3297. return function setHSL( h, s, l ) {
  3298. // h,s,l ranges are in 0.0 - 1.0
  3299. h = _Math.euclideanModulo( h, 1 );
  3300. s = _Math.clamp( s, 0, 1 );
  3301. l = _Math.clamp( l, 0, 1 );
  3302. if ( s === 0 ) {
  3303. this.r = this.g = this.b = l;
  3304. } else {
  3305. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3306. var q = ( 2 * l ) - p;
  3307. this.r = hue2rgb( q, p, h + 1 / 3 );
  3308. this.g = hue2rgb( q, p, h );
  3309. this.b = hue2rgb( q, p, h - 1 / 3 );
  3310. }
  3311. return this;
  3312. };
  3313. }(),
  3314. setStyle: function ( style ) {
  3315. function handleAlpha( string ) {
  3316. if ( string === undefined ) return;
  3317. if ( parseFloat( string ) < 1 ) {
  3318. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3319. }
  3320. }
  3321. var m;
  3322. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3323. // rgb / hsl
  3324. var color;
  3325. var name = m[ 1 ];
  3326. var components = m[ 2 ];
  3327. switch ( name ) {
  3328. case 'rgb':
  3329. case 'rgba':
  3330. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3331. // rgb(255,0,0) rgba(255,0,0,0.5)
  3332. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3333. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3334. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3335. handleAlpha( color[ 5 ] );
  3336. return this;
  3337. }
  3338. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3339. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3340. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3341. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3342. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3343. handleAlpha( color[ 5 ] );
  3344. return this;
  3345. }
  3346. break;
  3347. case 'hsl':
  3348. case 'hsla':
  3349. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3350. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3351. var h = parseFloat( color[ 1 ] ) / 360;
  3352. var s = parseInt( color[ 2 ], 10 ) / 100;
  3353. var l = parseInt( color[ 3 ], 10 ) / 100;
  3354. handleAlpha( color[ 5 ] );
  3355. return this.setHSL( h, s, l );
  3356. }
  3357. break;
  3358. }
  3359. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3360. // hex color
  3361. var hex = m[ 1 ];
  3362. var size = hex.length;
  3363. if ( size === 3 ) {
  3364. // #ff0
  3365. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3366. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3367. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3368. return this;
  3369. } else if ( size === 6 ) {
  3370. // #ff0000
  3371. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3372. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3373. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3374. return this;
  3375. }
  3376. }
  3377. if ( style && style.length > 0 ) {
  3378. // color keywords
  3379. var hex = ColorKeywords[ style ];
  3380. if ( hex !== undefined ) {
  3381. // red
  3382. this.setHex( hex );
  3383. } else {
  3384. // unknown color
  3385. console.warn( 'THREE.Color: Unknown color ' + style );
  3386. }
  3387. }
  3388. return this;
  3389. },
  3390. clone: function () {
  3391. return new this.constructor( this.r, this.g, this.b );
  3392. },
  3393. copy: function ( color ) {
  3394. this.r = color.r;
  3395. this.g = color.g;
  3396. this.b = color.b;
  3397. return this;
  3398. },
  3399. copyGammaToLinear: function ( color, gammaFactor ) {
  3400. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3401. this.r = Math.pow( color.r, gammaFactor );
  3402. this.g = Math.pow( color.g, gammaFactor );
  3403. this.b = Math.pow( color.b, gammaFactor );
  3404. return this;
  3405. },
  3406. copyLinearToGamma: function ( color, gammaFactor ) {
  3407. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3408. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3409. this.r = Math.pow( color.r, safeInverse );
  3410. this.g = Math.pow( color.g, safeInverse );
  3411. this.b = Math.pow( color.b, safeInverse );
  3412. return this;
  3413. },
  3414. convertGammaToLinear: function () {
  3415. var r = this.r, g = this.g, b = this.b;
  3416. this.r = r * r;
  3417. this.g = g * g;
  3418. this.b = b * b;
  3419. return this;
  3420. },
  3421. convertLinearToGamma: function () {
  3422. this.r = Math.sqrt( this.r );
  3423. this.g = Math.sqrt( this.g );
  3424. this.b = Math.sqrt( this.b );
  3425. return this;
  3426. },
  3427. getHex: function () {
  3428. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3429. },
  3430. getHexString: function () {
  3431. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3432. },
  3433. getHSL: function ( optionalTarget ) {
  3434. // h,s,l ranges are in 0.0 - 1.0
  3435. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3436. var r = this.r, g = this.g, b = this.b;
  3437. var max = Math.max( r, g, b );
  3438. var min = Math.min( r, g, b );
  3439. var hue, saturation;
  3440. var lightness = ( min + max ) / 2.0;
  3441. if ( min === max ) {
  3442. hue = 0;
  3443. saturation = 0;
  3444. } else {
  3445. var delta = max - min;
  3446. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3447. switch ( max ) {
  3448. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3449. case g: hue = ( b - r ) / delta + 2; break;
  3450. case b: hue = ( r - g ) / delta + 4; break;
  3451. }
  3452. hue /= 6;
  3453. }
  3454. hsl.h = hue;
  3455. hsl.s = saturation;
  3456. hsl.l = lightness;
  3457. return hsl;
  3458. },
  3459. getStyle: function () {
  3460. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3461. },
  3462. offsetHSL: function ( h, s, l ) {
  3463. var hsl = this.getHSL();
  3464. hsl.h += h; hsl.s += s; hsl.l += l;
  3465. this.setHSL( hsl.h, hsl.s, hsl.l );
  3466. return this;
  3467. },
  3468. add: function ( color ) {
  3469. this.r += color.r;
  3470. this.g += color.g;
  3471. this.b += color.b;
  3472. return this;
  3473. },
  3474. addColors: function ( color1, color2 ) {
  3475. this.r = color1.r + color2.r;
  3476. this.g = color1.g + color2.g;
  3477. this.b = color1.b + color2.b;
  3478. return this;
  3479. },
  3480. addScalar: function ( s ) {
  3481. this.r += s;
  3482. this.g += s;
  3483. this.b += s;
  3484. return this;
  3485. },
  3486. sub: function( color ) {
  3487. this.r = Math.max( 0, this.r - color.r );
  3488. this.g = Math.max( 0, this.g - color.g );
  3489. this.b = Math.max( 0, this.b - color.b );
  3490. return this;
  3491. },
  3492. multiply: function ( color ) {
  3493. this.r *= color.r;
  3494. this.g *= color.g;
  3495. this.b *= color.b;
  3496. return this;
  3497. },
  3498. multiplyScalar: function ( s ) {
  3499. this.r *= s;
  3500. this.g *= s;
  3501. this.b *= s;
  3502. return this;
  3503. },
  3504. lerp: function ( color, alpha ) {
  3505. this.r += ( color.r - this.r ) * alpha;
  3506. this.g += ( color.g - this.g ) * alpha;
  3507. this.b += ( color.b - this.b ) * alpha;
  3508. return this;
  3509. },
  3510. equals: function ( c ) {
  3511. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3512. },
  3513. fromArray: function ( array, offset ) {
  3514. if ( offset === undefined ) offset = 0;
  3515. this.r = array[ offset ];
  3516. this.g = array[ offset + 1 ];
  3517. this.b = array[ offset + 2 ];
  3518. return this;
  3519. },
  3520. toArray: function ( array, offset ) {
  3521. if ( array === undefined ) array = [];
  3522. if ( offset === undefined ) offset = 0;
  3523. array[ offset ] = this.r;
  3524. array[ offset + 1 ] = this.g;
  3525. array[ offset + 2 ] = this.b;
  3526. return array;
  3527. },
  3528. toJSON: function () {
  3529. return this.getHex();
  3530. }
  3531. };
  3532. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3533. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3534. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3535. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3536. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3537. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3538. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3539. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3540. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3541. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3542. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3543. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3544. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3545. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3546. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3547. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3548. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3549. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3550. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3551. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3552. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3553. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3554. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3555. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3556. /**
  3557. * @author alteredq / http://alteredqualia.com/
  3558. */
  3559. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  3560. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  3561. this.image = { data: data, width: width, height: height };
  3562. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  3563. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  3564. this.generateMipmaps = false;
  3565. this.flipY = false;
  3566. this.unpackAlignment = 1;
  3567. }
  3568. DataTexture.prototype = Object.create( Texture.prototype );
  3569. DataTexture.prototype.constructor = DataTexture;
  3570. DataTexture.prototype.isDataTexture = true;
  3571. /**
  3572. * Uniforms library for shared webgl shaders
  3573. */
  3574. var UniformsLib = {
  3575. common: {
  3576. diffuse: { value: new Color( 0xeeeeee ) },
  3577. opacity: { value: 1.0 },
  3578. map: { value: null },
  3579. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3580. specularMap: { value: null },
  3581. alphaMap: { value: null },
  3582. envMap: { value: null },
  3583. flipEnvMap: { value: - 1 },
  3584. reflectivity: { value: 1.0 },
  3585. refractionRatio: { value: 0.98 }
  3586. },
  3587. aomap: {
  3588. aoMap: { value: null },
  3589. aoMapIntensity: { value: 1 }
  3590. },
  3591. lightmap: {
  3592. lightMap: { value: null },
  3593. lightMapIntensity: { value: 1 }
  3594. },
  3595. emissivemap: {
  3596. emissiveMap: { value: null }
  3597. },
  3598. bumpmap: {
  3599. bumpMap: { value: null },
  3600. bumpScale: { value: 1 }
  3601. },
  3602. normalmap: {
  3603. normalMap: { value: null },
  3604. normalScale: { value: new Vector2( 1, 1 ) }
  3605. },
  3606. displacementmap: {
  3607. displacementMap: { value: null },
  3608. displacementScale: { value: 1 },
  3609. displacementBias: { value: 0 }
  3610. },
  3611. roughnessmap: {
  3612. roughnessMap: { value: null }
  3613. },
  3614. metalnessmap: {
  3615. metalnessMap: { value: null }
  3616. },
  3617. gradientmap: {
  3618. gradientMap: { value: null }
  3619. },
  3620. fog: {
  3621. fogDensity: { value: 0.00025 },
  3622. fogNear: { value: 1 },
  3623. fogFar: { value: 2000 },
  3624. fogColor: { value: new Color( 0xffffff ) }
  3625. },
  3626. lights: {
  3627. ambientLightColor: { value: [] },
  3628. directionalLights: { value: [], properties: {
  3629. direction: {},
  3630. color: {},
  3631. shadow: {},
  3632. shadowBias: {},
  3633. shadowRadius: {},
  3634. shadowMapSize: {}
  3635. } },
  3636. directionalShadowMap: { value: [] },
  3637. directionalShadowMatrix: { value: [] },
  3638. spotLights: { value: [], properties: {
  3639. color: {},
  3640. position: {},
  3641. direction: {},
  3642. distance: {},
  3643. coneCos: {},
  3644. penumbraCos: {},
  3645. decay: {},
  3646. shadow: {},
  3647. shadowBias: {},
  3648. shadowRadius: {},
  3649. shadowMapSize: {}
  3650. } },
  3651. spotShadowMap: { value: [] },
  3652. spotShadowMatrix: { value: [] },
  3653. pointLights: { value: [], properties: {
  3654. color: {},
  3655. position: {},
  3656. decay: {},
  3657. distance: {},
  3658. shadow: {},
  3659. shadowBias: {},
  3660. shadowRadius: {},
  3661. shadowMapSize: {}
  3662. } },
  3663. pointShadowMap: { value: [] },
  3664. pointShadowMatrix: { value: [] },
  3665. hemisphereLights: { value: [], properties: {
  3666. direction: {},
  3667. skyColor: {},
  3668. groundColor: {}
  3669. } },
  3670. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3671. rectAreaLights: { value: [], properties: {
  3672. color: {},
  3673. position: {},
  3674. width: {},
  3675. height: {},
  3676. } }
  3677. },
  3678. points: {
  3679. diffuse: { value: new Color( 0xeeeeee ) },
  3680. opacity: { value: 1.0 },
  3681. size: { value: 1.0 },
  3682. scale: { value: 1.0 },
  3683. map: { value: null },
  3684. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3685. }
  3686. };
  3687. /**
  3688. * @author alteredq / http://alteredqualia.com/
  3689. * @author mrdoob / http://mrdoob.com/
  3690. * @author mikael emtinger / http://gomo.se/
  3691. */
  3692. var ShaderLib = {
  3693. basic: {
  3694. uniforms: UniformsUtils.merge( [
  3695. UniformsLib.common,
  3696. UniformsLib.aomap,
  3697. UniformsLib.lightmap,
  3698. UniformsLib.fog
  3699. ] ),
  3700. vertexShader: ShaderChunk.meshbasic_vert,
  3701. fragmentShader: ShaderChunk.meshbasic_frag
  3702. },
  3703. lambert: {
  3704. uniforms: UniformsUtils.merge( [
  3705. UniformsLib.common,
  3706. UniformsLib.aomap,
  3707. UniformsLib.lightmap,
  3708. UniformsLib.emissivemap,
  3709. UniformsLib.fog,
  3710. UniformsLib.lights,
  3711. {
  3712. emissive: { value: new Color( 0x000000 ) }
  3713. }
  3714. ] ),
  3715. vertexShader: ShaderChunk.meshlambert_vert,
  3716. fragmentShader: ShaderChunk.meshlambert_frag
  3717. },
  3718. phong: {
  3719. uniforms: UniformsUtils.merge( [
  3720. UniformsLib.common,
  3721. UniformsLib.aomap,
  3722. UniformsLib.lightmap,
  3723. UniformsLib.emissivemap,
  3724. UniformsLib.bumpmap,
  3725. UniformsLib.normalmap,
  3726. UniformsLib.displacementmap,
  3727. UniformsLib.gradientmap,
  3728. UniformsLib.fog,
  3729. UniformsLib.lights,
  3730. {
  3731. emissive: { value: new Color( 0x000000 ) },
  3732. specular: { value: new Color( 0x111111 ) },
  3733. shininess: { value: 30 }
  3734. }
  3735. ] ),
  3736. vertexShader: ShaderChunk.meshphong_vert,
  3737. fragmentShader: ShaderChunk.meshphong_frag
  3738. },
  3739. standard: {
  3740. uniforms: UniformsUtils.merge( [
  3741. UniformsLib.common,
  3742. UniformsLib.aomap,
  3743. UniformsLib.lightmap,
  3744. UniformsLib.emissivemap,
  3745. UniformsLib.bumpmap,
  3746. UniformsLib.normalmap,
  3747. UniformsLib.displacementmap,
  3748. UniformsLib.roughnessmap,
  3749. UniformsLib.metalnessmap,
  3750. UniformsLib.fog,
  3751. UniformsLib.lights,
  3752. {
  3753. emissive: { value: new Color( 0x000000 ) },
  3754. roughness: { value: 0.5 },
  3755. metalness: { value: 0 },
  3756. envMapIntensity: { value: 1 } // temporary
  3757. }
  3758. ] ),
  3759. vertexShader: ShaderChunk.meshphysical_vert,
  3760. fragmentShader: ShaderChunk.meshphysical_frag
  3761. },
  3762. points: {
  3763. uniforms: UniformsUtils.merge( [
  3764. UniformsLib.points,
  3765. UniformsLib.fog
  3766. ] ),
  3767. vertexShader: ShaderChunk.points_vert,
  3768. fragmentShader: ShaderChunk.points_frag
  3769. },
  3770. dashed: {
  3771. uniforms: UniformsUtils.merge( [
  3772. UniformsLib.common,
  3773. UniformsLib.fog,
  3774. {
  3775. scale: { value: 1 },
  3776. dashSize: { value: 1 },
  3777. totalSize: { value: 2 }
  3778. }
  3779. ] ),
  3780. vertexShader: ShaderChunk.linedashed_vert,
  3781. fragmentShader: ShaderChunk.linedashed_frag
  3782. },
  3783. depth: {
  3784. uniforms: UniformsUtils.merge( [
  3785. UniformsLib.common,
  3786. UniformsLib.displacementmap
  3787. ] ),
  3788. vertexShader: ShaderChunk.depth_vert,
  3789. fragmentShader: ShaderChunk.depth_frag
  3790. },
  3791. normal: {
  3792. uniforms: UniformsUtils.merge( [
  3793. UniformsLib.common,
  3794. UniformsLib.bumpmap,
  3795. UniformsLib.normalmap,
  3796. UniformsLib.displacementmap,
  3797. {
  3798. opacity: { value: 1.0 }
  3799. }
  3800. ] ),
  3801. vertexShader: ShaderChunk.normal_vert,
  3802. fragmentShader: ShaderChunk.normal_frag
  3803. },
  3804. /* -------------------------------------------------------------------------
  3805. // Cube map shader
  3806. ------------------------------------------------------------------------- */
  3807. cube: {
  3808. uniforms: {
  3809. tCube: { value: null },
  3810. tFlip: { value: - 1 },
  3811. opacity: { value: 1.0 }
  3812. },
  3813. vertexShader: ShaderChunk.cube_vert,
  3814. fragmentShader: ShaderChunk.cube_frag
  3815. },
  3816. /* -------------------------------------------------------------------------
  3817. // Cube map shader
  3818. ------------------------------------------------------------------------- */
  3819. equirect: {
  3820. uniforms: {
  3821. tEquirect: { value: null },
  3822. tFlip: { value: - 1 }
  3823. },
  3824. vertexShader: ShaderChunk.equirect_vert,
  3825. fragmentShader: ShaderChunk.equirect_frag
  3826. },
  3827. distanceRGBA: {
  3828. uniforms: {
  3829. lightPos: { value: new Vector3() }
  3830. },
  3831. vertexShader: ShaderChunk.distanceRGBA_vert,
  3832. fragmentShader: ShaderChunk.distanceRGBA_frag
  3833. }
  3834. };
  3835. ShaderLib.physical = {
  3836. uniforms: UniformsUtils.merge( [
  3837. ShaderLib.standard.uniforms,
  3838. {
  3839. clearCoat: { value: 0 },
  3840. clearCoatRoughness: { value: 0 }
  3841. }
  3842. ] ),
  3843. vertexShader: ShaderChunk.meshphysical_vert,
  3844. fragmentShader: ShaderChunk.meshphysical_frag
  3845. };
  3846. /**
  3847. * @author bhouston / http://clara.io
  3848. */
  3849. function Box2( min, max ) {
  3850. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3851. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3852. }
  3853. Box2.prototype = {
  3854. constructor: Box2,
  3855. set: function ( min, max ) {
  3856. this.min.copy( min );
  3857. this.max.copy( max );
  3858. return this;
  3859. },
  3860. setFromPoints: function ( points ) {
  3861. this.makeEmpty();
  3862. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3863. this.expandByPoint( points[ i ] );
  3864. }
  3865. return this;
  3866. },
  3867. setFromCenterAndSize: function () {
  3868. var v1 = new Vector2();
  3869. return function setFromCenterAndSize( center, size ) {
  3870. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3871. this.min.copy( center ).sub( halfSize );
  3872. this.max.copy( center ).add( halfSize );
  3873. return this;
  3874. };
  3875. }(),
  3876. clone: function () {
  3877. return new this.constructor().copy( this );
  3878. },
  3879. copy: function ( box ) {
  3880. this.min.copy( box.min );
  3881. this.max.copy( box.max );
  3882. return this;
  3883. },
  3884. makeEmpty: function () {
  3885. this.min.x = this.min.y = + Infinity;
  3886. this.max.x = this.max.y = - Infinity;
  3887. return this;
  3888. },
  3889. isEmpty: function () {
  3890. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3891. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3892. },
  3893. getCenter: function ( optionalTarget ) {
  3894. var result = optionalTarget || new Vector2();
  3895. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3896. },
  3897. getSize: function ( optionalTarget ) {
  3898. var result = optionalTarget || new Vector2();
  3899. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3900. },
  3901. expandByPoint: function ( point ) {
  3902. this.min.min( point );
  3903. this.max.max( point );
  3904. return this;
  3905. },
  3906. expandByVector: function ( vector ) {
  3907. this.min.sub( vector );
  3908. this.max.add( vector );
  3909. return this;
  3910. },
  3911. expandByScalar: function ( scalar ) {
  3912. this.min.addScalar( - scalar );
  3913. this.max.addScalar( scalar );
  3914. return this;
  3915. },
  3916. containsPoint: function ( point ) {
  3917. return point.x < this.min.x || point.x > this.max.x ||
  3918. point.y < this.min.y || point.y > this.max.y ? false : true;
  3919. },
  3920. containsBox: function ( box ) {
  3921. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3922. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3923. },
  3924. getParameter: function ( point, optionalTarget ) {
  3925. // This can potentially have a divide by zero if the box
  3926. // has a size dimension of 0.
  3927. var result = optionalTarget || new Vector2();
  3928. return result.set(
  3929. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3930. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3931. );
  3932. },
  3933. intersectsBox: function ( box ) {
  3934. // using 6 splitting planes to rule out intersections.
  3935. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3936. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3937. },
  3938. clampPoint: function ( point, optionalTarget ) {
  3939. var result = optionalTarget || new Vector2();
  3940. return result.copy( point ).clamp( this.min, this.max );
  3941. },
  3942. distanceToPoint: function () {
  3943. var v1 = new Vector2();
  3944. return function distanceToPoint( point ) {
  3945. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3946. return clampedPoint.sub( point ).length();
  3947. };
  3948. }(),
  3949. intersect: function ( box ) {
  3950. this.min.max( box.min );
  3951. this.max.min( box.max );
  3952. return this;
  3953. },
  3954. union: function ( box ) {
  3955. this.min.min( box.min );
  3956. this.max.max( box.max );
  3957. return this;
  3958. },
  3959. translate: function ( offset ) {
  3960. this.min.add( offset );
  3961. this.max.add( offset );
  3962. return this;
  3963. },
  3964. equals: function ( box ) {
  3965. return box.min.equals( this.min ) && box.max.equals( this.max );
  3966. }
  3967. };
  3968. /**
  3969. * @author mikael emtinger / http://gomo.se/
  3970. * @author alteredq / http://alteredqualia.com/
  3971. */
  3972. function LensFlarePlugin( renderer, flares ) {
  3973. var gl = renderer.context;
  3974. var state = renderer.state;
  3975. var vertexBuffer, elementBuffer;
  3976. var shader, program, attributes, uniforms;
  3977. var tempTexture, occlusionTexture;
  3978. function init() {
  3979. var vertices = new Float32Array( [
  3980. - 1, - 1, 0, 0,
  3981. 1, - 1, 1, 0,
  3982. 1, 1, 1, 1,
  3983. - 1, 1, 0, 1
  3984. ] );
  3985. var faces = new Uint16Array( [
  3986. 0, 1, 2,
  3987. 0, 2, 3
  3988. ] );
  3989. // buffers
  3990. vertexBuffer = gl.createBuffer();
  3991. elementBuffer = gl.createBuffer();
  3992. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3993. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3994. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3995. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3996. // textures
  3997. tempTexture = gl.createTexture();
  3998. occlusionTexture = gl.createTexture();
  3999. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4000. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  4001. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  4002. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  4003. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  4004. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  4005. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4006. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  4007. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  4008. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  4009. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  4010. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  4011. shader = {
  4012. vertexShader: [
  4013. "uniform lowp int renderType;",
  4014. "uniform vec3 screenPosition;",
  4015. "uniform vec2 scale;",
  4016. "uniform float rotation;",
  4017. "uniform sampler2D occlusionMap;",
  4018. "attribute vec2 position;",
  4019. "attribute vec2 uv;",
  4020. "varying vec2 vUV;",
  4021. "varying float vVisibility;",
  4022. "void main() {",
  4023. "vUV = uv;",
  4024. "vec2 pos = position;",
  4025. "if ( renderType == 2 ) {",
  4026. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  4027. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  4028. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  4029. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  4030. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  4031. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  4032. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  4033. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  4034. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  4035. "vVisibility = visibility.r / 9.0;",
  4036. "vVisibility *= 1.0 - visibility.g / 9.0;",
  4037. "vVisibility *= visibility.b / 9.0;",
  4038. "vVisibility *= 1.0 - visibility.a / 9.0;",
  4039. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  4040. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  4041. "}",
  4042. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  4043. "}"
  4044. ].join( "\n" ),
  4045. fragmentShader: [
  4046. "uniform lowp int renderType;",
  4047. "uniform sampler2D map;",
  4048. "uniform float opacity;",
  4049. "uniform vec3 color;",
  4050. "varying vec2 vUV;",
  4051. "varying float vVisibility;",
  4052. "void main() {",
  4053. // pink square
  4054. "if ( renderType == 0 ) {",
  4055. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4056. // restore
  4057. "} else if ( renderType == 1 ) {",
  4058. "gl_FragColor = texture2D( map, vUV );",
  4059. // flare
  4060. "} else {",
  4061. "vec4 texture = texture2D( map, vUV );",
  4062. "texture.a *= opacity * vVisibility;",
  4063. "gl_FragColor = texture;",
  4064. "gl_FragColor.rgb *= color;",
  4065. "}",
  4066. "}"
  4067. ].join( "\n" )
  4068. };
  4069. program = createProgram( shader );
  4070. attributes = {
  4071. vertex: gl.getAttribLocation ( program, "position" ),
  4072. uv: gl.getAttribLocation ( program, "uv" )
  4073. };
  4074. uniforms = {
  4075. renderType: gl.getUniformLocation( program, "renderType" ),
  4076. map: gl.getUniformLocation( program, "map" ),
  4077. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4078. opacity: gl.getUniformLocation( program, "opacity" ),
  4079. color: gl.getUniformLocation( program, "color" ),
  4080. scale: gl.getUniformLocation( program, "scale" ),
  4081. rotation: gl.getUniformLocation( program, "rotation" ),
  4082. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4083. };
  4084. }
  4085. /*
  4086. * Render lens flares
  4087. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4088. * reads these back and calculates occlusion.
  4089. */
  4090. this.render = function ( scene, camera, viewport ) {
  4091. if ( flares.length === 0 ) return;
  4092. var tempPosition = new Vector3();
  4093. var invAspect = viewport.w / viewport.z,
  4094. halfViewportWidth = viewport.z * 0.5,
  4095. halfViewportHeight = viewport.w * 0.5;
  4096. var size = 16 / viewport.w,
  4097. scale = new Vector2( size * invAspect, size );
  4098. var screenPosition = new Vector3( 1, 1, 0 ),
  4099. screenPositionPixels = new Vector2( 1, 1 );
  4100. var validArea = new Box2();
  4101. validArea.min.set( viewport.x, viewport.y );
  4102. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4103. if ( program === undefined ) {
  4104. init();
  4105. }
  4106. gl.useProgram( program );
  4107. state.initAttributes();
  4108. state.enableAttribute( attributes.vertex );
  4109. state.enableAttribute( attributes.uv );
  4110. state.disableUnusedAttributes();
  4111. // loop through all lens flares to update their occlusion and positions
  4112. // setup gl and common used attribs/uniforms
  4113. gl.uniform1i( uniforms.occlusionMap, 0 );
  4114. gl.uniform1i( uniforms.map, 1 );
  4115. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4116. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4117. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4118. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4119. state.disable( gl.CULL_FACE );
  4120. state.setDepthWrite( false );
  4121. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4122. size = 16 / viewport.w;
  4123. scale.set( size * invAspect, size );
  4124. // calc object screen position
  4125. var flare = flares[ i ];
  4126. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4127. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4128. tempPosition.applyProjection( camera.projectionMatrix );
  4129. // setup arrays for gl programs
  4130. screenPosition.copy( tempPosition );
  4131. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4132. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4133. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4134. // screen cull
  4135. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4136. // save current RGB to temp texture
  4137. state.activeTexture( gl.TEXTURE0 );
  4138. state.bindTexture( gl.TEXTURE_2D, null );
  4139. state.activeTexture( gl.TEXTURE1 );
  4140. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4141. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4142. // render pink quad
  4143. gl.uniform1i( uniforms.renderType, 0 );
  4144. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4145. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4146. state.disable( gl.BLEND );
  4147. state.enable( gl.DEPTH_TEST );
  4148. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4149. // copy result to occlusionMap
  4150. state.activeTexture( gl.TEXTURE0 );
  4151. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4152. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4153. // restore graphics
  4154. gl.uniform1i( uniforms.renderType, 1 );
  4155. state.disable( gl.DEPTH_TEST );
  4156. state.activeTexture( gl.TEXTURE1 );
  4157. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4158. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4159. // update object positions
  4160. flare.positionScreen.copy( screenPosition );
  4161. if ( flare.customUpdateCallback ) {
  4162. flare.customUpdateCallback( flare );
  4163. } else {
  4164. flare.updateLensFlares();
  4165. }
  4166. // render flares
  4167. gl.uniform1i( uniforms.renderType, 2 );
  4168. state.enable( gl.BLEND );
  4169. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4170. var sprite = flare.lensFlares[ j ];
  4171. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4172. screenPosition.x = sprite.x;
  4173. screenPosition.y = sprite.y;
  4174. screenPosition.z = sprite.z;
  4175. size = sprite.size * sprite.scale / viewport.w;
  4176. scale.x = size * invAspect;
  4177. scale.y = size;
  4178. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4179. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4180. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4181. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4182. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4183. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4184. renderer.setTexture2D( sprite.texture, 1 );
  4185. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4186. }
  4187. }
  4188. }
  4189. }
  4190. // restore gl
  4191. state.enable( gl.CULL_FACE );
  4192. state.enable( gl.DEPTH_TEST );
  4193. state.setDepthWrite( true );
  4194. renderer.resetGLState();
  4195. };
  4196. function createProgram( shader ) {
  4197. var program = gl.createProgram();
  4198. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4199. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4200. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4201. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4202. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4203. gl.compileShader( fragmentShader );
  4204. gl.compileShader( vertexShader );
  4205. gl.attachShader( program, fragmentShader );
  4206. gl.attachShader( program, vertexShader );
  4207. gl.linkProgram( program );
  4208. return program;
  4209. }
  4210. }
  4211. /**
  4212. * @author mikael emtinger / http://gomo.se/
  4213. * @author alteredq / http://alteredqualia.com/
  4214. */
  4215. function SpritePlugin( renderer, sprites ) {
  4216. var gl = renderer.context;
  4217. var state = renderer.state;
  4218. var vertexBuffer, elementBuffer;
  4219. var program, attributes, uniforms;
  4220. var texture;
  4221. // decompose matrixWorld
  4222. var spritePosition = new Vector3();
  4223. var spriteRotation = new Quaternion();
  4224. var spriteScale = new Vector3();
  4225. function init() {
  4226. var vertices = new Float32Array( [
  4227. - 0.5, - 0.5, 0, 0,
  4228. 0.5, - 0.5, 1, 0,
  4229. 0.5, 0.5, 1, 1,
  4230. - 0.5, 0.5, 0, 1
  4231. ] );
  4232. var faces = new Uint16Array( [
  4233. 0, 1, 2,
  4234. 0, 2, 3
  4235. ] );
  4236. vertexBuffer = gl.createBuffer();
  4237. elementBuffer = gl.createBuffer();
  4238. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4239. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4240. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4241. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4242. program = createProgram();
  4243. attributes = {
  4244. position: gl.getAttribLocation ( program, 'position' ),
  4245. uv: gl.getAttribLocation ( program, 'uv' )
  4246. };
  4247. uniforms = {
  4248. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4249. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4250. rotation: gl.getUniformLocation( program, 'rotation' ),
  4251. scale: gl.getUniformLocation( program, 'scale' ),
  4252. color: gl.getUniformLocation( program, 'color' ),
  4253. map: gl.getUniformLocation( program, 'map' ),
  4254. opacity: gl.getUniformLocation( program, 'opacity' ),
  4255. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4256. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4257. fogType: gl.getUniformLocation( program, 'fogType' ),
  4258. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4259. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4260. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4261. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4262. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4263. };
  4264. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4265. canvas.width = 8;
  4266. canvas.height = 8;
  4267. var context = canvas.getContext( '2d' );
  4268. context.fillStyle = 'white';
  4269. context.fillRect( 0, 0, 8, 8 );
  4270. texture = new Texture( canvas );
  4271. texture.needsUpdate = true;
  4272. }
  4273. this.render = function ( scene, camera ) {
  4274. if ( sprites.length === 0 ) return;
  4275. // setup gl
  4276. if ( program === undefined ) {
  4277. init();
  4278. }
  4279. gl.useProgram( program );
  4280. state.initAttributes();
  4281. state.enableAttribute( attributes.position );
  4282. state.enableAttribute( attributes.uv );
  4283. state.disableUnusedAttributes();
  4284. state.disable( gl.CULL_FACE );
  4285. state.enable( gl.BLEND );
  4286. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4287. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4288. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4289. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4290. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4291. state.activeTexture( gl.TEXTURE0 );
  4292. gl.uniform1i( uniforms.map, 0 );
  4293. var oldFogType = 0;
  4294. var sceneFogType = 0;
  4295. var fog = scene.fog;
  4296. if ( fog ) {
  4297. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4298. if ( fog.isFog ) {
  4299. gl.uniform1f( uniforms.fogNear, fog.near );
  4300. gl.uniform1f( uniforms.fogFar, fog.far );
  4301. gl.uniform1i( uniforms.fogType, 1 );
  4302. oldFogType = 1;
  4303. sceneFogType = 1;
  4304. } else if ( fog.isFogExp2 ) {
  4305. gl.uniform1f( uniforms.fogDensity, fog.density );
  4306. gl.uniform1i( uniforms.fogType, 2 );
  4307. oldFogType = 2;
  4308. sceneFogType = 2;
  4309. }
  4310. } else {
  4311. gl.uniform1i( uniforms.fogType, 0 );
  4312. oldFogType = 0;
  4313. sceneFogType = 0;
  4314. }
  4315. // update positions and sort
  4316. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4317. var sprite = sprites[ i ];
  4318. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4319. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4320. }
  4321. sprites.sort( painterSortStable );
  4322. // render all sprites
  4323. var scale = [];
  4324. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4325. var sprite = sprites[ i ];
  4326. var material = sprite.material;
  4327. if ( material.visible === false ) continue;
  4328. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4329. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4330. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4331. scale[ 0 ] = spriteScale.x;
  4332. scale[ 1 ] = spriteScale.y;
  4333. var fogType = 0;
  4334. if ( scene.fog && material.fog ) {
  4335. fogType = sceneFogType;
  4336. }
  4337. if ( oldFogType !== fogType ) {
  4338. gl.uniform1i( uniforms.fogType, fogType );
  4339. oldFogType = fogType;
  4340. }
  4341. if ( material.map !== null ) {
  4342. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4343. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4344. } else {
  4345. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4346. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4347. }
  4348. gl.uniform1f( uniforms.opacity, material.opacity );
  4349. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4350. gl.uniform1f( uniforms.rotation, material.rotation );
  4351. gl.uniform2fv( uniforms.scale, scale );
  4352. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4353. state.setDepthTest( material.depthTest );
  4354. state.setDepthWrite( material.depthWrite );
  4355. if ( material.map ) {
  4356. renderer.setTexture2D( material.map, 0 );
  4357. } else {
  4358. renderer.setTexture2D( texture, 0 );
  4359. }
  4360. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4361. }
  4362. // restore gl
  4363. state.enable( gl.CULL_FACE );
  4364. renderer.resetGLState();
  4365. };
  4366. function createProgram() {
  4367. var program = gl.createProgram();
  4368. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4369. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4370. gl.shaderSource( vertexShader, [
  4371. 'precision ' + renderer.getPrecision() + ' float;',
  4372. 'uniform mat4 modelViewMatrix;',
  4373. 'uniform mat4 projectionMatrix;',
  4374. 'uniform float rotation;',
  4375. 'uniform vec2 scale;',
  4376. 'uniform vec2 uvOffset;',
  4377. 'uniform vec2 uvScale;',
  4378. 'attribute vec2 position;',
  4379. 'attribute vec2 uv;',
  4380. 'varying vec2 vUV;',
  4381. 'void main() {',
  4382. 'vUV = uvOffset + uv * uvScale;',
  4383. 'vec2 alignedPosition = position * scale;',
  4384. 'vec2 rotatedPosition;',
  4385. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4386. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4387. 'vec4 finalPosition;',
  4388. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4389. 'finalPosition.xy += rotatedPosition;',
  4390. 'finalPosition = projectionMatrix * finalPosition;',
  4391. 'gl_Position = finalPosition;',
  4392. '}'
  4393. ].join( '\n' ) );
  4394. gl.shaderSource( fragmentShader, [
  4395. 'precision ' + renderer.getPrecision() + ' float;',
  4396. 'uniform vec3 color;',
  4397. 'uniform sampler2D map;',
  4398. 'uniform float opacity;',
  4399. 'uniform int fogType;',
  4400. 'uniform vec3 fogColor;',
  4401. 'uniform float fogDensity;',
  4402. 'uniform float fogNear;',
  4403. 'uniform float fogFar;',
  4404. 'uniform float alphaTest;',
  4405. 'varying vec2 vUV;',
  4406. 'void main() {',
  4407. 'vec4 texture = texture2D( map, vUV );',
  4408. 'if ( texture.a < alphaTest ) discard;',
  4409. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4410. 'if ( fogType > 0 ) {',
  4411. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4412. 'float fogFactor = 0.0;',
  4413. 'if ( fogType == 1 ) {',
  4414. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4415. '} else {',
  4416. 'const float LOG2 = 1.442695;',
  4417. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4418. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4419. '}',
  4420. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4421. '}',
  4422. '}'
  4423. ].join( '\n' ) );
  4424. gl.compileShader( vertexShader );
  4425. gl.compileShader( fragmentShader );
  4426. gl.attachShader( program, vertexShader );
  4427. gl.attachShader( program, fragmentShader );
  4428. gl.linkProgram( program );
  4429. return program;
  4430. }
  4431. function painterSortStable( a, b ) {
  4432. if ( a.renderOrder !== b.renderOrder ) {
  4433. return a.renderOrder - b.renderOrder;
  4434. } else if ( a.z !== b.z ) {
  4435. return b.z - a.z;
  4436. } else {
  4437. return b.id - a.id;
  4438. }
  4439. }
  4440. }
  4441. /**
  4442. * @author mrdoob / http://mrdoob.com/
  4443. * @author alteredq / http://alteredqualia.com/
  4444. */
  4445. var materialId = 0;
  4446. function Material() {
  4447. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4448. this.uuid = _Math.generateUUID();
  4449. this.name = '';
  4450. this.type = 'Material';
  4451. this.fog = true;
  4452. this.lights = true;
  4453. this.blending = NormalBlending;
  4454. this.side = FrontSide;
  4455. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4456. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4457. this.opacity = 1;
  4458. this.transparent = false;
  4459. this.blendSrc = SrcAlphaFactor;
  4460. this.blendDst = OneMinusSrcAlphaFactor;
  4461. this.blendEquation = AddEquation;
  4462. this.blendSrcAlpha = null;
  4463. this.blendDstAlpha = null;
  4464. this.blendEquationAlpha = null;
  4465. this.depthFunc = LessEqualDepth;
  4466. this.depthTest = true;
  4467. this.depthWrite = true;
  4468. this.clippingPlanes = null;
  4469. this.clipIntersection = false;
  4470. this.clipShadows = false;
  4471. this.colorWrite = true;
  4472. this.precision = null; // override the renderer's default precision for this material
  4473. this.polygonOffset = false;
  4474. this.polygonOffsetFactor = 0;
  4475. this.polygonOffsetUnits = 0;
  4476. this.alphaTest = 0;
  4477. this.premultipliedAlpha = false;
  4478. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4479. this.visible = true;
  4480. this._needsUpdate = true;
  4481. }
  4482. Material.prototype = {
  4483. constructor: Material,
  4484. isMaterial: true,
  4485. get needsUpdate() {
  4486. return this._needsUpdate;
  4487. },
  4488. set needsUpdate( value ) {
  4489. if ( value === true ) this.update();
  4490. this._needsUpdate = value;
  4491. },
  4492. setValues: function ( values ) {
  4493. if ( values === undefined ) return;
  4494. for ( var key in values ) {
  4495. var newValue = values[ key ];
  4496. if ( newValue === undefined ) {
  4497. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4498. continue;
  4499. }
  4500. var currentValue = this[ key ];
  4501. if ( currentValue === undefined ) {
  4502. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4503. continue;
  4504. }
  4505. if ( currentValue && currentValue.isColor ) {
  4506. currentValue.set( newValue );
  4507. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4508. currentValue.copy( newValue );
  4509. } else if ( key === 'overdraw' ) {
  4510. // ensure overdraw is backwards-compatible with legacy boolean type
  4511. this[ key ] = Number( newValue );
  4512. } else {
  4513. this[ key ] = newValue;
  4514. }
  4515. }
  4516. },
  4517. toJSON: function ( meta ) {
  4518. var isRoot = meta === undefined;
  4519. if ( isRoot ) {
  4520. meta = {
  4521. textures: {},
  4522. images: {}
  4523. };
  4524. }
  4525. var data = {
  4526. metadata: {
  4527. version: 4.4,
  4528. type: 'Material',
  4529. generator: 'Material.toJSON'
  4530. }
  4531. };
  4532. // standard Material serialization
  4533. data.uuid = this.uuid;
  4534. data.type = this.type;
  4535. if ( this.name !== '' ) data.name = this.name;
  4536. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4537. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4538. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4539. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4540. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4541. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4542. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4543. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4544. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4545. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4546. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4547. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4548. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4549. data.bumpScale = this.bumpScale;
  4550. }
  4551. if ( this.normalMap && this.normalMap.isTexture ) {
  4552. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4553. data.normalScale = this.normalScale.toArray();
  4554. }
  4555. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4556. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4557. data.displacementScale = this.displacementScale;
  4558. data.displacementBias = this.displacementBias;
  4559. }
  4560. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4561. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4562. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4563. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4564. if ( this.envMap && this.envMap.isTexture ) {
  4565. data.envMap = this.envMap.toJSON( meta ).uuid;
  4566. data.reflectivity = this.reflectivity; // Scale behind envMap
  4567. }
  4568. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4569. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4570. }
  4571. if ( this.size !== undefined ) data.size = this.size;
  4572. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4573. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4574. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4575. if ( this.side !== FrontSide ) data.side = this.side;
  4576. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4577. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4578. if ( this.transparent === true ) data.transparent = this.transparent;
  4579. data.depthFunc = this.depthFunc;
  4580. data.depthTest = this.depthTest;
  4581. data.depthWrite = this.depthWrite;
  4582. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4583. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4584. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4585. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4586. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4587. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4588. data.skinning = this.skinning;
  4589. data.morphTargets = this.morphTargets;
  4590. // TODO: Copied from Object3D.toJSON
  4591. function extractFromCache( cache ) {
  4592. var values = [];
  4593. for ( var key in cache ) {
  4594. var data = cache[ key ];
  4595. delete data.metadata;
  4596. values.push( data );
  4597. }
  4598. return values;
  4599. }
  4600. if ( isRoot ) {
  4601. var textures = extractFromCache( meta.textures );
  4602. var images = extractFromCache( meta.images );
  4603. if ( textures.length > 0 ) data.textures = textures;
  4604. if ( images.length > 0 ) data.images = images;
  4605. }
  4606. return data;
  4607. },
  4608. clone: function () {
  4609. return new this.constructor().copy( this );
  4610. },
  4611. copy: function ( source ) {
  4612. this.name = source.name;
  4613. this.fog = source.fog;
  4614. this.lights = source.lights;
  4615. this.blending = source.blending;
  4616. this.side = source.side;
  4617. this.shading = source.shading;
  4618. this.vertexColors = source.vertexColors;
  4619. this.opacity = source.opacity;
  4620. this.transparent = source.transparent;
  4621. this.blendSrc = source.blendSrc;
  4622. this.blendDst = source.blendDst;
  4623. this.blendEquation = source.blendEquation;
  4624. this.blendSrcAlpha = source.blendSrcAlpha;
  4625. this.blendDstAlpha = source.blendDstAlpha;
  4626. this.blendEquationAlpha = source.blendEquationAlpha;
  4627. this.depthFunc = source.depthFunc;
  4628. this.depthTest = source.depthTest;
  4629. this.depthWrite = source.depthWrite;
  4630. this.colorWrite = source.colorWrite;
  4631. this.precision = source.precision;
  4632. this.polygonOffset = source.polygonOffset;
  4633. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4634. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4635. this.alphaTest = source.alphaTest;
  4636. this.premultipliedAlpha = source.premultipliedAlpha;
  4637. this.overdraw = source.overdraw;
  4638. this.visible = source.visible;
  4639. this.clipShadows = source.clipShadows;
  4640. this.clipIntersection = source.clipIntersection;
  4641. var srcPlanes = source.clippingPlanes,
  4642. dstPlanes = null;
  4643. if ( srcPlanes !== null ) {
  4644. var n = srcPlanes.length;
  4645. dstPlanes = new Array( n );
  4646. for ( var i = 0; i !== n; ++ i )
  4647. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4648. }
  4649. this.clippingPlanes = dstPlanes;
  4650. return this;
  4651. },
  4652. update: function () {
  4653. this.dispatchEvent( { type: 'update' } );
  4654. },
  4655. dispose: function () {
  4656. this.dispatchEvent( { type: 'dispose' } );
  4657. }
  4658. };
  4659. Object.assign( Material.prototype, EventDispatcher.prototype );
  4660. /**
  4661. * @author alteredq / http://alteredqualia.com/
  4662. *
  4663. * parameters = {
  4664. * defines: { "label" : "value" },
  4665. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4666. *
  4667. * fragmentShader: <string>,
  4668. * vertexShader: <string>,
  4669. *
  4670. * wireframe: <boolean>,
  4671. * wireframeLinewidth: <float>,
  4672. *
  4673. * lights: <bool>,
  4674. *
  4675. * skinning: <bool>,
  4676. * morphTargets: <bool>,
  4677. * morphNormals: <bool>
  4678. * }
  4679. */
  4680. function ShaderMaterial( parameters ) {
  4681. Material.call( this );
  4682. this.type = 'ShaderMaterial';
  4683. this.defines = {};
  4684. this.uniforms = {};
  4685. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4686. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4687. this.linewidth = 1;
  4688. this.wireframe = false;
  4689. this.wireframeLinewidth = 1;
  4690. this.fog = false; // set to use scene fog
  4691. this.lights = false; // set to use scene lights
  4692. this.clipping = false; // set to use user-defined clipping planes
  4693. this.skinning = false; // set to use skinning attribute streams
  4694. this.morphTargets = false; // set to use morph targets
  4695. this.morphNormals = false; // set to use morph normals
  4696. this.extensions = {
  4697. derivatives: false, // set to use derivatives
  4698. fragDepth: false, // set to use fragment depth values
  4699. drawBuffers: false, // set to use draw buffers
  4700. shaderTextureLOD: false // set to use shader texture LOD
  4701. };
  4702. // When rendered geometry doesn't include these attributes but the material does,
  4703. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4704. this.defaultAttributeValues = {
  4705. 'color': [ 1, 1, 1 ],
  4706. 'uv': [ 0, 0 ],
  4707. 'uv2': [ 0, 0 ]
  4708. };
  4709. this.index0AttributeName = undefined;
  4710. if ( parameters !== undefined ) {
  4711. if ( parameters.attributes !== undefined ) {
  4712. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4713. }
  4714. this.setValues( parameters );
  4715. }
  4716. }
  4717. ShaderMaterial.prototype = Object.create( Material.prototype );
  4718. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4719. ShaderMaterial.prototype.isShaderMaterial = true;
  4720. ShaderMaterial.prototype.copy = function ( source ) {
  4721. Material.prototype.copy.call( this, source );
  4722. this.fragmentShader = source.fragmentShader;
  4723. this.vertexShader = source.vertexShader;
  4724. this.uniforms = UniformsUtils.clone( source.uniforms );
  4725. this.defines = source.defines;
  4726. this.wireframe = source.wireframe;
  4727. this.wireframeLinewidth = source.wireframeLinewidth;
  4728. this.lights = source.lights;
  4729. this.clipping = source.clipping;
  4730. this.skinning = source.skinning;
  4731. this.morphTargets = source.morphTargets;
  4732. this.morphNormals = source.morphNormals;
  4733. this.extensions = source.extensions;
  4734. return this;
  4735. };
  4736. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4737. var data = Material.prototype.toJSON.call( this, meta );
  4738. data.uniforms = this.uniforms;
  4739. data.vertexShader = this.vertexShader;
  4740. data.fragmentShader = this.fragmentShader;
  4741. return data;
  4742. };
  4743. /**
  4744. * @author mrdoob / http://mrdoob.com/
  4745. * @author alteredq / http://alteredqualia.com/
  4746. * @author bhouston / https://clara.io
  4747. * @author WestLangley / http://github.com/WestLangley
  4748. *
  4749. * parameters = {
  4750. *
  4751. * opacity: <float>,
  4752. *
  4753. * map: new THREE.Texture( <Image> ),
  4754. *
  4755. * alphaMap: new THREE.Texture( <Image> ),
  4756. *
  4757. * displacementMap: new THREE.Texture( <Image> ),
  4758. * displacementScale: <float>,
  4759. * displacementBias: <float>,
  4760. *
  4761. * wireframe: <boolean>,
  4762. * wireframeLinewidth: <float>
  4763. * }
  4764. */
  4765. function MeshDepthMaterial( parameters ) {
  4766. Material.call( this );
  4767. this.type = 'MeshDepthMaterial';
  4768. this.depthPacking = BasicDepthPacking;
  4769. this.skinning = false;
  4770. this.morphTargets = false;
  4771. this.map = null;
  4772. this.alphaMap = null;
  4773. this.displacementMap = null;
  4774. this.displacementScale = 1;
  4775. this.displacementBias = 0;
  4776. this.wireframe = false;
  4777. this.wireframeLinewidth = 1;
  4778. this.fog = false;
  4779. this.lights = false;
  4780. this.setValues( parameters );
  4781. }
  4782. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4783. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4784. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4785. MeshDepthMaterial.prototype.copy = function ( source ) {
  4786. Material.prototype.copy.call( this, source );
  4787. this.depthPacking = source.depthPacking;
  4788. this.skinning = source.skinning;
  4789. this.morphTargets = source.morphTargets;
  4790. this.map = source.map;
  4791. this.alphaMap = source.alphaMap;
  4792. this.displacementMap = source.displacementMap;
  4793. this.displacementScale = source.displacementScale;
  4794. this.displacementBias = source.displacementBias;
  4795. this.wireframe = source.wireframe;
  4796. this.wireframeLinewidth = source.wireframeLinewidth;
  4797. return this;
  4798. };
  4799. /**
  4800. * @author bhouston / http://clara.io
  4801. * @author WestLangley / http://github.com/WestLangley
  4802. */
  4803. function Box3( min, max ) {
  4804. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4805. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4806. }
  4807. Box3.prototype = {
  4808. constructor: Box3,
  4809. isBox3: true,
  4810. set: function ( min, max ) {
  4811. this.min.copy( min );
  4812. this.max.copy( max );
  4813. return this;
  4814. },
  4815. setFromArray: function ( array ) {
  4816. var minX = + Infinity;
  4817. var minY = + Infinity;
  4818. var minZ = + Infinity;
  4819. var maxX = - Infinity;
  4820. var maxY = - Infinity;
  4821. var maxZ = - Infinity;
  4822. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4823. var x = array[ i ];
  4824. var y = array[ i + 1 ];
  4825. var z = array[ i + 2 ];
  4826. if ( x < minX ) minX = x;
  4827. if ( y < minY ) minY = y;
  4828. if ( z < minZ ) minZ = z;
  4829. if ( x > maxX ) maxX = x;
  4830. if ( y > maxY ) maxY = y;
  4831. if ( z > maxZ ) maxZ = z;
  4832. }
  4833. this.min.set( minX, minY, minZ );
  4834. this.max.set( maxX, maxY, maxZ );
  4835. },
  4836. setFromBufferAttribute: function ( attribute ) {
  4837. var minX = + Infinity;
  4838. var minY = + Infinity;
  4839. var minZ = + Infinity;
  4840. var maxX = - Infinity;
  4841. var maxY = - Infinity;
  4842. var maxZ = - Infinity;
  4843. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4844. var x = attribute.getX( i );
  4845. var y = attribute.getY( i );
  4846. var z = attribute.getZ( i );
  4847. if ( x < minX ) minX = x;
  4848. if ( y < minY ) minY = y;
  4849. if ( z < minZ ) minZ = z;
  4850. if ( x > maxX ) maxX = x;
  4851. if ( y > maxY ) maxY = y;
  4852. if ( z > maxZ ) maxZ = z;
  4853. }
  4854. this.min.set( minX, minY, minZ );
  4855. this.max.set( maxX, maxY, maxZ );
  4856. },
  4857. setFromPoints: function ( points ) {
  4858. this.makeEmpty();
  4859. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4860. this.expandByPoint( points[ i ] );
  4861. }
  4862. return this;
  4863. },
  4864. setFromCenterAndSize: function () {
  4865. var v1 = new Vector3();
  4866. return function setFromCenterAndSize( center, size ) {
  4867. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4868. this.min.copy( center ).sub( halfSize );
  4869. this.max.copy( center ).add( halfSize );
  4870. return this;
  4871. };
  4872. }(),
  4873. setFromObject: function () {
  4874. // Computes the world-axis-aligned bounding box of an object (including its children),
  4875. // accounting for both the object's, and children's, world transforms
  4876. var v1 = new Vector3();
  4877. return function setFromObject( object ) {
  4878. var scope = this;
  4879. object.updateMatrixWorld( true );
  4880. this.makeEmpty();
  4881. object.traverse( function ( node ) {
  4882. var i, l;
  4883. var geometry = node.geometry;
  4884. if ( geometry !== undefined ) {
  4885. if ( geometry.isGeometry ) {
  4886. var vertices = geometry.vertices;
  4887. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4888. v1.copy( vertices[ i ] );
  4889. v1.applyMatrix4( node.matrixWorld );
  4890. scope.expandByPoint( v1 );
  4891. }
  4892. } else if ( geometry.isBufferGeometry ) {
  4893. var attribute = geometry.attributes.position;
  4894. if ( attribute !== undefined ) {
  4895. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4896. v1.fromAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4897. scope.expandByPoint( v1 );
  4898. }
  4899. }
  4900. }
  4901. }
  4902. } );
  4903. return this;
  4904. };
  4905. }(),
  4906. clone: function () {
  4907. return new this.constructor().copy( this );
  4908. },
  4909. copy: function ( box ) {
  4910. this.min.copy( box.min );
  4911. this.max.copy( box.max );
  4912. return this;
  4913. },
  4914. makeEmpty: function () {
  4915. this.min.x = this.min.y = this.min.z = + Infinity;
  4916. this.max.x = this.max.y = this.max.z = - Infinity;
  4917. return this;
  4918. },
  4919. isEmpty: function () {
  4920. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4921. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4922. },
  4923. getCenter: function ( optionalTarget ) {
  4924. var result = optionalTarget || new Vector3();
  4925. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4926. },
  4927. getSize: function ( optionalTarget ) {
  4928. var result = optionalTarget || new Vector3();
  4929. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4930. },
  4931. expandByPoint: function ( point ) {
  4932. this.min.min( point );
  4933. this.max.max( point );
  4934. return this;
  4935. },
  4936. expandByVector: function ( vector ) {
  4937. this.min.sub( vector );
  4938. this.max.add( vector );
  4939. return this;
  4940. },
  4941. expandByScalar: function ( scalar ) {
  4942. this.min.addScalar( - scalar );
  4943. this.max.addScalar( scalar );
  4944. return this;
  4945. },
  4946. containsPoint: function ( point ) {
  4947. return point.x < this.min.x || point.x > this.max.x ||
  4948. point.y < this.min.y || point.y > this.max.y ||
  4949. point.z < this.min.z || point.z > this.max.z ? false : true;
  4950. },
  4951. containsBox: function ( box ) {
  4952. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4953. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4954. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4955. },
  4956. getParameter: function ( point, optionalTarget ) {
  4957. // This can potentially have a divide by zero if the box
  4958. // has a size dimension of 0.
  4959. var result = optionalTarget || new Vector3();
  4960. return result.set(
  4961. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4962. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4963. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4964. );
  4965. },
  4966. intersectsBox: function ( box ) {
  4967. // using 6 splitting planes to rule out intersections.
  4968. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4969. box.max.y < this.min.y || box.min.y > this.max.y ||
  4970. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4971. },
  4972. intersectsSphere: ( function () {
  4973. var closestPoint;
  4974. return function intersectsSphere( sphere ) {
  4975. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4976. // Find the point on the AABB closest to the sphere center.
  4977. this.clampPoint( sphere.center, closestPoint );
  4978. // If that point is inside the sphere, the AABB and sphere intersect.
  4979. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4980. };
  4981. } )(),
  4982. intersectsPlane: function ( plane ) {
  4983. // We compute the minimum and maximum dot product values. If those values
  4984. // are on the same side (back or front) of the plane, then there is no intersection.
  4985. var min, max;
  4986. if ( plane.normal.x > 0 ) {
  4987. min = plane.normal.x * this.min.x;
  4988. max = plane.normal.x * this.max.x;
  4989. } else {
  4990. min = plane.normal.x * this.max.x;
  4991. max = plane.normal.x * this.min.x;
  4992. }
  4993. if ( plane.normal.y > 0 ) {
  4994. min += plane.normal.y * this.min.y;
  4995. max += plane.normal.y * this.max.y;
  4996. } else {
  4997. min += plane.normal.y * this.max.y;
  4998. max += plane.normal.y * this.min.y;
  4999. }
  5000. if ( plane.normal.z > 0 ) {
  5001. min += plane.normal.z * this.min.z;
  5002. max += plane.normal.z * this.max.z;
  5003. } else {
  5004. min += plane.normal.z * this.max.z;
  5005. max += plane.normal.z * this.min.z;
  5006. }
  5007. return ( min <= plane.constant && max >= plane.constant );
  5008. },
  5009. clampPoint: function ( point, optionalTarget ) {
  5010. var result = optionalTarget || new Vector3();
  5011. return result.copy( point ).clamp( this.min, this.max );
  5012. },
  5013. distanceToPoint: function () {
  5014. var v1 = new Vector3();
  5015. return function distanceToPoint( point ) {
  5016. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5017. return clampedPoint.sub( point ).length();
  5018. };
  5019. }(),
  5020. getBoundingSphere: function () {
  5021. var v1 = new Vector3();
  5022. return function getBoundingSphere( optionalTarget ) {
  5023. var result = optionalTarget || new Sphere();
  5024. this.getCenter( result.center );
  5025. result.radius = this.getSize( v1 ).length() * 0.5;
  5026. return result;
  5027. };
  5028. }(),
  5029. intersect: function ( box ) {
  5030. this.min.max( box.min );
  5031. this.max.min( box.max );
  5032. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  5033. if( this.isEmpty() ) this.makeEmpty();
  5034. return this;
  5035. },
  5036. union: function ( box ) {
  5037. this.min.min( box.min );
  5038. this.max.max( box.max );
  5039. return this;
  5040. },
  5041. applyMatrix4: function () {
  5042. var points = [
  5043. new Vector3(),
  5044. new Vector3(),
  5045. new Vector3(),
  5046. new Vector3(),
  5047. new Vector3(),
  5048. new Vector3(),
  5049. new Vector3(),
  5050. new Vector3()
  5051. ];
  5052. return function applyMatrix4( matrix ) {
  5053. // transform of empty box is an empty box.
  5054. if( this.isEmpty() ) return this;
  5055. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5056. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5057. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5058. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5059. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5060. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5061. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5062. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5063. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5064. this.setFromPoints( points );
  5065. return this;
  5066. };
  5067. }(),
  5068. translate: function ( offset ) {
  5069. this.min.add( offset );
  5070. this.max.add( offset );
  5071. return this;
  5072. },
  5073. equals: function ( box ) {
  5074. return box.min.equals( this.min ) && box.max.equals( this.max );
  5075. }
  5076. };
  5077. /**
  5078. * @author bhouston / http://clara.io
  5079. * @author mrdoob / http://mrdoob.com/
  5080. */
  5081. function Sphere( center, radius ) {
  5082. this.center = ( center !== undefined ) ? center : new Vector3();
  5083. this.radius = ( radius !== undefined ) ? radius : 0;
  5084. }
  5085. Sphere.prototype = {
  5086. constructor: Sphere,
  5087. set: function ( center, radius ) {
  5088. this.center.copy( center );
  5089. this.radius = radius;
  5090. return this;
  5091. },
  5092. setFromPoints: function () {
  5093. var box = new Box3();
  5094. return function setFromPoints( points, optionalCenter ) {
  5095. var center = this.center;
  5096. if ( optionalCenter !== undefined ) {
  5097. center.copy( optionalCenter );
  5098. } else {
  5099. box.setFromPoints( points ).getCenter( center );
  5100. }
  5101. var maxRadiusSq = 0;
  5102. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5103. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5104. }
  5105. this.radius = Math.sqrt( maxRadiusSq );
  5106. return this;
  5107. };
  5108. }(),
  5109. clone: function () {
  5110. return new this.constructor().copy( this );
  5111. },
  5112. copy: function ( sphere ) {
  5113. this.center.copy( sphere.center );
  5114. this.radius = sphere.radius;
  5115. return this;
  5116. },
  5117. empty: function () {
  5118. return ( this.radius <= 0 );
  5119. },
  5120. containsPoint: function ( point ) {
  5121. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5122. },
  5123. distanceToPoint: function ( point ) {
  5124. return ( point.distanceTo( this.center ) - this.radius );
  5125. },
  5126. intersectsSphere: function ( sphere ) {
  5127. var radiusSum = this.radius + sphere.radius;
  5128. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5129. },
  5130. intersectsBox: function ( box ) {
  5131. return box.intersectsSphere( this );
  5132. },
  5133. intersectsPlane: function ( plane ) {
  5134. // We use the following equation to compute the signed distance from
  5135. // the center of the sphere to the plane.
  5136. //
  5137. // distance = q * n - d
  5138. //
  5139. // If this distance is greater than the radius of the sphere,
  5140. // then there is no intersection.
  5141. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5142. },
  5143. clampPoint: function ( point, optionalTarget ) {
  5144. var deltaLengthSq = this.center.distanceToSquared( point );
  5145. var result = optionalTarget || new Vector3();
  5146. result.copy( point );
  5147. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5148. result.sub( this.center ).normalize();
  5149. result.multiplyScalar( this.radius ).add( this.center );
  5150. }
  5151. return result;
  5152. },
  5153. getBoundingBox: function ( optionalTarget ) {
  5154. var box = optionalTarget || new Box3();
  5155. box.set( this.center, this.center );
  5156. box.expandByScalar( this.radius );
  5157. return box;
  5158. },
  5159. applyMatrix4: function ( matrix ) {
  5160. this.center.applyMatrix4( matrix );
  5161. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5162. return this;
  5163. },
  5164. translate: function ( offset ) {
  5165. this.center.add( offset );
  5166. return this;
  5167. },
  5168. equals: function ( sphere ) {
  5169. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5170. }
  5171. };
  5172. /**
  5173. * @author alteredq / http://alteredqualia.com/
  5174. * @author WestLangley / http://github.com/WestLangley
  5175. * @author bhouston / http://clara.io
  5176. * @author tschw
  5177. */
  5178. function Matrix3() {
  5179. this.elements = new Float32Array( [
  5180. 1, 0, 0,
  5181. 0, 1, 0,
  5182. 0, 0, 1
  5183. ] );
  5184. if ( arguments.length > 0 ) {
  5185. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5186. }
  5187. }
  5188. Matrix3.prototype = {
  5189. constructor: Matrix3,
  5190. isMatrix3: true,
  5191. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5192. var te = this.elements;
  5193. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5194. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5195. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5196. return this;
  5197. },
  5198. identity: function () {
  5199. this.set(
  5200. 1, 0, 0,
  5201. 0, 1, 0,
  5202. 0, 0, 1
  5203. );
  5204. return this;
  5205. },
  5206. clone: function () {
  5207. return new this.constructor().fromArray( this.elements );
  5208. },
  5209. copy: function ( m ) {
  5210. var me = m.elements;
  5211. this.set(
  5212. me[ 0 ], me[ 3 ], me[ 6 ],
  5213. me[ 1 ], me[ 4 ], me[ 7 ],
  5214. me[ 2 ], me[ 5 ], me[ 8 ]
  5215. );
  5216. return this;
  5217. },
  5218. setFromMatrix4: function( m ) {
  5219. var me = m.elements;
  5220. this.set(
  5221. me[ 0 ], me[ 4 ], me[ 8 ],
  5222. me[ 1 ], me[ 5 ], me[ 9 ],
  5223. me[ 2 ], me[ 6 ], me[ 10 ]
  5224. );
  5225. return this;
  5226. },
  5227. applyToVector3Array: function () {
  5228. var v1;
  5229. return function applyToVector3Array( array, offset, length ) {
  5230. if ( v1 === undefined ) v1 = new Vector3();
  5231. if ( offset === undefined ) offset = 0;
  5232. if ( length === undefined ) length = array.length;
  5233. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  5234. v1.fromArray( array, j );
  5235. v1.applyMatrix3( this );
  5236. v1.toArray( array, j );
  5237. }
  5238. return array;
  5239. };
  5240. }(),
  5241. applyToBufferAttribute: function () {
  5242. var v1;
  5243. return function applyToBufferAttribute( attribute ) {
  5244. if ( v1 === undefined ) v1 = new Vector3();
  5245. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5246. v1.x = attribute.getX( i );
  5247. v1.y = attribute.getY( i );
  5248. v1.z = attribute.getZ( i );
  5249. v1.applyMatrix3( this );
  5250. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5251. }
  5252. return attribute;
  5253. };
  5254. }(),
  5255. multiplyScalar: function ( s ) {
  5256. var te = this.elements;
  5257. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5258. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5259. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5260. return this;
  5261. },
  5262. determinant: function () {
  5263. var te = this.elements;
  5264. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5265. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5266. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5267. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5268. },
  5269. getInverse: function ( matrix, throwOnDegenerate ) {
  5270. if ( matrix && matrix.isMatrix4 ) {
  5271. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5272. }
  5273. var me = matrix.elements,
  5274. te = this.elements,
  5275. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5276. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5277. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5278. t11 = n33 * n22 - n32 * n23,
  5279. t12 = n32 * n13 - n33 * n12,
  5280. t13 = n23 * n12 - n22 * n13,
  5281. det = n11 * t11 + n21 * t12 + n31 * t13;
  5282. if ( det === 0 ) {
  5283. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5284. if ( throwOnDegenerate === true ) {
  5285. throw new Error( msg );
  5286. } else {
  5287. console.warn( msg );
  5288. }
  5289. return this.identity();
  5290. }
  5291. var detInv = 1 / det;
  5292. te[ 0 ] = t11 * detInv;
  5293. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5294. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5295. te[ 3 ] = t12 * detInv;
  5296. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5297. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5298. te[ 6 ] = t13 * detInv;
  5299. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5300. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5301. return this;
  5302. },
  5303. transpose: function () {
  5304. var tmp, m = this.elements;
  5305. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5306. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5307. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5308. return this;
  5309. },
  5310. getNormalMatrix: function ( matrix4 ) {
  5311. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5312. },
  5313. transposeIntoArray: function ( r ) {
  5314. var m = this.elements;
  5315. r[ 0 ] = m[ 0 ];
  5316. r[ 1 ] = m[ 3 ];
  5317. r[ 2 ] = m[ 6 ];
  5318. r[ 3 ] = m[ 1 ];
  5319. r[ 4 ] = m[ 4 ];
  5320. r[ 5 ] = m[ 7 ];
  5321. r[ 6 ] = m[ 2 ];
  5322. r[ 7 ] = m[ 5 ];
  5323. r[ 8 ] = m[ 8 ];
  5324. return this;
  5325. },
  5326. fromArray: function ( array, offset ) {
  5327. if ( offset === undefined ) offset = 0;
  5328. for( var i = 0; i < 9; i ++ ) {
  5329. this.elements[ i ] = array[ i + offset ];
  5330. }
  5331. return this;
  5332. },
  5333. toArray: function ( array, offset ) {
  5334. if ( array === undefined ) array = [];
  5335. if ( offset === undefined ) offset = 0;
  5336. var te = this.elements;
  5337. array[ offset ] = te[ 0 ];
  5338. array[ offset + 1 ] = te[ 1 ];
  5339. array[ offset + 2 ] = te[ 2 ];
  5340. array[ offset + 3 ] = te[ 3 ];
  5341. array[ offset + 4 ] = te[ 4 ];
  5342. array[ offset + 5 ] = te[ 5 ];
  5343. array[ offset + 6 ] = te[ 6 ];
  5344. array[ offset + 7 ] = te[ 7 ];
  5345. array[ offset + 8 ] = te[ 8 ];
  5346. return array;
  5347. }
  5348. };
  5349. /**
  5350. * @author bhouston / http://clara.io
  5351. */
  5352. function Plane( normal, constant ) {
  5353. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5354. this.constant = ( constant !== undefined ) ? constant : 0;
  5355. }
  5356. Plane.prototype = {
  5357. constructor: Plane,
  5358. set: function ( normal, constant ) {
  5359. this.normal.copy( normal );
  5360. this.constant = constant;
  5361. return this;
  5362. },
  5363. setComponents: function ( x, y, z, w ) {
  5364. this.normal.set( x, y, z );
  5365. this.constant = w;
  5366. return this;
  5367. },
  5368. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5369. this.normal.copy( normal );
  5370. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5371. return this;
  5372. },
  5373. setFromCoplanarPoints: function () {
  5374. var v1 = new Vector3();
  5375. var v2 = new Vector3();
  5376. return function setFromCoplanarPoints( a, b, c ) {
  5377. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5378. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5379. this.setFromNormalAndCoplanarPoint( normal, a );
  5380. return this;
  5381. };
  5382. }(),
  5383. clone: function () {
  5384. return new this.constructor().copy( this );
  5385. },
  5386. copy: function ( plane ) {
  5387. this.normal.copy( plane.normal );
  5388. this.constant = plane.constant;
  5389. return this;
  5390. },
  5391. normalize: function () {
  5392. // Note: will lead to a divide by zero if the plane is invalid.
  5393. var inverseNormalLength = 1.0 / this.normal.length();
  5394. this.normal.multiplyScalar( inverseNormalLength );
  5395. this.constant *= inverseNormalLength;
  5396. return this;
  5397. },
  5398. negate: function () {
  5399. this.constant *= - 1;
  5400. this.normal.negate();
  5401. return this;
  5402. },
  5403. distanceToPoint: function ( point ) {
  5404. return this.normal.dot( point ) + this.constant;
  5405. },
  5406. distanceToSphere: function ( sphere ) {
  5407. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5408. },
  5409. projectPoint: function ( point, optionalTarget ) {
  5410. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5411. },
  5412. orthoPoint: function ( point, optionalTarget ) {
  5413. var perpendicularMagnitude = this.distanceToPoint( point );
  5414. var result = optionalTarget || new Vector3();
  5415. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5416. },
  5417. intersectLine: function () {
  5418. var v1 = new Vector3();
  5419. return function intersectLine( line, optionalTarget ) {
  5420. var result = optionalTarget || new Vector3();
  5421. var direction = line.delta( v1 );
  5422. var denominator = this.normal.dot( direction );
  5423. if ( denominator === 0 ) {
  5424. // line is coplanar, return origin
  5425. if ( this.distanceToPoint( line.start ) === 0 ) {
  5426. return result.copy( line.start );
  5427. }
  5428. // Unsure if this is the correct method to handle this case.
  5429. return undefined;
  5430. }
  5431. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5432. if ( t < 0 || t > 1 ) {
  5433. return undefined;
  5434. }
  5435. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5436. };
  5437. }(),
  5438. intersectsLine: function ( line ) {
  5439. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5440. var startSign = this.distanceToPoint( line.start );
  5441. var endSign = this.distanceToPoint( line.end );
  5442. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5443. },
  5444. intersectsBox: function ( box ) {
  5445. return box.intersectsPlane( this );
  5446. },
  5447. intersectsSphere: function ( sphere ) {
  5448. return sphere.intersectsPlane( this );
  5449. },
  5450. coplanarPoint: function ( optionalTarget ) {
  5451. var result = optionalTarget || new Vector3();
  5452. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5453. },
  5454. applyMatrix4: function () {
  5455. var v1 = new Vector3();
  5456. var m1 = new Matrix3();
  5457. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5458. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5459. // transform normal based on theory here:
  5460. // http://www.songho.ca/opengl/gl_normaltransform.html
  5461. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5462. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5463. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5464. this.constant = - referencePoint.dot( normal );
  5465. return this;
  5466. };
  5467. }(),
  5468. translate: function ( offset ) {
  5469. this.constant = this.constant - offset.dot( this.normal );
  5470. return this;
  5471. },
  5472. equals: function ( plane ) {
  5473. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5474. }
  5475. };
  5476. /**
  5477. * @author mrdoob / http://mrdoob.com/
  5478. * @author alteredq / http://alteredqualia.com/
  5479. * @author bhouston / http://clara.io
  5480. */
  5481. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5482. this.planes = [
  5483. ( p0 !== undefined ) ? p0 : new Plane(),
  5484. ( p1 !== undefined ) ? p1 : new Plane(),
  5485. ( p2 !== undefined ) ? p2 : new Plane(),
  5486. ( p3 !== undefined ) ? p3 : new Plane(),
  5487. ( p4 !== undefined ) ? p4 : new Plane(),
  5488. ( p5 !== undefined ) ? p5 : new Plane()
  5489. ];
  5490. }
  5491. Frustum.prototype = {
  5492. constructor: Frustum,
  5493. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5494. var planes = this.planes;
  5495. planes[ 0 ].copy( p0 );
  5496. planes[ 1 ].copy( p1 );
  5497. planes[ 2 ].copy( p2 );
  5498. planes[ 3 ].copy( p3 );
  5499. planes[ 4 ].copy( p4 );
  5500. planes[ 5 ].copy( p5 );
  5501. return this;
  5502. },
  5503. clone: function () {
  5504. return new this.constructor().copy( this );
  5505. },
  5506. copy: function ( frustum ) {
  5507. var planes = this.planes;
  5508. for ( var i = 0; i < 6; i ++ ) {
  5509. planes[ i ].copy( frustum.planes[ i ] );
  5510. }
  5511. return this;
  5512. },
  5513. setFromMatrix: function ( m ) {
  5514. var planes = this.planes;
  5515. var me = m.elements;
  5516. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5517. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5518. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5519. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5520. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5521. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5522. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5523. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5524. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5525. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5526. return this;
  5527. },
  5528. intersectsObject: function () {
  5529. var sphere = new Sphere();
  5530. return function intersectsObject( object ) {
  5531. var geometry = object.geometry;
  5532. if ( geometry.boundingSphere === null )
  5533. geometry.computeBoundingSphere();
  5534. sphere.copy( geometry.boundingSphere )
  5535. .applyMatrix4( object.matrixWorld );
  5536. return this.intersectsSphere( sphere );
  5537. };
  5538. }(),
  5539. intersectsSprite: function () {
  5540. var sphere = new Sphere();
  5541. return function intersectsSprite( sprite ) {
  5542. sphere.center.set( 0, 0, 0 );
  5543. sphere.radius = 0.7071067811865476;
  5544. sphere.applyMatrix4( sprite.matrixWorld );
  5545. return this.intersectsSphere( sphere );
  5546. };
  5547. }(),
  5548. intersectsSphere: function ( sphere ) {
  5549. var planes = this.planes;
  5550. var center = sphere.center;
  5551. var negRadius = - sphere.radius;
  5552. for ( var i = 0; i < 6; i ++ ) {
  5553. var distance = planes[ i ].distanceToPoint( center );
  5554. if ( distance < negRadius ) {
  5555. return false;
  5556. }
  5557. }
  5558. return true;
  5559. },
  5560. intersectsBox: function () {
  5561. var p1 = new Vector3(),
  5562. p2 = new Vector3();
  5563. return function intersectsBox( box ) {
  5564. var planes = this.planes;
  5565. for ( var i = 0; i < 6 ; i ++ ) {
  5566. var plane = planes[ i ];
  5567. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5568. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5569. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5570. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5571. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5572. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5573. var d1 = plane.distanceToPoint( p1 );
  5574. var d2 = plane.distanceToPoint( p2 );
  5575. // if both outside plane, no intersection
  5576. if ( d1 < 0 && d2 < 0 ) {
  5577. return false;
  5578. }
  5579. }
  5580. return true;
  5581. };
  5582. }(),
  5583. containsPoint: function ( point ) {
  5584. var planes = this.planes;
  5585. for ( var i = 0; i < 6; i ++ ) {
  5586. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5587. return false;
  5588. }
  5589. }
  5590. return true;
  5591. }
  5592. };
  5593. /**
  5594. * @author alteredq / http://alteredqualia.com/
  5595. * @author mrdoob / http://mrdoob.com/
  5596. */
  5597. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5598. var _gl = _renderer.context,
  5599. _state = _renderer.state,
  5600. _frustum = new Frustum(),
  5601. _projScreenMatrix = new Matrix4(),
  5602. _lightShadows = _lights.shadows,
  5603. _shadowMapSize = new Vector2(),
  5604. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5605. _lookTarget = new Vector3(),
  5606. _lightPositionWorld = new Vector3(),
  5607. _renderList = [],
  5608. _MorphingFlag = 1,
  5609. _SkinningFlag = 2,
  5610. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5611. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5612. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5613. _materialCache = {};
  5614. var cubeDirections = [
  5615. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5616. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5617. ];
  5618. var cubeUps = [
  5619. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5620. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5621. ];
  5622. var cube2DViewPorts = [
  5623. new Vector4(), new Vector4(), new Vector4(),
  5624. new Vector4(), new Vector4(), new Vector4()
  5625. ];
  5626. // init
  5627. var depthMaterialTemplate = new MeshDepthMaterial();
  5628. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5629. depthMaterialTemplate.clipping = true;
  5630. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5631. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  5632. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5633. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5634. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5635. var depthMaterial = depthMaterialTemplate.clone();
  5636. depthMaterial.morphTargets = useMorphing;
  5637. depthMaterial.skinning = useSkinning;
  5638. _depthMaterials[ i ] = depthMaterial;
  5639. var distanceMaterial = new ShaderMaterial( {
  5640. defines: {
  5641. 'USE_SHADOWMAP': ''
  5642. },
  5643. uniforms: distanceUniforms,
  5644. vertexShader: distanceShader.vertexShader,
  5645. fragmentShader: distanceShader.fragmentShader,
  5646. morphTargets: useMorphing,
  5647. skinning: useSkinning,
  5648. clipping: true
  5649. } );
  5650. _distanceMaterials[ i ] = distanceMaterial;
  5651. }
  5652. //
  5653. var scope = this;
  5654. this.enabled = false;
  5655. this.autoUpdate = true;
  5656. this.needsUpdate = false;
  5657. this.type = PCFShadowMap;
  5658. this.renderReverseSided = true;
  5659. this.renderSingleSided = true;
  5660. this.render = function ( scene, camera ) {
  5661. if ( scope.enabled === false ) return;
  5662. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5663. if ( _lightShadows.length === 0 ) return;
  5664. // Set GL state for depth map.
  5665. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5666. _state.disable( _gl.BLEND );
  5667. _state.setDepthTest( true );
  5668. _state.setScissorTest( false );
  5669. // render depth map
  5670. var faceCount, isPointLight;
  5671. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5672. var light = _lightShadows[ i ];
  5673. var shadow = light.shadow;
  5674. if ( shadow === undefined ) {
  5675. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5676. continue;
  5677. }
  5678. var shadowCamera = shadow.camera;
  5679. _shadowMapSize.copy( shadow.mapSize );
  5680. _shadowMapSize.min( _maxShadowMapSize );
  5681. if ( light && light.isPointLight ) {
  5682. faceCount = 6;
  5683. isPointLight = true;
  5684. var vpWidth = _shadowMapSize.x;
  5685. var vpHeight = _shadowMapSize.y;
  5686. // These viewports map a cube-map onto a 2D texture with the
  5687. // following orientation:
  5688. //
  5689. // xzXZ
  5690. // y Y
  5691. //
  5692. // X - Positive x direction
  5693. // x - Negative x direction
  5694. // Y - Positive y direction
  5695. // y - Negative y direction
  5696. // Z - Positive z direction
  5697. // z - Negative z direction
  5698. // positive X
  5699. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5700. // negative X
  5701. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5702. // positive Z
  5703. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5704. // negative Z
  5705. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5706. // positive Y
  5707. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5708. // negative Y
  5709. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5710. _shadowMapSize.x *= 4.0;
  5711. _shadowMapSize.y *= 2.0;
  5712. } else {
  5713. faceCount = 1;
  5714. isPointLight = false;
  5715. }
  5716. if ( shadow.map === null ) {
  5717. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5718. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5719. shadowCamera.updateProjectionMatrix();
  5720. }
  5721. if ( shadow.isSpotLightShadow ) {
  5722. shadow.update( light );
  5723. }
  5724. // TODO (abelnation / sam-g-steel): is this needed?
  5725. if (shadow && shadow.isRectAreaLightShadow ) {
  5726. shadow.update( light );
  5727. }
  5728. var shadowMap = shadow.map;
  5729. var shadowMatrix = shadow.matrix;
  5730. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5731. shadowCamera.position.copy( _lightPositionWorld );
  5732. _renderer.setRenderTarget( shadowMap );
  5733. _renderer.clear();
  5734. // render shadow map for each cube face (if omni-directional) or
  5735. // run a single pass if not
  5736. for ( var face = 0; face < faceCount; face ++ ) {
  5737. if ( isPointLight ) {
  5738. _lookTarget.copy( shadowCamera.position );
  5739. _lookTarget.add( cubeDirections[ face ] );
  5740. shadowCamera.up.copy( cubeUps[ face ] );
  5741. shadowCamera.lookAt( _lookTarget );
  5742. var vpDimensions = cube2DViewPorts[ face ];
  5743. _state.viewport( vpDimensions );
  5744. } else {
  5745. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5746. shadowCamera.lookAt( _lookTarget );
  5747. }
  5748. shadowCamera.updateMatrixWorld();
  5749. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5750. // compute shadow matrix
  5751. shadowMatrix.set(
  5752. 0.5, 0.0, 0.0, 0.5,
  5753. 0.0, 0.5, 0.0, 0.5,
  5754. 0.0, 0.0, 0.5, 0.5,
  5755. 0.0, 0.0, 0.0, 1.0
  5756. );
  5757. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5758. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5759. // update camera matrices and frustum
  5760. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5761. _frustum.setFromMatrix( _projScreenMatrix );
  5762. // set object matrices & frustum culling
  5763. _renderList.length = 0;
  5764. projectObject( scene, camera, shadowCamera );
  5765. // render shadow map
  5766. // render regular objects
  5767. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  5768. var object = _renderList[ j ];
  5769. var geometry = _objects.update( object );
  5770. var material = object.material;
  5771. if ( material && material.isMultiMaterial ) {
  5772. var groups = geometry.groups;
  5773. var materials = material.materials;
  5774. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5775. var group = groups[ k ];
  5776. var groupMaterial = materials[ group.materialIndex ];
  5777. if ( groupMaterial.visible === true ) {
  5778. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5779. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5780. }
  5781. }
  5782. } else {
  5783. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5784. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5785. }
  5786. }
  5787. }
  5788. }
  5789. // Restore GL state.
  5790. var clearColor = _renderer.getClearColor(),
  5791. clearAlpha = _renderer.getClearAlpha();
  5792. _renderer.setClearColor( clearColor, clearAlpha );
  5793. scope.needsUpdate = false;
  5794. };
  5795. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5796. var geometry = object.geometry;
  5797. var result = null;
  5798. var materialVariants = _depthMaterials;
  5799. var customMaterial = object.customDepthMaterial;
  5800. if ( isPointLight ) {
  5801. materialVariants = _distanceMaterials;
  5802. customMaterial = object.customDistanceMaterial;
  5803. }
  5804. if ( ! customMaterial ) {
  5805. var useMorphing = false;
  5806. if ( material.morphTargets ) {
  5807. if ( geometry && geometry.isBufferGeometry ) {
  5808. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5809. } else if ( geometry && geometry.isGeometry ) {
  5810. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5811. }
  5812. }
  5813. var useSkinning = object.isSkinnedMesh && material.skinning;
  5814. var variantIndex = 0;
  5815. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5816. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5817. result = materialVariants[ variantIndex ];
  5818. } else {
  5819. result = customMaterial;
  5820. }
  5821. if ( _renderer.localClippingEnabled &&
  5822. material.clipShadows === true &&
  5823. material.clippingPlanes.length !== 0 ) {
  5824. // in this case we need a unique material instance reflecting the
  5825. // appropriate state
  5826. var keyA = result.uuid, keyB = material.uuid;
  5827. var materialsForVariant = _materialCache[ keyA ];
  5828. if ( materialsForVariant === undefined ) {
  5829. materialsForVariant = {};
  5830. _materialCache[ keyA ] = materialsForVariant;
  5831. }
  5832. var cachedMaterial = materialsForVariant[ keyB ];
  5833. if ( cachedMaterial === undefined ) {
  5834. cachedMaterial = result.clone();
  5835. materialsForVariant[ keyB ] = cachedMaterial;
  5836. }
  5837. result = cachedMaterial;
  5838. }
  5839. result.visible = material.visible;
  5840. result.wireframe = material.wireframe;
  5841. var side = material.side;
  5842. if ( scope.renderSingleSided && side == DoubleSide ) {
  5843. side = FrontSide;
  5844. }
  5845. if ( scope.renderReverseSided ) {
  5846. if ( side === FrontSide ) side = BackSide;
  5847. else if ( side === BackSide ) side = FrontSide;
  5848. }
  5849. result.side = side;
  5850. result.clipShadows = material.clipShadows;
  5851. result.clippingPlanes = material.clippingPlanes;
  5852. result.wireframeLinewidth = material.wireframeLinewidth;
  5853. result.linewidth = material.linewidth;
  5854. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5855. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5856. }
  5857. return result;
  5858. }
  5859. function projectObject( object, camera, shadowCamera ) {
  5860. if ( object.visible === false ) return;
  5861. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  5862. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5863. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  5864. var material = object.material;
  5865. if ( material.visible === true ) {
  5866. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5867. _renderList.push( object );
  5868. }
  5869. }
  5870. }
  5871. var children = object.children;
  5872. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5873. projectObject( children[ i ], camera, shadowCamera );
  5874. }
  5875. }
  5876. }
  5877. /**
  5878. * @author bhouston / http://clara.io
  5879. */
  5880. function Ray( origin, direction ) {
  5881. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5882. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5883. }
  5884. Ray.prototype = {
  5885. constructor: Ray,
  5886. set: function ( origin, direction ) {
  5887. this.origin.copy( origin );
  5888. this.direction.copy( direction );
  5889. return this;
  5890. },
  5891. clone: function () {
  5892. return new this.constructor().copy( this );
  5893. },
  5894. copy: function ( ray ) {
  5895. this.origin.copy( ray.origin );
  5896. this.direction.copy( ray.direction );
  5897. return this;
  5898. },
  5899. at: function ( t, optionalTarget ) {
  5900. var result = optionalTarget || new Vector3();
  5901. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5902. },
  5903. lookAt: function ( v ) {
  5904. this.direction.copy( v ).sub( this.origin ).normalize();
  5905. return this;
  5906. },
  5907. recast: function () {
  5908. var v1 = new Vector3();
  5909. return function recast( t ) {
  5910. this.origin.copy( this.at( t, v1 ) );
  5911. return this;
  5912. };
  5913. }(),
  5914. closestPointToPoint: function ( point, optionalTarget ) {
  5915. var result = optionalTarget || new Vector3();
  5916. result.subVectors( point, this.origin );
  5917. var directionDistance = result.dot( this.direction );
  5918. if ( directionDistance < 0 ) {
  5919. return result.copy( this.origin );
  5920. }
  5921. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5922. },
  5923. distanceToPoint: function ( point ) {
  5924. return Math.sqrt( this.distanceSqToPoint( point ) );
  5925. },
  5926. distanceSqToPoint: function () {
  5927. var v1 = new Vector3();
  5928. return function distanceSqToPoint( point ) {
  5929. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5930. // point behind the ray
  5931. if ( directionDistance < 0 ) {
  5932. return this.origin.distanceToSquared( point );
  5933. }
  5934. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5935. return v1.distanceToSquared( point );
  5936. };
  5937. }(),
  5938. distanceSqToSegment: function () {
  5939. var segCenter = new Vector3();
  5940. var segDir = new Vector3();
  5941. var diff = new Vector3();
  5942. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5943. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5944. // It returns the min distance between the ray and the segment
  5945. // defined by v0 and v1
  5946. // It can also set two optional targets :
  5947. // - The closest point on the ray
  5948. // - The closest point on the segment
  5949. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5950. segDir.copy( v1 ).sub( v0 ).normalize();
  5951. diff.copy( this.origin ).sub( segCenter );
  5952. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5953. var a01 = - this.direction.dot( segDir );
  5954. var b0 = diff.dot( this.direction );
  5955. var b1 = - diff.dot( segDir );
  5956. var c = diff.lengthSq();
  5957. var det = Math.abs( 1 - a01 * a01 );
  5958. var s0, s1, sqrDist, extDet;
  5959. if ( det > 0 ) {
  5960. // The ray and segment are not parallel.
  5961. s0 = a01 * b1 - b0;
  5962. s1 = a01 * b0 - b1;
  5963. extDet = segExtent * det;
  5964. if ( s0 >= 0 ) {
  5965. if ( s1 >= - extDet ) {
  5966. if ( s1 <= extDet ) {
  5967. // region 0
  5968. // Minimum at interior points of ray and segment.
  5969. var invDet = 1 / det;
  5970. s0 *= invDet;
  5971. s1 *= invDet;
  5972. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5973. } else {
  5974. // region 1
  5975. s1 = segExtent;
  5976. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5977. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5978. }
  5979. } else {
  5980. // region 5
  5981. s1 = - segExtent;
  5982. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5983. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5984. }
  5985. } else {
  5986. if ( s1 <= - extDet ) {
  5987. // region 4
  5988. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5989. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5990. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5991. } else if ( s1 <= extDet ) {
  5992. // region 3
  5993. s0 = 0;
  5994. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5995. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5996. } else {
  5997. // region 2
  5998. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5999. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6000. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6001. }
  6002. }
  6003. } else {
  6004. // Ray and segment are parallel.
  6005. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6006. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6007. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6008. }
  6009. if ( optionalPointOnRay ) {
  6010. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  6011. }
  6012. if ( optionalPointOnSegment ) {
  6013. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  6014. }
  6015. return sqrDist;
  6016. };
  6017. }(),
  6018. intersectSphere: function () {
  6019. var v1 = new Vector3();
  6020. return function intersectSphere( sphere, optionalTarget ) {
  6021. v1.subVectors( sphere.center, this.origin );
  6022. var tca = v1.dot( this.direction );
  6023. var d2 = v1.dot( v1 ) - tca * tca;
  6024. var radius2 = sphere.radius * sphere.radius;
  6025. if ( d2 > radius2 ) return null;
  6026. var thc = Math.sqrt( radius2 - d2 );
  6027. // t0 = first intersect point - entrance on front of sphere
  6028. var t0 = tca - thc;
  6029. // t1 = second intersect point - exit point on back of sphere
  6030. var t1 = tca + thc;
  6031. // test to see if both t0 and t1 are behind the ray - if so, return null
  6032. if ( t0 < 0 && t1 < 0 ) return null;
  6033. // test to see if t0 is behind the ray:
  6034. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6035. // in order to always return an intersect point that is in front of the ray.
  6036. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  6037. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6038. return this.at( t0, optionalTarget );
  6039. };
  6040. }(),
  6041. intersectsSphere: function ( sphere ) {
  6042. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  6043. },
  6044. distanceToPlane: function ( plane ) {
  6045. var denominator = plane.normal.dot( this.direction );
  6046. if ( denominator === 0 ) {
  6047. // line is coplanar, return origin
  6048. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6049. return 0;
  6050. }
  6051. // Null is preferable to undefined since undefined means.... it is undefined
  6052. return null;
  6053. }
  6054. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6055. // Return if the ray never intersects the plane
  6056. return t >= 0 ? t : null;
  6057. },
  6058. intersectPlane: function ( plane, optionalTarget ) {
  6059. var t = this.distanceToPlane( plane );
  6060. if ( t === null ) {
  6061. return null;
  6062. }
  6063. return this.at( t, optionalTarget );
  6064. },
  6065. intersectsPlane: function ( plane ) {
  6066. // check if the ray lies on the plane first
  6067. var distToPoint = plane.distanceToPoint( this.origin );
  6068. if ( distToPoint === 0 ) {
  6069. return true;
  6070. }
  6071. var denominator = plane.normal.dot( this.direction );
  6072. if ( denominator * distToPoint < 0 ) {
  6073. return true;
  6074. }
  6075. // ray origin is behind the plane (and is pointing behind it)
  6076. return false;
  6077. },
  6078. intersectBox: function ( box, optionalTarget ) {
  6079. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6080. var invdirx = 1 / this.direction.x,
  6081. invdiry = 1 / this.direction.y,
  6082. invdirz = 1 / this.direction.z;
  6083. var origin = this.origin;
  6084. if ( invdirx >= 0 ) {
  6085. tmin = ( box.min.x - origin.x ) * invdirx;
  6086. tmax = ( box.max.x - origin.x ) * invdirx;
  6087. } else {
  6088. tmin = ( box.max.x - origin.x ) * invdirx;
  6089. tmax = ( box.min.x - origin.x ) * invdirx;
  6090. }
  6091. if ( invdiry >= 0 ) {
  6092. tymin = ( box.min.y - origin.y ) * invdiry;
  6093. tymax = ( box.max.y - origin.y ) * invdiry;
  6094. } else {
  6095. tymin = ( box.max.y - origin.y ) * invdiry;
  6096. tymax = ( box.min.y - origin.y ) * invdiry;
  6097. }
  6098. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6099. // These lines also handle the case where tmin or tmax is NaN
  6100. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6101. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6102. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6103. if ( invdirz >= 0 ) {
  6104. tzmin = ( box.min.z - origin.z ) * invdirz;
  6105. tzmax = ( box.max.z - origin.z ) * invdirz;
  6106. } else {
  6107. tzmin = ( box.max.z - origin.z ) * invdirz;
  6108. tzmax = ( box.min.z - origin.z ) * invdirz;
  6109. }
  6110. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6111. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6112. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6113. //return point closest to the ray (positive side)
  6114. if ( tmax < 0 ) return null;
  6115. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6116. },
  6117. intersectsBox: ( function () {
  6118. var v = new Vector3();
  6119. return function intersectsBox( box ) {
  6120. return this.intersectBox( box, v ) !== null;
  6121. };
  6122. } )(),
  6123. intersectTriangle: function () {
  6124. // Compute the offset origin, edges, and normal.
  6125. var diff = new Vector3();
  6126. var edge1 = new Vector3();
  6127. var edge2 = new Vector3();
  6128. var normal = new Vector3();
  6129. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6130. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6131. edge1.subVectors( b, a );
  6132. edge2.subVectors( c, a );
  6133. normal.crossVectors( edge1, edge2 );
  6134. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6135. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6136. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6137. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6138. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6139. var DdN = this.direction.dot( normal );
  6140. var sign;
  6141. if ( DdN > 0 ) {
  6142. if ( backfaceCulling ) return null;
  6143. sign = 1;
  6144. } else if ( DdN < 0 ) {
  6145. sign = - 1;
  6146. DdN = - DdN;
  6147. } else {
  6148. return null;
  6149. }
  6150. diff.subVectors( this.origin, a );
  6151. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6152. // b1 < 0, no intersection
  6153. if ( DdQxE2 < 0 ) {
  6154. return null;
  6155. }
  6156. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6157. // b2 < 0, no intersection
  6158. if ( DdE1xQ < 0 ) {
  6159. return null;
  6160. }
  6161. // b1+b2 > 1, no intersection
  6162. if ( DdQxE2 + DdE1xQ > DdN ) {
  6163. return null;
  6164. }
  6165. // Line intersects triangle, check if ray does.
  6166. var QdN = - sign * diff.dot( normal );
  6167. // t < 0, no intersection
  6168. if ( QdN < 0 ) {
  6169. return null;
  6170. }
  6171. // Ray intersects triangle.
  6172. return this.at( QdN / DdN, optionalTarget );
  6173. };
  6174. }(),
  6175. applyMatrix4: function ( matrix4 ) {
  6176. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6177. this.origin.applyMatrix4( matrix4 );
  6178. this.direction.sub( this.origin );
  6179. this.direction.normalize();
  6180. return this;
  6181. },
  6182. equals: function ( ray ) {
  6183. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6184. }
  6185. };
  6186. /**
  6187. * @author mrdoob / http://mrdoob.com/
  6188. * @author WestLangley / http://github.com/WestLangley
  6189. * @author bhouston / http://clara.io
  6190. */
  6191. function Euler( x, y, z, order ) {
  6192. this._x = x || 0;
  6193. this._y = y || 0;
  6194. this._z = z || 0;
  6195. this._order = order || Euler.DefaultOrder;
  6196. }
  6197. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6198. Euler.DefaultOrder = 'XYZ';
  6199. Euler.prototype = {
  6200. constructor: Euler,
  6201. isEuler: true,
  6202. get x () {
  6203. return this._x;
  6204. },
  6205. set x ( value ) {
  6206. this._x = value;
  6207. this.onChangeCallback();
  6208. },
  6209. get y () {
  6210. return this._y;
  6211. },
  6212. set y ( value ) {
  6213. this._y = value;
  6214. this.onChangeCallback();
  6215. },
  6216. get z () {
  6217. return this._z;
  6218. },
  6219. set z ( value ) {
  6220. this._z = value;
  6221. this.onChangeCallback();
  6222. },
  6223. get order () {
  6224. return this._order;
  6225. },
  6226. set order ( value ) {
  6227. this._order = value;
  6228. this.onChangeCallback();
  6229. },
  6230. set: function ( x, y, z, order ) {
  6231. this._x = x;
  6232. this._y = y;
  6233. this._z = z;
  6234. this._order = order || this._order;
  6235. this.onChangeCallback();
  6236. return this;
  6237. },
  6238. clone: function () {
  6239. return new this.constructor( this._x, this._y, this._z, this._order );
  6240. },
  6241. copy: function ( euler ) {
  6242. this._x = euler._x;
  6243. this._y = euler._y;
  6244. this._z = euler._z;
  6245. this._order = euler._order;
  6246. this.onChangeCallback();
  6247. return this;
  6248. },
  6249. setFromRotationMatrix: function ( m, order, update ) {
  6250. var clamp = _Math.clamp;
  6251. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6252. var te = m.elements;
  6253. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6254. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6255. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6256. order = order || this._order;
  6257. if ( order === 'XYZ' ) {
  6258. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6259. if ( Math.abs( m13 ) < 0.99999 ) {
  6260. this._x = Math.atan2( - m23, m33 );
  6261. this._z = Math.atan2( - m12, m11 );
  6262. } else {
  6263. this._x = Math.atan2( m32, m22 );
  6264. this._z = 0;
  6265. }
  6266. } else if ( order === 'YXZ' ) {
  6267. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6268. if ( Math.abs( m23 ) < 0.99999 ) {
  6269. this._y = Math.atan2( m13, m33 );
  6270. this._z = Math.atan2( m21, m22 );
  6271. } else {
  6272. this._y = Math.atan2( - m31, m11 );
  6273. this._z = 0;
  6274. }
  6275. } else if ( order === 'ZXY' ) {
  6276. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6277. if ( Math.abs( m32 ) < 0.99999 ) {
  6278. this._y = Math.atan2( - m31, m33 );
  6279. this._z = Math.atan2( - m12, m22 );
  6280. } else {
  6281. this._y = 0;
  6282. this._z = Math.atan2( m21, m11 );
  6283. }
  6284. } else if ( order === 'ZYX' ) {
  6285. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6286. if ( Math.abs( m31 ) < 0.99999 ) {
  6287. this._x = Math.atan2( m32, m33 );
  6288. this._z = Math.atan2( m21, m11 );
  6289. } else {
  6290. this._x = 0;
  6291. this._z = Math.atan2( - m12, m22 );
  6292. }
  6293. } else if ( order === 'YZX' ) {
  6294. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6295. if ( Math.abs( m21 ) < 0.99999 ) {
  6296. this._x = Math.atan2( - m23, m22 );
  6297. this._y = Math.atan2( - m31, m11 );
  6298. } else {
  6299. this._x = 0;
  6300. this._y = Math.atan2( m13, m33 );
  6301. }
  6302. } else if ( order === 'XZY' ) {
  6303. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6304. if ( Math.abs( m12 ) < 0.99999 ) {
  6305. this._x = Math.atan2( m32, m22 );
  6306. this._y = Math.atan2( m13, m11 );
  6307. } else {
  6308. this._x = Math.atan2( - m23, m33 );
  6309. this._y = 0;
  6310. }
  6311. } else {
  6312. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6313. }
  6314. this._order = order;
  6315. if ( update !== false ) this.onChangeCallback();
  6316. return this;
  6317. },
  6318. setFromQuaternion: function () {
  6319. var matrix;
  6320. return function setFromQuaternion( q, order, update ) {
  6321. if ( matrix === undefined ) matrix = new Matrix4();
  6322. matrix.makeRotationFromQuaternion( q );
  6323. return this.setFromRotationMatrix( matrix, order, update );
  6324. };
  6325. }(),
  6326. setFromVector3: function ( v, order ) {
  6327. return this.set( v.x, v.y, v.z, order || this._order );
  6328. },
  6329. reorder: function () {
  6330. // WARNING: this discards revolution information -bhouston
  6331. var q = new Quaternion();
  6332. return function reorder( newOrder ) {
  6333. q.setFromEuler( this );
  6334. return this.setFromQuaternion( q, newOrder );
  6335. };
  6336. }(),
  6337. equals: function ( euler ) {
  6338. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6339. },
  6340. fromArray: function ( array ) {
  6341. this._x = array[ 0 ];
  6342. this._y = array[ 1 ];
  6343. this._z = array[ 2 ];
  6344. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6345. this.onChangeCallback();
  6346. return this;
  6347. },
  6348. toArray: function ( array, offset ) {
  6349. if ( array === undefined ) array = [];
  6350. if ( offset === undefined ) offset = 0;
  6351. array[ offset ] = this._x;
  6352. array[ offset + 1 ] = this._y;
  6353. array[ offset + 2 ] = this._z;
  6354. array[ offset + 3 ] = this._order;
  6355. return array;
  6356. },
  6357. toVector3: function ( optionalResult ) {
  6358. if ( optionalResult ) {
  6359. return optionalResult.set( this._x, this._y, this._z );
  6360. } else {
  6361. return new Vector3( this._x, this._y, this._z );
  6362. }
  6363. },
  6364. onChange: function ( callback ) {
  6365. this.onChangeCallback = callback;
  6366. return this;
  6367. },
  6368. onChangeCallback: function () {}
  6369. };
  6370. /**
  6371. * @author mrdoob / http://mrdoob.com/
  6372. */
  6373. function Layers() {
  6374. this.mask = 1;
  6375. }
  6376. Layers.prototype = {
  6377. constructor: Layers,
  6378. set: function ( channel ) {
  6379. this.mask = 1 << channel;
  6380. },
  6381. enable: function ( channel ) {
  6382. this.mask |= 1 << channel;
  6383. },
  6384. toggle: function ( channel ) {
  6385. this.mask ^= 1 << channel;
  6386. },
  6387. disable: function ( channel ) {
  6388. this.mask &= ~ ( 1 << channel );
  6389. },
  6390. test: function ( layers ) {
  6391. return ( this.mask & layers.mask ) !== 0;
  6392. }
  6393. };
  6394. /**
  6395. * @author mrdoob / http://mrdoob.com/
  6396. * @author mikael emtinger / http://gomo.se/
  6397. * @author alteredq / http://alteredqualia.com/
  6398. * @author WestLangley / http://github.com/WestLangley
  6399. * @author elephantatwork / www.elephantatwork.ch
  6400. */
  6401. var object3DId = 0;
  6402. function Object3D() {
  6403. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6404. this.uuid = _Math.generateUUID();
  6405. this.name = '';
  6406. this.type = 'Object3D';
  6407. this.parent = null;
  6408. this.children = [];
  6409. this.up = Object3D.DefaultUp.clone();
  6410. var position = new Vector3();
  6411. var rotation = new Euler();
  6412. var quaternion = new Quaternion();
  6413. var scale = new Vector3( 1, 1, 1 );
  6414. function onRotationChange() {
  6415. quaternion.setFromEuler( rotation, false );
  6416. }
  6417. function onQuaternionChange() {
  6418. rotation.setFromQuaternion( quaternion, undefined, false );
  6419. }
  6420. rotation.onChange( onRotationChange );
  6421. quaternion.onChange( onQuaternionChange );
  6422. Object.defineProperties( this, {
  6423. position: {
  6424. enumerable: true,
  6425. value: position
  6426. },
  6427. rotation: {
  6428. enumerable: true,
  6429. value: rotation
  6430. },
  6431. quaternion: {
  6432. enumerable: true,
  6433. value: quaternion
  6434. },
  6435. scale: {
  6436. enumerable: true,
  6437. value: scale
  6438. },
  6439. modelViewMatrix: {
  6440. value: new Matrix4()
  6441. },
  6442. normalMatrix: {
  6443. value: new Matrix3()
  6444. }
  6445. } );
  6446. this.matrix = new Matrix4();
  6447. this.matrixWorld = new Matrix4();
  6448. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6449. this.matrixWorldNeedsUpdate = false;
  6450. this.layers = new Layers();
  6451. this.visible = true;
  6452. this.castShadow = false;
  6453. this.receiveShadow = false;
  6454. this.frustumCulled = true;
  6455. this.renderOrder = 0;
  6456. this.userData = {};
  6457. this.onBeforeRender = function () {};
  6458. this.onAfterRender = function () {};
  6459. }
  6460. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6461. Object3D.DefaultMatrixAutoUpdate = true;
  6462. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6463. isObject3D: true,
  6464. applyMatrix: function ( matrix ) {
  6465. this.matrix.multiplyMatrices( matrix, this.matrix );
  6466. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6467. },
  6468. setRotationFromAxisAngle: function ( axis, angle ) {
  6469. // assumes axis is normalized
  6470. this.quaternion.setFromAxisAngle( axis, angle );
  6471. },
  6472. setRotationFromEuler: function ( euler ) {
  6473. this.quaternion.setFromEuler( euler, true );
  6474. },
  6475. setRotationFromMatrix: function ( m ) {
  6476. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6477. this.quaternion.setFromRotationMatrix( m );
  6478. },
  6479. setRotationFromQuaternion: function ( q ) {
  6480. // assumes q is normalized
  6481. this.quaternion.copy( q );
  6482. },
  6483. rotateOnAxis: function () {
  6484. // rotate object on axis in object space
  6485. // axis is assumed to be normalized
  6486. var q1 = new Quaternion();
  6487. return function rotateOnAxis( axis, angle ) {
  6488. q1.setFromAxisAngle( axis, angle );
  6489. this.quaternion.multiply( q1 );
  6490. return this;
  6491. };
  6492. }(),
  6493. rotateX: function () {
  6494. var v1 = new Vector3( 1, 0, 0 );
  6495. return function rotateX( angle ) {
  6496. return this.rotateOnAxis( v1, angle );
  6497. };
  6498. }(),
  6499. rotateY: function () {
  6500. var v1 = new Vector3( 0, 1, 0 );
  6501. return function rotateY( angle ) {
  6502. return this.rotateOnAxis( v1, angle );
  6503. };
  6504. }(),
  6505. rotateZ: function () {
  6506. var v1 = new Vector3( 0, 0, 1 );
  6507. return function rotateZ( angle ) {
  6508. return this.rotateOnAxis( v1, angle );
  6509. };
  6510. }(),
  6511. translateOnAxis: function () {
  6512. // translate object by distance along axis in object space
  6513. // axis is assumed to be normalized
  6514. var v1 = new Vector3();
  6515. return function translateOnAxis( axis, distance ) {
  6516. v1.copy( axis ).applyQuaternion( this.quaternion );
  6517. this.position.add( v1.multiplyScalar( distance ) );
  6518. return this;
  6519. };
  6520. }(),
  6521. translateX: function () {
  6522. var v1 = new Vector3( 1, 0, 0 );
  6523. return function translateX( distance ) {
  6524. return this.translateOnAxis( v1, distance );
  6525. };
  6526. }(),
  6527. translateY: function () {
  6528. var v1 = new Vector3( 0, 1, 0 );
  6529. return function translateY( distance ) {
  6530. return this.translateOnAxis( v1, distance );
  6531. };
  6532. }(),
  6533. translateZ: function () {
  6534. var v1 = new Vector3( 0, 0, 1 );
  6535. return function translateZ( distance ) {
  6536. return this.translateOnAxis( v1, distance );
  6537. };
  6538. }(),
  6539. localToWorld: function ( vector ) {
  6540. return vector.applyMatrix4( this.matrixWorld );
  6541. },
  6542. worldToLocal: function () {
  6543. var m1 = new Matrix4();
  6544. return function worldToLocal( vector ) {
  6545. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6546. };
  6547. }(),
  6548. lookAt: function () {
  6549. // This routine does not support objects with rotated and/or translated parent(s)
  6550. var m1 = new Matrix4();
  6551. return function lookAt( vector ) {
  6552. m1.lookAt( vector, this.position, this.up );
  6553. this.quaternion.setFromRotationMatrix( m1 );
  6554. };
  6555. }(),
  6556. add: function ( object ) {
  6557. if ( arguments.length > 1 ) {
  6558. for ( var i = 0; i < arguments.length; i ++ ) {
  6559. this.add( arguments[ i ] );
  6560. }
  6561. return this;
  6562. }
  6563. if ( object === this ) {
  6564. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6565. return this;
  6566. }
  6567. if ( ( object && object.isObject3D ) ) {
  6568. if ( object.parent !== null ) {
  6569. object.parent.remove( object );
  6570. }
  6571. object.parent = this;
  6572. object.dispatchEvent( { type: 'added' } );
  6573. this.children.push( object );
  6574. } else {
  6575. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6576. }
  6577. return this;
  6578. },
  6579. remove: function ( object ) {
  6580. if ( arguments.length > 1 ) {
  6581. for ( var i = 0; i < arguments.length; i ++ ) {
  6582. this.remove( arguments[ i ] );
  6583. }
  6584. }
  6585. var index = this.children.indexOf( object );
  6586. if ( index !== - 1 ) {
  6587. object.parent = null;
  6588. object.dispatchEvent( { type: 'removed' } );
  6589. this.children.splice( index, 1 );
  6590. }
  6591. },
  6592. getObjectById: function ( id ) {
  6593. return this.getObjectByProperty( 'id', id );
  6594. },
  6595. getObjectByName: function ( name ) {
  6596. return this.getObjectByProperty( 'name', name );
  6597. },
  6598. getObjectByProperty: function ( name, value ) {
  6599. if ( this[ name ] === value ) return this;
  6600. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6601. var child = this.children[ i ];
  6602. var object = child.getObjectByProperty( name, value );
  6603. if ( object !== undefined ) {
  6604. return object;
  6605. }
  6606. }
  6607. return undefined;
  6608. },
  6609. getWorldPosition: function ( optionalTarget ) {
  6610. var result = optionalTarget || new Vector3();
  6611. this.updateMatrixWorld( true );
  6612. return result.setFromMatrixPosition( this.matrixWorld );
  6613. },
  6614. getWorldQuaternion: function () {
  6615. var position = new Vector3();
  6616. var scale = new Vector3();
  6617. return function getWorldQuaternion( optionalTarget ) {
  6618. var result = optionalTarget || new Quaternion();
  6619. this.updateMatrixWorld( true );
  6620. this.matrixWorld.decompose( position, result, scale );
  6621. return result;
  6622. };
  6623. }(),
  6624. getWorldRotation: function () {
  6625. var quaternion = new Quaternion();
  6626. return function getWorldRotation( optionalTarget ) {
  6627. var result = optionalTarget || new Euler();
  6628. this.getWorldQuaternion( quaternion );
  6629. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6630. };
  6631. }(),
  6632. getWorldScale: function () {
  6633. var position = new Vector3();
  6634. var quaternion = new Quaternion();
  6635. return function getWorldScale( optionalTarget ) {
  6636. var result = optionalTarget || new Vector3();
  6637. this.updateMatrixWorld( true );
  6638. this.matrixWorld.decompose( position, quaternion, result );
  6639. return result;
  6640. };
  6641. }(),
  6642. getWorldDirection: function () {
  6643. var quaternion = new Quaternion();
  6644. return function getWorldDirection( optionalTarget ) {
  6645. var result = optionalTarget || new Vector3();
  6646. this.getWorldQuaternion( quaternion );
  6647. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6648. };
  6649. }(),
  6650. raycast: function () {},
  6651. traverse: function ( callback ) {
  6652. callback( this );
  6653. var children = this.children;
  6654. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6655. children[ i ].traverse( callback );
  6656. }
  6657. },
  6658. traverseVisible: function ( callback ) {
  6659. if ( this.visible === false ) return;
  6660. callback( this );
  6661. var children = this.children;
  6662. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6663. children[ i ].traverseVisible( callback );
  6664. }
  6665. },
  6666. traverseAncestors: function ( callback ) {
  6667. var parent = this.parent;
  6668. if ( parent !== null ) {
  6669. callback( parent );
  6670. parent.traverseAncestors( callback );
  6671. }
  6672. },
  6673. updateMatrix: function () {
  6674. this.matrix.compose( this.position, this.quaternion, this.scale );
  6675. this.matrixWorldNeedsUpdate = true;
  6676. },
  6677. updateMatrixWorld: function ( force ) {
  6678. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  6679. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  6680. if ( this.parent === null ) {
  6681. this.matrixWorld.copy( this.matrix );
  6682. } else {
  6683. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6684. }
  6685. this.matrixWorldNeedsUpdate = false;
  6686. force = true;
  6687. }
  6688. // update children
  6689. var children = this.children;
  6690. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6691. children[ i ].updateMatrixWorld( force );
  6692. }
  6693. },
  6694. toJSON: function ( meta ) {
  6695. // meta is '' when called from JSON.stringify
  6696. var isRootObject = ( meta === undefined || meta === '' );
  6697. var output = {};
  6698. // meta is a hash used to collect geometries, materials.
  6699. // not providing it implies that this is the root object
  6700. // being serialized.
  6701. if ( isRootObject ) {
  6702. // initialize meta obj
  6703. meta = {
  6704. geometries: {},
  6705. materials: {},
  6706. textures: {},
  6707. images: {}
  6708. };
  6709. output.metadata = {
  6710. version: 4.4,
  6711. type: 'Object',
  6712. generator: 'Object3D.toJSON'
  6713. };
  6714. }
  6715. // standard Object3D serialization
  6716. var object = {};
  6717. object.uuid = this.uuid;
  6718. object.type = this.type;
  6719. if ( this.name !== '' ) object.name = this.name;
  6720. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6721. if ( this.castShadow === true ) object.castShadow = true;
  6722. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6723. if ( this.visible === false ) object.visible = false;
  6724. object.matrix = this.matrix.toArray();
  6725. //
  6726. if ( this.geometry !== undefined ) {
  6727. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  6728. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  6729. }
  6730. object.geometry = this.geometry.uuid;
  6731. }
  6732. if ( this.material !== undefined ) {
  6733. if ( meta.materials[ this.material.uuid ] === undefined ) {
  6734. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  6735. }
  6736. object.material = this.material.uuid;
  6737. }
  6738. //
  6739. if ( this.children.length > 0 ) {
  6740. object.children = [];
  6741. for ( var i = 0; i < this.children.length; i ++ ) {
  6742. object.children.push( this.children[ i ].toJSON( meta ).object );
  6743. }
  6744. }
  6745. if ( isRootObject ) {
  6746. var geometries = extractFromCache( meta.geometries );
  6747. var materials = extractFromCache( meta.materials );
  6748. var textures = extractFromCache( meta.textures );
  6749. var images = extractFromCache( meta.images );
  6750. if ( geometries.length > 0 ) output.geometries = geometries;
  6751. if ( materials.length > 0 ) output.materials = materials;
  6752. if ( textures.length > 0 ) output.textures = textures;
  6753. if ( images.length > 0 ) output.images = images;
  6754. }
  6755. output.object = object;
  6756. return output;
  6757. // extract data from the cache hash
  6758. // remove metadata on each item
  6759. // and return as array
  6760. function extractFromCache( cache ) {
  6761. var values = [];
  6762. for ( var key in cache ) {
  6763. var data = cache[ key ];
  6764. delete data.metadata;
  6765. values.push( data );
  6766. }
  6767. return values;
  6768. }
  6769. },
  6770. clone: function ( recursive ) {
  6771. return new this.constructor().copy( this, recursive );
  6772. },
  6773. copy: function ( source, recursive ) {
  6774. if ( recursive === undefined ) recursive = true;
  6775. this.name = source.name;
  6776. this.up.copy( source.up );
  6777. this.position.copy( source.position );
  6778. this.quaternion.copy( source.quaternion );
  6779. this.scale.copy( source.scale );
  6780. this.matrix.copy( source.matrix );
  6781. this.matrixWorld.copy( source.matrixWorld );
  6782. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6783. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6784. this.layers.mask = source.layers.mask;
  6785. this.visible = source.visible;
  6786. this.castShadow = source.castShadow;
  6787. this.receiveShadow = source.receiveShadow;
  6788. this.frustumCulled = source.frustumCulled;
  6789. this.renderOrder = source.renderOrder;
  6790. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6791. if ( recursive === true ) {
  6792. for ( var i = 0; i < source.children.length; i ++ ) {
  6793. var child = source.children[ i ];
  6794. this.add( child.clone() );
  6795. }
  6796. }
  6797. return this;
  6798. }
  6799. } );
  6800. /**
  6801. * @author bhouston / http://clara.io
  6802. */
  6803. function Line3( start, end ) {
  6804. this.start = ( start !== undefined ) ? start : new Vector3();
  6805. this.end = ( end !== undefined ) ? end : new Vector3();
  6806. }
  6807. Line3.prototype = {
  6808. constructor: Line3,
  6809. set: function ( start, end ) {
  6810. this.start.copy( start );
  6811. this.end.copy( end );
  6812. return this;
  6813. },
  6814. clone: function () {
  6815. return new this.constructor().copy( this );
  6816. },
  6817. copy: function ( line ) {
  6818. this.start.copy( line.start );
  6819. this.end.copy( line.end );
  6820. return this;
  6821. },
  6822. getCenter: function ( optionalTarget ) {
  6823. var result = optionalTarget || new Vector3();
  6824. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6825. },
  6826. delta: function ( optionalTarget ) {
  6827. var result = optionalTarget || new Vector3();
  6828. return result.subVectors( this.end, this.start );
  6829. },
  6830. distanceSq: function () {
  6831. return this.start.distanceToSquared( this.end );
  6832. },
  6833. distance: function () {
  6834. return this.start.distanceTo( this.end );
  6835. },
  6836. at: function ( t, optionalTarget ) {
  6837. var result = optionalTarget || new Vector3();
  6838. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6839. },
  6840. closestPointToPointParameter: function () {
  6841. var startP = new Vector3();
  6842. var startEnd = new Vector3();
  6843. return function closestPointToPointParameter( point, clampToLine ) {
  6844. startP.subVectors( point, this.start );
  6845. startEnd.subVectors( this.end, this.start );
  6846. var startEnd2 = startEnd.dot( startEnd );
  6847. var startEnd_startP = startEnd.dot( startP );
  6848. var t = startEnd_startP / startEnd2;
  6849. if ( clampToLine ) {
  6850. t = _Math.clamp( t, 0, 1 );
  6851. }
  6852. return t;
  6853. };
  6854. }(),
  6855. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6856. var t = this.closestPointToPointParameter( point, clampToLine );
  6857. var result = optionalTarget || new Vector3();
  6858. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6859. },
  6860. applyMatrix4: function ( matrix ) {
  6861. this.start.applyMatrix4( matrix );
  6862. this.end.applyMatrix4( matrix );
  6863. return this;
  6864. },
  6865. equals: function ( line ) {
  6866. return line.start.equals( this.start ) && line.end.equals( this.end );
  6867. }
  6868. };
  6869. /**
  6870. * @author bhouston / http://clara.io
  6871. * @author mrdoob / http://mrdoob.com/
  6872. */
  6873. function Triangle( a, b, c ) {
  6874. this.a = ( a !== undefined ) ? a : new Vector3();
  6875. this.b = ( b !== undefined ) ? b : new Vector3();
  6876. this.c = ( c !== undefined ) ? c : new Vector3();
  6877. }
  6878. Triangle.normal = function () {
  6879. var v0 = new Vector3();
  6880. return function normal( a, b, c, optionalTarget ) {
  6881. var result = optionalTarget || new Vector3();
  6882. result.subVectors( c, b );
  6883. v0.subVectors( a, b );
  6884. result.cross( v0 );
  6885. var resultLengthSq = result.lengthSq();
  6886. if ( resultLengthSq > 0 ) {
  6887. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6888. }
  6889. return result.set( 0, 0, 0 );
  6890. };
  6891. }();
  6892. // static/instance method to calculate barycentric coordinates
  6893. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6894. Triangle.barycoordFromPoint = function () {
  6895. var v0 = new Vector3();
  6896. var v1 = new Vector3();
  6897. var v2 = new Vector3();
  6898. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6899. v0.subVectors( c, a );
  6900. v1.subVectors( b, a );
  6901. v2.subVectors( point, a );
  6902. var dot00 = v0.dot( v0 );
  6903. var dot01 = v0.dot( v1 );
  6904. var dot02 = v0.dot( v2 );
  6905. var dot11 = v1.dot( v1 );
  6906. var dot12 = v1.dot( v2 );
  6907. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6908. var result = optionalTarget || new Vector3();
  6909. // collinear or singular triangle
  6910. if ( denom === 0 ) {
  6911. // arbitrary location outside of triangle?
  6912. // not sure if this is the best idea, maybe should be returning undefined
  6913. return result.set( - 2, - 1, - 1 );
  6914. }
  6915. var invDenom = 1 / denom;
  6916. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6917. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6918. // barycentric coordinates must always sum to 1
  6919. return result.set( 1 - u - v, v, u );
  6920. };
  6921. }();
  6922. Triangle.containsPoint = function () {
  6923. var v1 = new Vector3();
  6924. return function containsPoint( point, a, b, c ) {
  6925. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6926. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6927. };
  6928. }();
  6929. Triangle.prototype = {
  6930. constructor: Triangle,
  6931. set: function ( a, b, c ) {
  6932. this.a.copy( a );
  6933. this.b.copy( b );
  6934. this.c.copy( c );
  6935. return this;
  6936. },
  6937. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6938. this.a.copy( points[ i0 ] );
  6939. this.b.copy( points[ i1 ] );
  6940. this.c.copy( points[ i2 ] );
  6941. return this;
  6942. },
  6943. clone: function () {
  6944. return new this.constructor().copy( this );
  6945. },
  6946. copy: function ( triangle ) {
  6947. this.a.copy( triangle.a );
  6948. this.b.copy( triangle.b );
  6949. this.c.copy( triangle.c );
  6950. return this;
  6951. },
  6952. area: function () {
  6953. var v0 = new Vector3();
  6954. var v1 = new Vector3();
  6955. return function area() {
  6956. v0.subVectors( this.c, this.b );
  6957. v1.subVectors( this.a, this.b );
  6958. return v0.cross( v1 ).length() * 0.5;
  6959. };
  6960. }(),
  6961. midpoint: function ( optionalTarget ) {
  6962. var result = optionalTarget || new Vector3();
  6963. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6964. },
  6965. normal: function ( optionalTarget ) {
  6966. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6967. },
  6968. plane: function ( optionalTarget ) {
  6969. var result = optionalTarget || new Plane();
  6970. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6971. },
  6972. barycoordFromPoint: function ( point, optionalTarget ) {
  6973. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6974. },
  6975. containsPoint: function ( point ) {
  6976. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6977. },
  6978. closestPointToPoint: function () {
  6979. var plane, edgeList, projectedPoint, closestPoint;
  6980. return function closestPointToPoint( point, optionalTarget ) {
  6981. if ( plane === undefined ) {
  6982. plane = new Plane();
  6983. edgeList = [ new Line3(), new Line3(), new Line3() ];
  6984. projectedPoint = new Vector3();
  6985. closestPoint = new Vector3();
  6986. }
  6987. var result = optionalTarget || new Vector3();
  6988. var minDistance = Infinity;
  6989. // project the point onto the plane of the triangle
  6990. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6991. plane.projectPoint( point, projectedPoint );
  6992. // check if the projection lies within the triangle
  6993. if( this.containsPoint( projectedPoint ) === true ) {
  6994. // if so, this is the closest point
  6995. result.copy( projectedPoint );
  6996. } else {
  6997. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6998. edgeList[ 0 ].set( this.a, this.b );
  6999. edgeList[ 1 ].set( this.b, this.c );
  7000. edgeList[ 2 ].set( this.c, this.a );
  7001. for( var i = 0; i < edgeList.length; i ++ ) {
  7002. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  7003. var distance = projectedPoint.distanceToSquared( closestPoint );
  7004. if( distance < minDistance ) {
  7005. minDistance = distance;
  7006. result.copy( closestPoint );
  7007. }
  7008. }
  7009. }
  7010. return result;
  7011. };
  7012. }(),
  7013. equals: function ( triangle ) {
  7014. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  7015. }
  7016. };
  7017. /**
  7018. * @author mrdoob / http://mrdoob.com/
  7019. * @author alteredq / http://alteredqualia.com/
  7020. */
  7021. function Face3( a, b, c, normal, color, materialIndex ) {
  7022. this.a = a;
  7023. this.b = b;
  7024. this.c = c;
  7025. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  7026. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  7027. this.color = (color && color.isColor) ? color : new Color();
  7028. this.vertexColors = Array.isArray( color ) ? color : [];
  7029. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  7030. }
  7031. Face3.prototype = {
  7032. constructor: Face3,
  7033. clone: function () {
  7034. return new this.constructor().copy( this );
  7035. },
  7036. copy: function ( source ) {
  7037. this.a = source.a;
  7038. this.b = source.b;
  7039. this.c = source.c;
  7040. this.normal.copy( source.normal );
  7041. this.color.copy( source.color );
  7042. this.materialIndex = source.materialIndex;
  7043. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  7044. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  7045. }
  7046. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  7047. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  7048. }
  7049. return this;
  7050. }
  7051. };
  7052. /**
  7053. * @author mrdoob / http://mrdoob.com/
  7054. * @author alteredq / http://alteredqualia.com/
  7055. *
  7056. * parameters = {
  7057. * color: <hex>,
  7058. * opacity: <float>,
  7059. * map: new THREE.Texture( <Image> ),
  7060. *
  7061. * lightMap: new THREE.Texture( <Image> ),
  7062. * lightMapIntensity: <float>
  7063. *
  7064. * aoMap: new THREE.Texture( <Image> ),
  7065. * aoMapIntensity: <float>
  7066. *
  7067. * specularMap: new THREE.Texture( <Image> ),
  7068. *
  7069. * alphaMap: new THREE.Texture( <Image> ),
  7070. *
  7071. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7072. * combine: THREE.Multiply,
  7073. * reflectivity: <float>,
  7074. * refractionRatio: <float>,
  7075. *
  7076. * shading: THREE.SmoothShading,
  7077. * depthTest: <bool>,
  7078. * depthWrite: <bool>,
  7079. *
  7080. * wireframe: <boolean>,
  7081. * wireframeLinewidth: <float>,
  7082. *
  7083. * skinning: <bool>,
  7084. * morphTargets: <bool>
  7085. * }
  7086. */
  7087. function MeshBasicMaterial( parameters ) {
  7088. Material.call( this );
  7089. this.type = 'MeshBasicMaterial';
  7090. this.color = new Color( 0xffffff ); // emissive
  7091. this.map = null;
  7092. this.lightMap = null;
  7093. this.lightMapIntensity = 1.0;
  7094. this.aoMap = null;
  7095. this.aoMapIntensity = 1.0;
  7096. this.specularMap = null;
  7097. this.alphaMap = null;
  7098. this.envMap = null;
  7099. this.combine = MultiplyOperation;
  7100. this.reflectivity = 1;
  7101. this.refractionRatio = 0.98;
  7102. this.wireframe = false;
  7103. this.wireframeLinewidth = 1;
  7104. this.wireframeLinecap = 'round';
  7105. this.wireframeLinejoin = 'round';
  7106. this.skinning = false;
  7107. this.morphTargets = false;
  7108. this.lights = false;
  7109. this.setValues( parameters );
  7110. }
  7111. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7112. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7113. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7114. MeshBasicMaterial.prototype.copy = function ( source ) {
  7115. Material.prototype.copy.call( this, source );
  7116. this.color.copy( source.color );
  7117. this.map = source.map;
  7118. this.lightMap = source.lightMap;
  7119. this.lightMapIntensity = source.lightMapIntensity;
  7120. this.aoMap = source.aoMap;
  7121. this.aoMapIntensity = source.aoMapIntensity;
  7122. this.specularMap = source.specularMap;
  7123. this.alphaMap = source.alphaMap;
  7124. this.envMap = source.envMap;
  7125. this.combine = source.combine;
  7126. this.reflectivity = source.reflectivity;
  7127. this.refractionRatio = source.refractionRatio;
  7128. this.wireframe = source.wireframe;
  7129. this.wireframeLinewidth = source.wireframeLinewidth;
  7130. this.wireframeLinecap = source.wireframeLinecap;
  7131. this.wireframeLinejoin = source.wireframeLinejoin;
  7132. this.skinning = source.skinning;
  7133. this.morphTargets = source.morphTargets;
  7134. return this;
  7135. };
  7136. /**
  7137. * @author mrdoob / http://mrdoob.com/
  7138. */
  7139. function BufferAttribute( array, itemSize, normalized ) {
  7140. if ( Array.isArray( array ) ) {
  7141. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7142. }
  7143. this.uuid = _Math.generateUUID();
  7144. this.array = array;
  7145. this.itemSize = itemSize;
  7146. this.count = array !== undefined ? array.length / itemSize : 0;
  7147. this.normalized = normalized === true;
  7148. this.dynamic = false;
  7149. this.updateRange = { offset: 0, count: - 1 };
  7150. this.onUploadCallback = function () {};
  7151. this.version = 0;
  7152. }
  7153. BufferAttribute.prototype = {
  7154. constructor: BufferAttribute,
  7155. isBufferAttribute: true,
  7156. set needsUpdate( value ) {
  7157. if ( value === true ) this.version ++;
  7158. },
  7159. setArray: function ( array ) {
  7160. if ( Array.isArray( array ) ) {
  7161. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7162. }
  7163. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7164. this.array = array;
  7165. },
  7166. setDynamic: function ( value ) {
  7167. this.dynamic = value;
  7168. return this;
  7169. },
  7170. copy: function ( source ) {
  7171. this.array = new source.array.constructor( source.array );
  7172. this.itemSize = source.itemSize;
  7173. this.count = source.count;
  7174. this.normalized = source.normalized;
  7175. this.dynamic = source.dynamic;
  7176. return this;
  7177. },
  7178. copyAt: function ( index1, attribute, index2 ) {
  7179. index1 *= this.itemSize;
  7180. index2 *= attribute.itemSize;
  7181. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7182. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7183. }
  7184. return this;
  7185. },
  7186. copyArray: function ( array ) {
  7187. this.array.set( array );
  7188. return this;
  7189. },
  7190. copyColorsArray: function ( colors ) {
  7191. var array = this.array, offset = 0;
  7192. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7193. var color = colors[ i ];
  7194. if ( color === undefined ) {
  7195. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7196. color = new Color();
  7197. }
  7198. array[ offset ++ ] = color.r;
  7199. array[ offset ++ ] = color.g;
  7200. array[ offset ++ ] = color.b;
  7201. }
  7202. return this;
  7203. },
  7204. copyIndicesArray: function ( indices ) {
  7205. var array = this.array, offset = 0;
  7206. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7207. var index = indices[ i ];
  7208. array[ offset ++ ] = index.a;
  7209. array[ offset ++ ] = index.b;
  7210. array[ offset ++ ] = index.c;
  7211. }
  7212. return this;
  7213. },
  7214. copyVector2sArray: function ( vectors ) {
  7215. var array = this.array, offset = 0;
  7216. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7217. var vector = vectors[ i ];
  7218. if ( vector === undefined ) {
  7219. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7220. vector = new Vector2();
  7221. }
  7222. array[ offset ++ ] = vector.x;
  7223. array[ offset ++ ] = vector.y;
  7224. }
  7225. return this;
  7226. },
  7227. copyVector3sArray: function ( vectors ) {
  7228. var array = this.array, offset = 0;
  7229. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7230. var vector = vectors[ i ];
  7231. if ( vector === undefined ) {
  7232. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7233. vector = new Vector3();
  7234. }
  7235. array[ offset ++ ] = vector.x;
  7236. array[ offset ++ ] = vector.y;
  7237. array[ offset ++ ] = vector.z;
  7238. }
  7239. return this;
  7240. },
  7241. copyVector4sArray: function ( vectors ) {
  7242. var array = this.array, offset = 0;
  7243. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7244. var vector = vectors[ i ];
  7245. if ( vector === undefined ) {
  7246. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7247. vector = new Vector4();
  7248. }
  7249. array[ offset ++ ] = vector.x;
  7250. array[ offset ++ ] = vector.y;
  7251. array[ offset ++ ] = vector.z;
  7252. array[ offset ++ ] = vector.w;
  7253. }
  7254. return this;
  7255. },
  7256. set: function ( value, offset ) {
  7257. if ( offset === undefined ) offset = 0;
  7258. this.array.set( value, offset );
  7259. return this;
  7260. },
  7261. getX: function ( index ) {
  7262. return this.array[ index * this.itemSize ];
  7263. },
  7264. setX: function ( index, x ) {
  7265. this.array[ index * this.itemSize ] = x;
  7266. return this;
  7267. },
  7268. getY: function ( index ) {
  7269. return this.array[ index * this.itemSize + 1 ];
  7270. },
  7271. setY: function ( index, y ) {
  7272. this.array[ index * this.itemSize + 1 ] = y;
  7273. return this;
  7274. },
  7275. getZ: function ( index ) {
  7276. return this.array[ index * this.itemSize + 2 ];
  7277. },
  7278. setZ: function ( index, z ) {
  7279. this.array[ index * this.itemSize + 2 ] = z;
  7280. return this;
  7281. },
  7282. getW: function ( index ) {
  7283. return this.array[ index * this.itemSize + 3 ];
  7284. },
  7285. setW: function ( index, w ) {
  7286. this.array[ index * this.itemSize + 3 ] = w;
  7287. return this;
  7288. },
  7289. setXY: function ( index, x, y ) {
  7290. index *= this.itemSize;
  7291. this.array[ index + 0 ] = x;
  7292. this.array[ index + 1 ] = y;
  7293. return this;
  7294. },
  7295. setXYZ: function ( index, x, y, z ) {
  7296. index *= this.itemSize;
  7297. this.array[ index + 0 ] = x;
  7298. this.array[ index + 1 ] = y;
  7299. this.array[ index + 2 ] = z;
  7300. return this;
  7301. },
  7302. setXYZW: function ( index, x, y, z, w ) {
  7303. index *= this.itemSize;
  7304. this.array[ index + 0 ] = x;
  7305. this.array[ index + 1 ] = y;
  7306. this.array[ index + 2 ] = z;
  7307. this.array[ index + 3 ] = w;
  7308. return this;
  7309. },
  7310. onUpload: function ( callback ) {
  7311. this.onUploadCallback = callback;
  7312. return this;
  7313. },
  7314. clone: function () {
  7315. return new this.constructor().copy( this );
  7316. }
  7317. };
  7318. //
  7319. function Int8BufferAttribute( array, itemSize ) {
  7320. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7321. }
  7322. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7323. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7324. function Uint8BufferAttribute( array, itemSize ) {
  7325. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7326. }
  7327. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7328. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7329. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7330. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7331. }
  7332. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7333. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7334. function Int16BufferAttribute( array, itemSize ) {
  7335. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7336. }
  7337. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7338. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7339. function Uint16BufferAttribute( array, itemSize ) {
  7340. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7341. }
  7342. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7343. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7344. function Int32BufferAttribute( array, itemSize ) {
  7345. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7346. }
  7347. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7348. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7349. function Uint32BufferAttribute( array, itemSize ) {
  7350. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7351. }
  7352. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7353. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7354. function Float32BufferAttribute( array, itemSize ) {
  7355. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7356. }
  7357. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7358. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7359. function Float64BufferAttribute( array, itemSize ) {
  7360. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7361. }
  7362. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7363. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7364. /**
  7365. * @author mrdoob / http://mrdoob.com/
  7366. */
  7367. function DirectGeometry() {
  7368. this.indices = [];
  7369. this.vertices = [];
  7370. this.normals = [];
  7371. this.colors = [];
  7372. this.uvs = [];
  7373. this.uvs2 = [];
  7374. this.groups = [];
  7375. this.morphTargets = {};
  7376. this.skinWeights = [];
  7377. this.skinIndices = [];
  7378. // this.lineDistances = [];
  7379. this.boundingBox = null;
  7380. this.boundingSphere = null;
  7381. // update flags
  7382. this.verticesNeedUpdate = false;
  7383. this.normalsNeedUpdate = false;
  7384. this.colorsNeedUpdate = false;
  7385. this.uvsNeedUpdate = false;
  7386. this.groupsNeedUpdate = false;
  7387. }
  7388. Object.assign( DirectGeometry.prototype, {
  7389. computeGroups: function ( geometry ) {
  7390. var group;
  7391. var groups = [];
  7392. var materialIndex = undefined;
  7393. var faces = geometry.faces;
  7394. for ( var i = 0; i < faces.length; i ++ ) {
  7395. var face = faces[ i ];
  7396. // materials
  7397. if ( face.materialIndex !== materialIndex ) {
  7398. materialIndex = face.materialIndex;
  7399. if ( group !== undefined ) {
  7400. group.count = ( i * 3 ) - group.start;
  7401. groups.push( group );
  7402. }
  7403. group = {
  7404. start: i * 3,
  7405. materialIndex: materialIndex
  7406. };
  7407. }
  7408. }
  7409. if ( group !== undefined ) {
  7410. group.count = ( i * 3 ) - group.start;
  7411. groups.push( group );
  7412. }
  7413. this.groups = groups;
  7414. },
  7415. fromGeometry: function ( geometry ) {
  7416. var faces = geometry.faces;
  7417. var vertices = geometry.vertices;
  7418. var faceVertexUvs = geometry.faceVertexUvs;
  7419. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7420. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7421. // morphs
  7422. var morphTargets = geometry.morphTargets;
  7423. var morphTargetsLength = morphTargets.length;
  7424. var morphTargetsPosition;
  7425. if ( morphTargetsLength > 0 ) {
  7426. morphTargetsPosition = [];
  7427. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7428. morphTargetsPosition[ i ] = [];
  7429. }
  7430. this.morphTargets.position = morphTargetsPosition;
  7431. }
  7432. var morphNormals = geometry.morphNormals;
  7433. var morphNormalsLength = morphNormals.length;
  7434. var morphTargetsNormal;
  7435. if ( morphNormalsLength > 0 ) {
  7436. morphTargetsNormal = [];
  7437. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7438. morphTargetsNormal[ i ] = [];
  7439. }
  7440. this.morphTargets.normal = morphTargetsNormal;
  7441. }
  7442. // skins
  7443. var skinIndices = geometry.skinIndices;
  7444. var skinWeights = geometry.skinWeights;
  7445. var hasSkinIndices = skinIndices.length === vertices.length;
  7446. var hasSkinWeights = skinWeights.length === vertices.length;
  7447. //
  7448. for ( var i = 0; i < faces.length; i ++ ) {
  7449. var face = faces[ i ];
  7450. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7451. var vertexNormals = face.vertexNormals;
  7452. if ( vertexNormals.length === 3 ) {
  7453. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7454. } else {
  7455. var normal = face.normal;
  7456. this.normals.push( normal, normal, normal );
  7457. }
  7458. var vertexColors = face.vertexColors;
  7459. if ( vertexColors.length === 3 ) {
  7460. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7461. } else {
  7462. var color = face.color;
  7463. this.colors.push( color, color, color );
  7464. }
  7465. if ( hasFaceVertexUv === true ) {
  7466. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7467. if ( vertexUvs !== undefined ) {
  7468. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7469. } else {
  7470. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7471. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7472. }
  7473. }
  7474. if ( hasFaceVertexUv2 === true ) {
  7475. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7476. if ( vertexUvs !== undefined ) {
  7477. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7478. } else {
  7479. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7480. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7481. }
  7482. }
  7483. // morphs
  7484. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7485. var morphTarget = morphTargets[ j ].vertices;
  7486. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7487. }
  7488. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7489. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7490. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7491. }
  7492. // skins
  7493. if ( hasSkinIndices ) {
  7494. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7495. }
  7496. if ( hasSkinWeights ) {
  7497. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7498. }
  7499. }
  7500. this.computeGroups( geometry );
  7501. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7502. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7503. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7504. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7505. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7506. return this;
  7507. }
  7508. } );
  7509. /**
  7510. * @author mrdoob / http://mrdoob.com/
  7511. * @author kile / http://kile.stravaganza.org/
  7512. * @author alteredq / http://alteredqualia.com/
  7513. * @author mikael emtinger / http://gomo.se/
  7514. * @author zz85 / http://www.lab4games.net/zz85/blog
  7515. * @author bhouston / http://clara.io
  7516. */
  7517. function Geometry() {
  7518. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7519. this.uuid = _Math.generateUUID();
  7520. this.name = '';
  7521. this.type = 'Geometry';
  7522. this.vertices = [];
  7523. this.colors = [];
  7524. this.faces = [];
  7525. this.faceVertexUvs = [ [] ];
  7526. this.morphTargets = [];
  7527. this.morphNormals = [];
  7528. this.skinWeights = [];
  7529. this.skinIndices = [];
  7530. this.lineDistances = [];
  7531. this.boundingBox = null;
  7532. this.boundingSphere = null;
  7533. // update flags
  7534. this.elementsNeedUpdate = false;
  7535. this.verticesNeedUpdate = false;
  7536. this.uvsNeedUpdate = false;
  7537. this.normalsNeedUpdate = false;
  7538. this.colorsNeedUpdate = false;
  7539. this.lineDistancesNeedUpdate = false;
  7540. this.groupsNeedUpdate = false;
  7541. }
  7542. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7543. isGeometry: true,
  7544. applyMatrix: function ( matrix ) {
  7545. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7546. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7547. var vertex = this.vertices[ i ];
  7548. vertex.applyMatrix4( matrix );
  7549. }
  7550. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7551. var face = this.faces[ i ];
  7552. face.normal.applyMatrix3( normalMatrix ).normalize();
  7553. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7554. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7555. }
  7556. }
  7557. if ( this.boundingBox !== null ) {
  7558. this.computeBoundingBox();
  7559. }
  7560. if ( this.boundingSphere !== null ) {
  7561. this.computeBoundingSphere();
  7562. }
  7563. this.verticesNeedUpdate = true;
  7564. this.normalsNeedUpdate = true;
  7565. return this;
  7566. },
  7567. rotateX: function () {
  7568. // rotate geometry around world x-axis
  7569. var m1;
  7570. return function rotateX( angle ) {
  7571. if ( m1 === undefined ) m1 = new Matrix4();
  7572. m1.makeRotationX( angle );
  7573. this.applyMatrix( m1 );
  7574. return this;
  7575. };
  7576. }(),
  7577. rotateY: function () {
  7578. // rotate geometry around world y-axis
  7579. var m1;
  7580. return function rotateY( angle ) {
  7581. if ( m1 === undefined ) m1 = new Matrix4();
  7582. m1.makeRotationY( angle );
  7583. this.applyMatrix( m1 );
  7584. return this;
  7585. };
  7586. }(),
  7587. rotateZ: function () {
  7588. // rotate geometry around world z-axis
  7589. var m1;
  7590. return function rotateZ( angle ) {
  7591. if ( m1 === undefined ) m1 = new Matrix4();
  7592. m1.makeRotationZ( angle );
  7593. this.applyMatrix( m1 );
  7594. return this;
  7595. };
  7596. }(),
  7597. translate: function () {
  7598. // translate geometry
  7599. var m1;
  7600. return function translate( x, y, z ) {
  7601. if ( m1 === undefined ) m1 = new Matrix4();
  7602. m1.makeTranslation( x, y, z );
  7603. this.applyMatrix( m1 );
  7604. return this;
  7605. };
  7606. }(),
  7607. scale: function () {
  7608. // scale geometry
  7609. var m1;
  7610. return function scale( x, y, z ) {
  7611. if ( m1 === undefined ) m1 = new Matrix4();
  7612. m1.makeScale( x, y, z );
  7613. this.applyMatrix( m1 );
  7614. return this;
  7615. };
  7616. }(),
  7617. lookAt: function () {
  7618. var obj;
  7619. return function lookAt( vector ) {
  7620. if ( obj === undefined ) obj = new Object3D();
  7621. obj.lookAt( vector );
  7622. obj.updateMatrix();
  7623. this.applyMatrix( obj.matrix );
  7624. };
  7625. }(),
  7626. fromBufferGeometry: function ( geometry ) {
  7627. var scope = this;
  7628. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7629. var attributes = geometry.attributes;
  7630. var positions = attributes.position.array;
  7631. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7632. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7633. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7634. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7635. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7636. var tempNormals = [];
  7637. var tempUVs = [];
  7638. var tempUVs2 = [];
  7639. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7640. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7641. if ( normals !== undefined ) {
  7642. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7643. }
  7644. if ( colors !== undefined ) {
  7645. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7646. }
  7647. if ( uvs !== undefined ) {
  7648. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7649. }
  7650. if ( uvs2 !== undefined ) {
  7651. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7652. }
  7653. }
  7654. function addFace( a, b, c, materialIndex ) {
  7655. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7656. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7657. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7658. scope.faces.push( face );
  7659. if ( uvs !== undefined ) {
  7660. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7661. }
  7662. if ( uvs2 !== undefined ) {
  7663. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7664. }
  7665. }
  7666. if ( indices !== undefined ) {
  7667. var groups = geometry.groups;
  7668. if ( groups.length > 0 ) {
  7669. for ( var i = 0; i < groups.length; i ++ ) {
  7670. var group = groups[ i ];
  7671. var start = group.start;
  7672. var count = group.count;
  7673. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7674. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7675. }
  7676. }
  7677. } else {
  7678. for ( var i = 0; i < indices.length; i += 3 ) {
  7679. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7680. }
  7681. }
  7682. } else {
  7683. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7684. addFace( i, i + 1, i + 2 );
  7685. }
  7686. }
  7687. this.computeFaceNormals();
  7688. if ( geometry.boundingBox !== null ) {
  7689. this.boundingBox = geometry.boundingBox.clone();
  7690. }
  7691. if ( geometry.boundingSphere !== null ) {
  7692. this.boundingSphere = geometry.boundingSphere.clone();
  7693. }
  7694. return this;
  7695. },
  7696. center: function () {
  7697. this.computeBoundingBox();
  7698. var offset = this.boundingBox.getCenter().negate();
  7699. this.translate( offset.x, offset.y, offset.z );
  7700. return offset;
  7701. },
  7702. normalize: function () {
  7703. this.computeBoundingSphere();
  7704. var center = this.boundingSphere.center;
  7705. var radius = this.boundingSphere.radius;
  7706. var s = radius === 0 ? 1 : 1.0 / radius;
  7707. var matrix = new Matrix4();
  7708. matrix.set(
  7709. s, 0, 0, - s * center.x,
  7710. 0, s, 0, - s * center.y,
  7711. 0, 0, s, - s * center.z,
  7712. 0, 0, 0, 1
  7713. );
  7714. this.applyMatrix( matrix );
  7715. return this;
  7716. },
  7717. computeFaceNormals: function () {
  7718. var cb = new Vector3(), ab = new Vector3();
  7719. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7720. var face = this.faces[ f ];
  7721. var vA = this.vertices[ face.a ];
  7722. var vB = this.vertices[ face.b ];
  7723. var vC = this.vertices[ face.c ];
  7724. cb.subVectors( vC, vB );
  7725. ab.subVectors( vA, vB );
  7726. cb.cross( ab );
  7727. cb.normalize();
  7728. face.normal.copy( cb );
  7729. }
  7730. },
  7731. computeVertexNormals: function ( areaWeighted ) {
  7732. if ( areaWeighted === undefined ) areaWeighted = true;
  7733. var v, vl, f, fl, face, vertices;
  7734. vertices = new Array( this.vertices.length );
  7735. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7736. vertices[ v ] = new Vector3();
  7737. }
  7738. if ( areaWeighted ) {
  7739. // vertex normals weighted by triangle areas
  7740. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7741. var vA, vB, vC;
  7742. var cb = new Vector3(), ab = new Vector3();
  7743. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7744. face = this.faces[ f ];
  7745. vA = this.vertices[ face.a ];
  7746. vB = this.vertices[ face.b ];
  7747. vC = this.vertices[ face.c ];
  7748. cb.subVectors( vC, vB );
  7749. ab.subVectors( vA, vB );
  7750. cb.cross( ab );
  7751. vertices[ face.a ].add( cb );
  7752. vertices[ face.b ].add( cb );
  7753. vertices[ face.c ].add( cb );
  7754. }
  7755. } else {
  7756. this.computeFaceNormals();
  7757. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7758. face = this.faces[ f ];
  7759. vertices[ face.a ].add( face.normal );
  7760. vertices[ face.b ].add( face.normal );
  7761. vertices[ face.c ].add( face.normal );
  7762. }
  7763. }
  7764. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7765. vertices[ v ].normalize();
  7766. }
  7767. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7768. face = this.faces[ f ];
  7769. var vertexNormals = face.vertexNormals;
  7770. if ( vertexNormals.length === 3 ) {
  7771. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7772. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7773. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7774. } else {
  7775. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7776. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7777. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7778. }
  7779. }
  7780. if ( this.faces.length > 0 ) {
  7781. this.normalsNeedUpdate = true;
  7782. }
  7783. },
  7784. computeFlatVertexNormals: function () {
  7785. var f, fl, face;
  7786. this.computeFaceNormals();
  7787. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7788. face = this.faces[ f ];
  7789. var vertexNormals = face.vertexNormals;
  7790. if ( vertexNormals.length === 3 ) {
  7791. vertexNormals[ 0 ].copy( face.normal );
  7792. vertexNormals[ 1 ].copy( face.normal );
  7793. vertexNormals[ 2 ].copy( face.normal );
  7794. } else {
  7795. vertexNormals[ 0 ] = face.normal.clone();
  7796. vertexNormals[ 1 ] = face.normal.clone();
  7797. vertexNormals[ 2 ] = face.normal.clone();
  7798. }
  7799. }
  7800. if ( this.faces.length > 0 ) {
  7801. this.normalsNeedUpdate = true;
  7802. }
  7803. },
  7804. computeMorphNormals: function () {
  7805. var i, il, f, fl, face;
  7806. // save original normals
  7807. // - create temp variables on first access
  7808. // otherwise just copy (for faster repeated calls)
  7809. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7810. face = this.faces[ f ];
  7811. if ( ! face.__originalFaceNormal ) {
  7812. face.__originalFaceNormal = face.normal.clone();
  7813. } else {
  7814. face.__originalFaceNormal.copy( face.normal );
  7815. }
  7816. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7817. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7818. if ( ! face.__originalVertexNormals[ i ] ) {
  7819. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7820. } else {
  7821. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7822. }
  7823. }
  7824. }
  7825. // use temp geometry to compute face and vertex normals for each morph
  7826. var tmpGeo = new Geometry();
  7827. tmpGeo.faces = this.faces;
  7828. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7829. // create on first access
  7830. if ( ! this.morphNormals[ i ] ) {
  7831. this.morphNormals[ i ] = {};
  7832. this.morphNormals[ i ].faceNormals = [];
  7833. this.morphNormals[ i ].vertexNormals = [];
  7834. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7835. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7836. var faceNormal, vertexNormals;
  7837. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7838. faceNormal = new Vector3();
  7839. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7840. dstNormalsFace.push( faceNormal );
  7841. dstNormalsVertex.push( vertexNormals );
  7842. }
  7843. }
  7844. var morphNormals = this.morphNormals[ i ];
  7845. // set vertices to morph target
  7846. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7847. // compute morph normals
  7848. tmpGeo.computeFaceNormals();
  7849. tmpGeo.computeVertexNormals();
  7850. // store morph normals
  7851. var faceNormal, vertexNormals;
  7852. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7853. face = this.faces[ f ];
  7854. faceNormal = morphNormals.faceNormals[ f ];
  7855. vertexNormals = morphNormals.vertexNormals[ f ];
  7856. faceNormal.copy( face.normal );
  7857. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7858. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7859. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7860. }
  7861. }
  7862. // restore original normals
  7863. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7864. face = this.faces[ f ];
  7865. face.normal = face.__originalFaceNormal;
  7866. face.vertexNormals = face.__originalVertexNormals;
  7867. }
  7868. },
  7869. computeLineDistances: function () {
  7870. var d = 0;
  7871. var vertices = this.vertices;
  7872. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7873. if ( i > 0 ) {
  7874. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7875. }
  7876. this.lineDistances[ i ] = d;
  7877. }
  7878. },
  7879. computeBoundingBox: function () {
  7880. if ( this.boundingBox === null ) {
  7881. this.boundingBox = new Box3();
  7882. }
  7883. this.boundingBox.setFromPoints( this.vertices );
  7884. },
  7885. computeBoundingSphere: function () {
  7886. if ( this.boundingSphere === null ) {
  7887. this.boundingSphere = new Sphere();
  7888. }
  7889. this.boundingSphere.setFromPoints( this.vertices );
  7890. },
  7891. merge: function ( geometry, matrix, materialIndexOffset ) {
  7892. if ( (geometry && geometry.isGeometry) === false ) {
  7893. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7894. return;
  7895. }
  7896. var normalMatrix,
  7897. vertexOffset = this.vertices.length,
  7898. vertices1 = this.vertices,
  7899. vertices2 = geometry.vertices,
  7900. faces1 = this.faces,
  7901. faces2 = geometry.faces,
  7902. uvs1 = this.faceVertexUvs[ 0 ],
  7903. uvs2 = geometry.faceVertexUvs[ 0 ],
  7904. colors1 = this.colors,
  7905. colors2 = geometry.colors;
  7906. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7907. if ( matrix !== undefined ) {
  7908. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7909. }
  7910. // vertices
  7911. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7912. var vertex = vertices2[ i ];
  7913. var vertexCopy = vertex.clone();
  7914. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7915. vertices1.push( vertexCopy );
  7916. }
  7917. // colors
  7918. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7919. colors1.push( colors2[ i ].clone() );
  7920. }
  7921. // faces
  7922. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7923. var face = faces2[ i ], faceCopy, normal, color,
  7924. faceVertexNormals = face.vertexNormals,
  7925. faceVertexColors = face.vertexColors;
  7926. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7927. faceCopy.normal.copy( face.normal );
  7928. if ( normalMatrix !== undefined ) {
  7929. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7930. }
  7931. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7932. normal = faceVertexNormals[ j ].clone();
  7933. if ( normalMatrix !== undefined ) {
  7934. normal.applyMatrix3( normalMatrix ).normalize();
  7935. }
  7936. faceCopy.vertexNormals.push( normal );
  7937. }
  7938. faceCopy.color.copy( face.color );
  7939. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7940. color = faceVertexColors[ j ];
  7941. faceCopy.vertexColors.push( color.clone() );
  7942. }
  7943. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7944. faces1.push( faceCopy );
  7945. }
  7946. // uvs
  7947. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7948. var uv = uvs2[ i ], uvCopy = [];
  7949. if ( uv === undefined ) {
  7950. continue;
  7951. }
  7952. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7953. uvCopy.push( uv[ j ].clone() );
  7954. }
  7955. uvs1.push( uvCopy );
  7956. }
  7957. },
  7958. mergeMesh: function ( mesh ) {
  7959. if ( (mesh && mesh.isMesh) === false ) {
  7960. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7961. return;
  7962. }
  7963. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7964. this.merge( mesh.geometry, mesh.matrix );
  7965. },
  7966. /*
  7967. * Checks for duplicate vertices with hashmap.
  7968. * Duplicated vertices are removed
  7969. * and faces' vertices are updated.
  7970. */
  7971. mergeVertices: function () {
  7972. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7973. var unique = [], changes = [];
  7974. var v, key;
  7975. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7976. var precision = Math.pow( 10, precisionPoints );
  7977. var i, il, face;
  7978. var indices, j, jl;
  7979. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7980. v = this.vertices[ i ];
  7981. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7982. if ( verticesMap[ key ] === undefined ) {
  7983. verticesMap[ key ] = i;
  7984. unique.push( this.vertices[ i ] );
  7985. changes[ i ] = unique.length - 1;
  7986. } else {
  7987. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7988. changes[ i ] = changes[ verticesMap[ key ] ];
  7989. }
  7990. }
  7991. // if faces are completely degenerate after merging vertices, we
  7992. // have to remove them from the geometry.
  7993. var faceIndicesToRemove = [];
  7994. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7995. face = this.faces[ i ];
  7996. face.a = changes[ face.a ];
  7997. face.b = changes[ face.b ];
  7998. face.c = changes[ face.c ];
  7999. indices = [ face.a, face.b, face.c ];
  8000. var dupIndex = - 1;
  8001. // if any duplicate vertices are found in a Face3
  8002. // we have to remove the face as nothing can be saved
  8003. for ( var n = 0; n < 3; n ++ ) {
  8004. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  8005. dupIndex = n;
  8006. faceIndicesToRemove.push( i );
  8007. break;
  8008. }
  8009. }
  8010. }
  8011. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  8012. var idx = faceIndicesToRemove[ i ];
  8013. this.faces.splice( idx, 1 );
  8014. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  8015. this.faceVertexUvs[ j ].splice( idx, 1 );
  8016. }
  8017. }
  8018. // Use unique set of vertices
  8019. var diff = this.vertices.length - unique.length;
  8020. this.vertices = unique;
  8021. return diff;
  8022. },
  8023. sortFacesByMaterialIndex: function () {
  8024. var faces = this.faces;
  8025. var length = faces.length;
  8026. // tag faces
  8027. for ( var i = 0; i < length; i ++ ) {
  8028. faces[ i ]._id = i;
  8029. }
  8030. // sort faces
  8031. function materialIndexSort( a, b ) {
  8032. return a.materialIndex - b.materialIndex;
  8033. }
  8034. faces.sort( materialIndexSort );
  8035. // sort uvs
  8036. var uvs1 = this.faceVertexUvs[ 0 ];
  8037. var uvs2 = this.faceVertexUvs[ 1 ];
  8038. var newUvs1, newUvs2;
  8039. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  8040. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  8041. for ( var i = 0; i < length; i ++ ) {
  8042. var id = faces[ i ]._id;
  8043. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  8044. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  8045. }
  8046. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8047. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8048. },
  8049. toJSON: function () {
  8050. var data = {
  8051. metadata: {
  8052. version: 4.4,
  8053. type: 'Geometry',
  8054. generator: 'Geometry.toJSON'
  8055. }
  8056. };
  8057. // standard Geometry serialization
  8058. data.uuid = this.uuid;
  8059. data.type = this.type;
  8060. if ( this.name !== '' ) data.name = this.name;
  8061. if ( this.parameters !== undefined ) {
  8062. var parameters = this.parameters;
  8063. for ( var key in parameters ) {
  8064. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8065. }
  8066. return data;
  8067. }
  8068. var vertices = [];
  8069. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8070. var vertex = this.vertices[ i ];
  8071. vertices.push( vertex.x, vertex.y, vertex.z );
  8072. }
  8073. var faces = [];
  8074. var normals = [];
  8075. var normalsHash = {};
  8076. var colors = [];
  8077. var colorsHash = {};
  8078. var uvs = [];
  8079. var uvsHash = {};
  8080. for ( var i = 0; i < this.faces.length; i ++ ) {
  8081. var face = this.faces[ i ];
  8082. var hasMaterial = true;
  8083. var hasFaceUv = false; // deprecated
  8084. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8085. var hasFaceNormal = face.normal.length() > 0;
  8086. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8087. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8088. var hasFaceVertexColor = face.vertexColors.length > 0;
  8089. var faceType = 0;
  8090. faceType = setBit( faceType, 0, 0 ); // isQuad
  8091. faceType = setBit( faceType, 1, hasMaterial );
  8092. faceType = setBit( faceType, 2, hasFaceUv );
  8093. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8094. faceType = setBit( faceType, 4, hasFaceNormal );
  8095. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8096. faceType = setBit( faceType, 6, hasFaceColor );
  8097. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8098. faces.push( faceType );
  8099. faces.push( face.a, face.b, face.c );
  8100. faces.push( face.materialIndex );
  8101. if ( hasFaceVertexUv ) {
  8102. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8103. faces.push(
  8104. getUvIndex( faceVertexUvs[ 0 ] ),
  8105. getUvIndex( faceVertexUvs[ 1 ] ),
  8106. getUvIndex( faceVertexUvs[ 2 ] )
  8107. );
  8108. }
  8109. if ( hasFaceNormal ) {
  8110. faces.push( getNormalIndex( face.normal ) );
  8111. }
  8112. if ( hasFaceVertexNormal ) {
  8113. var vertexNormals = face.vertexNormals;
  8114. faces.push(
  8115. getNormalIndex( vertexNormals[ 0 ] ),
  8116. getNormalIndex( vertexNormals[ 1 ] ),
  8117. getNormalIndex( vertexNormals[ 2 ] )
  8118. );
  8119. }
  8120. if ( hasFaceColor ) {
  8121. faces.push( getColorIndex( face.color ) );
  8122. }
  8123. if ( hasFaceVertexColor ) {
  8124. var vertexColors = face.vertexColors;
  8125. faces.push(
  8126. getColorIndex( vertexColors[ 0 ] ),
  8127. getColorIndex( vertexColors[ 1 ] ),
  8128. getColorIndex( vertexColors[ 2 ] )
  8129. );
  8130. }
  8131. }
  8132. function setBit( value, position, enabled ) {
  8133. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8134. }
  8135. function getNormalIndex( normal ) {
  8136. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8137. if ( normalsHash[ hash ] !== undefined ) {
  8138. return normalsHash[ hash ];
  8139. }
  8140. normalsHash[ hash ] = normals.length / 3;
  8141. normals.push( normal.x, normal.y, normal.z );
  8142. return normalsHash[ hash ];
  8143. }
  8144. function getColorIndex( color ) {
  8145. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8146. if ( colorsHash[ hash ] !== undefined ) {
  8147. return colorsHash[ hash ];
  8148. }
  8149. colorsHash[ hash ] = colors.length;
  8150. colors.push( color.getHex() );
  8151. return colorsHash[ hash ];
  8152. }
  8153. function getUvIndex( uv ) {
  8154. var hash = uv.x.toString() + uv.y.toString();
  8155. if ( uvsHash[ hash ] !== undefined ) {
  8156. return uvsHash[ hash ];
  8157. }
  8158. uvsHash[ hash ] = uvs.length / 2;
  8159. uvs.push( uv.x, uv.y );
  8160. return uvsHash[ hash ];
  8161. }
  8162. data.data = {};
  8163. data.data.vertices = vertices;
  8164. data.data.normals = normals;
  8165. if ( colors.length > 0 ) data.data.colors = colors;
  8166. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8167. data.data.faces = faces;
  8168. return data;
  8169. },
  8170. clone: function () {
  8171. /*
  8172. // Handle primitives
  8173. var parameters = this.parameters;
  8174. if ( parameters !== undefined ) {
  8175. var values = [];
  8176. for ( var key in parameters ) {
  8177. values.push( parameters[ key ] );
  8178. }
  8179. var geometry = Object.create( this.constructor.prototype );
  8180. this.constructor.apply( geometry, values );
  8181. return geometry;
  8182. }
  8183. return new this.constructor().copy( this );
  8184. */
  8185. return new Geometry().copy( this );
  8186. },
  8187. copy: function ( source ) {
  8188. this.vertices = [];
  8189. this.faces = [];
  8190. this.faceVertexUvs = [ [] ];
  8191. this.colors = [];
  8192. var vertices = source.vertices;
  8193. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8194. this.vertices.push( vertices[ i ].clone() );
  8195. }
  8196. var colors = source.colors;
  8197. for ( var i = 0, il = colors.length; i < il; i ++ ) {
  8198. this.colors.push( colors[ i ].clone() );
  8199. }
  8200. var faces = source.faces;
  8201. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  8202. this.faces.push( faces[ i ].clone() );
  8203. }
  8204. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8205. var faceVertexUvs = source.faceVertexUvs[ i ];
  8206. if ( this.faceVertexUvs[ i ] === undefined ) {
  8207. this.faceVertexUvs[ i ] = [];
  8208. }
  8209. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8210. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8211. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  8212. var uv = uvs[ k ];
  8213. uvsCopy.push( uv.clone() );
  8214. }
  8215. this.faceVertexUvs[ i ].push( uvsCopy );
  8216. }
  8217. }
  8218. return this;
  8219. },
  8220. dispose: function () {
  8221. this.dispatchEvent( { type: 'dispose' } );
  8222. }
  8223. } );
  8224. var count = 0;
  8225. function GeometryIdCount() { return count++; }
  8226. /**
  8227. * @author alteredq / http://alteredqualia.com/
  8228. * @author mrdoob / http://mrdoob.com/
  8229. */
  8230. function BufferGeometry() {
  8231. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8232. this.uuid = _Math.generateUUID();
  8233. this.name = '';
  8234. this.type = 'BufferGeometry';
  8235. this.index = null;
  8236. this.attributes = {};
  8237. this.morphAttributes = {};
  8238. this.groups = [];
  8239. this.boundingBox = null;
  8240. this.boundingSphere = null;
  8241. this.drawRange = { start: 0, count: Infinity };
  8242. }
  8243. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8244. isBufferGeometry: true,
  8245. getIndex: function () {
  8246. return this.index;
  8247. },
  8248. setIndex: function ( index ) {
  8249. this.index = index;
  8250. },
  8251. addAttribute: function ( name, attribute ) {
  8252. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8253. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8254. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8255. return;
  8256. }
  8257. if ( name === 'index' ) {
  8258. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8259. this.setIndex( attribute );
  8260. return;
  8261. }
  8262. this.attributes[ name ] = attribute;
  8263. return this;
  8264. },
  8265. getAttribute: function ( name ) {
  8266. return this.attributes[ name ];
  8267. },
  8268. removeAttribute: function ( name ) {
  8269. delete this.attributes[ name ];
  8270. return this;
  8271. },
  8272. addGroup: function ( start, count, materialIndex ) {
  8273. this.groups.push( {
  8274. start: start,
  8275. count: count,
  8276. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8277. } );
  8278. },
  8279. clearGroups: function () {
  8280. this.groups = [];
  8281. },
  8282. setDrawRange: function ( start, count ) {
  8283. this.drawRange.start = start;
  8284. this.drawRange.count = count;
  8285. },
  8286. applyMatrix: function ( matrix ) {
  8287. var position = this.attributes.position;
  8288. if ( position !== undefined ) {
  8289. matrix.applyToVector3Array( position.array );
  8290. position.needsUpdate = true;
  8291. }
  8292. var normal = this.attributes.normal;
  8293. if ( normal !== undefined ) {
  8294. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8295. normalMatrix.applyToVector3Array( normal.array );
  8296. normal.needsUpdate = true;
  8297. }
  8298. if ( this.boundingBox !== null ) {
  8299. this.computeBoundingBox();
  8300. }
  8301. if ( this.boundingSphere !== null ) {
  8302. this.computeBoundingSphere();
  8303. }
  8304. return this;
  8305. },
  8306. rotateX: function () {
  8307. // rotate geometry around world x-axis
  8308. var m1;
  8309. return function rotateX( angle ) {
  8310. if ( m1 === undefined ) m1 = new Matrix4();
  8311. m1.makeRotationX( angle );
  8312. this.applyMatrix( m1 );
  8313. return this;
  8314. };
  8315. }(),
  8316. rotateY: function () {
  8317. // rotate geometry around world y-axis
  8318. var m1;
  8319. return function rotateY( angle ) {
  8320. if ( m1 === undefined ) m1 = new Matrix4();
  8321. m1.makeRotationY( angle );
  8322. this.applyMatrix( m1 );
  8323. return this;
  8324. };
  8325. }(),
  8326. rotateZ: function () {
  8327. // rotate geometry around world z-axis
  8328. var m1;
  8329. return function rotateZ( angle ) {
  8330. if ( m1 === undefined ) m1 = new Matrix4();
  8331. m1.makeRotationZ( angle );
  8332. this.applyMatrix( m1 );
  8333. return this;
  8334. };
  8335. }(),
  8336. translate: function () {
  8337. // translate geometry
  8338. var m1;
  8339. return function translate( x, y, z ) {
  8340. if ( m1 === undefined ) m1 = new Matrix4();
  8341. m1.makeTranslation( x, y, z );
  8342. this.applyMatrix( m1 );
  8343. return this;
  8344. };
  8345. }(),
  8346. scale: function () {
  8347. // scale geometry
  8348. var m1;
  8349. return function scale( x, y, z ) {
  8350. if ( m1 === undefined ) m1 = new Matrix4();
  8351. m1.makeScale( x, y, z );
  8352. this.applyMatrix( m1 );
  8353. return this;
  8354. };
  8355. }(),
  8356. lookAt: function () {
  8357. var obj;
  8358. return function lookAt( vector ) {
  8359. if ( obj === undefined ) obj = new Object3D();
  8360. obj.lookAt( vector );
  8361. obj.updateMatrix();
  8362. this.applyMatrix( obj.matrix );
  8363. };
  8364. }(),
  8365. center: function () {
  8366. this.computeBoundingBox();
  8367. var offset = this.boundingBox.getCenter().negate();
  8368. this.translate( offset.x, offset.y, offset.z );
  8369. return offset;
  8370. },
  8371. setFromObject: function ( object ) {
  8372. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8373. var geometry = object.geometry;
  8374. if ( object.isPoints || object.isLine ) {
  8375. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8376. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8377. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8378. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8379. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8380. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8381. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8382. }
  8383. if ( geometry.boundingSphere !== null ) {
  8384. this.boundingSphere = geometry.boundingSphere.clone();
  8385. }
  8386. if ( geometry.boundingBox !== null ) {
  8387. this.boundingBox = geometry.boundingBox.clone();
  8388. }
  8389. } else if ( object.isMesh ) {
  8390. if ( geometry && geometry.isGeometry ) {
  8391. this.fromGeometry( geometry );
  8392. }
  8393. }
  8394. return this;
  8395. },
  8396. updateFromObject: function ( object ) {
  8397. var geometry = object.geometry;
  8398. if ( object.isMesh ) {
  8399. var direct = geometry.__directGeometry;
  8400. if ( geometry.elementsNeedUpdate === true ) {
  8401. direct = undefined;
  8402. geometry.elementsNeedUpdate = false;
  8403. }
  8404. if ( direct === undefined ) {
  8405. return this.fromGeometry( geometry );
  8406. }
  8407. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8408. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8409. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8410. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8411. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8412. geometry.verticesNeedUpdate = false;
  8413. geometry.normalsNeedUpdate = false;
  8414. geometry.colorsNeedUpdate = false;
  8415. geometry.uvsNeedUpdate = false;
  8416. geometry.groupsNeedUpdate = false;
  8417. geometry = direct;
  8418. }
  8419. var attribute;
  8420. if ( geometry.verticesNeedUpdate === true ) {
  8421. attribute = this.attributes.position;
  8422. if ( attribute !== undefined ) {
  8423. attribute.copyVector3sArray( geometry.vertices );
  8424. attribute.needsUpdate = true;
  8425. }
  8426. geometry.verticesNeedUpdate = false;
  8427. }
  8428. if ( geometry.normalsNeedUpdate === true ) {
  8429. attribute = this.attributes.normal;
  8430. if ( attribute !== undefined ) {
  8431. attribute.copyVector3sArray( geometry.normals );
  8432. attribute.needsUpdate = true;
  8433. }
  8434. geometry.normalsNeedUpdate = false;
  8435. }
  8436. if ( geometry.colorsNeedUpdate === true ) {
  8437. attribute = this.attributes.color;
  8438. if ( attribute !== undefined ) {
  8439. attribute.copyColorsArray( geometry.colors );
  8440. attribute.needsUpdate = true;
  8441. }
  8442. geometry.colorsNeedUpdate = false;
  8443. }
  8444. if ( geometry.uvsNeedUpdate ) {
  8445. attribute = this.attributes.uv;
  8446. if ( attribute !== undefined ) {
  8447. attribute.copyVector2sArray( geometry.uvs );
  8448. attribute.needsUpdate = true;
  8449. }
  8450. geometry.uvsNeedUpdate = false;
  8451. }
  8452. if ( geometry.lineDistancesNeedUpdate ) {
  8453. attribute = this.attributes.lineDistance;
  8454. if ( attribute !== undefined ) {
  8455. attribute.copyArray( geometry.lineDistances );
  8456. attribute.needsUpdate = true;
  8457. }
  8458. geometry.lineDistancesNeedUpdate = false;
  8459. }
  8460. if ( geometry.groupsNeedUpdate ) {
  8461. geometry.computeGroups( object.geometry );
  8462. this.groups = geometry.groups;
  8463. geometry.groupsNeedUpdate = false;
  8464. }
  8465. return this;
  8466. },
  8467. fromGeometry: function ( geometry ) {
  8468. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8469. return this.fromDirectGeometry( geometry.__directGeometry );
  8470. },
  8471. fromDirectGeometry: function ( geometry ) {
  8472. var positions = new Float32Array( geometry.vertices.length * 3 );
  8473. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8474. if ( geometry.normals.length > 0 ) {
  8475. var normals = new Float32Array( geometry.normals.length * 3 );
  8476. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8477. }
  8478. if ( geometry.colors.length > 0 ) {
  8479. var colors = new Float32Array( geometry.colors.length * 3 );
  8480. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8481. }
  8482. if ( geometry.uvs.length > 0 ) {
  8483. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8484. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8485. }
  8486. if ( geometry.uvs2.length > 0 ) {
  8487. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8488. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8489. }
  8490. if ( geometry.indices.length > 0 ) {
  8491. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  8492. var indices = new TypeArray( geometry.indices.length * 3 );
  8493. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8494. }
  8495. // groups
  8496. this.groups = geometry.groups;
  8497. // morphs
  8498. for ( var name in geometry.morphTargets ) {
  8499. var array = [];
  8500. var morphTargets = geometry.morphTargets[ name ];
  8501. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8502. var morphTarget = morphTargets[ i ];
  8503. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8504. array.push( attribute.copyVector3sArray( morphTarget ) );
  8505. }
  8506. this.morphAttributes[ name ] = array;
  8507. }
  8508. // skinning
  8509. if ( geometry.skinIndices.length > 0 ) {
  8510. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8511. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8512. }
  8513. if ( geometry.skinWeights.length > 0 ) {
  8514. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8515. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8516. }
  8517. //
  8518. if ( geometry.boundingSphere !== null ) {
  8519. this.boundingSphere = geometry.boundingSphere.clone();
  8520. }
  8521. if ( geometry.boundingBox !== null ) {
  8522. this.boundingBox = geometry.boundingBox.clone();
  8523. }
  8524. return this;
  8525. },
  8526. computeBoundingBox: function () {
  8527. if ( this.boundingBox === null ) {
  8528. this.boundingBox = new Box3();
  8529. }
  8530. var position = this.attributes.position;
  8531. if ( position !== undefined ) {
  8532. this.boundingBox.setFromBufferAttribute( position );
  8533. } else {
  8534. this.boundingBox.makeEmpty();
  8535. }
  8536. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8537. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8538. }
  8539. },
  8540. computeBoundingSphere: function () {
  8541. var box = new Box3();
  8542. var vector = new Vector3();
  8543. return function computeBoundingSphere() {
  8544. if ( this.boundingSphere === null ) {
  8545. this.boundingSphere = new Sphere();
  8546. }
  8547. var position = this.attributes.position;
  8548. if ( position ) {
  8549. var center = this.boundingSphere.center;
  8550. box.setFromBufferAttribute( position );
  8551. box.getCenter( center );
  8552. // hoping to find a boundingSphere with a radius smaller than the
  8553. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8554. var maxRadiusSq = 0;
  8555. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8556. vector.x = position.getX( i );
  8557. vector.y = position.getY( i );
  8558. vector.z = position.getZ( i );
  8559. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8560. }
  8561. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8562. if ( isNaN( this.boundingSphere.radius ) ) {
  8563. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8564. }
  8565. }
  8566. };
  8567. }(),
  8568. computeFaceNormals: function () {
  8569. // backwards compatibility
  8570. },
  8571. computeVertexNormals: function () {
  8572. var index = this.index;
  8573. var attributes = this.attributes;
  8574. var groups = this.groups;
  8575. if ( attributes.position ) {
  8576. var positions = attributes.position.array;
  8577. if ( attributes.normal === undefined ) {
  8578. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8579. } else {
  8580. // reset existing normals to zero
  8581. var array = attributes.normal.array;
  8582. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8583. array[ i ] = 0;
  8584. }
  8585. }
  8586. var normals = attributes.normal.array;
  8587. var vA, vB, vC;
  8588. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8589. var cb = new Vector3(), ab = new Vector3();
  8590. // indexed elements
  8591. if ( index ) {
  8592. var indices = index.array;
  8593. if ( groups.length === 0 ) {
  8594. this.addGroup( 0, indices.length );
  8595. }
  8596. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8597. var group = groups[ j ];
  8598. var start = group.start;
  8599. var count = group.count;
  8600. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8601. vA = indices[ i + 0 ] * 3;
  8602. vB = indices[ i + 1 ] * 3;
  8603. vC = indices[ i + 2 ] * 3;
  8604. pA.fromArray( positions, vA );
  8605. pB.fromArray( positions, vB );
  8606. pC.fromArray( positions, vC );
  8607. cb.subVectors( pC, pB );
  8608. ab.subVectors( pA, pB );
  8609. cb.cross( ab );
  8610. normals[ vA ] += cb.x;
  8611. normals[ vA + 1 ] += cb.y;
  8612. normals[ vA + 2 ] += cb.z;
  8613. normals[ vB ] += cb.x;
  8614. normals[ vB + 1 ] += cb.y;
  8615. normals[ vB + 2 ] += cb.z;
  8616. normals[ vC ] += cb.x;
  8617. normals[ vC + 1 ] += cb.y;
  8618. normals[ vC + 2 ] += cb.z;
  8619. }
  8620. }
  8621. } else {
  8622. // non-indexed elements (unconnected triangle soup)
  8623. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8624. pA.fromArray( positions, i );
  8625. pB.fromArray( positions, i + 3 );
  8626. pC.fromArray( positions, i + 6 );
  8627. cb.subVectors( pC, pB );
  8628. ab.subVectors( pA, pB );
  8629. cb.cross( ab );
  8630. normals[ i ] = cb.x;
  8631. normals[ i + 1 ] = cb.y;
  8632. normals[ i + 2 ] = cb.z;
  8633. normals[ i + 3 ] = cb.x;
  8634. normals[ i + 4 ] = cb.y;
  8635. normals[ i + 5 ] = cb.z;
  8636. normals[ i + 6 ] = cb.x;
  8637. normals[ i + 7 ] = cb.y;
  8638. normals[ i + 8 ] = cb.z;
  8639. }
  8640. }
  8641. this.normalizeNormals();
  8642. attributes.normal.needsUpdate = true;
  8643. }
  8644. },
  8645. merge: function ( geometry, offset ) {
  8646. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8647. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8648. return;
  8649. }
  8650. if ( offset === undefined ) offset = 0;
  8651. var attributes = this.attributes;
  8652. for ( var key in attributes ) {
  8653. if ( geometry.attributes[ key ] === undefined ) continue;
  8654. var attribute1 = attributes[ key ];
  8655. var attributeArray1 = attribute1.array;
  8656. var attribute2 = geometry.attributes[ key ];
  8657. var attributeArray2 = attribute2.array;
  8658. var attributeSize = attribute2.itemSize;
  8659. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8660. attributeArray1[ j ] = attributeArray2[ i ];
  8661. }
  8662. }
  8663. return this;
  8664. },
  8665. normalizeNormals: function () {
  8666. var normals = this.attributes.normal.array;
  8667. var x, y, z, n;
  8668. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  8669. x = normals[ i ];
  8670. y = normals[ i + 1 ];
  8671. z = normals[ i + 2 ];
  8672. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8673. normals[ i ] *= n;
  8674. normals[ i + 1 ] *= n;
  8675. normals[ i + 2 ] *= n;
  8676. }
  8677. },
  8678. toNonIndexed: function () {
  8679. if ( this.index === null ) {
  8680. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8681. return this;
  8682. }
  8683. var geometry2 = new BufferGeometry();
  8684. var indices = this.index.array;
  8685. var attributes = this.attributes;
  8686. for ( var name in attributes ) {
  8687. var attribute = attributes[ name ];
  8688. var array = attribute.array;
  8689. var itemSize = attribute.itemSize;
  8690. var array2 = new array.constructor( indices.length * itemSize );
  8691. var index = 0, index2 = 0;
  8692. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8693. index = indices[ i ] * itemSize;
  8694. for ( var j = 0; j < itemSize; j ++ ) {
  8695. array2[ index2 ++ ] = array[ index ++ ];
  8696. }
  8697. }
  8698. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8699. }
  8700. return geometry2;
  8701. },
  8702. toJSON: function () {
  8703. var data = {
  8704. metadata: {
  8705. version: 4.4,
  8706. type: 'BufferGeometry',
  8707. generator: 'BufferGeometry.toJSON'
  8708. }
  8709. };
  8710. // standard BufferGeometry serialization
  8711. data.uuid = this.uuid;
  8712. data.type = this.type;
  8713. if ( this.name !== '' ) data.name = this.name;
  8714. if ( this.parameters !== undefined ) {
  8715. var parameters = this.parameters;
  8716. for ( var key in parameters ) {
  8717. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8718. }
  8719. return data;
  8720. }
  8721. data.data = { attributes: {} };
  8722. var index = this.index;
  8723. if ( index !== null ) {
  8724. var array = Array.prototype.slice.call( index.array );
  8725. data.data.index = {
  8726. type: index.array.constructor.name,
  8727. array: array
  8728. };
  8729. }
  8730. var attributes = this.attributes;
  8731. for ( var key in attributes ) {
  8732. var attribute = attributes[ key ];
  8733. var array = Array.prototype.slice.call( attribute.array );
  8734. data.data.attributes[ key ] = {
  8735. itemSize: attribute.itemSize,
  8736. type: attribute.array.constructor.name,
  8737. array: array,
  8738. normalized: attribute.normalized
  8739. };
  8740. }
  8741. var groups = this.groups;
  8742. if ( groups.length > 0 ) {
  8743. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8744. }
  8745. var boundingSphere = this.boundingSphere;
  8746. if ( boundingSphere !== null ) {
  8747. data.data.boundingSphere = {
  8748. center: boundingSphere.center.toArray(),
  8749. radius: boundingSphere.radius
  8750. };
  8751. }
  8752. return data;
  8753. },
  8754. clone: function () {
  8755. /*
  8756. // Handle primitives
  8757. var parameters = this.parameters;
  8758. if ( parameters !== undefined ) {
  8759. var values = [];
  8760. for ( var key in parameters ) {
  8761. values.push( parameters[ key ] );
  8762. }
  8763. var geometry = Object.create( this.constructor.prototype );
  8764. this.constructor.apply( geometry, values );
  8765. return geometry;
  8766. }
  8767. return new this.constructor().copy( this );
  8768. */
  8769. return new BufferGeometry().copy( this );
  8770. },
  8771. copy: function ( source ) {
  8772. var index = source.index;
  8773. if ( index !== null ) {
  8774. this.setIndex( index.clone() );
  8775. }
  8776. var attributes = source.attributes;
  8777. for ( var name in attributes ) {
  8778. var attribute = attributes[ name ];
  8779. this.addAttribute( name, attribute.clone() );
  8780. }
  8781. var groups = source.groups;
  8782. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  8783. var group = groups[ i ];
  8784. this.addGroup( group.start, group.count, group.materialIndex );
  8785. }
  8786. return this;
  8787. },
  8788. dispose: function () {
  8789. this.dispatchEvent( { type: 'dispose' } );
  8790. }
  8791. } );
  8792. BufferGeometry.MaxIndex = 65535;
  8793. /**
  8794. * @author mrdoob / http://mrdoob.com/
  8795. * @author alteredq / http://alteredqualia.com/
  8796. * @author mikael emtinger / http://gomo.se/
  8797. * @author jonobr1 / http://jonobr1.com/
  8798. */
  8799. function Mesh( geometry, material ) {
  8800. Object3D.call( this );
  8801. this.type = 'Mesh';
  8802. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8803. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8804. this.drawMode = TrianglesDrawMode;
  8805. this.updateMorphTargets();
  8806. }
  8807. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8808. constructor: Mesh,
  8809. isMesh: true,
  8810. setDrawMode: function ( value ) {
  8811. this.drawMode = value;
  8812. },
  8813. copy: function ( source ) {
  8814. Object3D.prototype.copy.call( this, source );
  8815. this.drawMode = source.drawMode;
  8816. return this;
  8817. },
  8818. updateMorphTargets: function () {
  8819. var morphTargets = this.geometry.morphTargets;
  8820. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8821. this.morphTargetInfluences = [];
  8822. this.morphTargetDictionary = {};
  8823. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8824. this.morphTargetInfluences.push( 0 );
  8825. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8826. }
  8827. }
  8828. },
  8829. raycast: ( function () {
  8830. var inverseMatrix = new Matrix4();
  8831. var ray = new Ray();
  8832. var sphere = new Sphere();
  8833. var vA = new Vector3();
  8834. var vB = new Vector3();
  8835. var vC = new Vector3();
  8836. var tempA = new Vector3();
  8837. var tempB = new Vector3();
  8838. var tempC = new Vector3();
  8839. var uvA = new Vector2();
  8840. var uvB = new Vector2();
  8841. var uvC = new Vector2();
  8842. var barycoord = new Vector3();
  8843. var intersectionPoint = new Vector3();
  8844. var intersectionPointWorld = new Vector3();
  8845. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8846. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8847. uv1.multiplyScalar( barycoord.x );
  8848. uv2.multiplyScalar( barycoord.y );
  8849. uv3.multiplyScalar( barycoord.z );
  8850. uv1.add( uv2 ).add( uv3 );
  8851. return uv1.clone();
  8852. }
  8853. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8854. var intersect;
  8855. var material = object.material;
  8856. if ( material.side === BackSide ) {
  8857. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8858. } else {
  8859. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8860. }
  8861. if ( intersect === null ) return null;
  8862. intersectionPointWorld.copy( point );
  8863. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8864. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8865. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8866. return {
  8867. distance: distance,
  8868. point: intersectionPointWorld.clone(),
  8869. object: object
  8870. };
  8871. }
  8872. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  8873. vA.fromArray( positions, a * 3 );
  8874. vB.fromArray( positions, b * 3 );
  8875. vC.fromArray( positions, c * 3 );
  8876. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8877. if ( intersection ) {
  8878. if ( uvs ) {
  8879. uvA.fromArray( uvs, a * 2 );
  8880. uvB.fromArray( uvs, b * 2 );
  8881. uvC.fromArray( uvs, c * 2 );
  8882. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8883. }
  8884. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8885. intersection.faceIndex = a;
  8886. }
  8887. return intersection;
  8888. }
  8889. return function raycast( raycaster, intersects ) {
  8890. var geometry = this.geometry;
  8891. var material = this.material;
  8892. var matrixWorld = this.matrixWorld;
  8893. if ( material === undefined ) return;
  8894. // Checking boundingSphere distance to ray
  8895. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8896. sphere.copy( geometry.boundingSphere );
  8897. sphere.applyMatrix4( matrixWorld );
  8898. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8899. //
  8900. inverseMatrix.getInverse( matrixWorld );
  8901. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8902. // Check boundingBox before continuing
  8903. if ( geometry.boundingBox !== null ) {
  8904. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8905. }
  8906. var uvs, intersection;
  8907. if ( geometry.isBufferGeometry ) {
  8908. var a, b, c;
  8909. var index = geometry.index;
  8910. var attributes = geometry.attributes;
  8911. var positions = attributes.position.array;
  8912. if ( attributes.uv !== undefined ) {
  8913. uvs = attributes.uv.array;
  8914. }
  8915. if ( index !== null ) {
  8916. var indices = index.array;
  8917. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  8918. a = indices[ i ];
  8919. b = indices[ i + 1 ];
  8920. c = indices[ i + 2 ];
  8921. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8922. if ( intersection ) {
  8923. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8924. intersects.push( intersection );
  8925. }
  8926. }
  8927. } else {
  8928. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  8929. a = i / 3;
  8930. b = a + 1;
  8931. c = a + 2;
  8932. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  8933. if ( intersection ) {
  8934. intersection.index = a; // triangle number in positions buffer semantics
  8935. intersects.push( intersection );
  8936. }
  8937. }
  8938. }
  8939. } else if ( geometry.isGeometry ) {
  8940. var fvA, fvB, fvC;
  8941. var isFaceMaterial = (material && material.isMultiMaterial);
  8942. var materials = isFaceMaterial === true ? material.materials : null;
  8943. var vertices = geometry.vertices;
  8944. var faces = geometry.faces;
  8945. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  8946. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  8947. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  8948. var face = faces[ f ];
  8949. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  8950. if ( faceMaterial === undefined ) continue;
  8951. fvA = vertices[ face.a ];
  8952. fvB = vertices[ face.b ];
  8953. fvC = vertices[ face.c ];
  8954. if ( faceMaterial.morphTargets === true ) {
  8955. var morphTargets = geometry.morphTargets;
  8956. var morphInfluences = this.morphTargetInfluences;
  8957. vA.set( 0, 0, 0 );
  8958. vB.set( 0, 0, 0 );
  8959. vC.set( 0, 0, 0 );
  8960. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8961. var influence = morphInfluences[ t ];
  8962. if ( influence === 0 ) continue;
  8963. var targets = morphTargets[ t ].vertices;
  8964. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  8965. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  8966. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  8967. }
  8968. vA.add( fvA );
  8969. vB.add( fvB );
  8970. vC.add( fvC );
  8971. fvA = vA;
  8972. fvB = vB;
  8973. fvC = vC;
  8974. }
  8975. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  8976. if ( intersection ) {
  8977. if ( uvs ) {
  8978. var uvs_f = uvs[ f ];
  8979. uvA.copy( uvs_f[ 0 ] );
  8980. uvB.copy( uvs_f[ 1 ] );
  8981. uvC.copy( uvs_f[ 2 ] );
  8982. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  8983. }
  8984. intersection.face = face;
  8985. intersection.faceIndex = f;
  8986. intersects.push( intersection );
  8987. }
  8988. }
  8989. }
  8990. };
  8991. }() ),
  8992. clone: function () {
  8993. return new this.constructor( this.geometry, this.material ).copy( this );
  8994. }
  8995. } );
  8996. /**
  8997. * @author Mugen87 / https://github.com/Mugen87
  8998. */
  8999. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9000. BufferGeometry.call( this );
  9001. this.type = 'BoxBufferGeometry';
  9002. this.parameters = {
  9003. width: width,
  9004. height: height,
  9005. depth: depth,
  9006. widthSegments: widthSegments,
  9007. heightSegments: heightSegments,
  9008. depthSegments: depthSegments
  9009. };
  9010. var scope = this;
  9011. // segments
  9012. widthSegments = Math.floor( widthSegments ) || 1;
  9013. heightSegments = Math.floor( heightSegments ) || 1;
  9014. depthSegments = Math.floor( depthSegments ) || 1;
  9015. // these are used to calculate buffer length
  9016. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  9017. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  9018. // buffers
  9019. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  9020. var vertices = new Float32Array( vertexCount * 3 );
  9021. var normals = new Float32Array( vertexCount * 3 );
  9022. var uvs = new Float32Array( vertexCount * 2 );
  9023. // offset variables
  9024. var vertexBufferOffset = 0;
  9025. var uvBufferOffset = 0;
  9026. var indexBufferOffset = 0;
  9027. var numberOfVertices = 0;
  9028. // group variables
  9029. var groupStart = 0;
  9030. // build each side of the box geometry
  9031. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  9032. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9033. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9034. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9035. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9036. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9037. // build geometry
  9038. this.setIndex( new BufferAttribute( indices, 1 ) );
  9039. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9040. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9041. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9042. // helper functions
  9043. function calculateVertexCount( w, h, d ) {
  9044. var vertices = 0;
  9045. // calculate the amount of vertices for each side (plane)
  9046. vertices += (w + 1) * (h + 1) * 2; // xy
  9047. vertices += (w + 1) * (d + 1) * 2; // xz
  9048. vertices += (d + 1) * (h + 1) * 2; // zy
  9049. return vertices;
  9050. }
  9051. function calculateIndexCount( w, h, d ) {
  9052. var index = 0;
  9053. // calculate the amount of squares for each side
  9054. index += w * h * 2; // xy
  9055. index += w * d * 2; // xz
  9056. index += d * h * 2; // zy
  9057. return index * 6; // two triangles per square => six vertices per square
  9058. }
  9059. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9060. var segmentWidth = width / gridX;
  9061. var segmentHeight = height / gridY;
  9062. var widthHalf = width / 2;
  9063. var heightHalf = height / 2;
  9064. var depthHalf = depth / 2;
  9065. var gridX1 = gridX + 1;
  9066. var gridY1 = gridY + 1;
  9067. var vertexCounter = 0;
  9068. var groupCount = 0;
  9069. var vector = new Vector3();
  9070. // generate vertices, normals and uvs
  9071. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9072. var y = iy * segmentHeight - heightHalf;
  9073. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9074. var x = ix * segmentWidth - widthHalf;
  9075. // set values to correct vector component
  9076. vector[ u ] = x * udir;
  9077. vector[ v ] = y * vdir;
  9078. vector[ w ] = depthHalf;
  9079. // now apply vector to vertex buffer
  9080. vertices[ vertexBufferOffset ] = vector.x;
  9081. vertices[ vertexBufferOffset + 1 ] = vector.y;
  9082. vertices[ vertexBufferOffset + 2 ] = vector.z;
  9083. // set values to correct vector component
  9084. vector[ u ] = 0;
  9085. vector[ v ] = 0;
  9086. vector[ w ] = depth > 0 ? 1 : - 1;
  9087. // now apply vector to normal buffer
  9088. normals[ vertexBufferOffset ] = vector.x;
  9089. normals[ vertexBufferOffset + 1 ] = vector.y;
  9090. normals[ vertexBufferOffset + 2 ] = vector.z;
  9091. // uvs
  9092. uvs[ uvBufferOffset ] = ix / gridX;
  9093. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  9094. // update offsets and counters
  9095. vertexBufferOffset += 3;
  9096. uvBufferOffset += 2;
  9097. vertexCounter += 1;
  9098. }
  9099. }
  9100. // 1. you need three indices to draw a single face
  9101. // 2. a single segment consists of two faces
  9102. // 3. so we need to generate six (2*3) indices per segment
  9103. for ( iy = 0; iy < gridY; iy ++ ) {
  9104. for ( ix = 0; ix < gridX; ix ++ ) {
  9105. // indices
  9106. var a = numberOfVertices + ix + gridX1 * iy;
  9107. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9108. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9109. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9110. // face one
  9111. indices[ indexBufferOffset ] = a;
  9112. indices[ indexBufferOffset + 1 ] = b;
  9113. indices[ indexBufferOffset + 2 ] = d;
  9114. // face two
  9115. indices[ indexBufferOffset + 3 ] = b;
  9116. indices[ indexBufferOffset + 4 ] = c;
  9117. indices[ indexBufferOffset + 5 ] = d;
  9118. // update offsets and counters
  9119. indexBufferOffset += 6;
  9120. groupCount += 6;
  9121. }
  9122. }
  9123. // add a group to the geometry. this will ensure multi material support
  9124. scope.addGroup( groupStart, groupCount, materialIndex );
  9125. // calculate new start value for groups
  9126. groupStart += groupCount;
  9127. // update total number of vertices
  9128. numberOfVertices += vertexCounter;
  9129. }
  9130. }
  9131. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9132. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9133. /**
  9134. * @author mrdoob / http://mrdoob.com/
  9135. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9136. */
  9137. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9138. BufferGeometry.call( this );
  9139. this.type = 'PlaneBufferGeometry';
  9140. this.parameters = {
  9141. width: width,
  9142. height: height,
  9143. widthSegments: widthSegments,
  9144. heightSegments: heightSegments
  9145. };
  9146. var width_half = width / 2;
  9147. var height_half = height / 2;
  9148. var gridX = Math.floor( widthSegments ) || 1;
  9149. var gridY = Math.floor( heightSegments ) || 1;
  9150. var gridX1 = gridX + 1;
  9151. var gridY1 = gridY + 1;
  9152. var segment_width = width / gridX;
  9153. var segment_height = height / gridY;
  9154. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  9155. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  9156. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  9157. var offset = 0;
  9158. var offset2 = 0;
  9159. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9160. var y = iy * segment_height - height_half;
  9161. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9162. var x = ix * segment_width - width_half;
  9163. vertices[ offset ] = x;
  9164. vertices[ offset + 1 ] = - y;
  9165. normals[ offset + 2 ] = 1;
  9166. uvs[ offset2 ] = ix / gridX;
  9167. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  9168. offset += 3;
  9169. offset2 += 2;
  9170. }
  9171. }
  9172. offset = 0;
  9173. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  9174. for ( var iy = 0; iy < gridY; iy ++ ) {
  9175. for ( var ix = 0; ix < gridX; ix ++ ) {
  9176. var a = ix + gridX1 * iy;
  9177. var b = ix + gridX1 * ( iy + 1 );
  9178. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9179. var d = ( ix + 1 ) + gridX1 * iy;
  9180. indices[ offset ] = a;
  9181. indices[ offset + 1 ] = b;
  9182. indices[ offset + 2 ] = d;
  9183. indices[ offset + 3 ] = b;
  9184. indices[ offset + 4 ] = c;
  9185. indices[ offset + 5 ] = d;
  9186. offset += 6;
  9187. }
  9188. }
  9189. this.setIndex( new BufferAttribute( indices, 1 ) );
  9190. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9191. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9192. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9193. }
  9194. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9195. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9196. /**
  9197. * @author mrdoob / http://mrdoob.com/
  9198. * @author mikael emtinger / http://gomo.se/
  9199. * @author WestLangley / http://github.com/WestLangley
  9200. */
  9201. function Camera() {
  9202. Object3D.call( this );
  9203. this.type = 'Camera';
  9204. this.matrixWorldInverse = new Matrix4();
  9205. this.projectionMatrix = new Matrix4();
  9206. }
  9207. Camera.prototype = Object.create( Object3D.prototype );
  9208. Camera.prototype.constructor = Camera;
  9209. Camera.prototype.isCamera = true;
  9210. Camera.prototype.getWorldDirection = function () {
  9211. var quaternion = new Quaternion();
  9212. return function getWorldDirection( optionalTarget ) {
  9213. var result = optionalTarget || new Vector3();
  9214. this.getWorldQuaternion( quaternion );
  9215. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9216. };
  9217. }();
  9218. Camera.prototype.lookAt = function () {
  9219. // This routine does not support cameras with rotated and/or translated parent(s)
  9220. var m1 = new Matrix4();
  9221. return function lookAt( vector ) {
  9222. m1.lookAt( this.position, vector, this.up );
  9223. this.quaternion.setFromRotationMatrix( m1 );
  9224. };
  9225. }();
  9226. Camera.prototype.clone = function () {
  9227. return new this.constructor().copy( this );
  9228. };
  9229. Camera.prototype.copy = function ( source ) {
  9230. Object3D.prototype.copy.call( this, source );
  9231. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9232. this.projectionMatrix.copy( source.projectionMatrix );
  9233. return this;
  9234. };
  9235. /**
  9236. * @author mrdoob / http://mrdoob.com/
  9237. * @author greggman / http://games.greggman.com/
  9238. * @author zz85 / http://www.lab4games.net/zz85/blog
  9239. * @author tschw
  9240. */
  9241. function PerspectiveCamera( fov, aspect, near, far ) {
  9242. Camera.call( this );
  9243. this.type = 'PerspectiveCamera';
  9244. this.fov = fov !== undefined ? fov : 50;
  9245. this.zoom = 1;
  9246. this.near = near !== undefined ? near : 0.1;
  9247. this.far = far !== undefined ? far : 2000;
  9248. this.focus = 10;
  9249. this.aspect = aspect !== undefined ? aspect : 1;
  9250. this.view = null;
  9251. this.filmGauge = 35; // width of the film (default in millimeters)
  9252. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9253. this.updateProjectionMatrix();
  9254. }
  9255. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9256. constructor: PerspectiveCamera,
  9257. isPerspectiveCamera: true,
  9258. copy: function ( source ) {
  9259. Camera.prototype.copy.call( this, source );
  9260. this.fov = source.fov;
  9261. this.zoom = source.zoom;
  9262. this.near = source.near;
  9263. this.far = source.far;
  9264. this.focus = source.focus;
  9265. this.aspect = source.aspect;
  9266. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9267. this.filmGauge = source.filmGauge;
  9268. this.filmOffset = source.filmOffset;
  9269. return this;
  9270. },
  9271. /**
  9272. * Sets the FOV by focal length in respect to the current .filmGauge.
  9273. *
  9274. * The default film gauge is 35, so that the focal length can be specified for
  9275. * a 35mm (full frame) camera.
  9276. *
  9277. * Values for focal length and film gauge must have the same unit.
  9278. */
  9279. setFocalLength: function ( focalLength ) {
  9280. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9281. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9282. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9283. this.updateProjectionMatrix();
  9284. },
  9285. /**
  9286. * Calculates the focal length from the current .fov and .filmGauge.
  9287. */
  9288. getFocalLength: function () {
  9289. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9290. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9291. },
  9292. getEffectiveFOV: function () {
  9293. return _Math.RAD2DEG * 2 * Math.atan(
  9294. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9295. },
  9296. getFilmWidth: function () {
  9297. // film not completely covered in portrait format (aspect < 1)
  9298. return this.filmGauge * Math.min( this.aspect, 1 );
  9299. },
  9300. getFilmHeight: function () {
  9301. // film not completely covered in landscape format (aspect > 1)
  9302. return this.filmGauge / Math.max( this.aspect, 1 );
  9303. },
  9304. /**
  9305. * Sets an offset in a larger frustum. This is useful for multi-window or
  9306. * multi-monitor/multi-machine setups.
  9307. *
  9308. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9309. * the monitors are in grid like this
  9310. *
  9311. * +---+---+---+
  9312. * | A | B | C |
  9313. * +---+---+---+
  9314. * | D | E | F |
  9315. * +---+---+---+
  9316. *
  9317. * then for each monitor you would call it like this
  9318. *
  9319. * var w = 1920;
  9320. * var h = 1080;
  9321. * var fullWidth = w * 3;
  9322. * var fullHeight = h * 2;
  9323. *
  9324. * --A--
  9325. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9326. * --B--
  9327. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9328. * --C--
  9329. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9330. * --D--
  9331. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9332. * --E--
  9333. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9334. * --F--
  9335. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9336. *
  9337. * Note there is no reason monitors have to be the same size or in a grid.
  9338. */
  9339. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9340. this.aspect = fullWidth / fullHeight;
  9341. this.view = {
  9342. fullWidth: fullWidth,
  9343. fullHeight: fullHeight,
  9344. offsetX: x,
  9345. offsetY: y,
  9346. width: width,
  9347. height: height
  9348. };
  9349. this.updateProjectionMatrix();
  9350. },
  9351. clearViewOffset: function() {
  9352. this.view = null;
  9353. this.updateProjectionMatrix();
  9354. },
  9355. updateProjectionMatrix: function () {
  9356. var near = this.near,
  9357. top = near * Math.tan(
  9358. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9359. height = 2 * top,
  9360. width = this.aspect * height,
  9361. left = - 0.5 * width,
  9362. view = this.view;
  9363. if ( view !== null ) {
  9364. var fullWidth = view.fullWidth,
  9365. fullHeight = view.fullHeight;
  9366. left += view.offsetX * width / fullWidth;
  9367. top -= view.offsetY * height / fullHeight;
  9368. width *= view.width / fullWidth;
  9369. height *= view.height / fullHeight;
  9370. }
  9371. var skew = this.filmOffset;
  9372. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9373. this.projectionMatrix.makeFrustum(
  9374. left, left + width, top - height, top, near, this.far );
  9375. },
  9376. toJSON: function ( meta ) {
  9377. var data = Object3D.prototype.toJSON.call( this, meta );
  9378. data.object.fov = this.fov;
  9379. data.object.zoom = this.zoom;
  9380. data.object.near = this.near;
  9381. data.object.far = this.far;
  9382. data.object.focus = this.focus;
  9383. data.object.aspect = this.aspect;
  9384. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9385. data.object.filmGauge = this.filmGauge;
  9386. data.object.filmOffset = this.filmOffset;
  9387. return data;
  9388. }
  9389. } );
  9390. /**
  9391. * @author alteredq / http://alteredqualia.com/
  9392. * @author arose / http://github.com/arose
  9393. */
  9394. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9395. Camera.call( this );
  9396. this.type = 'OrthographicCamera';
  9397. this.zoom = 1;
  9398. this.view = null;
  9399. this.left = left;
  9400. this.right = right;
  9401. this.top = top;
  9402. this.bottom = bottom;
  9403. this.near = ( near !== undefined ) ? near : 0.1;
  9404. this.far = ( far !== undefined ) ? far : 2000;
  9405. this.updateProjectionMatrix();
  9406. }
  9407. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9408. constructor: OrthographicCamera,
  9409. isOrthographicCamera: true,
  9410. copy: function ( source ) {
  9411. Camera.prototype.copy.call( this, source );
  9412. this.left = source.left;
  9413. this.right = source.right;
  9414. this.top = source.top;
  9415. this.bottom = source.bottom;
  9416. this.near = source.near;
  9417. this.far = source.far;
  9418. this.zoom = source.zoom;
  9419. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9420. return this;
  9421. },
  9422. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9423. this.view = {
  9424. fullWidth: fullWidth,
  9425. fullHeight: fullHeight,
  9426. offsetX: x,
  9427. offsetY: y,
  9428. width: width,
  9429. height: height
  9430. };
  9431. this.updateProjectionMatrix();
  9432. },
  9433. clearViewOffset: function() {
  9434. this.view = null;
  9435. this.updateProjectionMatrix();
  9436. },
  9437. updateProjectionMatrix: function () {
  9438. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9439. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9440. var cx = ( this.right + this.left ) / 2;
  9441. var cy = ( this.top + this.bottom ) / 2;
  9442. var left = cx - dx;
  9443. var right = cx + dx;
  9444. var top = cy + dy;
  9445. var bottom = cy - dy;
  9446. if ( this.view !== null ) {
  9447. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9448. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9449. var scaleW = ( this.right - this.left ) / this.view.width;
  9450. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9451. left += scaleW * ( this.view.offsetX / zoomW );
  9452. right = left + scaleW * ( this.view.width / zoomW );
  9453. top -= scaleH * ( this.view.offsetY / zoomH );
  9454. bottom = top - scaleH * ( this.view.height / zoomH );
  9455. }
  9456. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9457. },
  9458. toJSON: function ( meta ) {
  9459. var data = Object3D.prototype.toJSON.call( this, meta );
  9460. data.object.zoom = this.zoom;
  9461. data.object.left = this.left;
  9462. data.object.right = this.right;
  9463. data.object.top = this.top;
  9464. data.object.bottom = this.bottom;
  9465. data.object.near = this.near;
  9466. data.object.far = this.far;
  9467. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9468. return data;
  9469. }
  9470. } );
  9471. /**
  9472. * @author mrdoob / http://mrdoob.com/
  9473. */
  9474. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9475. var mode;
  9476. function setMode( value ) {
  9477. mode = value;
  9478. }
  9479. var type, size;
  9480. function setIndex( index ) {
  9481. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9482. type = gl.UNSIGNED_INT;
  9483. size = 4;
  9484. } else if ( index.array instanceof Uint16Array ) {
  9485. type = gl.UNSIGNED_SHORT;
  9486. size = 2;
  9487. } else {
  9488. type = gl.UNSIGNED_BYTE;
  9489. size = 1;
  9490. }
  9491. }
  9492. function render( start, count ) {
  9493. gl.drawElements( mode, count, type, start * size );
  9494. infoRender.calls ++;
  9495. infoRender.vertices += count;
  9496. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9497. }
  9498. function renderInstances( geometry, start, count ) {
  9499. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9500. if ( extension === null ) {
  9501. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9502. return;
  9503. }
  9504. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9505. infoRender.calls ++;
  9506. infoRender.vertices += count * geometry.maxInstancedCount;
  9507. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9508. }
  9509. return {
  9510. setMode: setMode,
  9511. setIndex: setIndex,
  9512. render: render,
  9513. renderInstances: renderInstances
  9514. };
  9515. }
  9516. /**
  9517. * @author mrdoob / http://mrdoob.com/
  9518. */
  9519. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9520. var mode;
  9521. function setMode( value ) {
  9522. mode = value;
  9523. }
  9524. function render( start, count ) {
  9525. gl.drawArrays( mode, start, count );
  9526. infoRender.calls ++;
  9527. infoRender.vertices += count;
  9528. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9529. }
  9530. function renderInstances( geometry ) {
  9531. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9532. if ( extension === null ) {
  9533. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9534. return;
  9535. }
  9536. var position = geometry.attributes.position;
  9537. var count = 0;
  9538. if ( position.isInterleavedBufferAttribute ) {
  9539. count = position.data.count;
  9540. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9541. } else {
  9542. count = position.count;
  9543. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9544. }
  9545. infoRender.calls ++;
  9546. infoRender.vertices += count * geometry.maxInstancedCount;
  9547. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9548. }
  9549. return {
  9550. setMode: setMode,
  9551. render: render,
  9552. renderInstances: renderInstances
  9553. };
  9554. }
  9555. /**
  9556. * @author mrdoob / http://mrdoob.com/
  9557. */
  9558. function WebGLLights() {
  9559. var lights = {};
  9560. return {
  9561. get: function ( light ) {
  9562. if ( lights[ light.id ] !== undefined ) {
  9563. return lights[ light.id ];
  9564. }
  9565. var uniforms;
  9566. switch ( light.type ) {
  9567. case 'DirectionalLight':
  9568. uniforms = {
  9569. direction: new Vector3(),
  9570. color: new Color(),
  9571. shadow: false,
  9572. shadowBias: 0,
  9573. shadowRadius: 1,
  9574. shadowMapSize: new Vector2()
  9575. };
  9576. break;
  9577. case 'SpotLight':
  9578. uniforms = {
  9579. position: new Vector3(),
  9580. direction: new Vector3(),
  9581. color: new Color(),
  9582. distance: 0,
  9583. coneCos: 0,
  9584. penumbraCos: 0,
  9585. decay: 0,
  9586. shadow: false,
  9587. shadowBias: 0,
  9588. shadowRadius: 1,
  9589. shadowMapSize: new Vector2()
  9590. };
  9591. break;
  9592. case 'PointLight':
  9593. uniforms = {
  9594. position: new Vector3(),
  9595. color: new Color(),
  9596. distance: 0,
  9597. decay: 0,
  9598. shadow: false,
  9599. shadowBias: 0,
  9600. shadowRadius: 1,
  9601. shadowMapSize: new Vector2()
  9602. };
  9603. break;
  9604. case 'HemisphereLight':
  9605. uniforms = {
  9606. direction: new Vector3(),
  9607. skyColor: new Color(),
  9608. groundColor: new Color()
  9609. };
  9610. break;
  9611. case 'RectAreaLight':
  9612. uniforms = {
  9613. color: new Color(),
  9614. position: new Vector3(),
  9615. halfWidth: new Vector3(),
  9616. halfHeight: new Vector3()
  9617. // TODO (abelnation): set RectAreaLight shadow uniforms
  9618. };
  9619. break;
  9620. }
  9621. lights[ light.id ] = uniforms;
  9622. return uniforms;
  9623. }
  9624. };
  9625. }
  9626. /**
  9627. * @author mrdoob / http://mrdoob.com/
  9628. */
  9629. function addLineNumbers( string ) {
  9630. var lines = string.split( '\n' );
  9631. for ( var i = 0; i < lines.length; i ++ ) {
  9632. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9633. }
  9634. return lines.join( '\n' );
  9635. }
  9636. function WebGLShader( gl, type, string ) {
  9637. var shader = gl.createShader( type );
  9638. gl.shaderSource( shader, string );
  9639. gl.compileShader( shader );
  9640. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  9641. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  9642. }
  9643. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  9644. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  9645. }
  9646. // --enable-privileged-webgl-extension
  9647. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9648. return shader;
  9649. }
  9650. /**
  9651. * @author mrdoob / http://mrdoob.com/
  9652. */
  9653. var programIdCount = 0;
  9654. function getEncodingComponents( encoding ) {
  9655. switch ( encoding ) {
  9656. case LinearEncoding:
  9657. return [ 'Linear','( value )' ];
  9658. case sRGBEncoding:
  9659. return [ 'sRGB','( value )' ];
  9660. case RGBEEncoding:
  9661. return [ 'RGBE','( value )' ];
  9662. case RGBM7Encoding:
  9663. return [ 'RGBM','( value, 7.0 )' ];
  9664. case RGBM16Encoding:
  9665. return [ 'RGBM','( value, 16.0 )' ];
  9666. case RGBDEncoding:
  9667. return [ 'RGBD','( value, 256.0 )' ];
  9668. case GammaEncoding:
  9669. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  9670. default:
  9671. throw new Error( 'unsupported encoding: ' + encoding );
  9672. }
  9673. }
  9674. function getTexelDecodingFunction( functionName, encoding ) {
  9675. var components = getEncodingComponents( encoding );
  9676. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  9677. }
  9678. function getTexelEncodingFunction( functionName, encoding ) {
  9679. var components = getEncodingComponents( encoding );
  9680. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  9681. }
  9682. function getToneMappingFunction( functionName, toneMapping ) {
  9683. var toneMappingName;
  9684. switch ( toneMapping ) {
  9685. case LinearToneMapping:
  9686. toneMappingName = "Linear";
  9687. break;
  9688. case ReinhardToneMapping:
  9689. toneMappingName = "Reinhard";
  9690. break;
  9691. case Uncharted2ToneMapping:
  9692. toneMappingName = "Uncharted2";
  9693. break;
  9694. case CineonToneMapping:
  9695. toneMappingName = "OptimizedCineon";
  9696. break;
  9697. default:
  9698. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  9699. }
  9700. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  9701. }
  9702. function generateExtensions( extensions, parameters, rendererExtensions ) {
  9703. extensions = extensions || {};
  9704. var chunks = [
  9705. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9706. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  9707. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9708. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  9709. ];
  9710. return chunks.filter( filterEmptyLine ).join( '\n' );
  9711. }
  9712. function generateDefines( defines ) {
  9713. var chunks = [];
  9714. for ( var name in defines ) {
  9715. var value = defines[ name ];
  9716. if ( value === false ) continue;
  9717. chunks.push( '#define ' + name + ' ' + value );
  9718. }
  9719. return chunks.join( '\n' );
  9720. }
  9721. function fetchAttributeLocations( gl, program, identifiers ) {
  9722. var attributes = {};
  9723. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  9724. for ( var i = 0; i < n; i ++ ) {
  9725. var info = gl.getActiveAttrib( program, i );
  9726. var name = info.name;
  9727. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  9728. attributes[ name ] = gl.getAttribLocation( program, name );
  9729. }
  9730. return attributes;
  9731. }
  9732. function filterEmptyLine( string ) {
  9733. return string !== '';
  9734. }
  9735. function replaceLightNums( string, parameters ) {
  9736. return string
  9737. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9738. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9739. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  9740. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9741. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  9742. }
  9743. function parseIncludes( string ) {
  9744. var pattern = /#include +<([\w\d.]+)>/g;
  9745. function replace( match, include ) {
  9746. var replace = ShaderChunk[ include ];
  9747. if ( replace === undefined ) {
  9748. throw new Error( 'Can not resolve #include <' + include + '>' );
  9749. }
  9750. return parseIncludes( replace );
  9751. }
  9752. return string.replace( pattern, replace );
  9753. }
  9754. function unrollLoops( string ) {
  9755. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9756. function replace( match, start, end, snippet ) {
  9757. var unroll = '';
  9758. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9759. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  9760. }
  9761. return unroll;
  9762. }
  9763. return string.replace( pattern, replace );
  9764. }
  9765. function WebGLProgram( renderer, code, material, parameters ) {
  9766. var gl = renderer.context;
  9767. var extensions = material.extensions;
  9768. var defines = material.defines;
  9769. var vertexShader = material.__webglShader.vertexShader;
  9770. var fragmentShader = material.__webglShader.fragmentShader;
  9771. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9772. if ( parameters.shadowMapType === PCFShadowMap ) {
  9773. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9774. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9775. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9776. }
  9777. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9778. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9779. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9780. if ( parameters.envMap ) {
  9781. switch ( material.envMap.mapping ) {
  9782. case CubeReflectionMapping:
  9783. case CubeRefractionMapping:
  9784. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9785. break;
  9786. case CubeUVReflectionMapping:
  9787. case CubeUVRefractionMapping:
  9788. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9789. break;
  9790. case EquirectangularReflectionMapping:
  9791. case EquirectangularRefractionMapping:
  9792. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  9793. break;
  9794. case SphericalReflectionMapping:
  9795. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  9796. break;
  9797. }
  9798. switch ( material.envMap.mapping ) {
  9799. case CubeRefractionMapping:
  9800. case EquirectangularRefractionMapping:
  9801. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9802. break;
  9803. }
  9804. switch ( material.combine ) {
  9805. case MultiplyOperation:
  9806. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9807. break;
  9808. case MixOperation:
  9809. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9810. break;
  9811. case AddOperation:
  9812. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9813. break;
  9814. }
  9815. }
  9816. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9817. // console.log( 'building new program ' );
  9818. //
  9819. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  9820. var customDefines = generateDefines( defines );
  9821. //
  9822. var program = gl.createProgram();
  9823. var prefixVertex, prefixFragment;
  9824. if ( material.isRawShaderMaterial ) {
  9825. prefixVertex = [
  9826. customDefines,
  9827. '\n'
  9828. ].filter( filterEmptyLine ).join( '\n' );
  9829. prefixFragment = [
  9830. customExtensions,
  9831. customDefines,
  9832. '\n'
  9833. ].filter( filterEmptyLine ).join( '\n' );
  9834. } else {
  9835. prefixVertex = [
  9836. 'precision ' + parameters.precision + ' float;',
  9837. 'precision ' + parameters.precision + ' int;',
  9838. '#define SHADER_NAME ' + material.__webglShader.name,
  9839. customDefines,
  9840. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  9841. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9842. '#define MAX_BONES ' + parameters.maxBones,
  9843. parameters.map ? '#define USE_MAP' : '',
  9844. parameters.envMap ? '#define USE_ENVMAP' : '',
  9845. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9846. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9847. parameters.aoMap ? '#define USE_AOMAP' : '',
  9848. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9849. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9850. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9851. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  9852. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9853. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9854. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9855. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9856. parameters.vertexColors ? '#define USE_COLOR' : '',
  9857. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9858. parameters.skinning ? '#define USE_SKINNING' : '',
  9859. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  9860. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  9861. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  9862. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9863. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9864. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9865. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9866. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9867. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  9868. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9869. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9870. 'uniform mat4 modelMatrix;',
  9871. 'uniform mat4 modelViewMatrix;',
  9872. 'uniform mat4 projectionMatrix;',
  9873. 'uniform mat4 viewMatrix;',
  9874. 'uniform mat3 normalMatrix;',
  9875. 'uniform vec3 cameraPosition;',
  9876. 'attribute vec3 position;',
  9877. 'attribute vec3 normal;',
  9878. 'attribute vec2 uv;',
  9879. '#ifdef USE_COLOR',
  9880. ' attribute vec3 color;',
  9881. '#endif',
  9882. '#ifdef USE_MORPHTARGETS',
  9883. ' attribute vec3 morphTarget0;',
  9884. ' attribute vec3 morphTarget1;',
  9885. ' attribute vec3 morphTarget2;',
  9886. ' attribute vec3 morphTarget3;',
  9887. ' #ifdef USE_MORPHNORMALS',
  9888. ' attribute vec3 morphNormal0;',
  9889. ' attribute vec3 morphNormal1;',
  9890. ' attribute vec3 morphNormal2;',
  9891. ' attribute vec3 morphNormal3;',
  9892. ' #else',
  9893. ' attribute vec3 morphTarget4;',
  9894. ' attribute vec3 morphTarget5;',
  9895. ' attribute vec3 morphTarget6;',
  9896. ' attribute vec3 morphTarget7;',
  9897. ' #endif',
  9898. '#endif',
  9899. '#ifdef USE_SKINNING',
  9900. ' attribute vec4 skinIndex;',
  9901. ' attribute vec4 skinWeight;',
  9902. '#endif',
  9903. '\n'
  9904. ].filter( filterEmptyLine ).join( '\n' );
  9905. prefixFragment = [
  9906. customExtensions,
  9907. 'precision ' + parameters.precision + ' float;',
  9908. 'precision ' + parameters.precision + ' int;',
  9909. '#define SHADER_NAME ' + material.__webglShader.name,
  9910. customDefines,
  9911. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  9912. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9913. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  9914. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  9915. parameters.map ? '#define USE_MAP' : '',
  9916. parameters.envMap ? '#define USE_ENVMAP' : '',
  9917. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  9918. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9919. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  9920. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9921. parameters.aoMap ? '#define USE_AOMAP' : '',
  9922. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9923. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9924. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9925. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9926. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9927. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9928. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9929. parameters.vertexColors ? '#define USE_COLOR' : '',
  9930. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  9931. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9932. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9933. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9934. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9935. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  9936. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9937. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9938. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  9939. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  9940. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9941. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9942. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  9943. 'uniform mat4 viewMatrix;',
  9944. 'uniform vec3 cameraPosition;',
  9945. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  9946. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  9947. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  9948. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  9949. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  9950. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  9951. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  9952. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  9953. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  9954. '\n'
  9955. ].filter( filterEmptyLine ).join( '\n' );
  9956. }
  9957. vertexShader = parseIncludes( vertexShader, parameters );
  9958. vertexShader = replaceLightNums( vertexShader, parameters );
  9959. fragmentShader = parseIncludes( fragmentShader, parameters );
  9960. fragmentShader = replaceLightNums( fragmentShader, parameters );
  9961. if ( ! material.isShaderMaterial ) {
  9962. vertexShader = unrollLoops( vertexShader );
  9963. fragmentShader = unrollLoops( fragmentShader );
  9964. }
  9965. var vertexGlsl = prefixVertex + vertexShader;
  9966. var fragmentGlsl = prefixFragment + fragmentShader;
  9967. // console.log( '*VERTEX*', vertexGlsl );
  9968. // console.log( '*FRAGMENT*', fragmentGlsl );
  9969. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  9970. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  9971. gl.attachShader( program, glVertexShader );
  9972. gl.attachShader( program, glFragmentShader );
  9973. // Force a particular attribute to index 0.
  9974. if ( material.index0AttributeName !== undefined ) {
  9975. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  9976. } else if ( parameters.morphTargets === true ) {
  9977. // programs with morphTargets displace position out of attribute 0
  9978. gl.bindAttribLocation( program, 0, 'position' );
  9979. }
  9980. gl.linkProgram( program );
  9981. var programLog = gl.getProgramInfoLog( program );
  9982. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  9983. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  9984. var runnable = true;
  9985. var haveDiagnostics = true;
  9986. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  9987. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  9988. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  9989. runnable = false;
  9990. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  9991. } else if ( programLog !== '' ) {
  9992. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  9993. } else if ( vertexLog === '' || fragmentLog === '' ) {
  9994. haveDiagnostics = false;
  9995. }
  9996. if ( haveDiagnostics ) {
  9997. this.diagnostics = {
  9998. runnable: runnable,
  9999. material: material,
  10000. programLog: programLog,
  10001. vertexShader: {
  10002. log: vertexLog,
  10003. prefix: prefixVertex
  10004. },
  10005. fragmentShader: {
  10006. log: fragmentLog,
  10007. prefix: prefixFragment
  10008. }
  10009. };
  10010. }
  10011. // clean up
  10012. gl.deleteShader( glVertexShader );
  10013. gl.deleteShader( glFragmentShader );
  10014. // set up caching for uniform locations
  10015. var cachedUniforms;
  10016. this.getUniforms = function() {
  10017. if ( cachedUniforms === undefined ) {
  10018. cachedUniforms =
  10019. new WebGLUniforms( gl, program, renderer );
  10020. }
  10021. return cachedUniforms;
  10022. };
  10023. // set up caching for attribute locations
  10024. var cachedAttributes;
  10025. this.getAttributes = function() {
  10026. if ( cachedAttributes === undefined ) {
  10027. cachedAttributes = fetchAttributeLocations( gl, program );
  10028. }
  10029. return cachedAttributes;
  10030. };
  10031. // free resource
  10032. this.destroy = function() {
  10033. gl.deleteProgram( program );
  10034. this.program = undefined;
  10035. };
  10036. // DEPRECATED
  10037. Object.defineProperties( this, {
  10038. uniforms: {
  10039. get: function() {
  10040. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10041. return this.getUniforms();
  10042. }
  10043. },
  10044. attributes: {
  10045. get: function() {
  10046. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10047. return this.getAttributes();
  10048. }
  10049. }
  10050. } );
  10051. //
  10052. this.id = programIdCount ++;
  10053. this.code = code;
  10054. this.usedTimes = 1;
  10055. this.program = program;
  10056. this.vertexShader = glVertexShader;
  10057. this.fragmentShader = glFragmentShader;
  10058. return this;
  10059. }
  10060. /**
  10061. * @author mrdoob / http://mrdoob.com/
  10062. */
  10063. function WebGLPrograms( renderer, capabilities ) {
  10064. var programs = [];
  10065. var shaderIDs = {
  10066. MeshDepthMaterial: 'depth',
  10067. MeshNormalMaterial: 'normal',
  10068. MeshBasicMaterial: 'basic',
  10069. MeshLambertMaterial: 'lambert',
  10070. MeshPhongMaterial: 'phong',
  10071. MeshToonMaterial: 'phong',
  10072. MeshStandardMaterial: 'physical',
  10073. MeshPhysicalMaterial: 'physical',
  10074. LineBasicMaterial: 'basic',
  10075. LineDashedMaterial: 'dashed',
  10076. PointsMaterial: 'points'
  10077. };
  10078. var parameterNames = [
  10079. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10080. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10081. "roughnessMap", "metalnessMap", "gradientMap",
  10082. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10083. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10084. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10085. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10086. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10087. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10088. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  10089. ];
  10090. function allocateBones( object ) {
  10091. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  10092. return 1024;
  10093. } else {
  10094. // default for when object is not specified
  10095. // ( for example when prebuilding shader to be used with multiple objects )
  10096. //
  10097. // - leave some extra space for other uniforms
  10098. // - limit here is ANGLE's 254 max uniform vectors
  10099. // (up to 54 should be safe)
  10100. var nVertexUniforms = capabilities.maxVertexUniforms;
  10101. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10102. var maxBones = nVertexMatrices;
  10103. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  10104. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  10105. if ( maxBones < object.skeleton.bones.length ) {
  10106. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  10107. }
  10108. }
  10109. return maxBones;
  10110. }
  10111. }
  10112. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10113. var encoding;
  10114. if ( ! map ) {
  10115. encoding = LinearEncoding;
  10116. } else if ( map.isTexture ) {
  10117. encoding = map.encoding;
  10118. } else if ( map.isWebGLRenderTarget ) {
  10119. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10120. encoding = map.texture.encoding;
  10121. }
  10122. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10123. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10124. encoding = GammaEncoding;
  10125. }
  10126. return encoding;
  10127. }
  10128. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10129. var shaderID = shaderIDs[ material.type ];
  10130. // heuristics to create shader parameters according to lights in the scene
  10131. // (not to blow over maxLights budget)
  10132. var maxBones = allocateBones( object );
  10133. var precision = renderer.getPrecision();
  10134. if ( material.precision !== null ) {
  10135. precision = capabilities.getMaxPrecision( material.precision );
  10136. if ( precision !== material.precision ) {
  10137. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10138. }
  10139. }
  10140. var currentRenderTarget = renderer.getCurrentRenderTarget();
  10141. var parameters = {
  10142. shaderID: shaderID,
  10143. precision: precision,
  10144. supportsVertexTextures: capabilities.vertexTextures,
  10145. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10146. map: !! material.map,
  10147. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10148. envMap: !! material.envMap,
  10149. envMapMode: material.envMap && material.envMap.mapping,
  10150. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10151. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10152. lightMap: !! material.lightMap,
  10153. aoMap: !! material.aoMap,
  10154. emissiveMap: !! material.emissiveMap,
  10155. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10156. bumpMap: !! material.bumpMap,
  10157. normalMap: !! material.normalMap,
  10158. displacementMap: !! material.displacementMap,
  10159. roughnessMap: !! material.roughnessMap,
  10160. metalnessMap: !! material.metalnessMap,
  10161. specularMap: !! material.specularMap,
  10162. alphaMap: !! material.alphaMap,
  10163. gradientMap: !! material.gradientMap,
  10164. combine: material.combine,
  10165. vertexColors: material.vertexColors,
  10166. fog: !! fog,
  10167. useFog: material.fog,
  10168. fogExp: (fog && fog.isFogExp2),
  10169. flatShading: material.shading === FlatShading,
  10170. sizeAttenuation: material.sizeAttenuation,
  10171. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10172. skinning: material.skinning,
  10173. maxBones: maxBones,
  10174. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  10175. morphTargets: material.morphTargets,
  10176. morphNormals: material.morphNormals,
  10177. maxMorphTargets: renderer.maxMorphTargets,
  10178. maxMorphNormals: renderer.maxMorphNormals,
  10179. numDirLights: lights.directional.length,
  10180. numPointLights: lights.point.length,
  10181. numSpotLights: lights.spot.length,
  10182. numRectAreaLights: lights.rectArea.length,
  10183. numHemiLights: lights.hemi.length,
  10184. numClippingPlanes: nClipPlanes,
  10185. numClipIntersection: nClipIntersection,
  10186. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10187. shadowMapType: renderer.shadowMap.type,
  10188. toneMapping: renderer.toneMapping,
  10189. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10190. premultipliedAlpha: material.premultipliedAlpha,
  10191. alphaTest: material.alphaTest,
  10192. doubleSided: material.side === DoubleSide,
  10193. flipSided: material.side === BackSide,
  10194. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10195. };
  10196. return parameters;
  10197. };
  10198. this.getProgramCode = function ( material, parameters ) {
  10199. var array = [];
  10200. if ( parameters.shaderID ) {
  10201. array.push( parameters.shaderID );
  10202. } else {
  10203. array.push( material.fragmentShader );
  10204. array.push( material.vertexShader );
  10205. }
  10206. if ( material.defines !== undefined ) {
  10207. for ( var name in material.defines ) {
  10208. array.push( name );
  10209. array.push( material.defines[ name ] );
  10210. }
  10211. }
  10212. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10213. array.push( parameters[ parameterNames[ i ] ] );
  10214. }
  10215. return array.join();
  10216. };
  10217. this.acquireProgram = function ( material, parameters, code ) {
  10218. var program;
  10219. // Check if code has been already compiled
  10220. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10221. var programInfo = programs[ p ];
  10222. if ( programInfo.code === code ) {
  10223. program = programInfo;
  10224. ++ program.usedTimes;
  10225. break;
  10226. }
  10227. }
  10228. if ( program === undefined ) {
  10229. program = new WebGLProgram( renderer, code, material, parameters );
  10230. programs.push( program );
  10231. }
  10232. return program;
  10233. };
  10234. this.releaseProgram = function( program ) {
  10235. if ( -- program.usedTimes === 0 ) {
  10236. // Remove from unordered set
  10237. var i = programs.indexOf( program );
  10238. programs[ i ] = programs[ programs.length - 1 ];
  10239. programs.pop();
  10240. // Free WebGL resources
  10241. program.destroy();
  10242. }
  10243. };
  10244. // Exposed for resource monitoring & error feedback via renderer.info:
  10245. this.programs = programs;
  10246. }
  10247. /**
  10248. * @author mrdoob / http://mrdoob.com/
  10249. */
  10250. function WebGLGeometries( gl, properties, info ) {
  10251. var geometries = {};
  10252. function onGeometryDispose( event ) {
  10253. var geometry = event.target;
  10254. var buffergeometry = geometries[ geometry.id ];
  10255. if ( buffergeometry.index !== null ) {
  10256. deleteAttribute( buffergeometry.index );
  10257. }
  10258. deleteAttributes( buffergeometry.attributes );
  10259. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10260. delete geometries[ geometry.id ];
  10261. // TODO
  10262. var property = properties.get( geometry );
  10263. if ( property.wireframe ) {
  10264. deleteAttribute( property.wireframe );
  10265. }
  10266. properties.delete( geometry );
  10267. var bufferproperty = properties.get( buffergeometry );
  10268. if ( bufferproperty.wireframe ) {
  10269. deleteAttribute( bufferproperty.wireframe );
  10270. }
  10271. properties.delete( buffergeometry );
  10272. //
  10273. info.memory.geometries --;
  10274. }
  10275. function getAttributeBuffer( attribute ) {
  10276. if ( attribute.isInterleavedBufferAttribute ) {
  10277. return properties.get( attribute.data ).__webglBuffer;
  10278. }
  10279. return properties.get( attribute ).__webglBuffer;
  10280. }
  10281. function deleteAttribute( attribute ) {
  10282. var buffer = getAttributeBuffer( attribute );
  10283. if ( buffer !== undefined ) {
  10284. gl.deleteBuffer( buffer );
  10285. removeAttributeBuffer( attribute );
  10286. }
  10287. }
  10288. function deleteAttributes( attributes ) {
  10289. for ( var name in attributes ) {
  10290. deleteAttribute( attributes[ name ] );
  10291. }
  10292. }
  10293. function removeAttributeBuffer( attribute ) {
  10294. if ( attribute.isInterleavedBufferAttribute ) {
  10295. properties.delete( attribute.data );
  10296. } else {
  10297. properties.delete( attribute );
  10298. }
  10299. }
  10300. return {
  10301. get: function ( object ) {
  10302. var geometry = object.geometry;
  10303. if ( geometries[ geometry.id ] !== undefined ) {
  10304. return geometries[ geometry.id ];
  10305. }
  10306. geometry.addEventListener( 'dispose', onGeometryDispose );
  10307. var buffergeometry;
  10308. if ( geometry.isBufferGeometry ) {
  10309. buffergeometry = geometry;
  10310. } else if ( geometry.isGeometry ) {
  10311. if ( geometry._bufferGeometry === undefined ) {
  10312. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10313. }
  10314. buffergeometry = geometry._bufferGeometry;
  10315. }
  10316. geometries[ geometry.id ] = buffergeometry;
  10317. info.memory.geometries ++;
  10318. return buffergeometry;
  10319. }
  10320. };
  10321. }
  10322. /**
  10323. * @author mrdoob / http://mrdoob.com/
  10324. */
  10325. function WebGLObjects( gl, properties, info ) {
  10326. var geometries = new WebGLGeometries( gl, properties, info );
  10327. //
  10328. function update( object ) {
  10329. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  10330. var geometry = geometries.get( object );
  10331. if ( object.geometry.isGeometry ) {
  10332. geometry.updateFromObject( object );
  10333. }
  10334. var index = geometry.index;
  10335. var attributes = geometry.attributes;
  10336. if ( index !== null ) {
  10337. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  10338. }
  10339. for ( var name in attributes ) {
  10340. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  10341. }
  10342. // morph targets
  10343. var morphAttributes = geometry.morphAttributes;
  10344. for ( var name in morphAttributes ) {
  10345. var array = morphAttributes[ name ];
  10346. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10347. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  10348. }
  10349. }
  10350. return geometry;
  10351. }
  10352. function updateAttribute( attribute, bufferType ) {
  10353. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  10354. var attributeProperties = properties.get( data );
  10355. if ( attributeProperties.__webglBuffer === undefined ) {
  10356. createBuffer( attributeProperties, data, bufferType );
  10357. } else if ( attributeProperties.version !== data.version ) {
  10358. updateBuffer( attributeProperties, data, bufferType );
  10359. }
  10360. }
  10361. function createBuffer( attributeProperties, data, bufferType ) {
  10362. attributeProperties.__webglBuffer = gl.createBuffer();
  10363. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10364. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10365. gl.bufferData( bufferType, data.array, usage );
  10366. var type = gl.FLOAT;
  10367. var array = data.array;
  10368. if ( array instanceof Float32Array ) {
  10369. type = gl.FLOAT;
  10370. } else if ( array instanceof Float64Array ) {
  10371. console.warn( "Unsupported data buffer format: Float64Array" );
  10372. } else if ( array instanceof Uint16Array ) {
  10373. type = gl.UNSIGNED_SHORT;
  10374. } else if ( array instanceof Int16Array ) {
  10375. type = gl.SHORT;
  10376. } else if ( array instanceof Uint32Array ) {
  10377. type = gl.UNSIGNED_INT;
  10378. } else if ( array instanceof Int32Array ) {
  10379. type = gl.INT;
  10380. } else if ( array instanceof Int8Array ) {
  10381. type = gl.BYTE;
  10382. } else if ( array instanceof Uint8Array ) {
  10383. type = gl.UNSIGNED_BYTE;
  10384. }
  10385. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  10386. attributeProperties.type = type;
  10387. attributeProperties.version = data.version;
  10388. data.onUploadCallback();
  10389. }
  10390. function updateBuffer( attributeProperties, data, bufferType ) {
  10391. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10392. if ( data.dynamic === false ) {
  10393. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  10394. } else if ( data.updateRange.count === - 1 ) {
  10395. // Not using update ranges
  10396. gl.bufferSubData( bufferType, 0, data.array );
  10397. } else if ( data.updateRange.count === 0 ) {
  10398. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  10399. } else {
  10400. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  10401. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  10402. data.updateRange.count = 0; // reset range
  10403. }
  10404. attributeProperties.version = data.version;
  10405. }
  10406. function getAttributeBuffer( attribute ) {
  10407. if ( attribute.isInterleavedBufferAttribute ) {
  10408. return properties.get( attribute.data ).__webglBuffer;
  10409. }
  10410. return properties.get( attribute ).__webglBuffer;
  10411. }
  10412. function getAttributeProperties( attribute ) {
  10413. if ( attribute.isInterleavedBufferAttribute ) {
  10414. return properties.get( attribute.data );
  10415. }
  10416. return properties.get( attribute );
  10417. }
  10418. function getWireframeAttribute( geometry ) {
  10419. var property = properties.get( geometry );
  10420. if ( property.wireframe !== undefined ) {
  10421. return property.wireframe;
  10422. }
  10423. var indices = [];
  10424. var index = geometry.index;
  10425. var attributes = geometry.attributes;
  10426. var position = attributes.position;
  10427. // console.time( 'wireframe' );
  10428. if ( index !== null ) {
  10429. var edges = {};
  10430. var array = index.array;
  10431. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10432. var a = array[ i + 0 ];
  10433. var b = array[ i + 1 ];
  10434. var c = array[ i + 2 ];
  10435. indices.push( a, b, b, c, c, a );
  10436. }
  10437. } else {
  10438. var array = attributes.position.array;
  10439. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10440. var a = i + 0;
  10441. var b = i + 1;
  10442. var c = i + 2;
  10443. indices.push( a, b, b, c, c, a );
  10444. }
  10445. }
  10446. // console.timeEnd( 'wireframe' );
  10447. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  10448. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  10449. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10450. property.wireframe = attribute;
  10451. return attribute;
  10452. }
  10453. return {
  10454. getAttributeBuffer: getAttributeBuffer,
  10455. getAttributeProperties: getAttributeProperties,
  10456. getWireframeAttribute: getWireframeAttribute,
  10457. update: update
  10458. };
  10459. }
  10460. /**
  10461. * @author mrdoob / http://mrdoob.com/
  10462. */
  10463. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  10464. var _infoMemory = info.memory;
  10465. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10466. //
  10467. function clampToMaxSize( image, maxSize ) {
  10468. if ( image.width > maxSize || image.height > maxSize ) {
  10469. // Warning: Scaling through the canvas will only work with images that use
  10470. // premultiplied alpha.
  10471. var scale = maxSize / Math.max( image.width, image.height );
  10472. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10473. canvas.width = Math.floor( image.width * scale );
  10474. canvas.height = Math.floor( image.height * scale );
  10475. var context = canvas.getContext( '2d' );
  10476. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10477. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10478. return canvas;
  10479. }
  10480. return image;
  10481. }
  10482. function isPowerOfTwo( image ) {
  10483. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10484. }
  10485. function makePowerOfTwo( image ) {
  10486. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10487. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10488. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10489. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10490. var context = canvas.getContext( '2d' );
  10491. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10492. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10493. return canvas;
  10494. }
  10495. return image;
  10496. }
  10497. function textureNeedsPowerOfTwo( texture ) {
  10498. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10499. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10500. }
  10501. // Fallback filters for non-power-of-2 textures
  10502. function filterFallback( f ) {
  10503. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10504. return _gl.NEAREST;
  10505. }
  10506. return _gl.LINEAR;
  10507. }
  10508. //
  10509. function onTextureDispose( event ) {
  10510. var texture = event.target;
  10511. texture.removeEventListener( 'dispose', onTextureDispose );
  10512. deallocateTexture( texture );
  10513. _infoMemory.textures --;
  10514. }
  10515. function onRenderTargetDispose( event ) {
  10516. var renderTarget = event.target;
  10517. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10518. deallocateRenderTarget( renderTarget );
  10519. _infoMemory.textures --;
  10520. }
  10521. //
  10522. function deallocateTexture( texture ) {
  10523. var textureProperties = properties.get( texture );
  10524. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10525. // cube texture
  10526. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10527. } else {
  10528. // 2D texture
  10529. if ( textureProperties.__webglInit === undefined ) return;
  10530. _gl.deleteTexture( textureProperties.__webglTexture );
  10531. }
  10532. // remove all webgl properties
  10533. properties.delete( texture );
  10534. }
  10535. function deallocateRenderTarget( renderTarget ) {
  10536. var renderTargetProperties = properties.get( renderTarget );
  10537. var textureProperties = properties.get( renderTarget.texture );
  10538. if ( ! renderTarget ) return;
  10539. if ( textureProperties.__webglTexture !== undefined ) {
  10540. _gl.deleteTexture( textureProperties.__webglTexture );
  10541. }
  10542. if ( renderTarget.depthTexture ) {
  10543. renderTarget.depthTexture.dispose();
  10544. }
  10545. if ( renderTarget.isWebGLRenderTargetCube ) {
  10546. for ( var i = 0; i < 6; i ++ ) {
  10547. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10548. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10549. }
  10550. } else {
  10551. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10552. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10553. }
  10554. properties.delete( renderTarget.texture );
  10555. properties.delete( renderTarget );
  10556. }
  10557. //
  10558. function setTexture2D( texture, slot ) {
  10559. var textureProperties = properties.get( texture );
  10560. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10561. var image = texture.image;
  10562. if ( image === undefined ) {
  10563. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10564. } else if ( image.complete === false ) {
  10565. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10566. } else {
  10567. uploadTexture( textureProperties, texture, slot );
  10568. return;
  10569. }
  10570. }
  10571. state.activeTexture( _gl.TEXTURE0 + slot );
  10572. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10573. }
  10574. function setTextureCube( texture, slot ) {
  10575. var textureProperties = properties.get( texture );
  10576. if ( texture.image.length === 6 ) {
  10577. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10578. if ( ! textureProperties.__image__webglTextureCube ) {
  10579. texture.addEventListener( 'dispose', onTextureDispose );
  10580. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10581. _infoMemory.textures ++;
  10582. }
  10583. state.activeTexture( _gl.TEXTURE0 + slot );
  10584. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10585. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10586. var isCompressed = ( texture && texture.isCompressedTexture );
  10587. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  10588. var cubeImage = [];
  10589. for ( var i = 0; i < 6; i ++ ) {
  10590. if ( ! isCompressed && ! isDataTexture ) {
  10591. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10592. } else {
  10593. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10594. }
  10595. }
  10596. var image = cubeImage[ 0 ],
  10597. isPowerOfTwoImage = isPowerOfTwo( image ),
  10598. glFormat = paramThreeToGL( texture.format ),
  10599. glType = paramThreeToGL( texture.type );
  10600. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10601. for ( var i = 0; i < 6; i ++ ) {
  10602. if ( ! isCompressed ) {
  10603. if ( isDataTexture ) {
  10604. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10605. } else {
  10606. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10607. }
  10608. } else {
  10609. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10610. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10611. mipmap = mipmaps[ j ];
  10612. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10613. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10614. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10615. } else {
  10616. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10617. }
  10618. } else {
  10619. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10620. }
  10621. }
  10622. }
  10623. }
  10624. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10625. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10626. }
  10627. textureProperties.__version = texture.version;
  10628. if ( texture.onUpdate ) texture.onUpdate( texture );
  10629. } else {
  10630. state.activeTexture( _gl.TEXTURE0 + slot );
  10631. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10632. }
  10633. }
  10634. }
  10635. function setTextureCubeDynamic( texture, slot ) {
  10636. state.activeTexture( _gl.TEXTURE0 + slot );
  10637. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10638. }
  10639. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10640. var extension;
  10641. if ( isPowerOfTwoImage ) {
  10642. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10643. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10644. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10645. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10646. } else {
  10647. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10648. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10649. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10650. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10651. }
  10652. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10653. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10654. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10655. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10656. }
  10657. }
  10658. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10659. if ( extension ) {
  10660. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10661. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10662. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10663. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10664. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10665. }
  10666. }
  10667. }
  10668. function uploadTexture( textureProperties, texture, slot ) {
  10669. if ( textureProperties.__webglInit === undefined ) {
  10670. textureProperties.__webglInit = true;
  10671. texture.addEventListener( 'dispose', onTextureDispose );
  10672. textureProperties.__webglTexture = _gl.createTexture();
  10673. _infoMemory.textures ++;
  10674. }
  10675. state.activeTexture( _gl.TEXTURE0 + slot );
  10676. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10677. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10678. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10679. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10680. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10681. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10682. image = makePowerOfTwo( image );
  10683. }
  10684. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10685. glFormat = paramThreeToGL( texture.format ),
  10686. glType = paramThreeToGL( texture.type );
  10687. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10688. var mipmap, mipmaps = texture.mipmaps;
  10689. if ( texture.isDepthTexture ) {
  10690. // populate depth texture with dummy data
  10691. var internalFormat = _gl.DEPTH_COMPONENT;
  10692. if ( texture.type === FloatType ) {
  10693. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10694. internalFormat = _gl.DEPTH_COMPONENT32F;
  10695. } else if ( _isWebGL2 ) {
  10696. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10697. internalFormat = _gl.DEPTH_COMPONENT16;
  10698. }
  10699. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10700. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10701. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10702. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10703. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10704. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10705. texture.type = UnsignedShortType;
  10706. glType = paramThreeToGL( texture.type );
  10707. }
  10708. }
  10709. // Depth stencil textures need the DEPTH_STENCIL internal format
  10710. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10711. if ( texture.format === DepthStencilFormat ) {
  10712. internalFormat = _gl.DEPTH_STENCIL;
  10713. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10714. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10715. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10716. if ( texture.type !== UnsignedInt248Type ) {
  10717. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10718. texture.type = UnsignedInt248Type;
  10719. glType = paramThreeToGL( texture.type );
  10720. }
  10721. }
  10722. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10723. } else if ( texture.isDataTexture ) {
  10724. // use manually created mipmaps if available
  10725. // if there are no manual mipmaps
  10726. // set 0 level mipmap and then use GL to generate other mipmap levels
  10727. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10728. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10729. mipmap = mipmaps[ i ];
  10730. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10731. }
  10732. texture.generateMipmaps = false;
  10733. } else {
  10734. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10735. }
  10736. } else if ( texture.isCompressedTexture ) {
  10737. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10738. mipmap = mipmaps[ i ];
  10739. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10740. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10741. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10742. } else {
  10743. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10744. }
  10745. } else {
  10746. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10747. }
  10748. }
  10749. } else {
  10750. // regular Texture (image, video, canvas)
  10751. // use manually created mipmaps if available
  10752. // if there are no manual mipmaps
  10753. // set 0 level mipmap and then use GL to generate other mipmap levels
  10754. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10755. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10756. mipmap = mipmaps[ i ];
  10757. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10758. }
  10759. texture.generateMipmaps = false;
  10760. } else {
  10761. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10762. }
  10763. }
  10764. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10765. textureProperties.__version = texture.version;
  10766. if ( texture.onUpdate ) texture.onUpdate( texture );
  10767. }
  10768. // Render targets
  10769. // Setup storage for target texture and bind it to correct framebuffer
  10770. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10771. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10772. var glType = paramThreeToGL( renderTarget.texture.type );
  10773. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10774. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10775. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10776. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10777. }
  10778. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10779. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10780. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10781. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10782. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10783. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10784. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10785. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10786. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10787. } else {
  10788. // FIXME: We don't support !depth !stencil
  10789. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10790. }
  10791. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10792. }
  10793. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10794. function setupDepthTexture( framebuffer, renderTarget ) {
  10795. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10796. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10797. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10798. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10799. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10800. }
  10801. // upload an empty depth texture with framebuffer size
  10802. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10803. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10804. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10805. renderTarget.depthTexture.image.width = renderTarget.width;
  10806. renderTarget.depthTexture.image.height = renderTarget.height;
  10807. renderTarget.depthTexture.needsUpdate = true;
  10808. }
  10809. setTexture2D( renderTarget.depthTexture, 0 );
  10810. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10811. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10812. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10813. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10814. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10815. } else {
  10816. throw new Error('Unknown depthTexture format')
  10817. }
  10818. }
  10819. // Setup GL resources for a non-texture depth buffer
  10820. function setupDepthRenderbuffer( renderTarget ) {
  10821. var renderTargetProperties = properties.get( renderTarget );
  10822. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10823. if ( renderTarget.depthTexture ) {
  10824. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10825. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10826. } else {
  10827. if ( isCube ) {
  10828. renderTargetProperties.__webglDepthbuffer = [];
  10829. for ( var i = 0; i < 6; i ++ ) {
  10830. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10831. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10832. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10833. }
  10834. } else {
  10835. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  10836. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  10837. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  10838. }
  10839. }
  10840. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10841. }
  10842. // Set up GL resources for the render target
  10843. function setupRenderTarget( renderTarget ) {
  10844. var renderTargetProperties = properties.get( renderTarget );
  10845. var textureProperties = properties.get( renderTarget.texture );
  10846. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  10847. textureProperties.__webglTexture = _gl.createTexture();
  10848. _infoMemory.textures ++;
  10849. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10850. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  10851. // Setup framebuffer
  10852. if ( isCube ) {
  10853. renderTargetProperties.__webglFramebuffer = [];
  10854. for ( var i = 0; i < 6; i ++ ) {
  10855. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  10856. }
  10857. } else {
  10858. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  10859. }
  10860. // Setup color buffer
  10861. if ( isCube ) {
  10862. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  10863. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  10864. for ( var i = 0; i < 6; i ++ ) {
  10865. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  10866. }
  10867. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10868. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  10869. } else {
  10870. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10871. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  10872. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  10873. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10874. state.bindTexture( _gl.TEXTURE_2D, null );
  10875. }
  10876. // Setup depth and stencil buffers
  10877. if ( renderTarget.depthBuffer ) {
  10878. setupDepthRenderbuffer( renderTarget );
  10879. }
  10880. }
  10881. function updateRenderTargetMipmap( renderTarget ) {
  10882. var texture = renderTarget.texture;
  10883. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  10884. texture.minFilter !== NearestFilter &&
  10885. texture.minFilter !== LinearFilter ) {
  10886. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  10887. var webglTexture = properties.get( texture ).__webglTexture;
  10888. state.bindTexture( target, webglTexture );
  10889. _gl.generateMipmap( target );
  10890. state.bindTexture( target, null );
  10891. }
  10892. }
  10893. this.setTexture2D = setTexture2D;
  10894. this.setTextureCube = setTextureCube;
  10895. this.setTextureCubeDynamic = setTextureCubeDynamic;
  10896. this.setupRenderTarget = setupRenderTarget;
  10897. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  10898. }
  10899. /**
  10900. * @author fordacious / fordacious.github.io
  10901. */
  10902. function WebGLProperties() {
  10903. var properties = {};
  10904. return {
  10905. get: function ( object ) {
  10906. var uuid = object.uuid;
  10907. var map = properties[ uuid ];
  10908. if ( map === undefined ) {
  10909. map = {};
  10910. properties[ uuid ] = map;
  10911. }
  10912. return map;
  10913. },
  10914. delete: function ( object ) {
  10915. delete properties[ object.uuid ];
  10916. },
  10917. clear: function () {
  10918. properties = {};
  10919. }
  10920. };
  10921. }
  10922. /**
  10923. * @author mrdoob / http://mrdoob.com/
  10924. */
  10925. function WebGLState( gl, extensions, paramThreeToGL ) {
  10926. function ColorBuffer() {
  10927. var locked = false;
  10928. var color = new Vector4();
  10929. var currentColorMask = null;
  10930. var currentColorClear = new Vector4();
  10931. return {
  10932. setMask: function ( colorMask ) {
  10933. if ( currentColorMask !== colorMask && ! locked ) {
  10934. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  10935. currentColorMask = colorMask;
  10936. }
  10937. },
  10938. setLocked: function ( lock ) {
  10939. locked = lock;
  10940. },
  10941. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  10942. if ( premultipliedAlpha === true ) {
  10943. r *= a; g *= a; b *= a;
  10944. }
  10945. color.set( r, g, b, a );
  10946. if ( currentColorClear.equals( color ) === false ) {
  10947. gl.clearColor( r, g, b, a );
  10948. currentColorClear.copy( color );
  10949. }
  10950. },
  10951. reset: function () {
  10952. locked = false;
  10953. currentColorMask = null;
  10954. currentColorClear.set( 0, 0, 0, 1 );
  10955. }
  10956. };
  10957. }
  10958. function DepthBuffer() {
  10959. var locked = false;
  10960. var currentDepthMask = null;
  10961. var currentDepthFunc = null;
  10962. var currentDepthClear = null;
  10963. return {
  10964. setTest: function ( depthTest ) {
  10965. if ( depthTest ) {
  10966. enable( gl.DEPTH_TEST );
  10967. } else {
  10968. disable( gl.DEPTH_TEST );
  10969. }
  10970. },
  10971. setMask: function ( depthMask ) {
  10972. if ( currentDepthMask !== depthMask && ! locked ) {
  10973. gl.depthMask( depthMask );
  10974. currentDepthMask = depthMask;
  10975. }
  10976. },
  10977. setFunc: function ( depthFunc ) {
  10978. if ( currentDepthFunc !== depthFunc ) {
  10979. if ( depthFunc ) {
  10980. switch ( depthFunc ) {
  10981. case NeverDepth:
  10982. gl.depthFunc( gl.NEVER );
  10983. break;
  10984. case AlwaysDepth:
  10985. gl.depthFunc( gl.ALWAYS );
  10986. break;
  10987. case LessDepth:
  10988. gl.depthFunc( gl.LESS );
  10989. break;
  10990. case LessEqualDepth:
  10991. gl.depthFunc( gl.LEQUAL );
  10992. break;
  10993. case EqualDepth:
  10994. gl.depthFunc( gl.EQUAL );
  10995. break;
  10996. case GreaterEqualDepth:
  10997. gl.depthFunc( gl.GEQUAL );
  10998. break;
  10999. case GreaterDepth:
  11000. gl.depthFunc( gl.GREATER );
  11001. break;
  11002. case NotEqualDepth:
  11003. gl.depthFunc( gl.NOTEQUAL );
  11004. break;
  11005. default:
  11006. gl.depthFunc( gl.LEQUAL );
  11007. }
  11008. } else {
  11009. gl.depthFunc( gl.LEQUAL );
  11010. }
  11011. currentDepthFunc = depthFunc;
  11012. }
  11013. },
  11014. setLocked: function ( lock ) {
  11015. locked = lock;
  11016. },
  11017. setClear: function ( depth ) {
  11018. if ( currentDepthClear !== depth ) {
  11019. gl.clearDepth( depth );
  11020. currentDepthClear = depth;
  11021. }
  11022. },
  11023. reset: function () {
  11024. locked = false;
  11025. currentDepthMask = null;
  11026. currentDepthFunc = null;
  11027. currentDepthClear = null;
  11028. }
  11029. };
  11030. }
  11031. function StencilBuffer() {
  11032. var locked = false;
  11033. var currentStencilMask = null;
  11034. var currentStencilFunc = null;
  11035. var currentStencilRef = null;
  11036. var currentStencilFuncMask = null;
  11037. var currentStencilFail = null;
  11038. var currentStencilZFail = null;
  11039. var currentStencilZPass = null;
  11040. var currentStencilClear = null;
  11041. return {
  11042. setTest: function ( stencilTest ) {
  11043. if ( stencilTest ) {
  11044. enable( gl.STENCIL_TEST );
  11045. } else {
  11046. disable( gl.STENCIL_TEST );
  11047. }
  11048. },
  11049. setMask: function ( stencilMask ) {
  11050. if ( currentStencilMask !== stencilMask && ! locked ) {
  11051. gl.stencilMask( stencilMask );
  11052. currentStencilMask = stencilMask;
  11053. }
  11054. },
  11055. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11056. if ( currentStencilFunc !== stencilFunc ||
  11057. currentStencilRef !== stencilRef ||
  11058. currentStencilFuncMask !== stencilMask ) {
  11059. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11060. currentStencilFunc = stencilFunc;
  11061. currentStencilRef = stencilRef;
  11062. currentStencilFuncMask = stencilMask;
  11063. }
  11064. },
  11065. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11066. if ( currentStencilFail !== stencilFail ||
  11067. currentStencilZFail !== stencilZFail ||
  11068. currentStencilZPass !== stencilZPass ) {
  11069. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11070. currentStencilFail = stencilFail;
  11071. currentStencilZFail = stencilZFail;
  11072. currentStencilZPass = stencilZPass;
  11073. }
  11074. },
  11075. setLocked: function ( lock ) {
  11076. locked = lock;
  11077. },
  11078. setClear: function ( stencil ) {
  11079. if ( currentStencilClear !== stencil ) {
  11080. gl.clearStencil( stencil );
  11081. currentStencilClear = stencil;
  11082. }
  11083. },
  11084. reset: function () {
  11085. locked = false;
  11086. currentStencilMask = null;
  11087. currentStencilFunc = null;
  11088. currentStencilRef = null;
  11089. currentStencilFuncMask = null;
  11090. currentStencilFail = null;
  11091. currentStencilZFail = null;
  11092. currentStencilZPass = null;
  11093. currentStencilClear = null;
  11094. }
  11095. };
  11096. }
  11097. //
  11098. var colorBuffer = new ColorBuffer();
  11099. var depthBuffer = new DepthBuffer();
  11100. var stencilBuffer = new StencilBuffer();
  11101. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11102. var newAttributes = new Uint8Array( maxVertexAttributes );
  11103. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11104. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11105. var capabilities = {};
  11106. var compressedTextureFormats = null;
  11107. var currentBlending = null;
  11108. var currentBlendEquation = null;
  11109. var currentBlendSrc = null;
  11110. var currentBlendDst = null;
  11111. var currentBlendEquationAlpha = null;
  11112. var currentBlendSrcAlpha = null;
  11113. var currentBlendDstAlpha = null;
  11114. var currentPremultipledAlpha = false;
  11115. var currentFlipSided = null;
  11116. var currentCullFace = null;
  11117. var currentLineWidth = null;
  11118. var currentPolygonOffsetFactor = null;
  11119. var currentPolygonOffsetUnits = null;
  11120. var currentScissorTest = null;
  11121. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11122. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11123. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11124. var currentTextureSlot = null;
  11125. var currentBoundTextures = {};
  11126. var currentScissor = new Vector4();
  11127. var currentViewport = new Vector4();
  11128. function createTexture( type, target, count ) {
  11129. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11130. var texture = gl.createTexture();
  11131. gl.bindTexture( type, texture );
  11132. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11133. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11134. for ( var i = 0; i < count; i ++ ) {
  11135. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11136. }
  11137. return texture;
  11138. }
  11139. var emptyTextures = {};
  11140. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11141. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11142. //
  11143. function init() {
  11144. colorBuffer.setClear( 0, 0, 0, 1 );
  11145. depthBuffer.setClear( 1 );
  11146. stencilBuffer.setClear( 0 );
  11147. enable( gl.DEPTH_TEST );
  11148. setDepthFunc( LessEqualDepth );
  11149. setFlipSided( false );
  11150. setCullFace( CullFaceBack );
  11151. enable( gl.CULL_FACE );
  11152. enable( gl.BLEND );
  11153. setBlending( NormalBlending );
  11154. }
  11155. function initAttributes() {
  11156. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11157. newAttributes[ i ] = 0;
  11158. }
  11159. }
  11160. function enableAttribute( attribute ) {
  11161. newAttributes[ attribute ] = 1;
  11162. if ( enabledAttributes[ attribute ] === 0 ) {
  11163. gl.enableVertexAttribArray( attribute );
  11164. enabledAttributes[ attribute ] = 1;
  11165. }
  11166. if ( attributeDivisors[ attribute ] !== 0 ) {
  11167. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11168. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11169. attributeDivisors[ attribute ] = 0;
  11170. }
  11171. }
  11172. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  11173. newAttributes[ attribute ] = 1;
  11174. if ( enabledAttributes[ attribute ] === 0 ) {
  11175. gl.enableVertexAttribArray( attribute );
  11176. enabledAttributes[ attribute ] = 1;
  11177. }
  11178. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11179. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11180. attributeDivisors[ attribute ] = meshPerAttribute;
  11181. }
  11182. }
  11183. function disableUnusedAttributes() {
  11184. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11185. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11186. gl.disableVertexAttribArray( i );
  11187. enabledAttributes[ i ] = 0;
  11188. }
  11189. }
  11190. }
  11191. function enable( id ) {
  11192. if ( capabilities[ id ] !== true ) {
  11193. gl.enable( id );
  11194. capabilities[ id ] = true;
  11195. }
  11196. }
  11197. function disable( id ) {
  11198. if ( capabilities[ id ] !== false ) {
  11199. gl.disable( id );
  11200. capabilities[ id ] = false;
  11201. }
  11202. }
  11203. function getCompressedTextureFormats() {
  11204. if ( compressedTextureFormats === null ) {
  11205. compressedTextureFormats = [];
  11206. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11207. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11208. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11209. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11210. for ( var i = 0; i < formats.length; i ++ ) {
  11211. compressedTextureFormats.push( formats[ i ] );
  11212. }
  11213. }
  11214. }
  11215. return compressedTextureFormats;
  11216. }
  11217. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11218. if ( blending !== NoBlending ) {
  11219. enable( gl.BLEND );
  11220. } else {
  11221. disable( gl.BLEND );
  11222. }
  11223. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11224. if ( blending === AdditiveBlending ) {
  11225. if ( premultipliedAlpha ) {
  11226. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11227. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11228. } else {
  11229. gl.blendEquation( gl.FUNC_ADD );
  11230. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11231. }
  11232. } else if ( blending === SubtractiveBlending ) {
  11233. if ( premultipliedAlpha ) {
  11234. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11235. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11236. } else {
  11237. gl.blendEquation( gl.FUNC_ADD );
  11238. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11239. }
  11240. } else if ( blending === MultiplyBlending ) {
  11241. if ( premultipliedAlpha ) {
  11242. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11243. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11244. } else {
  11245. gl.blendEquation( gl.FUNC_ADD );
  11246. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11247. }
  11248. } else {
  11249. if ( premultipliedAlpha ) {
  11250. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11251. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11252. } else {
  11253. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11254. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11255. }
  11256. }
  11257. currentBlending = blending;
  11258. currentPremultipledAlpha = premultipliedAlpha;
  11259. }
  11260. if ( blending === CustomBlending ) {
  11261. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11262. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11263. blendDstAlpha = blendDstAlpha || blendDst;
  11264. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11265. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11266. currentBlendEquation = blendEquation;
  11267. currentBlendEquationAlpha = blendEquationAlpha;
  11268. }
  11269. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11270. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11271. currentBlendSrc = blendSrc;
  11272. currentBlendDst = blendDst;
  11273. currentBlendSrcAlpha = blendSrcAlpha;
  11274. currentBlendDstAlpha = blendDstAlpha;
  11275. }
  11276. } else {
  11277. currentBlendEquation = null;
  11278. currentBlendSrc = null;
  11279. currentBlendDst = null;
  11280. currentBlendEquationAlpha = null;
  11281. currentBlendSrcAlpha = null;
  11282. currentBlendDstAlpha = null;
  11283. }
  11284. }
  11285. // TODO Deprecate
  11286. function setColorWrite( colorWrite ) {
  11287. colorBuffer.setMask( colorWrite );
  11288. }
  11289. function setDepthTest( depthTest ) {
  11290. depthBuffer.setTest( depthTest );
  11291. }
  11292. function setDepthWrite( depthWrite ) {
  11293. depthBuffer.setMask( depthWrite );
  11294. }
  11295. function setDepthFunc( depthFunc ) {
  11296. depthBuffer.setFunc( depthFunc );
  11297. }
  11298. function setStencilTest( stencilTest ) {
  11299. stencilBuffer.setTest( stencilTest );
  11300. }
  11301. function setStencilWrite( stencilWrite ) {
  11302. stencilBuffer.setMask( stencilWrite );
  11303. }
  11304. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  11305. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  11306. }
  11307. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  11308. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  11309. }
  11310. //
  11311. function setFlipSided( flipSided ) {
  11312. if ( currentFlipSided !== flipSided ) {
  11313. if ( flipSided ) {
  11314. gl.frontFace( gl.CW );
  11315. } else {
  11316. gl.frontFace( gl.CCW );
  11317. }
  11318. currentFlipSided = flipSided;
  11319. }
  11320. }
  11321. function setCullFace( cullFace ) {
  11322. if ( cullFace !== CullFaceNone ) {
  11323. enable( gl.CULL_FACE );
  11324. if ( cullFace !== currentCullFace ) {
  11325. if ( cullFace === CullFaceBack ) {
  11326. gl.cullFace( gl.BACK );
  11327. } else if ( cullFace === CullFaceFront ) {
  11328. gl.cullFace( gl.FRONT );
  11329. } else {
  11330. gl.cullFace( gl.FRONT_AND_BACK );
  11331. }
  11332. }
  11333. } else {
  11334. disable( gl.CULL_FACE );
  11335. }
  11336. currentCullFace = cullFace;
  11337. }
  11338. function setLineWidth( width ) {
  11339. if ( width !== currentLineWidth ) {
  11340. if ( lineWidthAvailable ) gl.lineWidth( width );
  11341. currentLineWidth = width;
  11342. }
  11343. }
  11344. function setPolygonOffset( polygonOffset, factor, units ) {
  11345. if ( polygonOffset ) {
  11346. enable( gl.POLYGON_OFFSET_FILL );
  11347. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11348. gl.polygonOffset( factor, units );
  11349. currentPolygonOffsetFactor = factor;
  11350. currentPolygonOffsetUnits = units;
  11351. }
  11352. } else {
  11353. disable( gl.POLYGON_OFFSET_FILL );
  11354. }
  11355. }
  11356. function getScissorTest() {
  11357. return currentScissorTest;
  11358. }
  11359. function setScissorTest( scissorTest ) {
  11360. currentScissorTest = scissorTest;
  11361. if ( scissorTest ) {
  11362. enable( gl.SCISSOR_TEST );
  11363. } else {
  11364. disable( gl.SCISSOR_TEST );
  11365. }
  11366. }
  11367. // texture
  11368. function activeTexture( webglSlot ) {
  11369. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11370. if ( currentTextureSlot !== webglSlot ) {
  11371. gl.activeTexture( webglSlot );
  11372. currentTextureSlot = webglSlot;
  11373. }
  11374. }
  11375. function bindTexture( webglType, webglTexture ) {
  11376. if ( currentTextureSlot === null ) {
  11377. activeTexture();
  11378. }
  11379. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11380. if ( boundTexture === undefined ) {
  11381. boundTexture = { type: undefined, texture: undefined };
  11382. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11383. }
  11384. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11385. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11386. boundTexture.type = webglType;
  11387. boundTexture.texture = webglTexture;
  11388. }
  11389. }
  11390. function compressedTexImage2D() {
  11391. try {
  11392. gl.compressedTexImage2D.apply( gl, arguments );
  11393. } catch ( error ) {
  11394. console.error( error );
  11395. }
  11396. }
  11397. function texImage2D() {
  11398. try {
  11399. gl.texImage2D.apply( gl, arguments );
  11400. } catch ( error ) {
  11401. console.error( error );
  11402. }
  11403. }
  11404. //
  11405. function scissor( scissor ) {
  11406. if ( currentScissor.equals( scissor ) === false ) {
  11407. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11408. currentScissor.copy( scissor );
  11409. }
  11410. }
  11411. function viewport( viewport ) {
  11412. if ( currentViewport.equals( viewport ) === false ) {
  11413. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11414. currentViewport.copy( viewport );
  11415. }
  11416. }
  11417. //
  11418. function reset() {
  11419. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11420. if ( enabledAttributes[ i ] === 1 ) {
  11421. gl.disableVertexAttribArray( i );
  11422. enabledAttributes[ i ] = 0;
  11423. }
  11424. }
  11425. capabilities = {};
  11426. compressedTextureFormats = null;
  11427. currentTextureSlot = null;
  11428. currentBoundTextures = {};
  11429. currentBlending = null;
  11430. currentFlipSided = null;
  11431. currentCullFace = null;
  11432. colorBuffer.reset();
  11433. depthBuffer.reset();
  11434. stencilBuffer.reset();
  11435. }
  11436. return {
  11437. buffers: {
  11438. color: colorBuffer,
  11439. depth: depthBuffer,
  11440. stencil: stencilBuffer
  11441. },
  11442. init: init,
  11443. initAttributes: initAttributes,
  11444. enableAttribute: enableAttribute,
  11445. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11446. disableUnusedAttributes: disableUnusedAttributes,
  11447. enable: enable,
  11448. disable: disable,
  11449. getCompressedTextureFormats: getCompressedTextureFormats,
  11450. setBlending: setBlending,
  11451. setColorWrite: setColorWrite,
  11452. setDepthTest: setDepthTest,
  11453. setDepthWrite: setDepthWrite,
  11454. setDepthFunc: setDepthFunc,
  11455. setStencilTest: setStencilTest,
  11456. setStencilWrite: setStencilWrite,
  11457. setStencilFunc: setStencilFunc,
  11458. setStencilOp: setStencilOp,
  11459. setFlipSided: setFlipSided,
  11460. setCullFace: setCullFace,
  11461. setLineWidth: setLineWidth,
  11462. setPolygonOffset: setPolygonOffset,
  11463. getScissorTest: getScissorTest,
  11464. setScissorTest: setScissorTest,
  11465. activeTexture: activeTexture,
  11466. bindTexture: bindTexture,
  11467. compressedTexImage2D: compressedTexImage2D,
  11468. texImage2D: texImage2D,
  11469. scissor: scissor,
  11470. viewport: viewport,
  11471. reset: reset
  11472. };
  11473. }
  11474. /**
  11475. * @author mrdoob / http://mrdoob.com/
  11476. */
  11477. function WebGLCapabilities( gl, extensions, parameters ) {
  11478. var maxAnisotropy;
  11479. function getMaxAnisotropy() {
  11480. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11481. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11482. if ( extension !== null ) {
  11483. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11484. } else {
  11485. maxAnisotropy = 0;
  11486. }
  11487. return maxAnisotropy;
  11488. }
  11489. function getMaxPrecision( precision ) {
  11490. if ( precision === 'highp' ) {
  11491. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11492. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11493. return 'highp';
  11494. }
  11495. precision = 'mediump';
  11496. }
  11497. if ( precision === 'mediump' ) {
  11498. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11499. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11500. return 'mediump';
  11501. }
  11502. }
  11503. return 'lowp';
  11504. }
  11505. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11506. var maxPrecision = getMaxPrecision( precision );
  11507. if ( maxPrecision !== precision ) {
  11508. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11509. precision = maxPrecision;
  11510. }
  11511. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11512. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11513. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11514. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11515. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11516. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11517. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11518. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11519. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11520. var vertexTextures = maxVertexTextures > 0;
  11521. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11522. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11523. return {
  11524. getMaxAnisotropy: getMaxAnisotropy,
  11525. getMaxPrecision: getMaxPrecision,
  11526. precision: precision,
  11527. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11528. maxTextures: maxTextures,
  11529. maxVertexTextures: maxVertexTextures,
  11530. maxTextureSize: maxTextureSize,
  11531. maxCubemapSize: maxCubemapSize,
  11532. maxAttributes: maxAttributes,
  11533. maxVertexUniforms: maxVertexUniforms,
  11534. maxVaryings: maxVaryings,
  11535. maxFragmentUniforms: maxFragmentUniforms,
  11536. vertexTextures: vertexTextures,
  11537. floatFragmentTextures: floatFragmentTextures,
  11538. floatVertexTextures: floatVertexTextures
  11539. };
  11540. }
  11541. /**
  11542. * @author mrdoob / http://mrdoob.com/
  11543. */
  11544. function WebGLExtensions( gl ) {
  11545. var extensions = {};
  11546. return {
  11547. get: function ( name ) {
  11548. if ( extensions[ name ] !== undefined ) {
  11549. return extensions[ name ];
  11550. }
  11551. var extension;
  11552. switch ( name ) {
  11553. case 'WEBGL_depth_texture':
  11554. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11555. break;
  11556. case 'EXT_texture_filter_anisotropic':
  11557. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11558. break;
  11559. case 'WEBGL_compressed_texture_s3tc':
  11560. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11561. break;
  11562. case 'WEBGL_compressed_texture_pvrtc':
  11563. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11564. break;
  11565. case 'WEBGL_compressed_texture_etc1':
  11566. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11567. break;
  11568. default:
  11569. extension = gl.getExtension( name );
  11570. }
  11571. if ( extension === null ) {
  11572. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11573. }
  11574. extensions[ name ] = extension;
  11575. return extension;
  11576. }
  11577. };
  11578. }
  11579. /**
  11580. * @author tschw
  11581. */
  11582. function WebGLClipping() {
  11583. var scope = this,
  11584. globalState = null,
  11585. numGlobalPlanes = 0,
  11586. localClippingEnabled = false,
  11587. renderingShadows = false,
  11588. plane = new Plane(),
  11589. viewNormalMatrix = new Matrix3(),
  11590. uniform = { value: null, needsUpdate: false };
  11591. this.uniform = uniform;
  11592. this.numPlanes = 0;
  11593. this.numIntersection = 0;
  11594. this.init = function( planes, enableLocalClipping, camera ) {
  11595. var enabled =
  11596. planes.length !== 0 ||
  11597. enableLocalClipping ||
  11598. // enable state of previous frame - the clipping code has to
  11599. // run another frame in order to reset the state:
  11600. numGlobalPlanes !== 0 ||
  11601. localClippingEnabled;
  11602. localClippingEnabled = enableLocalClipping;
  11603. globalState = projectPlanes( planes, camera, 0 );
  11604. numGlobalPlanes = planes.length;
  11605. return enabled;
  11606. };
  11607. this.beginShadows = function() {
  11608. renderingShadows = true;
  11609. projectPlanes( null );
  11610. };
  11611. this.endShadows = function() {
  11612. renderingShadows = false;
  11613. resetGlobalState();
  11614. };
  11615. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11616. if ( ! localClippingEnabled ||
  11617. planes === null || planes.length === 0 ||
  11618. renderingShadows && ! clipShadows ) {
  11619. // there's no local clipping
  11620. if ( renderingShadows ) {
  11621. // there's no global clipping
  11622. projectPlanes( null );
  11623. } else {
  11624. resetGlobalState();
  11625. }
  11626. } else {
  11627. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11628. lGlobal = nGlobal * 4,
  11629. dstArray = cache.clippingState || null;
  11630. uniform.value = dstArray; // ensure unique state
  11631. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11632. for ( var i = 0; i !== lGlobal; ++ i ) {
  11633. dstArray[ i ] = globalState[ i ];
  11634. }
  11635. cache.clippingState = dstArray;
  11636. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11637. this.numPlanes += nGlobal;
  11638. }
  11639. };
  11640. function resetGlobalState() {
  11641. if ( uniform.value !== globalState ) {
  11642. uniform.value = globalState;
  11643. uniform.needsUpdate = numGlobalPlanes > 0;
  11644. }
  11645. scope.numPlanes = numGlobalPlanes;
  11646. scope.numIntersection = 0;
  11647. }
  11648. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11649. var nPlanes = planes !== null ? planes.length : 0,
  11650. dstArray = null;
  11651. if ( nPlanes !== 0 ) {
  11652. dstArray = uniform.value;
  11653. if ( skipTransform !== true || dstArray === null ) {
  11654. var flatSize = dstOffset + nPlanes * 4,
  11655. viewMatrix = camera.matrixWorldInverse;
  11656. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11657. if ( dstArray === null || dstArray.length < flatSize ) {
  11658. dstArray = new Float32Array( flatSize );
  11659. }
  11660. for ( var i = 0, i4 = dstOffset;
  11661. i !== nPlanes; ++ i, i4 += 4 ) {
  11662. plane.copy( planes[ i ] ).
  11663. applyMatrix4( viewMatrix, viewNormalMatrix );
  11664. plane.normal.toArray( dstArray, i4 );
  11665. dstArray[ i4 + 3 ] = plane.constant;
  11666. }
  11667. }
  11668. uniform.value = dstArray;
  11669. uniform.needsUpdate = true;
  11670. }
  11671. scope.numPlanes = nPlanes;
  11672. return dstArray;
  11673. }
  11674. }
  11675. /**
  11676. * @author supereggbert / http://www.paulbrunt.co.uk/
  11677. * @author mrdoob / http://mrdoob.com/
  11678. * @author alteredq / http://alteredqualia.com/
  11679. * @author szimek / https://github.com/szimek/
  11680. * @author tschw
  11681. */
  11682. function WebGLRenderer( parameters ) {
  11683. console.log( 'THREE.WebGLRenderer', REVISION );
  11684. parameters = parameters || {};
  11685. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11686. _context = parameters.context !== undefined ? parameters.context : null,
  11687. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11688. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11689. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11690. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11691. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11692. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11693. var lights = [];
  11694. var opaqueObjects = [];
  11695. var opaqueObjectsLastIndex = - 1;
  11696. var transparentObjects = [];
  11697. var transparentObjectsLastIndex = - 1;
  11698. var morphInfluences = new Float32Array( 8 );
  11699. var sprites = [];
  11700. var lensFlares = [];
  11701. // public properties
  11702. this.domElement = _canvas;
  11703. this.context = null;
  11704. // clearing
  11705. this.autoClear = true;
  11706. this.autoClearColor = true;
  11707. this.autoClearDepth = true;
  11708. this.autoClearStencil = true;
  11709. // scene graph
  11710. this.sortObjects = true;
  11711. // user-defined clipping
  11712. this.clippingPlanes = [];
  11713. this.localClippingEnabled = false;
  11714. // physically based shading
  11715. this.gammaFactor = 2.0; // for backwards compatibility
  11716. this.gammaInput = false;
  11717. this.gammaOutput = false;
  11718. // physical lights
  11719. this.physicallyCorrectLights = false;
  11720. // tone mapping
  11721. this.toneMapping = LinearToneMapping;
  11722. this.toneMappingExposure = 1.0;
  11723. this.toneMappingWhitePoint = 1.0;
  11724. // morphs
  11725. this.maxMorphTargets = 8;
  11726. this.maxMorphNormals = 4;
  11727. // internal properties
  11728. var _this = this,
  11729. // internal state cache
  11730. _currentProgram = null,
  11731. _currentRenderTarget = null,
  11732. _currentFramebuffer = null,
  11733. _currentMaterialId = - 1,
  11734. _currentGeometryProgram = '',
  11735. _currentCamera = null,
  11736. _currentScissor = new Vector4(),
  11737. _currentScissorTest = null,
  11738. _currentViewport = new Vector4(),
  11739. //
  11740. _usedTextureUnits = 0,
  11741. //
  11742. _clearColor = new Color( 0x000000 ),
  11743. _clearAlpha = 0,
  11744. _width = _canvas.width,
  11745. _height = _canvas.height,
  11746. _pixelRatio = 1,
  11747. _scissor = new Vector4( 0, 0, _width, _height ),
  11748. _scissorTest = false,
  11749. _viewport = new Vector4( 0, 0, _width, _height ),
  11750. // frustum
  11751. _frustum = new Frustum(),
  11752. // clipping
  11753. _clipping = new WebGLClipping(),
  11754. _clippingEnabled = false,
  11755. _localClippingEnabled = false,
  11756. _sphere = new Sphere(),
  11757. // camera matrices cache
  11758. _projScreenMatrix = new Matrix4(),
  11759. _vector3 = new Vector3(),
  11760. _matrix4 = new Matrix4(),
  11761. _matrix42 = new Matrix4(),
  11762. // light arrays cache
  11763. _lights = {
  11764. hash: '',
  11765. ambient: [ 0, 0, 0 ],
  11766. directional: [],
  11767. directionalShadowMap: [],
  11768. directionalShadowMatrix: [],
  11769. spot: [],
  11770. spotShadowMap: [],
  11771. spotShadowMatrix: [],
  11772. rectArea: [],
  11773. point: [],
  11774. pointShadowMap: [],
  11775. pointShadowMatrix: [],
  11776. hemi: [],
  11777. shadows: []
  11778. },
  11779. // info
  11780. _infoRender = {
  11781. calls: 0,
  11782. vertices: 0,
  11783. faces: 0,
  11784. points: 0
  11785. };
  11786. this.info = {
  11787. render: _infoRender,
  11788. memory: {
  11789. geometries: 0,
  11790. textures: 0
  11791. },
  11792. programs: null
  11793. };
  11794. // initialize
  11795. var _gl;
  11796. try {
  11797. var attributes = {
  11798. alpha: _alpha,
  11799. depth: _depth,
  11800. stencil: _stencil,
  11801. antialias: _antialias,
  11802. premultipliedAlpha: _premultipliedAlpha,
  11803. preserveDrawingBuffer: _preserveDrawingBuffer
  11804. };
  11805. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11806. if ( _gl === null ) {
  11807. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11808. throw 'Error creating WebGL context with your selected attributes.';
  11809. } else {
  11810. throw 'Error creating WebGL context.';
  11811. }
  11812. }
  11813. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11814. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11815. _gl.getShaderPrecisionFormat = function () {
  11816. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11817. };
  11818. }
  11819. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11820. } catch ( error ) {
  11821. console.error( 'THREE.WebGLRenderer: ' + error );
  11822. }
  11823. var extensions = new WebGLExtensions( _gl );
  11824. extensions.get( 'WEBGL_depth_texture' );
  11825. extensions.get( 'OES_texture_float' );
  11826. extensions.get( 'OES_texture_float_linear' );
  11827. extensions.get( 'OES_texture_half_float' );
  11828. extensions.get( 'OES_texture_half_float_linear' );
  11829. extensions.get( 'OES_standard_derivatives' );
  11830. extensions.get( 'ANGLE_instanced_arrays' );
  11831. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11832. BufferGeometry.MaxIndex = 4294967296;
  11833. }
  11834. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11835. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11836. var properties = new WebGLProperties();
  11837. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11838. var objects = new WebGLObjects( _gl, properties, this.info );
  11839. var programCache = new WebGLPrograms( this, capabilities );
  11840. var lightCache = new WebGLLights();
  11841. this.info.programs = programCache.programs;
  11842. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11843. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11844. //
  11845. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11846. var backgroundCamera2 = new PerspectiveCamera();
  11847. var backgroundPlaneMesh = new Mesh(
  11848. new PlaneBufferGeometry( 2, 2 ),
  11849. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11850. );
  11851. var backgroundBoxShader = ShaderLib[ 'cube' ];
  11852. var backgroundBoxMesh = new Mesh(
  11853. new BoxBufferGeometry( 5, 5, 5 ),
  11854. new ShaderMaterial( {
  11855. uniforms: backgroundBoxShader.uniforms,
  11856. vertexShader: backgroundBoxShader.vertexShader,
  11857. fragmentShader: backgroundBoxShader.fragmentShader,
  11858. side: BackSide,
  11859. depthTest: false,
  11860. depthWrite: false,
  11861. fog: false
  11862. } )
  11863. );
  11864. //
  11865. function getTargetPixelRatio() {
  11866. return _currentRenderTarget === null ? _pixelRatio : 1;
  11867. }
  11868. function setDefaultGLState() {
  11869. state.init();
  11870. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11871. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11872. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11873. }
  11874. function resetGLState() {
  11875. _currentProgram = null;
  11876. _currentCamera = null;
  11877. _currentGeometryProgram = '';
  11878. _currentMaterialId = - 1;
  11879. state.reset();
  11880. }
  11881. setDefaultGLState();
  11882. this.context = _gl;
  11883. this.capabilities = capabilities;
  11884. this.extensions = extensions;
  11885. this.properties = properties;
  11886. this.state = state;
  11887. // shadow map
  11888. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11889. this.shadowMap = shadowMap;
  11890. // Plugins
  11891. var spritePlugin = new SpritePlugin( this, sprites );
  11892. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11893. // API
  11894. this.getContext = function () {
  11895. return _gl;
  11896. };
  11897. this.getContextAttributes = function () {
  11898. return _gl.getContextAttributes();
  11899. };
  11900. this.forceContextLoss = function () {
  11901. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11902. };
  11903. this.getMaxAnisotropy = function () {
  11904. return capabilities.getMaxAnisotropy();
  11905. };
  11906. this.getPrecision = function () {
  11907. return capabilities.precision;
  11908. };
  11909. this.getPixelRatio = function () {
  11910. return _pixelRatio;
  11911. };
  11912. this.setPixelRatio = function ( value ) {
  11913. if ( value === undefined ) return;
  11914. _pixelRatio = value;
  11915. this.setSize( _viewport.z, _viewport.w, false );
  11916. };
  11917. this.getSize = function () {
  11918. return {
  11919. width: _width,
  11920. height: _height
  11921. };
  11922. };
  11923. this.setSize = function ( width, height, updateStyle ) {
  11924. _width = width;
  11925. _height = height;
  11926. _canvas.width = width * _pixelRatio;
  11927. _canvas.height = height * _pixelRatio;
  11928. if ( updateStyle !== false ) {
  11929. _canvas.style.width = width + 'px';
  11930. _canvas.style.height = height + 'px';
  11931. }
  11932. this.setViewport( 0, 0, width, height );
  11933. };
  11934. this.setViewport = function ( x, y, width, height ) {
  11935. state.viewport( _viewport.set( x, y, width, height ) );
  11936. };
  11937. this.setScissor = function ( x, y, width, height ) {
  11938. state.scissor( _scissor.set( x, y, width, height ) );
  11939. };
  11940. this.setScissorTest = function ( boolean ) {
  11941. state.setScissorTest( _scissorTest = boolean );
  11942. };
  11943. // Clearing
  11944. this.getClearColor = function () {
  11945. return _clearColor;
  11946. };
  11947. this.setClearColor = function ( color, alpha ) {
  11948. _clearColor.set( color );
  11949. _clearAlpha = alpha !== undefined ? alpha : 1;
  11950. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11951. };
  11952. this.getClearAlpha = function () {
  11953. return _clearAlpha;
  11954. };
  11955. this.setClearAlpha = function ( alpha ) {
  11956. _clearAlpha = alpha;
  11957. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11958. };
  11959. this.clear = function ( color, depth, stencil ) {
  11960. var bits = 0;
  11961. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11962. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11963. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11964. _gl.clear( bits );
  11965. };
  11966. this.clearColor = function () {
  11967. this.clear( true, false, false );
  11968. };
  11969. this.clearDepth = function () {
  11970. this.clear( false, true, false );
  11971. };
  11972. this.clearStencil = function () {
  11973. this.clear( false, false, true );
  11974. };
  11975. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11976. this.setRenderTarget( renderTarget );
  11977. this.clear( color, depth, stencil );
  11978. };
  11979. // Reset
  11980. this.resetGLState = resetGLState;
  11981. this.dispose = function() {
  11982. transparentObjects = [];
  11983. transparentObjectsLastIndex = -1;
  11984. opaqueObjects = [];
  11985. opaqueObjectsLastIndex = -1;
  11986. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11987. };
  11988. // Events
  11989. function onContextLost( event ) {
  11990. event.preventDefault();
  11991. resetGLState();
  11992. setDefaultGLState();
  11993. properties.clear();
  11994. }
  11995. function onMaterialDispose( event ) {
  11996. var material = event.target;
  11997. material.removeEventListener( 'dispose', onMaterialDispose );
  11998. deallocateMaterial( material );
  11999. }
  12000. // Buffer deallocation
  12001. function deallocateMaterial( material ) {
  12002. releaseMaterialProgramReference( material );
  12003. properties.delete( material );
  12004. }
  12005. function releaseMaterialProgramReference( material ) {
  12006. var programInfo = properties.get( material ).program;
  12007. material.program = undefined;
  12008. if ( programInfo !== undefined ) {
  12009. programCache.releaseProgram( programInfo );
  12010. }
  12011. }
  12012. // Buffer rendering
  12013. this.renderBufferImmediate = function ( object, program, material ) {
  12014. state.initAttributes();
  12015. var buffers = properties.get( object );
  12016. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12017. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12018. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12019. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12020. var attributes = program.getAttributes();
  12021. if ( object.hasPositions ) {
  12022. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12023. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12024. state.enableAttribute( attributes.position );
  12025. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12026. }
  12027. if ( object.hasNormals ) {
  12028. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12029. if ( ! material.isMeshPhongMaterial &&
  12030. ! material.isMeshStandardMaterial &&
  12031. ! material.isMeshNormalMaterial &&
  12032. material.shading === FlatShading ) {
  12033. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12034. var array = object.normalArray;
  12035. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12036. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12037. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12038. array[ i + 0 ] = nx;
  12039. array[ i + 1 ] = ny;
  12040. array[ i + 2 ] = nz;
  12041. array[ i + 3 ] = nx;
  12042. array[ i + 4 ] = ny;
  12043. array[ i + 5 ] = nz;
  12044. array[ i + 6 ] = nx;
  12045. array[ i + 7 ] = ny;
  12046. array[ i + 8 ] = nz;
  12047. }
  12048. }
  12049. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12050. state.enableAttribute( attributes.normal );
  12051. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12052. }
  12053. if ( object.hasUvs && material.map ) {
  12054. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12055. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12056. state.enableAttribute( attributes.uv );
  12057. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12058. }
  12059. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12060. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12061. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12062. state.enableAttribute( attributes.color );
  12063. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12064. }
  12065. state.disableUnusedAttributes();
  12066. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12067. object.count = 0;
  12068. };
  12069. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12070. setMaterial( material );
  12071. var program = setProgram( camera, fog, material, object );
  12072. var updateBuffers = false;
  12073. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  12074. if ( geometryProgram !== _currentGeometryProgram ) {
  12075. _currentGeometryProgram = geometryProgram;
  12076. updateBuffers = true;
  12077. }
  12078. // morph targets
  12079. var morphTargetInfluences = object.morphTargetInfluences;
  12080. if ( morphTargetInfluences !== undefined ) {
  12081. var activeInfluences = [];
  12082. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12083. var influence = morphTargetInfluences[ i ];
  12084. activeInfluences.push( [ influence, i ] );
  12085. }
  12086. activeInfluences.sort( absNumericalSort );
  12087. if ( activeInfluences.length > 8 ) {
  12088. activeInfluences.length = 8;
  12089. }
  12090. var morphAttributes = geometry.morphAttributes;
  12091. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12092. var influence = activeInfluences[ i ];
  12093. morphInfluences[ i ] = influence[ 0 ];
  12094. if ( influence[ 0 ] !== 0 ) {
  12095. var index = influence[ 1 ];
  12096. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12097. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12098. } else {
  12099. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12100. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12101. }
  12102. }
  12103. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12104. morphInfluences[ i ] = 0.0;
  12105. }
  12106. program.getUniforms().setValue(
  12107. _gl, 'morphTargetInfluences', morphInfluences );
  12108. updateBuffers = true;
  12109. }
  12110. //
  12111. var index = geometry.index;
  12112. var position = geometry.attributes.position;
  12113. var rangeFactor = 1;
  12114. if ( material.wireframe === true ) {
  12115. index = objects.getWireframeAttribute( geometry );
  12116. rangeFactor = 2;
  12117. }
  12118. var renderer;
  12119. if ( index !== null ) {
  12120. renderer = indexedBufferRenderer;
  12121. renderer.setIndex( index );
  12122. } else {
  12123. renderer = bufferRenderer;
  12124. }
  12125. if ( updateBuffers ) {
  12126. setupVertexAttributes( material, program, geometry );
  12127. if ( index !== null ) {
  12128. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  12129. }
  12130. }
  12131. //
  12132. var dataCount = 0;
  12133. if ( index !== null ) {
  12134. dataCount = index.count;
  12135. } else if ( position !== undefined ) {
  12136. dataCount = position.count;
  12137. }
  12138. var rangeStart = geometry.drawRange.start * rangeFactor;
  12139. var rangeCount = geometry.drawRange.count * rangeFactor;
  12140. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12141. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12142. var drawStart = Math.max( rangeStart, groupStart );
  12143. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12144. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12145. if ( drawCount === 0 ) return;
  12146. //
  12147. if ( object.isMesh ) {
  12148. if ( material.wireframe === true ) {
  12149. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12150. renderer.setMode( _gl.LINES );
  12151. } else {
  12152. switch ( object.drawMode ) {
  12153. case TrianglesDrawMode:
  12154. renderer.setMode( _gl.TRIANGLES );
  12155. break;
  12156. case TriangleStripDrawMode:
  12157. renderer.setMode( _gl.TRIANGLE_STRIP );
  12158. break;
  12159. case TriangleFanDrawMode:
  12160. renderer.setMode( _gl.TRIANGLE_FAN );
  12161. break;
  12162. }
  12163. }
  12164. } else if ( object.isLine ) {
  12165. var lineWidth = material.linewidth;
  12166. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12167. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12168. if ( object.isLineSegments ) {
  12169. renderer.setMode( _gl.LINES );
  12170. } else {
  12171. renderer.setMode( _gl.LINE_STRIP );
  12172. }
  12173. } else if ( object.isPoints ) {
  12174. renderer.setMode( _gl.POINTS );
  12175. }
  12176. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12177. if ( geometry.maxInstancedCount > 0 ) {
  12178. renderer.renderInstances( geometry, drawStart, drawCount );
  12179. }
  12180. } else {
  12181. renderer.render( drawStart, drawCount );
  12182. }
  12183. };
  12184. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12185. var extension;
  12186. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12187. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12188. if ( extension === null ) {
  12189. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12190. return;
  12191. }
  12192. }
  12193. if ( startIndex === undefined ) startIndex = 0;
  12194. state.initAttributes();
  12195. var geometryAttributes = geometry.attributes;
  12196. var programAttributes = program.getAttributes();
  12197. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12198. for ( var name in programAttributes ) {
  12199. var programAttribute = programAttributes[ name ];
  12200. if ( programAttribute >= 0 ) {
  12201. var geometryAttribute = geometryAttributes[ name ];
  12202. if ( geometryAttribute !== undefined ) {
  12203. var normalized = geometryAttribute.normalized;
  12204. var size = geometryAttribute.itemSize;
  12205. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  12206. var buffer = attributeProperties.__webglBuffer;
  12207. var type = attributeProperties.type;
  12208. var bytesPerElement = attributeProperties.bytesPerElement;
  12209. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12210. var data = geometryAttribute.data;
  12211. var stride = data.stride;
  12212. var offset = geometryAttribute.offset;
  12213. if ( data && data.isInstancedInterleavedBuffer ) {
  12214. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12215. if ( geometry.maxInstancedCount === undefined ) {
  12216. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12217. }
  12218. } else {
  12219. state.enableAttribute( programAttribute );
  12220. }
  12221. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12222. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12223. } else {
  12224. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12225. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12226. if ( geometry.maxInstancedCount === undefined ) {
  12227. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12228. }
  12229. } else {
  12230. state.enableAttribute( programAttribute );
  12231. }
  12232. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12233. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12234. }
  12235. } else if ( materialDefaultAttributeValues !== undefined ) {
  12236. var value = materialDefaultAttributeValues[ name ];
  12237. if ( value !== undefined ) {
  12238. switch ( value.length ) {
  12239. case 2:
  12240. _gl.vertexAttrib2fv( programAttribute, value );
  12241. break;
  12242. case 3:
  12243. _gl.vertexAttrib3fv( programAttribute, value );
  12244. break;
  12245. case 4:
  12246. _gl.vertexAttrib4fv( programAttribute, value );
  12247. break;
  12248. default:
  12249. _gl.vertexAttrib1fv( programAttribute, value );
  12250. }
  12251. }
  12252. }
  12253. }
  12254. }
  12255. state.disableUnusedAttributes();
  12256. }
  12257. // Sorting
  12258. function absNumericalSort( a, b ) {
  12259. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12260. }
  12261. function painterSortStable( a, b ) {
  12262. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12263. return a.object.renderOrder - b.object.renderOrder;
  12264. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12265. return a.material.program.id - b.material.program.id;
  12266. } else if ( a.material.id !== b.material.id ) {
  12267. return a.material.id - b.material.id;
  12268. } else if ( a.z !== b.z ) {
  12269. return a.z - b.z;
  12270. } else {
  12271. return a.id - b.id;
  12272. }
  12273. }
  12274. function reversePainterSortStable( a, b ) {
  12275. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12276. return a.object.renderOrder - b.object.renderOrder;
  12277. } if ( a.z !== b.z ) {
  12278. return b.z - a.z;
  12279. } else {
  12280. return a.id - b.id;
  12281. }
  12282. }
  12283. // Rendering
  12284. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12285. if ( camera !== undefined && camera.isCamera !== true ) {
  12286. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12287. return;
  12288. }
  12289. // reset caching for this frame
  12290. _currentGeometryProgram = '';
  12291. _currentMaterialId = - 1;
  12292. _currentCamera = null;
  12293. // update scene graph
  12294. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12295. // update camera matrices and frustum
  12296. if ( camera.parent === null ) camera.updateMatrixWorld();
  12297. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12298. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12299. _frustum.setFromMatrix( _projScreenMatrix );
  12300. lights.length = 0;
  12301. opaqueObjectsLastIndex = - 1;
  12302. transparentObjectsLastIndex = - 1;
  12303. sprites.length = 0;
  12304. lensFlares.length = 0;
  12305. _localClippingEnabled = this.localClippingEnabled;
  12306. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12307. projectObject( scene, camera );
  12308. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12309. transparentObjects.length = transparentObjectsLastIndex + 1;
  12310. if ( _this.sortObjects === true ) {
  12311. opaqueObjects.sort( painterSortStable );
  12312. transparentObjects.sort( reversePainterSortStable );
  12313. }
  12314. //
  12315. if ( _clippingEnabled ) _clipping.beginShadows();
  12316. setupShadows( lights );
  12317. shadowMap.render( scene, camera );
  12318. setupLights( lights, camera );
  12319. if ( _clippingEnabled ) _clipping.endShadows();
  12320. //
  12321. _infoRender.calls = 0;
  12322. _infoRender.vertices = 0;
  12323. _infoRender.faces = 0;
  12324. _infoRender.points = 0;
  12325. if ( renderTarget === undefined ) {
  12326. renderTarget = null;
  12327. }
  12328. this.setRenderTarget( renderTarget );
  12329. //
  12330. var background = scene.background;
  12331. if ( background === null ) {
  12332. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12333. } else if ( background && background.isColor ) {
  12334. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12335. forceClear = true;
  12336. }
  12337. if ( this.autoClear || forceClear ) {
  12338. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12339. }
  12340. if ( background && background.isCubeTexture ) {
  12341. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12342. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12343. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12344. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12345. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12346. objects.update( backgroundBoxMesh );
  12347. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12348. } else if ( background && background.isTexture ) {
  12349. backgroundPlaneMesh.material.map = background;
  12350. objects.update( backgroundPlaneMesh );
  12351. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12352. }
  12353. //
  12354. if ( scene.overrideMaterial ) {
  12355. var overrideMaterial = scene.overrideMaterial;
  12356. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12357. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12358. } else {
  12359. // opaque pass (front-to-back order)
  12360. state.setBlending( NoBlending );
  12361. renderObjects( opaqueObjects, scene, camera );
  12362. // transparent pass (back-to-front order)
  12363. renderObjects( transparentObjects, scene, camera );
  12364. }
  12365. // custom render plugins (post pass)
  12366. spritePlugin.render( scene, camera );
  12367. lensFlarePlugin.render( scene, camera, _currentViewport );
  12368. // Generate mipmap if we're using any kind of mipmap filtering
  12369. if ( renderTarget ) {
  12370. textures.updateRenderTargetMipmap( renderTarget );
  12371. }
  12372. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12373. state.setDepthTest( true );
  12374. state.setDepthWrite( true );
  12375. state.setColorWrite( true );
  12376. // _gl.finish();
  12377. };
  12378. function pushRenderItem( object, geometry, material, z, group ) {
  12379. var array, index;
  12380. // allocate the next position in the appropriate array
  12381. if ( material.transparent ) {
  12382. array = transparentObjects;
  12383. index = ++ transparentObjectsLastIndex;
  12384. } else {
  12385. array = opaqueObjects;
  12386. index = ++ opaqueObjectsLastIndex;
  12387. }
  12388. // recycle existing render item or grow the array
  12389. var renderItem = array[ index ];
  12390. if ( renderItem !== undefined ) {
  12391. renderItem.id = object.id;
  12392. renderItem.object = object;
  12393. renderItem.geometry = geometry;
  12394. renderItem.material = material;
  12395. renderItem.z = _vector3.z;
  12396. renderItem.group = group;
  12397. } else {
  12398. renderItem = {
  12399. id: object.id,
  12400. object: object,
  12401. geometry: geometry,
  12402. material: material,
  12403. z: _vector3.z,
  12404. group: group
  12405. };
  12406. // assert( index === array.length );
  12407. array.push( renderItem );
  12408. }
  12409. }
  12410. // TODO Duplicated code (Frustum)
  12411. function isObjectViewable( object ) {
  12412. var geometry = object.geometry;
  12413. if ( geometry.boundingSphere === null )
  12414. geometry.computeBoundingSphere();
  12415. _sphere.copy( geometry.boundingSphere ).
  12416. applyMatrix4( object.matrixWorld );
  12417. return isSphereViewable( _sphere );
  12418. }
  12419. function isSpriteViewable( sprite ) {
  12420. _sphere.center.set( 0, 0, 0 );
  12421. _sphere.radius = 0.7071067811865476;
  12422. _sphere.applyMatrix4( sprite.matrixWorld );
  12423. return isSphereViewable( _sphere );
  12424. }
  12425. function isSphereViewable( sphere ) {
  12426. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12427. var numPlanes = _clipping.numPlanes;
  12428. if ( numPlanes === 0 ) return true;
  12429. var planes = _this.clippingPlanes,
  12430. center = sphere.center,
  12431. negRad = - sphere.radius,
  12432. i = 0;
  12433. do {
  12434. // out when deeper than radius in the negative halfspace
  12435. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12436. } while ( ++ i !== numPlanes );
  12437. return true;
  12438. }
  12439. function projectObject( object, camera ) {
  12440. if ( object.visible === false ) return;
  12441. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  12442. if ( visible ) {
  12443. if ( object.isLight ) {
  12444. lights.push( object );
  12445. } else if ( object.isSprite ) {
  12446. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12447. sprites.push( object );
  12448. }
  12449. } else if ( object.isLensFlare ) {
  12450. lensFlares.push( object );
  12451. } else if ( object.isImmediateRenderObject ) {
  12452. if ( _this.sortObjects === true ) {
  12453. _vector3.setFromMatrixPosition( object.matrixWorld );
  12454. _vector3.applyProjection( _projScreenMatrix );
  12455. }
  12456. pushRenderItem( object, null, object.material, _vector3.z, null );
  12457. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12458. if ( object.isSkinnedMesh ) {
  12459. object.skeleton.update();
  12460. }
  12461. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12462. var material = object.material;
  12463. if ( material.visible === true ) {
  12464. if ( _this.sortObjects === true ) {
  12465. _vector3.setFromMatrixPosition( object.matrixWorld );
  12466. _vector3.applyProjection( _projScreenMatrix );
  12467. }
  12468. var geometry = objects.update( object );
  12469. if ( material.isMultiMaterial ) {
  12470. var groups = geometry.groups;
  12471. var materials = material.materials;
  12472. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12473. var group = groups[ i ];
  12474. var groupMaterial = materials[ group.materialIndex ];
  12475. if ( groupMaterial.visible === true ) {
  12476. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12477. }
  12478. }
  12479. } else {
  12480. pushRenderItem( object, geometry, material, _vector3.z, null );
  12481. }
  12482. }
  12483. }
  12484. }
  12485. }
  12486. var children = object.children;
  12487. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12488. projectObject( children[ i ], camera );
  12489. }
  12490. }
  12491. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12492. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12493. var renderItem = renderList[ i ];
  12494. var object = renderItem.object;
  12495. var geometry = renderItem.geometry;
  12496. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12497. var group = renderItem.group;
  12498. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12499. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12500. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12501. if ( object.isImmediateRenderObject ) {
  12502. setMaterial( material );
  12503. var program = setProgram( camera, scene.fog, material, object );
  12504. _currentGeometryProgram = '';
  12505. object.render( function ( object ) {
  12506. _this.renderBufferImmediate( object, program, material );
  12507. } );
  12508. } else {
  12509. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12510. }
  12511. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12512. }
  12513. }
  12514. function initMaterial( material, fog, object ) {
  12515. var materialProperties = properties.get( material );
  12516. var parameters = programCache.getParameters(
  12517. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12518. var code = programCache.getProgramCode( material, parameters );
  12519. var program = materialProperties.program;
  12520. var programChange = true;
  12521. if ( program === undefined ) {
  12522. // new material
  12523. material.addEventListener( 'dispose', onMaterialDispose );
  12524. } else if ( program.code !== code ) {
  12525. // changed glsl or parameters
  12526. releaseMaterialProgramReference( material );
  12527. } else if ( parameters.shaderID !== undefined ) {
  12528. // same glsl and uniform list
  12529. return;
  12530. } else {
  12531. // only rebuild uniform list
  12532. programChange = false;
  12533. }
  12534. if ( programChange ) {
  12535. if ( parameters.shaderID ) {
  12536. var shader = ShaderLib[ parameters.shaderID ];
  12537. materialProperties.__webglShader = {
  12538. name: material.type,
  12539. uniforms: UniformsUtils.clone( shader.uniforms ),
  12540. vertexShader: shader.vertexShader,
  12541. fragmentShader: shader.fragmentShader
  12542. };
  12543. } else {
  12544. materialProperties.__webglShader = {
  12545. name: material.type,
  12546. uniforms: material.uniforms,
  12547. vertexShader: material.vertexShader,
  12548. fragmentShader: material.fragmentShader
  12549. };
  12550. }
  12551. material.__webglShader = materialProperties.__webglShader;
  12552. program = programCache.acquireProgram( material, parameters, code );
  12553. materialProperties.program = program;
  12554. material.program = program;
  12555. }
  12556. var attributes = program.getAttributes();
  12557. if ( material.morphTargets ) {
  12558. material.numSupportedMorphTargets = 0;
  12559. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12560. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12561. material.numSupportedMorphTargets ++;
  12562. }
  12563. }
  12564. }
  12565. if ( material.morphNormals ) {
  12566. material.numSupportedMorphNormals = 0;
  12567. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12568. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12569. material.numSupportedMorphNormals ++;
  12570. }
  12571. }
  12572. }
  12573. var uniforms = materialProperties.__webglShader.uniforms;
  12574. if ( ! material.isShaderMaterial &&
  12575. ! material.isRawShaderMaterial ||
  12576. material.clipping === true ) {
  12577. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12578. materialProperties.numIntersection = _clipping.numIntersection;
  12579. uniforms.clippingPlanes = _clipping.uniform;
  12580. }
  12581. materialProperties.fog = fog;
  12582. // store the light setup it was created for
  12583. materialProperties.lightsHash = _lights.hash;
  12584. if ( material.lights ) {
  12585. // wire up the material to this renderer's lighting state
  12586. uniforms.ambientLightColor.value = _lights.ambient;
  12587. uniforms.directionalLights.value = _lights.directional;
  12588. uniforms.spotLights.value = _lights.spot;
  12589. uniforms.rectAreaLights.value = _lights.rectArea;
  12590. uniforms.pointLights.value = _lights.point;
  12591. uniforms.hemisphereLights.value = _lights.hemi;
  12592. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12593. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12594. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12595. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12596. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12597. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12598. // TODO (abelnation): add area lights shadow info to uniforms
  12599. }
  12600. var progUniforms = materialProperties.program.getUniforms(),
  12601. uniformsList =
  12602. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12603. materialProperties.uniformsList = uniformsList;
  12604. }
  12605. function setMaterial( material ) {
  12606. material.side === DoubleSide
  12607. ? state.disable( _gl.CULL_FACE )
  12608. : state.enable( _gl.CULL_FACE );
  12609. state.setFlipSided( material.side === BackSide );
  12610. material.transparent === true
  12611. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  12612. : state.setBlending( NoBlending );
  12613. state.setDepthFunc( material.depthFunc );
  12614. state.setDepthTest( material.depthTest );
  12615. state.setDepthWrite( material.depthWrite );
  12616. state.setColorWrite( material.colorWrite );
  12617. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12618. }
  12619. function setProgram( camera, fog, material, object ) {
  12620. _usedTextureUnits = 0;
  12621. var materialProperties = properties.get( material );
  12622. if ( _clippingEnabled ) {
  12623. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12624. var useCache =
  12625. camera === _currentCamera &&
  12626. material.id === _currentMaterialId;
  12627. // we might want to call this function with some ClippingGroup
  12628. // object instead of the material, once it becomes feasible
  12629. // (#8465, #8379)
  12630. _clipping.setState(
  12631. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12632. camera, materialProperties, useCache );
  12633. }
  12634. }
  12635. if ( material.needsUpdate === false ) {
  12636. if ( materialProperties.program === undefined ) {
  12637. material.needsUpdate = true;
  12638. } else if ( material.fog && materialProperties.fog !== fog ) {
  12639. material.needsUpdate = true;
  12640. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12641. material.needsUpdate = true;
  12642. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12643. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12644. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12645. material.needsUpdate = true;
  12646. }
  12647. }
  12648. if ( material.needsUpdate ) {
  12649. initMaterial( material, fog, object );
  12650. material.needsUpdate = false;
  12651. }
  12652. var refreshProgram = false;
  12653. var refreshMaterial = false;
  12654. var refreshLights = false;
  12655. var program = materialProperties.program,
  12656. p_uniforms = program.getUniforms(),
  12657. m_uniforms = materialProperties.__webglShader.uniforms;
  12658. if ( program.id !== _currentProgram ) {
  12659. _gl.useProgram( program.program );
  12660. _currentProgram = program.id;
  12661. refreshProgram = true;
  12662. refreshMaterial = true;
  12663. refreshLights = true;
  12664. }
  12665. if ( material.id !== _currentMaterialId ) {
  12666. _currentMaterialId = material.id;
  12667. refreshMaterial = true;
  12668. }
  12669. if ( refreshProgram || camera !== _currentCamera ) {
  12670. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12671. if ( capabilities.logarithmicDepthBuffer ) {
  12672. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12673. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12674. }
  12675. if ( camera !== _currentCamera ) {
  12676. _currentCamera = camera;
  12677. // lighting uniforms depend on the camera so enforce an update
  12678. // now, in case this material supports lights - or later, when
  12679. // the next material that does gets activated:
  12680. refreshMaterial = true; // set to true on material change
  12681. refreshLights = true; // remains set until update done
  12682. }
  12683. // load material specific uniforms
  12684. // (shader material also gets them for the sake of genericity)
  12685. if ( material.isShaderMaterial ||
  12686. material.isMeshPhongMaterial ||
  12687. material.isMeshStandardMaterial ||
  12688. material.envMap ) {
  12689. var uCamPos = p_uniforms.map.cameraPosition;
  12690. if ( uCamPos !== undefined ) {
  12691. uCamPos.setValue( _gl,
  12692. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12693. }
  12694. }
  12695. if ( material.isMeshPhongMaterial ||
  12696. material.isMeshLambertMaterial ||
  12697. material.isMeshBasicMaterial ||
  12698. material.isMeshStandardMaterial ||
  12699. material.isShaderMaterial ||
  12700. material.skinning ) {
  12701. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12702. }
  12703. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12704. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12705. }
  12706. // skinning uniforms must be set even if material didn't change
  12707. // auto-setting of texture unit for bone texture must go before other textures
  12708. // not sure why, but otherwise weird things happen
  12709. if ( material.skinning ) {
  12710. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12711. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12712. var skeleton = object.skeleton;
  12713. if ( skeleton ) {
  12714. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12715. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12716. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12717. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12718. } else {
  12719. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12720. }
  12721. }
  12722. }
  12723. if ( refreshMaterial ) {
  12724. if ( material.lights ) {
  12725. // the current material requires lighting info
  12726. // note: all lighting uniforms are always set correctly
  12727. // they simply reference the renderer's state for their
  12728. // values
  12729. //
  12730. // use the current material's .needsUpdate flags to set
  12731. // the GL state when required
  12732. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12733. }
  12734. // refresh uniforms common to several materials
  12735. if ( fog && material.fog ) {
  12736. refreshUniformsFog( m_uniforms, fog );
  12737. }
  12738. if ( material.isMeshBasicMaterial ||
  12739. material.isMeshLambertMaterial ||
  12740. material.isMeshPhongMaterial ||
  12741. material.isMeshStandardMaterial ||
  12742. material.isMeshNormalMaterial ||
  12743. material.isMeshDepthMaterial ) {
  12744. refreshUniformsCommon( m_uniforms, material );
  12745. }
  12746. // refresh single material specific uniforms
  12747. if ( material.isLineBasicMaterial ) {
  12748. refreshUniformsLine( m_uniforms, material );
  12749. } else if ( material.isLineDashedMaterial ) {
  12750. refreshUniformsLine( m_uniforms, material );
  12751. refreshUniformsDash( m_uniforms, material );
  12752. } else if ( material.isPointsMaterial ) {
  12753. refreshUniformsPoints( m_uniforms, material );
  12754. } else if ( material.isMeshLambertMaterial ) {
  12755. refreshUniformsLambert( m_uniforms, material );
  12756. } else if ( material.isMeshToonMaterial ) {
  12757. refreshUniformsToon( m_uniforms, material );
  12758. } else if ( material.isMeshPhongMaterial ) {
  12759. refreshUniformsPhong( m_uniforms, material );
  12760. } else if ( material.isMeshPhysicalMaterial ) {
  12761. refreshUniformsPhysical( m_uniforms, material );
  12762. } else if ( material.isMeshStandardMaterial ) {
  12763. refreshUniformsStandard( m_uniforms, material );
  12764. } else if ( material.isMeshDepthMaterial ) {
  12765. if ( material.displacementMap ) {
  12766. m_uniforms.displacementMap.value = material.displacementMap;
  12767. m_uniforms.displacementScale.value = material.displacementScale;
  12768. m_uniforms.displacementBias.value = material.displacementBias;
  12769. }
  12770. } else if ( material.isMeshNormalMaterial ) {
  12771. refreshUniformsNormal( m_uniforms, material );
  12772. }
  12773. // RectAreaLight Texture
  12774. // TODO (mrdoob): Find a nicer implementation
  12775. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  12776. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  12777. WebGLUniforms.upload(
  12778. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12779. }
  12780. // common matrices
  12781. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12782. p_uniforms.set( _gl, object, 'normalMatrix' );
  12783. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12784. return program;
  12785. }
  12786. // Uniforms (refresh uniforms objects)
  12787. function refreshUniformsCommon( uniforms, material ) {
  12788. uniforms.opacity.value = material.opacity;
  12789. uniforms.diffuse.value = material.color;
  12790. if ( material.emissive ) {
  12791. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12792. }
  12793. uniforms.map.value = material.map;
  12794. uniforms.specularMap.value = material.specularMap;
  12795. uniforms.alphaMap.value = material.alphaMap;
  12796. if ( material.lightMap ) {
  12797. uniforms.lightMap.value = material.lightMap;
  12798. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12799. }
  12800. if ( material.aoMap ) {
  12801. uniforms.aoMap.value = material.aoMap;
  12802. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12803. }
  12804. // uv repeat and offset setting priorities
  12805. // 1. color map
  12806. // 2. specular map
  12807. // 3. normal map
  12808. // 4. bump map
  12809. // 5. alpha map
  12810. // 6. emissive map
  12811. var uvScaleMap;
  12812. if ( material.map ) {
  12813. uvScaleMap = material.map;
  12814. } else if ( material.specularMap ) {
  12815. uvScaleMap = material.specularMap;
  12816. } else if ( material.displacementMap ) {
  12817. uvScaleMap = material.displacementMap;
  12818. } else if ( material.normalMap ) {
  12819. uvScaleMap = material.normalMap;
  12820. } else if ( material.bumpMap ) {
  12821. uvScaleMap = material.bumpMap;
  12822. } else if ( material.roughnessMap ) {
  12823. uvScaleMap = material.roughnessMap;
  12824. } else if ( material.metalnessMap ) {
  12825. uvScaleMap = material.metalnessMap;
  12826. } else if ( material.alphaMap ) {
  12827. uvScaleMap = material.alphaMap;
  12828. } else if ( material.emissiveMap ) {
  12829. uvScaleMap = material.emissiveMap;
  12830. }
  12831. if ( uvScaleMap !== undefined ) {
  12832. // backwards compatibility
  12833. if ( uvScaleMap.isWebGLRenderTarget ) {
  12834. uvScaleMap = uvScaleMap.texture;
  12835. }
  12836. var offset = uvScaleMap.offset;
  12837. var repeat = uvScaleMap.repeat;
  12838. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12839. }
  12840. uniforms.envMap.value = material.envMap;
  12841. // don't flip CubeTexture envMaps, flip everything else:
  12842. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12843. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12844. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12845. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12846. uniforms.reflectivity.value = material.reflectivity;
  12847. uniforms.refractionRatio.value = material.refractionRatio;
  12848. }
  12849. function refreshUniformsLine( uniforms, material ) {
  12850. uniforms.diffuse.value = material.color;
  12851. uniforms.opacity.value = material.opacity;
  12852. }
  12853. function refreshUniformsDash( uniforms, material ) {
  12854. uniforms.dashSize.value = material.dashSize;
  12855. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12856. uniforms.scale.value = material.scale;
  12857. }
  12858. function refreshUniformsPoints( uniforms, material ) {
  12859. uniforms.diffuse.value = material.color;
  12860. uniforms.opacity.value = material.opacity;
  12861. uniforms.size.value = material.size * _pixelRatio;
  12862. uniforms.scale.value = _height * 0.5;
  12863. uniforms.map.value = material.map;
  12864. if ( material.map !== null ) {
  12865. var offset = material.map.offset;
  12866. var repeat = material.map.repeat;
  12867. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12868. }
  12869. }
  12870. function refreshUniformsFog( uniforms, fog ) {
  12871. uniforms.fogColor.value = fog.color;
  12872. if ( fog.isFog ) {
  12873. uniforms.fogNear.value = fog.near;
  12874. uniforms.fogFar.value = fog.far;
  12875. } else if ( fog.isFogExp2 ) {
  12876. uniforms.fogDensity.value = fog.density;
  12877. }
  12878. }
  12879. function refreshUniformsLambert( uniforms, material ) {
  12880. if ( material.emissiveMap ) {
  12881. uniforms.emissiveMap.value = material.emissiveMap;
  12882. }
  12883. }
  12884. function refreshUniformsPhong( uniforms, material ) {
  12885. uniforms.specular.value = material.specular;
  12886. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12887. if ( material.emissiveMap ) {
  12888. uniforms.emissiveMap.value = material.emissiveMap;
  12889. }
  12890. if ( material.bumpMap ) {
  12891. uniforms.bumpMap.value = material.bumpMap;
  12892. uniforms.bumpScale.value = material.bumpScale;
  12893. }
  12894. if ( material.normalMap ) {
  12895. uniforms.normalMap.value = material.normalMap;
  12896. uniforms.normalScale.value.copy( material.normalScale );
  12897. }
  12898. if ( material.displacementMap ) {
  12899. uniforms.displacementMap.value = material.displacementMap;
  12900. uniforms.displacementScale.value = material.displacementScale;
  12901. uniforms.displacementBias.value = material.displacementBias;
  12902. }
  12903. }
  12904. function refreshUniformsToon( uniforms, material ) {
  12905. refreshUniformsPhong( uniforms, material );
  12906. if ( material.gradientMap ) {
  12907. uniforms.gradientMap.value = material.gradientMap;
  12908. }
  12909. }
  12910. function refreshUniformsStandard( uniforms, material ) {
  12911. uniforms.roughness.value = material.roughness;
  12912. uniforms.metalness.value = material.metalness;
  12913. if ( material.roughnessMap ) {
  12914. uniforms.roughnessMap.value = material.roughnessMap;
  12915. }
  12916. if ( material.metalnessMap ) {
  12917. uniforms.metalnessMap.value = material.metalnessMap;
  12918. }
  12919. if ( material.emissiveMap ) {
  12920. uniforms.emissiveMap.value = material.emissiveMap;
  12921. }
  12922. if ( material.bumpMap ) {
  12923. uniforms.bumpMap.value = material.bumpMap;
  12924. uniforms.bumpScale.value = material.bumpScale;
  12925. }
  12926. if ( material.normalMap ) {
  12927. uniforms.normalMap.value = material.normalMap;
  12928. uniforms.normalScale.value.copy( material.normalScale );
  12929. }
  12930. if ( material.displacementMap ) {
  12931. uniforms.displacementMap.value = material.displacementMap;
  12932. uniforms.displacementScale.value = material.displacementScale;
  12933. uniforms.displacementBias.value = material.displacementBias;
  12934. }
  12935. if ( material.envMap ) {
  12936. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12937. uniforms.envMapIntensity.value = material.envMapIntensity;
  12938. }
  12939. }
  12940. function refreshUniformsPhysical( uniforms, material ) {
  12941. uniforms.clearCoat.value = material.clearCoat;
  12942. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12943. refreshUniformsStandard( uniforms, material );
  12944. }
  12945. function refreshUniformsNormal( uniforms, material ) {
  12946. if ( material.bumpMap ) {
  12947. uniforms.bumpMap.value = material.bumpMap;
  12948. uniforms.bumpScale.value = material.bumpScale;
  12949. }
  12950. if ( material.normalMap ) {
  12951. uniforms.normalMap.value = material.normalMap;
  12952. uniforms.normalScale.value.copy( material.normalScale );
  12953. }
  12954. if ( material.displacementMap ) {
  12955. uniforms.displacementMap.value = material.displacementMap;
  12956. uniforms.displacementScale.value = material.displacementScale;
  12957. uniforms.displacementBias.value = material.displacementBias;
  12958. }
  12959. }
  12960. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12961. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12962. uniforms.ambientLightColor.needsUpdate = value;
  12963. uniforms.directionalLights.needsUpdate = value;
  12964. uniforms.pointLights.needsUpdate = value;
  12965. uniforms.spotLights.needsUpdate = value;
  12966. uniforms.rectAreaLights.needsUpdate = value;
  12967. uniforms.hemisphereLights.needsUpdate = value;
  12968. }
  12969. // Lighting
  12970. function setupShadows( lights ) {
  12971. var lightShadowsLength = 0;
  12972. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12973. var light = lights[ i ];
  12974. if ( light.castShadow ) {
  12975. _lights.shadows[ lightShadowsLength ++ ] = light;
  12976. }
  12977. }
  12978. _lights.shadows.length = lightShadowsLength;
  12979. }
  12980. function setupLights( lights, camera ) {
  12981. var l, ll, light,
  12982. r = 0, g = 0, b = 0,
  12983. color,
  12984. intensity,
  12985. distance,
  12986. shadowMap,
  12987. viewMatrix = camera.matrixWorldInverse,
  12988. directionalLength = 0,
  12989. pointLength = 0,
  12990. spotLength = 0,
  12991. rectAreaLength = 0,
  12992. hemiLength = 0;
  12993. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12994. light = lights[ l ];
  12995. color = light.color;
  12996. intensity = light.intensity;
  12997. distance = light.distance;
  12998. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12999. if ( light.isAmbientLight ) {
  13000. r += color.r * intensity;
  13001. g += color.g * intensity;
  13002. b += color.b * intensity;
  13003. } else if ( light.isDirectionalLight ) {
  13004. var uniforms = lightCache.get( light );
  13005. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13006. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13007. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13008. uniforms.direction.sub( _vector3 );
  13009. uniforms.direction.transformDirection( viewMatrix );
  13010. uniforms.shadow = light.castShadow;
  13011. if ( light.castShadow ) {
  13012. uniforms.shadowBias = light.shadow.bias;
  13013. uniforms.shadowRadius = light.shadow.radius;
  13014. uniforms.shadowMapSize = light.shadow.mapSize;
  13015. }
  13016. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  13017. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13018. _lights.directional[ directionalLength ++ ] = uniforms;
  13019. } else if ( light.isSpotLight ) {
  13020. var uniforms = lightCache.get( light );
  13021. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13022. uniforms.position.applyMatrix4( viewMatrix );
  13023. uniforms.color.copy( color ).multiplyScalar( intensity );
  13024. uniforms.distance = distance;
  13025. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13026. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13027. uniforms.direction.sub( _vector3 );
  13028. uniforms.direction.transformDirection( viewMatrix );
  13029. uniforms.coneCos = Math.cos( light.angle );
  13030. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13031. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13032. uniforms.shadow = light.castShadow;
  13033. if ( light.castShadow ) {
  13034. uniforms.shadowBias = light.shadow.bias;
  13035. uniforms.shadowRadius = light.shadow.radius;
  13036. uniforms.shadowMapSize = light.shadow.mapSize;
  13037. }
  13038. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13039. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13040. _lights.spot[ spotLength ++ ] = uniforms;
  13041. } else if ( light.isRectAreaLight ) {
  13042. var uniforms = lightCache.get( light );
  13043. // (a) intensity controls irradiance of entire light
  13044. uniforms.color
  13045. .copy( color )
  13046. .multiplyScalar( intensity / ( light.width * light.height ) );
  13047. // (b) intensity controls the radiance per light area
  13048. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13049. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13050. uniforms.position.applyMatrix4( viewMatrix );
  13051. // extract local rotation of light to derive width/height half vectors
  13052. _matrix42.identity();
  13053. _matrix4.copy( light.matrixWorld );
  13054. _matrix4.premultiply( viewMatrix );
  13055. _matrix42.extractRotation( _matrix4 );
  13056. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13057. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13058. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13059. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13060. // TODO (abelnation): RectAreaLight distance?
  13061. // uniforms.distance = distance;
  13062. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  13063. } else if ( light.isPointLight ) {
  13064. var uniforms = lightCache.get( light );
  13065. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13066. uniforms.position.applyMatrix4( viewMatrix );
  13067. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13068. uniforms.distance = light.distance;
  13069. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13070. uniforms.shadow = light.castShadow;
  13071. if ( light.castShadow ) {
  13072. uniforms.shadowBias = light.shadow.bias;
  13073. uniforms.shadowRadius = light.shadow.radius;
  13074. uniforms.shadowMapSize = light.shadow.mapSize;
  13075. }
  13076. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13077. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  13078. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  13079. }
  13080. // for point lights we set the shadow matrix to be a translation-only matrix
  13081. // equal to inverse of the light's position
  13082. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  13083. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  13084. _lights.point[ pointLength ++ ] = uniforms;
  13085. } else if ( light.isHemisphereLight ) {
  13086. var uniforms = lightCache.get( light );
  13087. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13088. uniforms.direction.transformDirection( viewMatrix );
  13089. uniforms.direction.normalize();
  13090. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13091. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13092. _lights.hemi[ hemiLength ++ ] = uniforms;
  13093. }
  13094. }
  13095. _lights.ambient[ 0 ] = r;
  13096. _lights.ambient[ 1 ] = g;
  13097. _lights.ambient[ 2 ] = b;
  13098. _lights.directional.length = directionalLength;
  13099. _lights.spot.length = spotLength;
  13100. _lights.rectArea.length = rectAreaLength;
  13101. _lights.point.length = pointLength;
  13102. _lights.hemi.length = hemiLength;
  13103. // TODO (sam-g-steel) why aren't we using join
  13104. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13105. }
  13106. // GL state setting
  13107. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13108. state.setCullFace( cullFace );
  13109. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13110. };
  13111. // Textures
  13112. function allocTextureUnit() {
  13113. var textureUnit = _usedTextureUnits;
  13114. if ( textureUnit >= capabilities.maxTextures ) {
  13115. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13116. }
  13117. _usedTextureUnits += 1;
  13118. return textureUnit;
  13119. }
  13120. this.allocTextureUnit = allocTextureUnit;
  13121. // this.setTexture2D = setTexture2D;
  13122. this.setTexture2D = ( function() {
  13123. var warned = false;
  13124. // backwards compatibility: peel texture.texture
  13125. return function setTexture2D( texture, slot ) {
  13126. if ( texture && texture.isWebGLRenderTarget ) {
  13127. if ( ! warned ) {
  13128. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13129. warned = true;
  13130. }
  13131. texture = texture.texture;
  13132. }
  13133. textures.setTexture2D( texture, slot );
  13134. };
  13135. }() );
  13136. this.setTexture = ( function() {
  13137. var warned = false;
  13138. return function setTexture( texture, slot ) {
  13139. if ( ! warned ) {
  13140. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13141. warned = true;
  13142. }
  13143. textures.setTexture2D( texture, slot );
  13144. };
  13145. }() );
  13146. this.setTextureCube = ( function() {
  13147. var warned = false;
  13148. return function setTextureCube( texture, slot ) {
  13149. // backwards compatibility: peel texture.texture
  13150. if ( texture && texture.isWebGLRenderTargetCube ) {
  13151. if ( ! warned ) {
  13152. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13153. warned = true;
  13154. }
  13155. texture = texture.texture;
  13156. }
  13157. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13158. // TODO: unify these code paths
  13159. if ( ( texture && texture.isCubeTexture ) ||
  13160. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13161. // CompressedTexture can have Array in image :/
  13162. // this function alone should take care of cube textures
  13163. textures.setTextureCube( texture, slot );
  13164. } else {
  13165. // assumed: texture property of THREE.WebGLRenderTargetCube
  13166. textures.setTextureCubeDynamic( texture, slot );
  13167. }
  13168. };
  13169. }() );
  13170. this.getCurrentRenderTarget = function() {
  13171. return _currentRenderTarget;
  13172. };
  13173. this.setRenderTarget = function ( renderTarget ) {
  13174. _currentRenderTarget = renderTarget;
  13175. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13176. textures.setupRenderTarget( renderTarget );
  13177. }
  13178. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13179. var framebuffer;
  13180. if ( renderTarget ) {
  13181. var renderTargetProperties = properties.get( renderTarget );
  13182. if ( isCube ) {
  13183. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13184. } else {
  13185. framebuffer = renderTargetProperties.__webglFramebuffer;
  13186. }
  13187. _currentScissor.copy( renderTarget.scissor );
  13188. _currentScissorTest = renderTarget.scissorTest;
  13189. _currentViewport.copy( renderTarget.viewport );
  13190. } else {
  13191. framebuffer = null;
  13192. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13193. _currentScissorTest = _scissorTest;
  13194. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13195. }
  13196. if ( _currentFramebuffer !== framebuffer ) {
  13197. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13198. _currentFramebuffer = framebuffer;
  13199. }
  13200. state.scissor( _currentScissor );
  13201. state.setScissorTest( _currentScissorTest );
  13202. state.viewport( _currentViewport );
  13203. if ( isCube ) {
  13204. var textureProperties = properties.get( renderTarget.texture );
  13205. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13206. }
  13207. };
  13208. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13209. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13210. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13211. return;
  13212. }
  13213. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13214. if ( framebuffer ) {
  13215. var restore = false;
  13216. if ( framebuffer !== _currentFramebuffer ) {
  13217. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13218. restore = true;
  13219. }
  13220. try {
  13221. var texture = renderTarget.texture;
  13222. var textureFormat = texture.format;
  13223. var textureType = texture.type;
  13224. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13225. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13226. return;
  13227. }
  13228. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13229. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13230. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13231. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13232. return;
  13233. }
  13234. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13235. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13236. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13237. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13238. }
  13239. } else {
  13240. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13241. }
  13242. } finally {
  13243. if ( restore ) {
  13244. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13245. }
  13246. }
  13247. }
  13248. };
  13249. // Map three.js constants to WebGL constants
  13250. function paramThreeToGL( p ) {
  13251. var extension;
  13252. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13253. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13254. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13255. if ( p === NearestFilter ) return _gl.NEAREST;
  13256. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13257. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13258. if ( p === LinearFilter ) return _gl.LINEAR;
  13259. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13260. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13261. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13262. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13263. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13264. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13265. if ( p === ByteType ) return _gl.BYTE;
  13266. if ( p === ShortType ) return _gl.SHORT;
  13267. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13268. if ( p === IntType ) return _gl.INT;
  13269. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13270. if ( p === FloatType ) return _gl.FLOAT;
  13271. if ( p === HalfFloatType ) {
  13272. extension = extensions.get( 'OES_texture_half_float' );
  13273. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13274. }
  13275. if ( p === AlphaFormat ) return _gl.ALPHA;
  13276. if ( p === RGBFormat ) return _gl.RGB;
  13277. if ( p === RGBAFormat ) return _gl.RGBA;
  13278. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13279. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13280. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13281. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13282. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13283. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13284. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13285. if ( p === ZeroFactor ) return _gl.ZERO;
  13286. if ( p === OneFactor ) return _gl.ONE;
  13287. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13288. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13289. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13290. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13291. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13292. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13293. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13294. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13295. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13296. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13297. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13298. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13299. if ( extension !== null ) {
  13300. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13301. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13302. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13303. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13304. }
  13305. }
  13306. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13307. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13308. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13309. if ( extension !== null ) {
  13310. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13311. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13312. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13313. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13314. }
  13315. }
  13316. if ( p === RGB_ETC1_Format ) {
  13317. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13318. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13319. }
  13320. if ( p === MinEquation || p === MaxEquation ) {
  13321. extension = extensions.get( 'EXT_blend_minmax' );
  13322. if ( extension !== null ) {
  13323. if ( p === MinEquation ) return extension.MIN_EXT;
  13324. if ( p === MaxEquation ) return extension.MAX_EXT;
  13325. }
  13326. }
  13327. if ( p === UnsignedInt248Type ) {
  13328. extension = extensions.get( 'WEBGL_depth_texture' );
  13329. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13330. }
  13331. return 0;
  13332. }
  13333. }
  13334. /**
  13335. * @author mrdoob / http://mrdoob.com/
  13336. * @author alteredq / http://alteredqualia.com/
  13337. */
  13338. function FogExp2 ( color, density ) {
  13339. this.name = '';
  13340. this.color = new Color( color );
  13341. this.density = ( density !== undefined ) ? density : 0.00025;
  13342. }
  13343. FogExp2.prototype.isFogExp2 = true;
  13344. FogExp2.prototype.clone = function () {
  13345. return new FogExp2( this.color.getHex(), this.density );
  13346. };
  13347. FogExp2.prototype.toJSON = function ( meta ) {
  13348. return {
  13349. type: 'FogExp2',
  13350. color: this.color.getHex(),
  13351. density: this.density
  13352. };
  13353. };
  13354. /**
  13355. * @author mrdoob / http://mrdoob.com/
  13356. * @author alteredq / http://alteredqualia.com/
  13357. */
  13358. function Fog ( color, near, far ) {
  13359. this.name = '';
  13360. this.color = new Color( color );
  13361. this.near = ( near !== undefined ) ? near : 1;
  13362. this.far = ( far !== undefined ) ? far : 1000;
  13363. }
  13364. Fog.prototype.isFog = true;
  13365. Fog.prototype.clone = function () {
  13366. return new Fog( this.color.getHex(), this.near, this.far );
  13367. };
  13368. Fog.prototype.toJSON = function ( meta ) {
  13369. return {
  13370. type: 'Fog',
  13371. color: this.color.getHex(),
  13372. near: this.near,
  13373. far: this.far
  13374. };
  13375. };
  13376. /**
  13377. * @author mrdoob / http://mrdoob.com/
  13378. */
  13379. function Scene () {
  13380. Object3D.call( this );
  13381. this.type = 'Scene';
  13382. this.background = null;
  13383. this.fog = null;
  13384. this.overrideMaterial = null;
  13385. this.autoUpdate = true; // checked by the renderer
  13386. }
  13387. Scene.prototype = Object.create( Object3D.prototype );
  13388. Scene.prototype.constructor = Scene;
  13389. Scene.prototype.copy = function ( source, recursive ) {
  13390. Object3D.prototype.copy.call( this, source, recursive );
  13391. if ( source.background !== null ) this.background = source.background.clone();
  13392. if ( source.fog !== null ) this.fog = source.fog.clone();
  13393. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13394. this.autoUpdate = source.autoUpdate;
  13395. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13396. return this;
  13397. };
  13398. Scene.prototype.toJSON = function ( meta ) {
  13399. var data = Object3D.prototype.toJSON.call( this, meta );
  13400. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13401. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13402. return data;
  13403. };
  13404. /**
  13405. * @author mikael emtinger / http://gomo.se/
  13406. * @author alteredq / http://alteredqualia.com/
  13407. */
  13408. function LensFlare( texture, size, distance, blending, color ) {
  13409. Object3D.call( this );
  13410. this.lensFlares = [];
  13411. this.positionScreen = new Vector3();
  13412. this.customUpdateCallback = undefined;
  13413. if ( texture !== undefined ) {
  13414. this.add( texture, size, distance, blending, color );
  13415. }
  13416. }
  13417. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13418. constructor: LensFlare,
  13419. isLensFlare: true,
  13420. copy: function ( source ) {
  13421. Object3D.prototype.copy.call( this, source );
  13422. this.positionScreen.copy( source.positionScreen );
  13423. this.customUpdateCallback = source.customUpdateCallback;
  13424. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13425. this.lensFlares.push( source.lensFlares[ i ] );
  13426. }
  13427. return this;
  13428. },
  13429. add: function ( texture, size, distance, blending, color, opacity ) {
  13430. if ( size === undefined ) size = - 1;
  13431. if ( distance === undefined ) distance = 0;
  13432. if ( opacity === undefined ) opacity = 1;
  13433. if ( color === undefined ) color = new Color( 0xffffff );
  13434. if ( blending === undefined ) blending = NormalBlending;
  13435. distance = Math.min( distance, Math.max( 0, distance ) );
  13436. this.lensFlares.push( {
  13437. texture: texture, // THREE.Texture
  13438. size: size, // size in pixels (-1 = use texture.width)
  13439. distance: distance, // distance (0-1) from light source (0=at light source)
  13440. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13441. scale: 1, // scale
  13442. rotation: 0, // rotation
  13443. opacity: opacity, // opacity
  13444. color: color, // color
  13445. blending: blending // blending
  13446. } );
  13447. },
  13448. /*
  13449. * Update lens flares update positions on all flares based on the screen position
  13450. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13451. */
  13452. updateLensFlares: function () {
  13453. var f, fl = this.lensFlares.length;
  13454. var flare;
  13455. var vecX = - this.positionScreen.x * 2;
  13456. var vecY = - this.positionScreen.y * 2;
  13457. for ( f = 0; f < fl; f ++ ) {
  13458. flare = this.lensFlares[ f ];
  13459. flare.x = this.positionScreen.x + vecX * flare.distance;
  13460. flare.y = this.positionScreen.y + vecY * flare.distance;
  13461. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13462. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13463. }
  13464. }
  13465. } );
  13466. /**
  13467. * @author alteredq / http://alteredqualia.com/
  13468. *
  13469. * parameters = {
  13470. * color: <hex>,
  13471. * opacity: <float>,
  13472. * map: new THREE.Texture( <Image> ),
  13473. *
  13474. * uvOffset: new THREE.Vector2(),
  13475. * uvScale: new THREE.Vector2()
  13476. * }
  13477. */
  13478. function SpriteMaterial( parameters ) {
  13479. Material.call( this );
  13480. this.type = 'SpriteMaterial';
  13481. this.color = new Color( 0xffffff );
  13482. this.map = null;
  13483. this.rotation = 0;
  13484. this.fog = false;
  13485. this.lights = false;
  13486. this.setValues( parameters );
  13487. }
  13488. SpriteMaterial.prototype = Object.create( Material.prototype );
  13489. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13490. SpriteMaterial.prototype.copy = function ( source ) {
  13491. Material.prototype.copy.call( this, source );
  13492. this.color.copy( source.color );
  13493. this.map = source.map;
  13494. this.rotation = source.rotation;
  13495. return this;
  13496. };
  13497. /**
  13498. * @author mikael emtinger / http://gomo.se/
  13499. * @author alteredq / http://alteredqualia.com/
  13500. */
  13501. function Sprite( material ) {
  13502. Object3D.call( this );
  13503. this.type = 'Sprite';
  13504. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13505. }
  13506. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13507. constructor: Sprite,
  13508. isSprite: true,
  13509. raycast: ( function () {
  13510. var matrixPosition = new Vector3();
  13511. return function raycast( raycaster, intersects ) {
  13512. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13513. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13514. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13515. if ( distanceSq > guessSizeSq ) {
  13516. return;
  13517. }
  13518. intersects.push( {
  13519. distance: Math.sqrt( distanceSq ),
  13520. point: this.position,
  13521. face: null,
  13522. object: this
  13523. } );
  13524. };
  13525. }() ),
  13526. clone: function () {
  13527. return new this.constructor( this.material ).copy( this );
  13528. }
  13529. } );
  13530. /**
  13531. * @author mikael emtinger / http://gomo.se/
  13532. * @author alteredq / http://alteredqualia.com/
  13533. * @author mrdoob / http://mrdoob.com/
  13534. */
  13535. function LOD() {
  13536. Object3D.call( this );
  13537. this.type = 'LOD';
  13538. Object.defineProperties( this, {
  13539. levels: {
  13540. enumerable: true,
  13541. value: []
  13542. }
  13543. } );
  13544. }
  13545. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13546. constructor: LOD,
  13547. copy: function ( source ) {
  13548. Object3D.prototype.copy.call( this, source, false );
  13549. var levels = source.levels;
  13550. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13551. var level = levels[ i ];
  13552. this.addLevel( level.object.clone(), level.distance );
  13553. }
  13554. return this;
  13555. },
  13556. addLevel: function ( object, distance ) {
  13557. if ( distance === undefined ) distance = 0;
  13558. distance = Math.abs( distance );
  13559. var levels = this.levels;
  13560. for ( var l = 0; l < levels.length; l ++ ) {
  13561. if ( distance < levels[ l ].distance ) {
  13562. break;
  13563. }
  13564. }
  13565. levels.splice( l, 0, { distance: distance, object: object } );
  13566. this.add( object );
  13567. },
  13568. getObjectForDistance: function ( distance ) {
  13569. var levels = this.levels;
  13570. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13571. if ( distance < levels[ i ].distance ) {
  13572. break;
  13573. }
  13574. }
  13575. return levels[ i - 1 ].object;
  13576. },
  13577. raycast: ( function () {
  13578. var matrixPosition = new Vector3();
  13579. return function raycast( raycaster, intersects ) {
  13580. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13581. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13582. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13583. };
  13584. }() ),
  13585. update: function () {
  13586. var v1 = new Vector3();
  13587. var v2 = new Vector3();
  13588. return function update( camera ) {
  13589. var levels = this.levels;
  13590. if ( levels.length > 1 ) {
  13591. v1.setFromMatrixPosition( camera.matrixWorld );
  13592. v2.setFromMatrixPosition( this.matrixWorld );
  13593. var distance = v1.distanceTo( v2 );
  13594. levels[ 0 ].object.visible = true;
  13595. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13596. if ( distance >= levels[ i ].distance ) {
  13597. levels[ i - 1 ].object.visible = false;
  13598. levels[ i ].object.visible = true;
  13599. } else {
  13600. break;
  13601. }
  13602. }
  13603. for ( ; i < l; i ++ ) {
  13604. levels[ i ].object.visible = false;
  13605. }
  13606. }
  13607. };
  13608. }(),
  13609. toJSON: function ( meta ) {
  13610. var data = Object3D.prototype.toJSON.call( this, meta );
  13611. data.object.levels = [];
  13612. var levels = this.levels;
  13613. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13614. var level = levels[ i ];
  13615. data.object.levels.push( {
  13616. object: level.object.uuid,
  13617. distance: level.distance
  13618. } );
  13619. }
  13620. return data;
  13621. }
  13622. } );
  13623. /**
  13624. * @author mikael emtinger / http://gomo.se/
  13625. * @author alteredq / http://alteredqualia.com/
  13626. * @author michael guerrero / http://realitymeltdown.com
  13627. * @author ikerr / http://verold.com
  13628. */
  13629. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13630. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13631. this.identityMatrix = new Matrix4();
  13632. // copy the bone array
  13633. bones = bones || [];
  13634. this.bones = bones.slice( 0 );
  13635. // create a bone texture or an array of floats
  13636. if ( this.useVertexTexture ) {
  13637. // layout (1 matrix = 4 pixels)
  13638. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13639. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13640. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13641. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13642. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13643. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13644. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13645. size = Math.max( size, 4 );
  13646. this.boneTextureWidth = size;
  13647. this.boneTextureHeight = size;
  13648. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13649. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13650. } else {
  13651. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13652. }
  13653. // use the supplied bone inverses or calculate the inverses
  13654. if ( boneInverses === undefined ) {
  13655. this.calculateInverses();
  13656. } else {
  13657. if ( this.bones.length === boneInverses.length ) {
  13658. this.boneInverses = boneInverses.slice( 0 );
  13659. } else {
  13660. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13661. this.boneInverses = [];
  13662. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13663. this.boneInverses.push( new Matrix4() );
  13664. }
  13665. }
  13666. }
  13667. }
  13668. Object.assign( Skeleton.prototype, {
  13669. calculateInverses: function () {
  13670. this.boneInverses = [];
  13671. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13672. var inverse = new Matrix4();
  13673. if ( this.bones[ b ] ) {
  13674. inverse.getInverse( this.bones[ b ].matrixWorld );
  13675. }
  13676. this.boneInverses.push( inverse );
  13677. }
  13678. },
  13679. pose: function () {
  13680. var bone;
  13681. // recover the bind-time world matrices
  13682. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13683. bone = this.bones[ b ];
  13684. if ( bone ) {
  13685. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13686. }
  13687. }
  13688. // compute the local matrices, positions, rotations and scales
  13689. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13690. bone = this.bones[ b ];
  13691. if ( bone ) {
  13692. if ( bone.parent && bone.parent.isBone ) {
  13693. bone.matrix.getInverse( bone.parent.matrixWorld );
  13694. bone.matrix.multiply( bone.matrixWorld );
  13695. } else {
  13696. bone.matrix.copy( bone.matrixWorld );
  13697. }
  13698. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13699. }
  13700. }
  13701. },
  13702. update: ( function () {
  13703. var offsetMatrix = new Matrix4();
  13704. return function update() {
  13705. // flatten bone matrices to array
  13706. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13707. // compute the offset between the current and the original transform
  13708. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13709. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13710. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13711. }
  13712. if ( this.useVertexTexture ) {
  13713. this.boneTexture.needsUpdate = true;
  13714. }
  13715. };
  13716. } )(),
  13717. clone: function () {
  13718. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13719. }
  13720. } );
  13721. /**
  13722. * @author mikael emtinger / http://gomo.se/
  13723. * @author alteredq / http://alteredqualia.com/
  13724. * @author ikerr / http://verold.com
  13725. */
  13726. function Bone() {
  13727. Object3D.call( this );
  13728. this.type = 'Bone';
  13729. }
  13730. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13731. constructor: Bone,
  13732. isBone: true
  13733. } );
  13734. /**
  13735. * @author mikael emtinger / http://gomo.se/
  13736. * @author alteredq / http://alteredqualia.com/
  13737. * @author ikerr / http://verold.com
  13738. */
  13739. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13740. Mesh.call( this, geometry, material );
  13741. this.type = 'SkinnedMesh';
  13742. this.bindMode = "attached";
  13743. this.bindMatrix = new Matrix4();
  13744. this.bindMatrixInverse = new Matrix4();
  13745. // init bones
  13746. // TODO: remove bone creation as there is no reason (other than
  13747. // convenience) for THREE.SkinnedMesh to do this.
  13748. var bones = [];
  13749. if ( this.geometry && this.geometry.bones !== undefined ) {
  13750. var bone, gbone;
  13751. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13752. gbone = this.geometry.bones[ b ];
  13753. bone = new Bone();
  13754. bones.push( bone );
  13755. bone.name = gbone.name;
  13756. bone.position.fromArray( gbone.pos );
  13757. bone.quaternion.fromArray( gbone.rotq );
  13758. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13759. }
  13760. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13761. gbone = this.geometry.bones[ b ];
  13762. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13763. bones[ gbone.parent ] !== undefined ) {
  13764. bones[ gbone.parent ].add( bones[ b ] );
  13765. } else {
  13766. this.add( bones[ b ] );
  13767. }
  13768. }
  13769. }
  13770. this.normalizeSkinWeights();
  13771. this.updateMatrixWorld( true );
  13772. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13773. }
  13774. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13775. constructor: SkinnedMesh,
  13776. isSkinnedMesh: true,
  13777. bind: function( skeleton, bindMatrix ) {
  13778. this.skeleton = skeleton;
  13779. if ( bindMatrix === undefined ) {
  13780. this.updateMatrixWorld( true );
  13781. this.skeleton.calculateInverses();
  13782. bindMatrix = this.matrixWorld;
  13783. }
  13784. this.bindMatrix.copy( bindMatrix );
  13785. this.bindMatrixInverse.getInverse( bindMatrix );
  13786. },
  13787. pose: function () {
  13788. this.skeleton.pose();
  13789. },
  13790. normalizeSkinWeights: function () {
  13791. if ( this.geometry && this.geometry.isGeometry ) {
  13792. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13793. var sw = this.geometry.skinWeights[ i ];
  13794. var scale = 1.0 / sw.lengthManhattan();
  13795. if ( scale !== Infinity ) {
  13796. sw.multiplyScalar( scale );
  13797. } else {
  13798. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13799. }
  13800. }
  13801. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13802. var vec = new Vector4();
  13803. var skinWeight = this.geometry.attributes.skinWeight;
  13804. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13805. vec.x = skinWeight.getX( i );
  13806. vec.y = skinWeight.getY( i );
  13807. vec.z = skinWeight.getZ( i );
  13808. vec.w = skinWeight.getW( i );
  13809. var scale = 1.0 / vec.lengthManhattan();
  13810. if ( scale !== Infinity ) {
  13811. vec.multiplyScalar( scale );
  13812. } else {
  13813. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13814. }
  13815. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13816. }
  13817. }
  13818. },
  13819. updateMatrixWorld: function( force ) {
  13820. Mesh.prototype.updateMatrixWorld.call( this, true );
  13821. if ( this.bindMode === "attached" ) {
  13822. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13823. } else if ( this.bindMode === "detached" ) {
  13824. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13825. } else {
  13826. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13827. }
  13828. },
  13829. clone: function() {
  13830. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13831. }
  13832. } );
  13833. /**
  13834. * @author mrdoob / http://mrdoob.com/
  13835. * @author alteredq / http://alteredqualia.com/
  13836. *
  13837. * parameters = {
  13838. * color: <hex>,
  13839. * opacity: <float>,
  13840. *
  13841. * linewidth: <float>,
  13842. * linecap: "round",
  13843. * linejoin: "round"
  13844. * }
  13845. */
  13846. function LineBasicMaterial( parameters ) {
  13847. Material.call( this );
  13848. this.type = 'LineBasicMaterial';
  13849. this.color = new Color( 0xffffff );
  13850. this.linewidth = 1;
  13851. this.linecap = 'round';
  13852. this.linejoin = 'round';
  13853. this.lights = false;
  13854. this.setValues( parameters );
  13855. }
  13856. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13857. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13858. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13859. LineBasicMaterial.prototype.copy = function ( source ) {
  13860. Material.prototype.copy.call( this, source );
  13861. this.color.copy( source.color );
  13862. this.linewidth = source.linewidth;
  13863. this.linecap = source.linecap;
  13864. this.linejoin = source.linejoin;
  13865. return this;
  13866. };
  13867. /**
  13868. * @author mrdoob / http://mrdoob.com/
  13869. */
  13870. function Line( geometry, material, mode ) {
  13871. if ( mode === 1 ) {
  13872. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13873. return new LineSegments( geometry, material );
  13874. }
  13875. Object3D.call( this );
  13876. this.type = 'Line';
  13877. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13878. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13879. }
  13880. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13881. constructor: Line,
  13882. isLine: true,
  13883. raycast: ( function () {
  13884. var inverseMatrix = new Matrix4();
  13885. var ray = new Ray();
  13886. var sphere = new Sphere();
  13887. return function raycast( raycaster, intersects ) {
  13888. var precision = raycaster.linePrecision;
  13889. var precisionSq = precision * precision;
  13890. var geometry = this.geometry;
  13891. var matrixWorld = this.matrixWorld;
  13892. // Checking boundingSphere distance to ray
  13893. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13894. sphere.copy( geometry.boundingSphere );
  13895. sphere.applyMatrix4( matrixWorld );
  13896. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13897. //
  13898. inverseMatrix.getInverse( matrixWorld );
  13899. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13900. var vStart = new Vector3();
  13901. var vEnd = new Vector3();
  13902. var interSegment = new Vector3();
  13903. var interRay = new Vector3();
  13904. var step = (this && this.isLineSegments) ? 2 : 1;
  13905. if ( geometry.isBufferGeometry ) {
  13906. var index = geometry.index;
  13907. var attributes = geometry.attributes;
  13908. var positions = attributes.position.array;
  13909. if ( index !== null ) {
  13910. var indices = index.array;
  13911. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13912. var a = indices[ i ];
  13913. var b = indices[ i + 1 ];
  13914. vStart.fromArray( positions, a * 3 );
  13915. vEnd.fromArray( positions, b * 3 );
  13916. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13917. if ( distSq > precisionSq ) continue;
  13918. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13919. var distance = raycaster.ray.origin.distanceTo( interRay );
  13920. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13921. intersects.push( {
  13922. distance: distance,
  13923. // What do we want? intersection point on the ray or on the segment??
  13924. // point: raycaster.ray.at( distance ),
  13925. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13926. index: i,
  13927. face: null,
  13928. faceIndex: null,
  13929. object: this
  13930. } );
  13931. }
  13932. } else {
  13933. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13934. vStart.fromArray( positions, 3 * i );
  13935. vEnd.fromArray( positions, 3 * i + 3 );
  13936. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13937. if ( distSq > precisionSq ) continue;
  13938. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13939. var distance = raycaster.ray.origin.distanceTo( interRay );
  13940. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13941. intersects.push( {
  13942. distance: distance,
  13943. // What do we want? intersection point on the ray or on the segment??
  13944. // point: raycaster.ray.at( distance ),
  13945. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13946. index: i,
  13947. face: null,
  13948. faceIndex: null,
  13949. object: this
  13950. } );
  13951. }
  13952. }
  13953. } else if ( geometry.isGeometry ) {
  13954. var vertices = geometry.vertices;
  13955. var nbVertices = vertices.length;
  13956. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13957. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13958. if ( distSq > precisionSq ) continue;
  13959. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13960. var distance = raycaster.ray.origin.distanceTo( interRay );
  13961. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13962. intersects.push( {
  13963. distance: distance,
  13964. // What do we want? intersection point on the ray or on the segment??
  13965. // point: raycaster.ray.at( distance ),
  13966. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13967. index: i,
  13968. face: null,
  13969. faceIndex: null,
  13970. object: this
  13971. } );
  13972. }
  13973. }
  13974. };
  13975. }() ),
  13976. clone: function () {
  13977. return new this.constructor( this.geometry, this.material ).copy( this );
  13978. }
  13979. } );
  13980. /**
  13981. * @author mrdoob / http://mrdoob.com/
  13982. */
  13983. function LineSegments( geometry, material ) {
  13984. Line.call( this, geometry, material );
  13985. this.type = 'LineSegments';
  13986. }
  13987. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13988. constructor: LineSegments,
  13989. isLineSegments: true
  13990. } );
  13991. /**
  13992. * @author mrdoob / http://mrdoob.com/
  13993. * @author alteredq / http://alteredqualia.com/
  13994. *
  13995. * parameters = {
  13996. * color: <hex>,
  13997. * opacity: <float>,
  13998. * map: new THREE.Texture( <Image> ),
  13999. *
  14000. * size: <float>,
  14001. * sizeAttenuation: <bool>
  14002. * }
  14003. */
  14004. function PointsMaterial( parameters ) {
  14005. Material.call( this );
  14006. this.type = 'PointsMaterial';
  14007. this.color = new Color( 0xffffff );
  14008. this.map = null;
  14009. this.size = 1;
  14010. this.sizeAttenuation = true;
  14011. this.lights = false;
  14012. this.setValues( parameters );
  14013. }
  14014. PointsMaterial.prototype = Object.create( Material.prototype );
  14015. PointsMaterial.prototype.constructor = PointsMaterial;
  14016. PointsMaterial.prototype.isPointsMaterial = true;
  14017. PointsMaterial.prototype.copy = function ( source ) {
  14018. Material.prototype.copy.call( this, source );
  14019. this.color.copy( source.color );
  14020. this.map = source.map;
  14021. this.size = source.size;
  14022. this.sizeAttenuation = source.sizeAttenuation;
  14023. return this;
  14024. };
  14025. /**
  14026. * @author alteredq / http://alteredqualia.com/
  14027. */
  14028. function Points( geometry, material ) {
  14029. Object3D.call( this );
  14030. this.type = 'Points';
  14031. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14032. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14033. }
  14034. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14035. constructor: Points,
  14036. isPoints: true,
  14037. raycast: ( function () {
  14038. var inverseMatrix = new Matrix4();
  14039. var ray = new Ray();
  14040. var sphere = new Sphere();
  14041. return function raycast( raycaster, intersects ) {
  14042. var object = this;
  14043. var geometry = this.geometry;
  14044. var matrixWorld = this.matrixWorld;
  14045. var threshold = raycaster.params.Points.threshold;
  14046. // Checking boundingSphere distance to ray
  14047. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14048. sphere.copy( geometry.boundingSphere );
  14049. sphere.applyMatrix4( matrixWorld );
  14050. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14051. //
  14052. inverseMatrix.getInverse( matrixWorld );
  14053. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14054. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14055. var localThresholdSq = localThreshold * localThreshold;
  14056. var position = new Vector3();
  14057. function testPoint( point, index ) {
  14058. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14059. if ( rayPointDistanceSq < localThresholdSq ) {
  14060. var intersectPoint = ray.closestPointToPoint( point );
  14061. intersectPoint.applyMatrix4( matrixWorld );
  14062. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14063. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14064. intersects.push( {
  14065. distance: distance,
  14066. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14067. point: intersectPoint.clone(),
  14068. index: index,
  14069. face: null,
  14070. object: object
  14071. } );
  14072. }
  14073. }
  14074. if ( geometry.isBufferGeometry ) {
  14075. var index = geometry.index;
  14076. var attributes = geometry.attributes;
  14077. var positions = attributes.position.array;
  14078. if ( index !== null ) {
  14079. var indices = index.array;
  14080. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14081. var a = indices[ i ];
  14082. position.fromArray( positions, a * 3 );
  14083. testPoint( position, a );
  14084. }
  14085. } else {
  14086. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14087. position.fromArray( positions, i * 3 );
  14088. testPoint( position, i );
  14089. }
  14090. }
  14091. } else {
  14092. var vertices = geometry.vertices;
  14093. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14094. testPoint( vertices[ i ], i );
  14095. }
  14096. }
  14097. };
  14098. }() ),
  14099. clone: function () {
  14100. return new this.constructor( this.geometry, this.material ).copy( this );
  14101. }
  14102. } );
  14103. /**
  14104. * @author mrdoob / http://mrdoob.com/
  14105. */
  14106. function Group() {
  14107. Object3D.call( this );
  14108. this.type = 'Group';
  14109. }
  14110. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14111. constructor: Group
  14112. } );
  14113. /**
  14114. * @author mrdoob / http://mrdoob.com/
  14115. */
  14116. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14117. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14118. this.generateMipmaps = false;
  14119. var scope = this;
  14120. function update() {
  14121. requestAnimationFrame( update );
  14122. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14123. scope.needsUpdate = true;
  14124. }
  14125. }
  14126. update();
  14127. }
  14128. VideoTexture.prototype = Object.create( Texture.prototype );
  14129. VideoTexture.prototype.constructor = VideoTexture;
  14130. /**
  14131. * @author alteredq / http://alteredqualia.com/
  14132. */
  14133. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14134. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14135. this.image = { width: width, height: height };
  14136. this.mipmaps = mipmaps;
  14137. // no flipping for cube textures
  14138. // (also flipping doesn't work for compressed textures )
  14139. this.flipY = false;
  14140. // can't generate mipmaps for compressed textures
  14141. // mips must be embedded in DDS files
  14142. this.generateMipmaps = false;
  14143. }
  14144. CompressedTexture.prototype = Object.create( Texture.prototype );
  14145. CompressedTexture.prototype.constructor = CompressedTexture;
  14146. CompressedTexture.prototype.isCompressedTexture = true;
  14147. /**
  14148. * @author mrdoob / http://mrdoob.com/
  14149. */
  14150. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14151. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14152. this.needsUpdate = true;
  14153. }
  14154. CanvasTexture.prototype = Object.create( Texture.prototype );
  14155. CanvasTexture.prototype.constructor = CanvasTexture;
  14156. /**
  14157. * @author Matt DesLauriers / @mattdesl
  14158. * @author atix / arthursilber.de
  14159. */
  14160. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14161. format = format !== undefined ? format : DepthFormat;
  14162. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14163. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14164. }
  14165. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14166. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14167. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14168. this.image = { width: width, height: height };
  14169. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14170. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14171. this.flipY = false;
  14172. this.generateMipmaps = false;
  14173. }
  14174. DepthTexture.prototype = Object.create( Texture.prototype );
  14175. DepthTexture.prototype.constructor = DepthTexture;
  14176. DepthTexture.prototype.isDepthTexture = true;
  14177. /**
  14178. * @author mrdoob / http://mrdoob.com/
  14179. */
  14180. function WireframeGeometry( geometry ) {
  14181. BufferGeometry.call( this );
  14182. var edge = [ 0, 0 ], hash = {};
  14183. function sortFunction( a, b ) {
  14184. return a - b;
  14185. }
  14186. var keys = [ 'a', 'b', 'c' ];
  14187. if ( geometry && geometry.isGeometry ) {
  14188. var vertices = geometry.vertices;
  14189. var faces = geometry.faces;
  14190. var numEdges = 0;
  14191. // allocate maximal size
  14192. var edges = new Uint32Array( 6 * faces.length );
  14193. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  14194. var face = faces[ i ];
  14195. for ( var j = 0; j < 3; j ++ ) {
  14196. edge[ 0 ] = face[ keys[ j ] ];
  14197. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  14198. edge.sort( sortFunction );
  14199. var key = edge.toString();
  14200. if ( hash[ key ] === undefined ) {
  14201. edges[ 2 * numEdges ] = edge[ 0 ];
  14202. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14203. hash[ key ] = true;
  14204. numEdges ++;
  14205. }
  14206. }
  14207. }
  14208. var coords = new Float32Array( numEdges * 2 * 3 );
  14209. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14210. for ( var j = 0; j < 2; j ++ ) {
  14211. var vertex = vertices[ edges [ 2 * i + j ] ];
  14212. var index = 6 * i + 3 * j;
  14213. coords[ index + 0 ] = vertex.x;
  14214. coords[ index + 1 ] = vertex.y;
  14215. coords[ index + 2 ] = vertex.z;
  14216. }
  14217. }
  14218. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14219. } else if ( geometry && geometry.isBufferGeometry ) {
  14220. if ( geometry.index !== null ) {
  14221. // Indexed BufferGeometry
  14222. var indices = geometry.index.array;
  14223. var vertices = geometry.attributes.position;
  14224. var groups = geometry.groups;
  14225. var numEdges = 0;
  14226. if ( groups.length === 0 ) {
  14227. geometry.addGroup( 0, indices.length );
  14228. }
  14229. // allocate maximal size
  14230. var edges = new Uint32Array( 2 * indices.length );
  14231. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  14232. var group = groups[ o ];
  14233. var start = group.start;
  14234. var count = group.count;
  14235. for ( var i = start, il = start + count; i < il; i += 3 ) {
  14236. for ( var j = 0; j < 3; j ++ ) {
  14237. edge[ 0 ] = indices[ i + j ];
  14238. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  14239. edge.sort( sortFunction );
  14240. var key = edge.toString();
  14241. if ( hash[ key ] === undefined ) {
  14242. edges[ 2 * numEdges ] = edge[ 0 ];
  14243. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14244. hash[ key ] = true;
  14245. numEdges ++;
  14246. }
  14247. }
  14248. }
  14249. }
  14250. var coords = new Float32Array( numEdges * 2 * 3 );
  14251. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14252. for ( var j = 0; j < 2; j ++ ) {
  14253. var index = 6 * i + 3 * j;
  14254. var index2 = edges[ 2 * i + j ];
  14255. coords[ index + 0 ] = vertices.getX( index2 );
  14256. coords[ index + 1 ] = vertices.getY( index2 );
  14257. coords[ index + 2 ] = vertices.getZ( index2 );
  14258. }
  14259. }
  14260. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14261. } else {
  14262. // non-indexed BufferGeometry
  14263. var vertices = geometry.attributes.position.array;
  14264. var numEdges = vertices.length / 3;
  14265. var numTris = numEdges / 3;
  14266. var coords = new Float32Array( numEdges * 2 * 3 );
  14267. for ( var i = 0, l = numTris; i < l; i ++ ) {
  14268. for ( var j = 0; j < 3; j ++ ) {
  14269. var index = 18 * i + 6 * j;
  14270. var index1 = 9 * i + 3 * j;
  14271. coords[ index + 0 ] = vertices[ index1 ];
  14272. coords[ index + 1 ] = vertices[ index1 + 1 ];
  14273. coords[ index + 2 ] = vertices[ index1 + 2 ];
  14274. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  14275. coords[ index + 3 ] = vertices[ index2 ];
  14276. coords[ index + 4 ] = vertices[ index2 + 1 ];
  14277. coords[ index + 5 ] = vertices[ index2 + 2 ];
  14278. }
  14279. }
  14280. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14281. }
  14282. }
  14283. }
  14284. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14285. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14286. /**
  14287. * @author Mugen87 / https://github.com/Mugen87
  14288. *
  14289. * Parametric Surfaces Geometry
  14290. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14291. */
  14292. function ParametricBufferGeometry( func, slices, stacks ) {
  14293. BufferGeometry.call( this );
  14294. this.type = 'ParametricBufferGeometry';
  14295. this.parameters = {
  14296. func: func,
  14297. slices: slices,
  14298. stacks: stacks
  14299. };
  14300. // generate vertices and uvs
  14301. var vertices = [];
  14302. var uvs = [];
  14303. var i, j, p;
  14304. var u, v;
  14305. var sliceCount = slices + 1;
  14306. for ( i = 0; i <= stacks; i ++ ) {
  14307. v = i / stacks;
  14308. for ( j = 0; j <= slices; j ++ ) {
  14309. u = j / slices;
  14310. p = func( u, v );
  14311. vertices.push( p.x, p.y, p.z );
  14312. uvs.push( u, v );
  14313. }
  14314. }
  14315. // generate indices
  14316. var indices = [];
  14317. var a, b, c, d;
  14318. for ( i = 0; i < stacks; i ++ ) {
  14319. for ( j = 0; j < slices; j ++ ) {
  14320. a = i * sliceCount + j;
  14321. b = i * sliceCount + j + 1;
  14322. c = ( i + 1 ) * sliceCount + j + 1;
  14323. d = ( i + 1 ) * sliceCount + j;
  14324. // faces one and two
  14325. indices.push( a, b, d );
  14326. indices.push( b, c, d );
  14327. }
  14328. }
  14329. // build geometry
  14330. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14331. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14332. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14333. // generate normals
  14334. this.computeVertexNormals();
  14335. }
  14336. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14337. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14338. /**
  14339. * @author zz85 / https://github.com/zz85
  14340. *
  14341. * Parametric Surfaces Geometry
  14342. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14343. */
  14344. function ParametricGeometry( func, slices, stacks ) {
  14345. Geometry.call( this );
  14346. this.type = 'ParametricGeometry';
  14347. this.parameters = {
  14348. func: func,
  14349. slices: slices,
  14350. stacks: stacks
  14351. };
  14352. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14353. this.mergeVertices();
  14354. }
  14355. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14356. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14357. /**
  14358. * @author Mugen87 / https://github.com/Mugen87
  14359. */
  14360. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14361. BufferGeometry.call( this );
  14362. this.type = 'PolyhedronBufferGeometry';
  14363. this.parameters = {
  14364. vertices: vertices,
  14365. indices: indices,
  14366. radius: radius,
  14367. detail: detail
  14368. };
  14369. radius = radius || 1;
  14370. detail = detail || 0;
  14371. // default buffer data
  14372. var vertexBuffer = [];
  14373. var uvBuffer = [];
  14374. // the subdivision creates the vertex buffer data
  14375. subdivide( detail );
  14376. // all vertices should lie on a conceptual sphere with a given radius
  14377. appplyRadius( radius );
  14378. // finally, create the uv data
  14379. generateUVs();
  14380. // build non-indexed geometry
  14381. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14382. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14383. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14384. this.normalizeNormals();
  14385. this.boundingSphere = new Sphere( new Vector3(), radius );
  14386. // helper functions
  14387. function subdivide( detail ) {
  14388. var a = new Vector3();
  14389. var b = new Vector3();
  14390. var c = new Vector3();
  14391. // iterate over all faces and apply a subdivison with the given detail value
  14392. for ( var i = 0; i < indices.length; i += 3 ) {
  14393. // get the vertices of the face
  14394. getVertexByIndex( indices[ i + 0 ], a );
  14395. getVertexByIndex( indices[ i + 1 ], b );
  14396. getVertexByIndex( indices[ i + 2 ], c );
  14397. // perform subdivision
  14398. subdivideFace( a, b, c, detail );
  14399. }
  14400. }
  14401. function subdivideFace( a, b, c, detail ) {
  14402. var cols = Math.pow( 2, detail );
  14403. // we use this multidimensional array as a data structure for creating the subdivision
  14404. var v = [];
  14405. var i, j;
  14406. // construct all of the vertices for this subdivision
  14407. for ( i = 0 ; i <= cols; i ++ ) {
  14408. v[ i ] = [];
  14409. var aj = a.clone().lerp( c, i / cols );
  14410. var bj = b.clone().lerp( c, i / cols );
  14411. var rows = cols - i;
  14412. for ( j = 0; j <= rows; j ++ ) {
  14413. if ( j === 0 && i === cols ) {
  14414. v[ i ][ j ] = aj;
  14415. } else {
  14416. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14417. }
  14418. }
  14419. }
  14420. // construct all of the faces
  14421. for ( i = 0; i < cols ; i ++ ) {
  14422. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14423. var k = Math.floor( j / 2 );
  14424. if ( j % 2 === 0 ) {
  14425. pushVertex( v[ i ][ k + 1 ] );
  14426. pushVertex( v[ i + 1 ][ k ] );
  14427. pushVertex( v[ i ][ k ] );
  14428. } else {
  14429. pushVertex( v[ i ][ k + 1 ] );
  14430. pushVertex( v[ i + 1 ][ k + 1 ] );
  14431. pushVertex( v[ i + 1 ][ k ] );
  14432. }
  14433. }
  14434. }
  14435. }
  14436. function appplyRadius( radius ) {
  14437. var vertex = new Vector3();
  14438. // iterate over the entire buffer and apply the radius to each vertex
  14439. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14440. vertex.x = vertexBuffer[ i + 0 ];
  14441. vertex.y = vertexBuffer[ i + 1 ];
  14442. vertex.z = vertexBuffer[ i + 2 ];
  14443. vertex.normalize().multiplyScalar( radius );
  14444. vertexBuffer[ i + 0 ] = vertex.x;
  14445. vertexBuffer[ i + 1 ] = vertex.y;
  14446. vertexBuffer[ i + 2 ] = vertex.z;
  14447. }
  14448. }
  14449. function generateUVs() {
  14450. var vertex = new Vector3();
  14451. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14452. vertex.x = vertexBuffer[ i + 0 ];
  14453. vertex.y = vertexBuffer[ i + 1 ];
  14454. vertex.z = vertexBuffer[ i + 2 ];
  14455. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14456. var v = inclination( vertex ) / Math.PI + 0.5;
  14457. uvBuffer.push( u, 1 - v );
  14458. }
  14459. correctUVs();
  14460. correctSeam();
  14461. }
  14462. function correctSeam() {
  14463. // handle case when face straddles the seam, see #3269
  14464. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14465. // uv data of a single face
  14466. var x0 = uvBuffer[ i + 0 ];
  14467. var x1 = uvBuffer[ i + 2 ];
  14468. var x2 = uvBuffer[ i + 4 ];
  14469. var max = Math.max( x0, x1, x2 );
  14470. var min = Math.min( x0, x1, x2 );
  14471. // 0.9 is somewhat arbitrary
  14472. if ( max > 0.9 && min < 0.1 ) {
  14473. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14474. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14475. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14476. }
  14477. }
  14478. }
  14479. function pushVertex( vertex ) {
  14480. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14481. }
  14482. function getVertexByIndex( index, vertex ) {
  14483. var stride = index * 3;
  14484. vertex.x = vertices[ stride + 0 ];
  14485. vertex.y = vertices[ stride + 1 ];
  14486. vertex.z = vertices[ stride + 2 ];
  14487. }
  14488. function correctUVs() {
  14489. var a = new Vector3();
  14490. var b = new Vector3();
  14491. var c = new Vector3();
  14492. var centroid = new Vector3();
  14493. var uvA = new Vector2();
  14494. var uvB = new Vector2();
  14495. var uvC = new Vector2();
  14496. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14497. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14498. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14499. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14500. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14501. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14502. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14503. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14504. var azi = azimuth( centroid );
  14505. correctUV( uvA, j + 0, a, azi );
  14506. correctUV( uvB, j + 2, b, azi );
  14507. correctUV( uvC, j + 4, c, azi );
  14508. }
  14509. }
  14510. function correctUV( uv, stride, vector, azimuth ) {
  14511. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14512. uvBuffer[ stride ] = uv.x - 1;
  14513. }
  14514. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14515. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14516. }
  14517. }
  14518. // Angle around the Y axis, counter-clockwise when looking from above.
  14519. function azimuth( vector ) {
  14520. return Math.atan2( vector.z, - vector.x );
  14521. }
  14522. // Angle above the XZ plane.
  14523. function inclination( vector ) {
  14524. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14525. }
  14526. }
  14527. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14528. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14529. /**
  14530. * @author Mugen87 / https://github.com/Mugen87
  14531. */
  14532. function TetrahedronBufferGeometry( radius, detail ) {
  14533. var vertices = [
  14534. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14535. ];
  14536. var indices = [
  14537. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14538. ];
  14539. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14540. this.type = 'TetrahedronBufferGeometry';
  14541. this.parameters = {
  14542. radius: radius,
  14543. detail: detail
  14544. };
  14545. }
  14546. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14547. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14548. /**
  14549. * @author timothypratley / https://github.com/timothypratley
  14550. */
  14551. function TetrahedronGeometry( radius, detail ) {
  14552. Geometry.call( this );
  14553. this.type = 'TetrahedronGeometry';
  14554. this.parameters = {
  14555. radius: radius,
  14556. detail: detail
  14557. };
  14558. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14559. this.mergeVertices();
  14560. }
  14561. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14562. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14563. /**
  14564. * @author Mugen87 / https://github.com/Mugen87
  14565. */
  14566. function OctahedronBufferGeometry( radius,detail ) {
  14567. var vertices = [
  14568. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14569. ];
  14570. var indices = [
  14571. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14572. ];
  14573. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14574. this.type = 'OctahedronBufferGeometry';
  14575. this.parameters = {
  14576. radius: radius,
  14577. detail: detail
  14578. };
  14579. }
  14580. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14581. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14582. /**
  14583. * @author timothypratley / https://github.com/timothypratley
  14584. */
  14585. function OctahedronGeometry( radius, detail ) {
  14586. Geometry.call( this );
  14587. this.type = 'OctahedronGeometry';
  14588. this.parameters = {
  14589. radius: radius,
  14590. detail: detail
  14591. };
  14592. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14593. this.mergeVertices();
  14594. }
  14595. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14596. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14597. /**
  14598. * @author Mugen87 / https://github.com/Mugen87
  14599. */
  14600. function IcosahedronBufferGeometry( radius, detail ) {
  14601. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14602. var vertices = [
  14603. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14604. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14605. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14606. ];
  14607. var indices = [
  14608. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14609. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14610. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14611. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14612. ];
  14613. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14614. this.type = 'IcosahedronBufferGeometry';
  14615. this.parameters = {
  14616. radius: radius,
  14617. detail: detail
  14618. };
  14619. }
  14620. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14621. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14622. /**
  14623. * @author timothypratley / https://github.com/timothypratley
  14624. */
  14625. function IcosahedronGeometry( radius, detail ) {
  14626. Geometry.call( this );
  14627. this.type = 'IcosahedronGeometry';
  14628. this.parameters = {
  14629. radius: radius,
  14630. detail: detail
  14631. };
  14632. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14633. this.mergeVertices();
  14634. }
  14635. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14636. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14637. /**
  14638. * @author Mugen87 / https://github.com/Mugen87
  14639. */
  14640. function DodecahedronBufferGeometry( radius, detail ) {
  14641. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14642. var r = 1 / t;
  14643. var vertices = [
  14644. // (±1, ±1, ±1)
  14645. - 1, - 1, - 1, - 1, - 1, 1,
  14646. - 1, 1, - 1, - 1, 1, 1,
  14647. 1, - 1, - 1, 1, - 1, 1,
  14648. 1, 1, - 1, 1, 1, 1,
  14649. // (0, ±1/φ, ±φ)
  14650. 0, - r, - t, 0, - r, t,
  14651. 0, r, - t, 0, r, t,
  14652. // (±1/φ, ±φ, 0)
  14653. - r, - t, 0, - r, t, 0,
  14654. r, - t, 0, r, t, 0,
  14655. // (±φ, 0, ±1/φ)
  14656. - t, 0, - r, t, 0, - r,
  14657. - t, 0, r, t, 0, r
  14658. ];
  14659. var indices = [
  14660. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14661. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14662. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14663. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14664. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14665. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14666. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14667. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14668. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14669. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14670. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14671. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14672. ];
  14673. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14674. this.type = 'DodecahedronBufferGeometry';
  14675. this.parameters = {
  14676. radius: radius,
  14677. detail: detail
  14678. };
  14679. }
  14680. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14681. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14682. /**
  14683. * @author Abe Pazos / https://hamoid.com
  14684. */
  14685. function DodecahedronGeometry( radius, detail ) {
  14686. Geometry.call( this );
  14687. this.type = 'DodecahedronGeometry';
  14688. this.parameters = {
  14689. radius: radius,
  14690. detail: detail
  14691. };
  14692. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14693. this.mergeVertices();
  14694. }
  14695. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14696. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14697. /**
  14698. * @author clockworkgeek / https://github.com/clockworkgeek
  14699. * @author timothypratley / https://github.com/timothypratley
  14700. * @author WestLangley / http://github.com/WestLangley
  14701. */
  14702. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14703. Geometry.call( this );
  14704. this.type = 'PolyhedronGeometry';
  14705. this.parameters = {
  14706. vertices: vertices,
  14707. indices: indices,
  14708. radius: radius,
  14709. detail: detail
  14710. };
  14711. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14712. this.mergeVertices();
  14713. }
  14714. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14715. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14716. /**
  14717. * @author Mugen87 / https://github.com/Mugen87
  14718. *
  14719. * Creates a tube which extrudes along a 3d spline.
  14720. *
  14721. */
  14722. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14723. BufferGeometry.call( this );
  14724. this.type = 'TubeBufferGeometry';
  14725. this.parameters = {
  14726. path: path,
  14727. tubularSegments: tubularSegments,
  14728. radius: radius,
  14729. radialSegments: radialSegments,
  14730. closed: closed
  14731. };
  14732. tubularSegments = tubularSegments || 64;
  14733. radius = radius || 1;
  14734. radialSegments = radialSegments || 8;
  14735. closed = closed || false;
  14736. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14737. // expose internals
  14738. this.tangents = frames.tangents;
  14739. this.normals = frames.normals;
  14740. this.binormals = frames.binormals;
  14741. // helper variables
  14742. var vertex = new Vector3();
  14743. var normal = new Vector3();
  14744. var uv = new Vector2();
  14745. var i, j;
  14746. // buffer
  14747. var vertices = [];
  14748. var normals = [];
  14749. var uvs = [];
  14750. var indices = [];
  14751. // create buffer data
  14752. generateBufferData();
  14753. // build geometry
  14754. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14755. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14756. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14757. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14758. // functions
  14759. function generateBufferData() {
  14760. for ( i = 0; i < tubularSegments; i ++ ) {
  14761. generateSegment( i );
  14762. }
  14763. // if the geometry is not closed, generate the last row of vertices and normals
  14764. // at the regular position on the given path
  14765. //
  14766. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  14767. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  14768. // uvs are generated in a separate function.
  14769. // this makes it easy compute correct values for closed geometries
  14770. generateUVs();
  14771. // finally create faces
  14772. generateIndices();
  14773. }
  14774. function generateSegment( i ) {
  14775. // we use getPointAt to sample evenly distributed points from the given path
  14776. var P = path.getPointAt( i / tubularSegments );
  14777. // retrieve corresponding normal and binormal
  14778. var N = frames.normals[ i ];
  14779. var B = frames.binormals[ i ];
  14780. // generate normals and vertices for the current segment
  14781. for ( j = 0; j <= radialSegments; j ++ ) {
  14782. var v = j / radialSegments * Math.PI * 2;
  14783. var sin = Math.sin( v );
  14784. var cos = - Math.cos( v );
  14785. // normal
  14786. normal.x = ( cos * N.x + sin * B.x );
  14787. normal.y = ( cos * N.y + sin * B.y );
  14788. normal.z = ( cos * N.z + sin * B.z );
  14789. normal.normalize();
  14790. normals.push( normal.x, normal.y, normal.z );
  14791. // vertex
  14792. vertex.x = P.x + radius * normal.x;
  14793. vertex.y = P.y + radius * normal.y;
  14794. vertex.z = P.z + radius * normal.z;
  14795. vertices.push( vertex.x, vertex.y, vertex.z );
  14796. }
  14797. }
  14798. function generateIndices() {
  14799. for ( j = 1; j <= tubularSegments; j ++ ) {
  14800. for ( i = 1; i <= radialSegments; i ++ ) {
  14801. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14802. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14803. var c = ( radialSegments + 1 ) * j + i;
  14804. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14805. // faces
  14806. indices.push( a, b, d );
  14807. indices.push( b, c, d );
  14808. }
  14809. }
  14810. }
  14811. function generateUVs() {
  14812. for ( i = 0; i <= tubularSegments; i ++ ) {
  14813. for ( j = 0; j <= radialSegments; j ++ ) {
  14814. uv.x = i / tubularSegments;
  14815. uv.y = j / radialSegments;
  14816. uvs.push( uv.x, uv.y );
  14817. }
  14818. }
  14819. }
  14820. }
  14821. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14822. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  14823. /**
  14824. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14825. * @author WestLangley / https://github.com/WestLangley
  14826. * @author zz85 / https://github.com/zz85
  14827. * @author miningold / https://github.com/miningold
  14828. * @author jonobr1 / https://github.com/jonobr1
  14829. *
  14830. * Creates a tube which extrudes along a 3d spline.
  14831. */
  14832. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14833. Geometry.call( this );
  14834. this.type = 'TubeGeometry';
  14835. this.parameters = {
  14836. path: path,
  14837. tubularSegments: tubularSegments,
  14838. radius: radius,
  14839. radialSegments: radialSegments,
  14840. closed: closed
  14841. };
  14842. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14843. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14844. // expose internals
  14845. this.tangents = bufferGeometry.tangents;
  14846. this.normals = bufferGeometry.normals;
  14847. this.binormals = bufferGeometry.binormals;
  14848. // create geometry
  14849. this.fromBufferGeometry( bufferGeometry );
  14850. this.mergeVertices();
  14851. }
  14852. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14853. TubeGeometry.prototype.constructor = TubeGeometry;
  14854. /**
  14855. * @author Mugen87 / https://github.com/Mugen87
  14856. *
  14857. * see: http://www.blackpawn.com/texts/pqtorus/
  14858. */
  14859. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  14860. BufferGeometry.call( this );
  14861. this.type = 'TorusKnotBufferGeometry';
  14862. this.parameters = {
  14863. radius: radius,
  14864. tube: tube,
  14865. tubularSegments: tubularSegments,
  14866. radialSegments: radialSegments,
  14867. p: p,
  14868. q: q
  14869. };
  14870. radius = radius || 100;
  14871. tube = tube || 40;
  14872. tubularSegments = Math.floor( tubularSegments ) || 64;
  14873. radialSegments = Math.floor( radialSegments ) || 8;
  14874. p = p || 2;
  14875. q = q || 3;
  14876. // used to calculate buffer length
  14877. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14878. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14879. // buffers
  14880. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  14881. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14882. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14883. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  14884. // helper variables
  14885. var i, j, index = 0, indexOffset = 0;
  14886. var vertex = new Vector3();
  14887. var normal = new Vector3();
  14888. var uv = new Vector2();
  14889. var P1 = new Vector3();
  14890. var P2 = new Vector3();
  14891. var B = new Vector3();
  14892. var T = new Vector3();
  14893. var N = new Vector3();
  14894. // generate vertices, normals and uvs
  14895. for ( i = 0; i <= tubularSegments; ++ i ) {
  14896. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  14897. var u = i / tubularSegments * p * Math.PI * 2;
  14898. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  14899. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  14900. calculatePositionOnCurve( u, p, q, radius, P1 );
  14901. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  14902. // calculate orthonormal basis
  14903. T.subVectors( P2, P1 );
  14904. N.addVectors( P2, P1 );
  14905. B.crossVectors( T, N );
  14906. N.crossVectors( B, T );
  14907. // normalize B, N. T can be ignored, we don't use it
  14908. B.normalize();
  14909. N.normalize();
  14910. for ( j = 0; j <= radialSegments; ++ j ) {
  14911. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  14912. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  14913. var v = j / radialSegments * Math.PI * 2;
  14914. var cx = - tube * Math.cos( v );
  14915. var cy = tube * Math.sin( v );
  14916. // now calculate the final vertex position.
  14917. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  14918. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  14919. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  14920. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  14921. // vertex
  14922. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  14923. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  14924. normal.subVectors( vertex, P1 ).normalize();
  14925. normals.setXYZ( index, normal.x, normal.y, normal.z );
  14926. // uv
  14927. uv.x = i / tubularSegments;
  14928. uv.y = j / radialSegments;
  14929. uvs.setXY( index, uv.x, uv.y );
  14930. // increase index
  14931. index ++;
  14932. }
  14933. }
  14934. // generate indices
  14935. for ( j = 1; j <= tubularSegments; j ++ ) {
  14936. for ( i = 1; i <= radialSegments; i ++ ) {
  14937. // indices
  14938. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14939. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14940. var c = ( radialSegments + 1 ) * j + i;
  14941. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14942. // face one
  14943. indices.setX( indexOffset, a ); indexOffset++;
  14944. indices.setX( indexOffset, b ); indexOffset++;
  14945. indices.setX( indexOffset, d ); indexOffset++;
  14946. // face two
  14947. indices.setX( indexOffset, b ); indexOffset++;
  14948. indices.setX( indexOffset, c ); indexOffset++;
  14949. indices.setX( indexOffset, d ); indexOffset++;
  14950. }
  14951. }
  14952. // build geometry
  14953. this.setIndex( indices );
  14954. this.addAttribute( 'position', vertices );
  14955. this.addAttribute( 'normal', normals );
  14956. this.addAttribute( 'uv', uvs );
  14957. // this function calculates the current position on the torus curve
  14958. function calculatePositionOnCurve( u, p, q, radius, position ) {
  14959. var cu = Math.cos( u );
  14960. var su = Math.sin( u );
  14961. var quOverP = q / p * u;
  14962. var cs = Math.cos( quOverP );
  14963. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  14964. position.y = radius * ( 2 + cs ) * su * 0.5;
  14965. position.z = radius * Math.sin( quOverP ) * 0.5;
  14966. }
  14967. }
  14968. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14969. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  14970. /**
  14971. * @author oosmoxiecode
  14972. */
  14973. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  14974. Geometry.call( this );
  14975. this.type = 'TorusKnotGeometry';
  14976. this.parameters = {
  14977. radius: radius,
  14978. tube: tube,
  14979. tubularSegments: tubularSegments,
  14980. radialSegments: radialSegments,
  14981. p: p,
  14982. q: q
  14983. };
  14984. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  14985. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  14986. this.mergeVertices();
  14987. }
  14988. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  14989. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  14990. /**
  14991. * @author Mugen87 / https://github.com/Mugen87
  14992. */
  14993. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  14994. BufferGeometry.call( this );
  14995. this.type = 'TorusBufferGeometry';
  14996. this.parameters = {
  14997. radius: radius,
  14998. tube: tube,
  14999. radialSegments: radialSegments,
  15000. tubularSegments: tubularSegments,
  15001. arc: arc
  15002. };
  15003. radius = radius || 100;
  15004. tube = tube || 40;
  15005. radialSegments = Math.floor( radialSegments ) || 8;
  15006. tubularSegments = Math.floor( tubularSegments ) || 6;
  15007. arc = arc || Math.PI * 2;
  15008. // used to calculate buffer length
  15009. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  15010. var indexCount = radialSegments * tubularSegments * 2 * 3;
  15011. // buffers
  15012. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  15013. var vertices = new Float32Array( vertexCount * 3 );
  15014. var normals = new Float32Array( vertexCount * 3 );
  15015. var uvs = new Float32Array( vertexCount * 2 );
  15016. // offset variables
  15017. var vertexBufferOffset = 0;
  15018. var uvBufferOffset = 0;
  15019. var indexBufferOffset = 0;
  15020. // helper variables
  15021. var center = new Vector3();
  15022. var vertex = new Vector3();
  15023. var normal = new Vector3();
  15024. var j, i;
  15025. // generate vertices, normals and uvs
  15026. for ( j = 0; j <= radialSegments; j ++ ) {
  15027. for ( i = 0; i <= tubularSegments; i ++ ) {
  15028. var u = i / tubularSegments * arc;
  15029. var v = j / radialSegments * Math.PI * 2;
  15030. // vertex
  15031. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15032. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15033. vertex.z = tube * Math.sin( v );
  15034. vertices[ vertexBufferOffset ] = vertex.x;
  15035. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  15036. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  15037. // this vector is used to calculate the normal
  15038. center.x = radius * Math.cos( u );
  15039. center.y = radius * Math.sin( u );
  15040. // normal
  15041. normal.subVectors( vertex, center ).normalize();
  15042. normals[ vertexBufferOffset ] = normal.x;
  15043. normals[ vertexBufferOffset + 1 ] = normal.y;
  15044. normals[ vertexBufferOffset + 2 ] = normal.z;
  15045. // uv
  15046. uvs[ uvBufferOffset ] = i / tubularSegments;
  15047. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  15048. // update offsets
  15049. vertexBufferOffset += 3;
  15050. uvBufferOffset += 2;
  15051. }
  15052. }
  15053. // generate indices
  15054. for ( j = 1; j <= radialSegments; j ++ ) {
  15055. for ( i = 1; i <= tubularSegments; i ++ ) {
  15056. // indices
  15057. var a = ( tubularSegments + 1 ) * j + i - 1;
  15058. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15059. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15060. var d = ( tubularSegments + 1 ) * j + i;
  15061. // face one
  15062. indices[ indexBufferOffset ] = a;
  15063. indices[ indexBufferOffset + 1 ] = b;
  15064. indices[ indexBufferOffset + 2 ] = d;
  15065. // face two
  15066. indices[ indexBufferOffset + 3 ] = b;
  15067. indices[ indexBufferOffset + 4 ] = c;
  15068. indices[ indexBufferOffset + 5 ] = d;
  15069. // update offset
  15070. indexBufferOffset += 6;
  15071. }
  15072. }
  15073. // build geometry
  15074. this.setIndex( new BufferAttribute( indices, 1 ) );
  15075. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  15076. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  15077. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  15078. }
  15079. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15080. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15081. /**
  15082. * @author oosmoxiecode
  15083. * @author mrdoob / http://mrdoob.com/
  15084. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15085. */
  15086. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15087. Geometry.call( this );
  15088. this.type = 'TorusGeometry';
  15089. this.parameters = {
  15090. radius: radius,
  15091. tube: tube,
  15092. radialSegments: radialSegments,
  15093. tubularSegments: tubularSegments,
  15094. arc: arc
  15095. };
  15096. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15097. }
  15098. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15099. TorusGeometry.prototype.constructor = TorusGeometry;
  15100. /**
  15101. * @author zz85 / http://www.lab4games.net/zz85/blog
  15102. */
  15103. var ShapeUtils = {
  15104. // calculate area of the contour polygon
  15105. area: function ( contour ) {
  15106. var n = contour.length;
  15107. var a = 0.0;
  15108. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15109. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15110. }
  15111. return a * 0.5;
  15112. },
  15113. triangulate: ( function () {
  15114. /**
  15115. * This code is a quick port of code written in C++ which was submitted to
  15116. * flipcode.com by John W. Ratcliff // July 22, 2000
  15117. * See original code and more information here:
  15118. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15119. *
  15120. * ported to actionscript by Zevan Rosser
  15121. * www.actionsnippet.com
  15122. *
  15123. * ported to javascript by Joshua Koo
  15124. * http://www.lab4games.net/zz85/blog
  15125. *
  15126. */
  15127. function snip( contour, u, v, w, n, verts ) {
  15128. var p;
  15129. var ax, ay, bx, by;
  15130. var cx, cy, px, py;
  15131. ax = contour[ verts[ u ] ].x;
  15132. ay = contour[ verts[ u ] ].y;
  15133. bx = contour[ verts[ v ] ].x;
  15134. by = contour[ verts[ v ] ].y;
  15135. cx = contour[ verts[ w ] ].x;
  15136. cy = contour[ verts[ w ] ].y;
  15137. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15138. var aX, aY, bX, bY, cX, cY;
  15139. var apx, apy, bpx, bpy, cpx, cpy;
  15140. var cCROSSap, bCROSScp, aCROSSbp;
  15141. aX = cx - bx; aY = cy - by;
  15142. bX = ax - cx; bY = ay - cy;
  15143. cX = bx - ax; cY = by - ay;
  15144. for ( p = 0; p < n; p ++ ) {
  15145. px = contour[ verts[ p ] ].x;
  15146. py = contour[ verts[ p ] ].y;
  15147. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15148. ( ( px === bx ) && ( py === by ) ) ||
  15149. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15150. apx = px - ax; apy = py - ay;
  15151. bpx = px - bx; bpy = py - by;
  15152. cpx = px - cx; cpy = py - cy;
  15153. // see if p is inside triangle abc
  15154. aCROSSbp = aX * bpy - aY * bpx;
  15155. cCROSSap = cX * apy - cY * apx;
  15156. bCROSScp = bX * cpy - bY * cpx;
  15157. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15158. }
  15159. return true;
  15160. }
  15161. // takes in an contour array and returns
  15162. return function triangulate( contour, indices ) {
  15163. var n = contour.length;
  15164. if ( n < 3 ) return null;
  15165. var result = [],
  15166. verts = [],
  15167. vertIndices = [];
  15168. /* we want a counter-clockwise polygon in verts */
  15169. var u, v, w;
  15170. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15171. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15172. } else {
  15173. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15174. }
  15175. var nv = n;
  15176. /* remove nv - 2 vertices, creating 1 triangle every time */
  15177. var count = 2 * nv; /* error detection */
  15178. for ( v = nv - 1; nv > 2; ) {
  15179. /* if we loop, it is probably a non-simple polygon */
  15180. if ( ( count -- ) <= 0 ) {
  15181. //** Triangulate: ERROR - probable bad polygon!
  15182. //throw ( "Warning, unable to triangulate polygon!" );
  15183. //return null;
  15184. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15185. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15186. if ( indices ) return vertIndices;
  15187. return result;
  15188. }
  15189. /* three consecutive vertices in current polygon, <u,v,w> */
  15190. u = v; if ( nv <= u ) u = 0; /* previous */
  15191. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15192. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15193. if ( snip( contour, u, v, w, nv, verts ) ) {
  15194. var a, b, c, s, t;
  15195. /* true names of the vertices */
  15196. a = verts[ u ];
  15197. b = verts[ v ];
  15198. c = verts[ w ];
  15199. /* output Triangle */
  15200. result.push( [ contour[ a ],
  15201. contour[ b ],
  15202. contour[ c ] ] );
  15203. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15204. /* remove v from the remaining polygon */
  15205. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15206. verts[ s ] = verts[ t ];
  15207. }
  15208. nv --;
  15209. /* reset error detection counter */
  15210. count = 2 * nv;
  15211. }
  15212. }
  15213. if ( indices ) return vertIndices;
  15214. return result;
  15215. }
  15216. } )(),
  15217. triangulateShape: function ( contour, holes ) {
  15218. function removeDupEndPts(points) {
  15219. var l = points.length;
  15220. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15221. points.pop();
  15222. }
  15223. }
  15224. removeDupEndPts( contour );
  15225. holes.forEach( removeDupEndPts );
  15226. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15227. // inOtherPt needs to be collinear to the inSegment
  15228. if ( inSegPt1.x !== inSegPt2.x ) {
  15229. if ( inSegPt1.x < inSegPt2.x ) {
  15230. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15231. } else {
  15232. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15233. }
  15234. } else {
  15235. if ( inSegPt1.y < inSegPt2.y ) {
  15236. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15237. } else {
  15238. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15239. }
  15240. }
  15241. }
  15242. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15243. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15244. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15245. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15246. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15247. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15248. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15249. if ( Math.abs( limit ) > Number.EPSILON ) {
  15250. // not parallel
  15251. var perpSeg2;
  15252. if ( limit > 0 ) {
  15253. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15254. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15255. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15256. } else {
  15257. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15258. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15259. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15260. }
  15261. // i.e. to reduce rounding errors
  15262. // intersection at endpoint of segment#1?
  15263. if ( perpSeg2 === 0 ) {
  15264. if ( ( inExcludeAdjacentSegs ) &&
  15265. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15266. return [ inSeg1Pt1 ];
  15267. }
  15268. if ( perpSeg2 === limit ) {
  15269. if ( ( inExcludeAdjacentSegs ) &&
  15270. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15271. return [ inSeg1Pt2 ];
  15272. }
  15273. // intersection at endpoint of segment#2?
  15274. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15275. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15276. // return real intersection point
  15277. var factorSeg1 = perpSeg2 / limit;
  15278. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15279. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15280. } else {
  15281. // parallel or collinear
  15282. if ( ( perpSeg1 !== 0 ) ||
  15283. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15284. // they are collinear or degenerate
  15285. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15286. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15287. // both segments are points
  15288. if ( seg1Pt && seg2Pt ) {
  15289. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15290. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15291. return [ inSeg1Pt1 ]; // they are the same point
  15292. }
  15293. // segment#1 is a single point
  15294. if ( seg1Pt ) {
  15295. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15296. return [ inSeg1Pt1 ];
  15297. }
  15298. // segment#2 is a single point
  15299. if ( seg2Pt ) {
  15300. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15301. return [ inSeg2Pt1 ];
  15302. }
  15303. // they are collinear segments, which might overlap
  15304. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15305. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15306. if ( seg1dx !== 0 ) {
  15307. // the segments are NOT on a vertical line
  15308. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15309. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15310. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15311. } else {
  15312. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15313. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15314. }
  15315. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15316. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15317. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15318. } else {
  15319. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15320. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15321. }
  15322. } else {
  15323. // the segments are on a vertical line
  15324. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15325. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15326. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15327. } else {
  15328. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15329. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15330. }
  15331. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15332. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15333. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15334. } else {
  15335. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15336. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15337. }
  15338. }
  15339. if ( seg1minVal <= seg2minVal ) {
  15340. if ( seg1maxVal < seg2minVal ) return [];
  15341. if ( seg1maxVal === seg2minVal ) {
  15342. if ( inExcludeAdjacentSegs ) return [];
  15343. return [ seg2min ];
  15344. }
  15345. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15346. return [ seg2min, seg2max ];
  15347. } else {
  15348. if ( seg1minVal > seg2maxVal ) return [];
  15349. if ( seg1minVal === seg2maxVal ) {
  15350. if ( inExcludeAdjacentSegs ) return [];
  15351. return [ seg1min ];
  15352. }
  15353. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15354. return [ seg1min, seg2max ];
  15355. }
  15356. }
  15357. }
  15358. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15359. // The order of legs is important
  15360. // translation of all points, so that Vertex is at (0,0)
  15361. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15362. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15363. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15364. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15365. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15366. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15367. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15368. // angle != 180 deg.
  15369. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15370. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15371. if ( from2toAngle > 0 ) {
  15372. // main angle < 180 deg.
  15373. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15374. } else {
  15375. // main angle > 180 deg.
  15376. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15377. }
  15378. } else {
  15379. // angle == 180 deg.
  15380. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15381. return ( from2otherAngle > 0 );
  15382. }
  15383. }
  15384. function removeHoles( contour, holes ) {
  15385. var shape = contour.concat(); // work on this shape
  15386. var hole;
  15387. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15388. // Check if hole point lies within angle around shape point
  15389. var lastShapeIdx = shape.length - 1;
  15390. var prevShapeIdx = inShapeIdx - 1;
  15391. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15392. var nextShapeIdx = inShapeIdx + 1;
  15393. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15394. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15395. if ( ! insideAngle ) {
  15396. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15397. return false;
  15398. }
  15399. // Check if shape point lies within angle around hole point
  15400. var lastHoleIdx = hole.length - 1;
  15401. var prevHoleIdx = inHoleIdx - 1;
  15402. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15403. var nextHoleIdx = inHoleIdx + 1;
  15404. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15405. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15406. if ( ! insideAngle ) {
  15407. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15408. return false;
  15409. }
  15410. return true;
  15411. }
  15412. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15413. // checks for intersections with shape edges
  15414. var sIdx, nextIdx, intersection;
  15415. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15416. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15417. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15418. if ( intersection.length > 0 ) return true;
  15419. }
  15420. return false;
  15421. }
  15422. var indepHoles = [];
  15423. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15424. // checks for intersections with hole edges
  15425. var ihIdx, chkHole,
  15426. hIdx, nextIdx, intersection;
  15427. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15428. chkHole = holes[ indepHoles[ ihIdx ]];
  15429. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15430. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15431. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15432. if ( intersection.length > 0 ) return true;
  15433. }
  15434. }
  15435. return false;
  15436. }
  15437. var holeIndex, shapeIndex,
  15438. shapePt, holePt,
  15439. holeIdx, cutKey, failedCuts = [],
  15440. tmpShape1, tmpShape2,
  15441. tmpHole1, tmpHole2;
  15442. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15443. indepHoles.push( h );
  15444. }
  15445. var minShapeIndex = 0;
  15446. var counter = indepHoles.length * 2;
  15447. while ( indepHoles.length > 0 ) {
  15448. counter --;
  15449. if ( counter < 0 ) {
  15450. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15451. break;
  15452. }
  15453. // search for shape-vertex and hole-vertex,
  15454. // which can be connected without intersections
  15455. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15456. shapePt = shape[ shapeIndex ];
  15457. holeIndex = - 1;
  15458. // search for hole which can be reached without intersections
  15459. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15460. holeIdx = indepHoles[ h ];
  15461. // prevent multiple checks
  15462. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15463. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15464. hole = holes[ holeIdx ];
  15465. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15466. holePt = hole[ h2 ];
  15467. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15468. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15469. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15470. holeIndex = h2;
  15471. indepHoles.splice( h, 1 );
  15472. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15473. tmpShape2 = shape.slice( shapeIndex );
  15474. tmpHole1 = hole.slice( holeIndex );
  15475. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15476. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15477. minShapeIndex = shapeIndex;
  15478. // Debug only, to show the selected cuts
  15479. // glob_CutLines.push( [ shapePt, holePt ] );
  15480. break;
  15481. }
  15482. if ( holeIndex >= 0 ) break; // hole-vertex found
  15483. failedCuts[ cutKey ] = true; // remember failure
  15484. }
  15485. if ( holeIndex >= 0 ) break; // hole-vertex found
  15486. }
  15487. }
  15488. return shape; /* shape with no holes */
  15489. }
  15490. var i, il, f, face,
  15491. key, index,
  15492. allPointsMap = {};
  15493. // 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.
  15494. var allpoints = contour.concat();
  15495. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15496. Array.prototype.push.apply( allpoints, holes[ h ] );
  15497. }
  15498. //console.log( "allpoints",allpoints, allpoints.length );
  15499. // prepare all points map
  15500. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15501. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15502. if ( allPointsMap[ key ] !== undefined ) {
  15503. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15504. }
  15505. allPointsMap[ key ] = i;
  15506. }
  15507. // remove holes by cutting paths to holes and adding them to the shape
  15508. var shapeWithoutHoles = removeHoles( contour, holes );
  15509. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15510. //console.log( "triangles",triangles, triangles.length );
  15511. // check all face vertices against all points map
  15512. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15513. face = triangles[ i ];
  15514. for ( f = 0; f < 3; f ++ ) {
  15515. key = face[ f ].x + ":" + face[ f ].y;
  15516. index = allPointsMap[ key ];
  15517. if ( index !== undefined ) {
  15518. face[ f ] = index;
  15519. }
  15520. }
  15521. }
  15522. return triangles.concat();
  15523. },
  15524. isClockWise: function ( pts ) {
  15525. return ShapeUtils.area( pts ) < 0;
  15526. },
  15527. // Bezier Curves formulas obtained from
  15528. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  15529. // Quad Bezier Functions
  15530. b2: ( function () {
  15531. function b2p0( t, p ) {
  15532. var k = 1 - t;
  15533. return k * k * p;
  15534. }
  15535. function b2p1( t, p ) {
  15536. return 2 * ( 1 - t ) * t * p;
  15537. }
  15538. function b2p2( t, p ) {
  15539. return t * t * p;
  15540. }
  15541. return function b2( t, p0, p1, p2 ) {
  15542. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  15543. };
  15544. } )(),
  15545. // Cubic Bezier Functions
  15546. b3: ( function () {
  15547. function b3p0( t, p ) {
  15548. var k = 1 - t;
  15549. return k * k * k * p;
  15550. }
  15551. function b3p1( t, p ) {
  15552. var k = 1 - t;
  15553. return 3 * k * k * t * p;
  15554. }
  15555. function b3p2( t, p ) {
  15556. var k = 1 - t;
  15557. return 3 * k * t * t * p;
  15558. }
  15559. function b3p3( t, p ) {
  15560. return t * t * t * p;
  15561. }
  15562. return function b3( t, p0, p1, p2, p3 ) {
  15563. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  15564. };
  15565. } )()
  15566. };
  15567. /**
  15568. * @author zz85 / http://www.lab4games.net/zz85/blog
  15569. *
  15570. * Creates extruded geometry from a path shape.
  15571. *
  15572. * parameters = {
  15573. *
  15574. * curveSegments: <int>, // number of points on the curves
  15575. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15576. * amount: <int>, // Depth to extrude the shape
  15577. *
  15578. * bevelEnabled: <bool>, // turn on bevel
  15579. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15580. * bevelSize: <float>, // how far from shape outline is bevel
  15581. * bevelSegments: <int>, // number of bevel layers
  15582. *
  15583. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15584. * frames: <Object> // containing arrays of tangents, normals, binormals
  15585. *
  15586. * uvGenerator: <Object> // object that provides UV generator functions
  15587. *
  15588. * }
  15589. **/
  15590. function ExtrudeGeometry( shapes, options ) {
  15591. if ( typeof( shapes ) === "undefined" ) {
  15592. shapes = [];
  15593. return;
  15594. }
  15595. Geometry.call( this );
  15596. this.type = 'ExtrudeGeometry';
  15597. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15598. this.addShapeList( shapes, options );
  15599. this.computeFaceNormals();
  15600. // can't really use automatic vertex normals
  15601. // as then front and back sides get smoothed too
  15602. // should do separate smoothing just for sides
  15603. //this.computeVertexNormals();
  15604. //console.log( "took", ( Date.now() - startTime ) );
  15605. }
  15606. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15607. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15608. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  15609. var sl = shapes.length;
  15610. for ( var s = 0; s < sl; s ++ ) {
  15611. var shape = shapes[ s ];
  15612. this.addShape( shape, options );
  15613. }
  15614. };
  15615. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  15616. var amount = options.amount !== undefined ? options.amount : 100;
  15617. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15618. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15619. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15620. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15621. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15622. var steps = options.steps !== undefined ? options.steps : 1;
  15623. var extrudePath = options.extrudePath;
  15624. var extrudePts, extrudeByPath = false;
  15625. // Use default WorldUVGenerator if no UV generators are specified.
  15626. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15627. var splineTube, binormal, normal, position2;
  15628. if ( extrudePath ) {
  15629. extrudePts = extrudePath.getSpacedPoints( steps );
  15630. extrudeByPath = true;
  15631. bevelEnabled = false; // bevels not supported for path extrusion
  15632. // SETUP TNB variables
  15633. // TODO1 - have a .isClosed in spline?
  15634. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15635. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15636. binormal = new Vector3();
  15637. normal = new Vector3();
  15638. position2 = new Vector3();
  15639. }
  15640. // Safeguards if bevels are not enabled
  15641. if ( ! bevelEnabled ) {
  15642. bevelSegments = 0;
  15643. bevelThickness = 0;
  15644. bevelSize = 0;
  15645. }
  15646. // Variables initialization
  15647. var ahole, h, hl; // looping of holes
  15648. var scope = this;
  15649. var shapesOffset = this.vertices.length;
  15650. var shapePoints = shape.extractPoints( curveSegments );
  15651. var vertices = shapePoints.shape;
  15652. var holes = shapePoints.holes;
  15653. var reverse = ! ShapeUtils.isClockWise( vertices );
  15654. if ( reverse ) {
  15655. vertices = vertices.reverse();
  15656. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15657. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15658. ahole = holes[ h ];
  15659. if ( ShapeUtils.isClockWise( ahole ) ) {
  15660. holes[ h ] = ahole.reverse();
  15661. }
  15662. }
  15663. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15664. }
  15665. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15666. /* Vertices */
  15667. var contour = vertices; // vertices has all points but contour has only points of circumference
  15668. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15669. ahole = holes[ h ];
  15670. vertices = vertices.concat( ahole );
  15671. }
  15672. function scalePt2( pt, vec, size ) {
  15673. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15674. return vec.clone().multiplyScalar( size ).add( pt );
  15675. }
  15676. var b, bs, t, z,
  15677. vert, vlen = vertices.length,
  15678. face, flen = faces.length;
  15679. // Find directions for point movement
  15680. function getBevelVec( inPt, inPrev, inNext ) {
  15681. // computes for inPt the corresponding point inPt' on a new contour
  15682. // shifted by 1 unit (length of normalized vector) to the left
  15683. // if we walk along contour clockwise, this new contour is outside the old one
  15684. //
  15685. // inPt' is the intersection of the two lines parallel to the two
  15686. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15687. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15688. // good reading for geometry algorithms (here: line-line intersection)
  15689. // http://geomalgorithms.com/a05-_intersect-1.html
  15690. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  15691. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  15692. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15693. // check for collinear edges
  15694. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15695. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15696. // not collinear
  15697. // length of vectors for normalizing
  15698. var v_prev_len = Math.sqrt( v_prev_lensq );
  15699. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15700. // shift adjacent points by unit vectors to the left
  15701. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15702. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15703. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15704. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15705. // scaling factor for v_prev to intersection point
  15706. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15707. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15708. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15709. // vector from inPt to intersection point
  15710. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15711. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15712. // Don't normalize!, otherwise sharp corners become ugly
  15713. // but prevent crazy spikes
  15714. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15715. if ( v_trans_lensq <= 2 ) {
  15716. return new Vector2( v_trans_x, v_trans_y );
  15717. } else {
  15718. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15719. }
  15720. } else {
  15721. // handle special case of collinear edges
  15722. var direction_eq = false; // assumes: opposite
  15723. if ( v_prev_x > Number.EPSILON ) {
  15724. if ( v_next_x > Number.EPSILON ) {
  15725. direction_eq = true;
  15726. }
  15727. } else {
  15728. if ( v_prev_x < - Number.EPSILON ) {
  15729. if ( v_next_x < - Number.EPSILON ) {
  15730. direction_eq = true;
  15731. }
  15732. } else {
  15733. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15734. direction_eq = true;
  15735. }
  15736. }
  15737. }
  15738. if ( direction_eq ) {
  15739. // console.log("Warning: lines are a straight sequence");
  15740. v_trans_x = - v_prev_y;
  15741. v_trans_y = v_prev_x;
  15742. shrink_by = Math.sqrt( v_prev_lensq );
  15743. } else {
  15744. // console.log("Warning: lines are a straight spike");
  15745. v_trans_x = v_prev_x;
  15746. v_trans_y = v_prev_y;
  15747. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15748. }
  15749. }
  15750. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15751. }
  15752. var contourMovements = [];
  15753. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15754. if ( j === il ) j = 0;
  15755. if ( k === il ) k = 0;
  15756. // (j)---(i)---(k)
  15757. // console.log('i,j,k', i, j , k)
  15758. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15759. }
  15760. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  15761. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15762. ahole = holes[ h ];
  15763. oneHoleMovements = [];
  15764. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15765. if ( j === il ) j = 0;
  15766. if ( k === il ) k = 0;
  15767. // (j)---(i)---(k)
  15768. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15769. }
  15770. holesMovements.push( oneHoleMovements );
  15771. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15772. }
  15773. // Loop bevelSegments, 1 for the front, 1 for the back
  15774. for ( b = 0; b < bevelSegments; b ++ ) {
  15775. //for ( b = bevelSegments; b > 0; b -- ) {
  15776. t = b / bevelSegments;
  15777. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15778. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15779. // contract shape
  15780. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15781. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15782. v( vert.x, vert.y, - z );
  15783. }
  15784. // expand holes
  15785. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15786. ahole = holes[ h ];
  15787. oneHoleMovements = holesMovements[ h ];
  15788. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15789. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15790. v( vert.x, vert.y, - z );
  15791. }
  15792. }
  15793. }
  15794. bs = bevelSize;
  15795. // Back facing vertices
  15796. for ( i = 0; i < vlen; i ++ ) {
  15797. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15798. if ( ! extrudeByPath ) {
  15799. v( vert.x, vert.y, 0 );
  15800. } else {
  15801. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15802. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15803. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15804. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15805. v( position2.x, position2.y, position2.z );
  15806. }
  15807. }
  15808. // Add stepped vertices...
  15809. // Including front facing vertices
  15810. var s;
  15811. for ( s = 1; s <= steps; s ++ ) {
  15812. for ( i = 0; i < vlen; i ++ ) {
  15813. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15814. if ( ! extrudeByPath ) {
  15815. v( vert.x, vert.y, amount / steps * s );
  15816. } else {
  15817. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15818. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15819. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15820. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15821. v( position2.x, position2.y, position2.z );
  15822. }
  15823. }
  15824. }
  15825. // Add bevel segments planes
  15826. //for ( b = 1; b <= bevelSegments; b ++ ) {
  15827. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  15828. t = b / bevelSegments;
  15829. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  15830. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15831. // contract shape
  15832. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15833. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15834. v( vert.x, vert.y, amount + z );
  15835. }
  15836. // expand holes
  15837. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15838. ahole = holes[ h ];
  15839. oneHoleMovements = holesMovements[ h ];
  15840. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15841. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15842. if ( ! extrudeByPath ) {
  15843. v( vert.x, vert.y, amount + z );
  15844. } else {
  15845. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  15846. }
  15847. }
  15848. }
  15849. }
  15850. /* Faces */
  15851. // Top and bottom faces
  15852. buildLidFaces();
  15853. // Sides faces
  15854. buildSideFaces();
  15855. ///// Internal functions
  15856. function buildLidFaces() {
  15857. if ( bevelEnabled ) {
  15858. var layer = 0; // steps + 1
  15859. var offset = vlen * layer;
  15860. // Bottom faces
  15861. for ( i = 0; i < flen; i ++ ) {
  15862. face = faces[ i ];
  15863. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  15864. }
  15865. layer = steps + bevelSegments * 2;
  15866. offset = vlen * layer;
  15867. // Top faces
  15868. for ( i = 0; i < flen; i ++ ) {
  15869. face = faces[ i ];
  15870. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  15871. }
  15872. } else {
  15873. // Bottom faces
  15874. for ( i = 0; i < flen; i ++ ) {
  15875. face = faces[ i ];
  15876. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  15877. }
  15878. // Top faces
  15879. for ( i = 0; i < flen; i ++ ) {
  15880. face = faces[ i ];
  15881. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  15882. }
  15883. }
  15884. }
  15885. // Create faces for the z-sides of the shape
  15886. function buildSideFaces() {
  15887. var layeroffset = 0;
  15888. sidewalls( contour, layeroffset );
  15889. layeroffset += contour.length;
  15890. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15891. ahole = holes[ h ];
  15892. sidewalls( ahole, layeroffset );
  15893. //, true
  15894. layeroffset += ahole.length;
  15895. }
  15896. }
  15897. function sidewalls( contour, layeroffset ) {
  15898. var j, k;
  15899. i = contour.length;
  15900. while ( -- i >= 0 ) {
  15901. j = i;
  15902. k = i - 1;
  15903. if ( k < 0 ) k = contour.length - 1;
  15904. //console.log('b', i,j, i-1, k,vertices.length);
  15905. var s = 0, sl = steps + bevelSegments * 2;
  15906. for ( s = 0; s < sl; s ++ ) {
  15907. var slen1 = vlen * s;
  15908. var slen2 = vlen * ( s + 1 );
  15909. var a = layeroffset + j + slen1,
  15910. b = layeroffset + k + slen1,
  15911. c = layeroffset + k + slen2,
  15912. d = layeroffset + j + slen2;
  15913. f4( a, b, c, d, contour, s, sl, j, k );
  15914. }
  15915. }
  15916. }
  15917. function v( x, y, z ) {
  15918. scope.vertices.push( new Vector3( x, y, z ) );
  15919. }
  15920. function f3( a, b, c ) {
  15921. a += shapesOffset;
  15922. b += shapesOffset;
  15923. c += shapesOffset;
  15924. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  15925. var uvs = uvgen.generateTopUV( scope, a, b, c );
  15926. scope.faceVertexUvs[ 0 ].push( uvs );
  15927. }
  15928. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  15929. a += shapesOffset;
  15930. b += shapesOffset;
  15931. c += shapesOffset;
  15932. d += shapesOffset;
  15933. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  15934. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  15935. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  15936. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  15937. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  15938. }
  15939. };
  15940. ExtrudeGeometry.WorldUVGenerator = {
  15941. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  15942. var vertices = geometry.vertices;
  15943. var a = vertices[ indexA ];
  15944. var b = vertices[ indexB ];
  15945. var c = vertices[ indexC ];
  15946. return [
  15947. new Vector2( a.x, a.y ),
  15948. new Vector2( b.x, b.y ),
  15949. new Vector2( c.x, c.y )
  15950. ];
  15951. },
  15952. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  15953. var vertices = geometry.vertices;
  15954. var a = vertices[ indexA ];
  15955. var b = vertices[ indexB ];
  15956. var c = vertices[ indexC ];
  15957. var d = vertices[ indexD ];
  15958. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  15959. return [
  15960. new Vector2( a.x, 1 - a.z ),
  15961. new Vector2( b.x, 1 - b.z ),
  15962. new Vector2( c.x, 1 - c.z ),
  15963. new Vector2( d.x, 1 - d.z )
  15964. ];
  15965. } else {
  15966. return [
  15967. new Vector2( a.y, 1 - a.z ),
  15968. new Vector2( b.y, 1 - b.z ),
  15969. new Vector2( c.y, 1 - c.z ),
  15970. new Vector2( d.y, 1 - d.z )
  15971. ];
  15972. }
  15973. }
  15974. };
  15975. /**
  15976. * @author zz85 / http://www.lab4games.net/zz85/blog
  15977. * @author alteredq / http://alteredqualia.com/
  15978. *
  15979. * Text = 3D Text
  15980. *
  15981. * parameters = {
  15982. * font: <THREE.Font>, // font
  15983. *
  15984. * size: <float>, // size of the text
  15985. * height: <float>, // thickness to extrude text
  15986. * curveSegments: <int>, // number of points on the curves
  15987. *
  15988. * bevelEnabled: <bool>, // turn on bevel
  15989. * bevelThickness: <float>, // how deep into text bevel goes
  15990. * bevelSize: <float> // how far from text outline is bevel
  15991. * }
  15992. */
  15993. function TextGeometry( text, parameters ) {
  15994. parameters = parameters || {};
  15995. var font = parameters.font;
  15996. if ( (font && font.isFont) === false ) {
  15997. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  15998. return new Geometry();
  15999. }
  16000. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16001. // translate parameters to ExtrudeGeometry API
  16002. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16003. // defaults
  16004. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16005. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16006. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16007. ExtrudeGeometry.call( this, shapes, parameters );
  16008. this.type = 'TextGeometry';
  16009. }
  16010. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  16011. TextGeometry.prototype.constructor = TextGeometry;
  16012. /**
  16013. * @author benaadams / https://twitter.com/ben_a_adams
  16014. * based on THREE.SphereGeometry
  16015. */
  16016. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16017. BufferGeometry.call( this );
  16018. this.type = 'SphereBufferGeometry';
  16019. this.parameters = {
  16020. radius: radius,
  16021. widthSegments: widthSegments,
  16022. heightSegments: heightSegments,
  16023. phiStart: phiStart,
  16024. phiLength: phiLength,
  16025. thetaStart: thetaStart,
  16026. thetaLength: thetaLength
  16027. };
  16028. radius = radius || 50;
  16029. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16030. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16031. phiStart = phiStart !== undefined ? phiStart : 0;
  16032. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16033. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16034. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16035. var thetaEnd = thetaStart + thetaLength;
  16036. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  16037. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16038. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16039. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16040. var index = 0, vertices = [], normal = new Vector3();
  16041. for ( var y = 0; y <= heightSegments; y ++ ) {
  16042. var verticesRow = [];
  16043. var v = y / heightSegments;
  16044. for ( var x = 0; x <= widthSegments; x ++ ) {
  16045. var u = x / widthSegments;
  16046. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16047. var py = radius * Math.cos( thetaStart + v * thetaLength );
  16048. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16049. normal.set( px, py, pz ).normalize();
  16050. positions.setXYZ( index, px, py, pz );
  16051. normals.setXYZ( index, normal.x, normal.y, normal.z );
  16052. uvs.setXY( index, u, 1 - v );
  16053. verticesRow.push( index );
  16054. index ++;
  16055. }
  16056. vertices.push( verticesRow );
  16057. }
  16058. var indices = [];
  16059. for ( var y = 0; y < heightSegments; y ++ ) {
  16060. for ( var x = 0; x < widthSegments; x ++ ) {
  16061. var v1 = vertices[ y ][ x + 1 ];
  16062. var v2 = vertices[ y ][ x ];
  16063. var v3 = vertices[ y + 1 ][ x ];
  16064. var v4 = vertices[ y + 1 ][ x + 1 ];
  16065. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  16066. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  16067. }
  16068. }
  16069. this.setIndex( new ( positions.count > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16070. this.addAttribute( 'position', positions );
  16071. this.addAttribute( 'normal', normals );
  16072. this.addAttribute( 'uv', uvs );
  16073. this.boundingSphere = new Sphere( new Vector3(), radius );
  16074. }
  16075. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16076. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16077. /**
  16078. * @author mrdoob / http://mrdoob.com/
  16079. */
  16080. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16081. Geometry.call( this );
  16082. this.type = 'SphereGeometry';
  16083. this.parameters = {
  16084. radius: radius,
  16085. widthSegments: widthSegments,
  16086. heightSegments: heightSegments,
  16087. phiStart: phiStart,
  16088. phiLength: phiLength,
  16089. thetaStart: thetaStart,
  16090. thetaLength: thetaLength
  16091. };
  16092. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16093. }
  16094. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16095. SphereGeometry.prototype.constructor = SphereGeometry;
  16096. /**
  16097. * @author Mugen87 / https://github.com/Mugen87
  16098. */
  16099. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16100. BufferGeometry.call( this );
  16101. this.type = 'RingBufferGeometry';
  16102. this.parameters = {
  16103. innerRadius: innerRadius,
  16104. outerRadius: outerRadius,
  16105. thetaSegments: thetaSegments,
  16106. phiSegments: phiSegments,
  16107. thetaStart: thetaStart,
  16108. thetaLength: thetaLength
  16109. };
  16110. innerRadius = innerRadius || 20;
  16111. outerRadius = outerRadius || 50;
  16112. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16113. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16114. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16115. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16116. // these are used to calculate buffer length
  16117. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  16118. var indexCount = thetaSegments * phiSegments * 2 * 3;
  16119. // buffers
  16120. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16121. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16122. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16123. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16124. // some helper variables
  16125. var index = 0, indexOffset = 0, segment;
  16126. var radius = innerRadius;
  16127. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16128. var vertex = new Vector3();
  16129. var uv = new Vector2();
  16130. var j, i;
  16131. // generate vertices, normals and uvs
  16132. // values are generate from the inside of the ring to the outside
  16133. for ( j = 0; j <= phiSegments; j ++ ) {
  16134. for ( i = 0; i <= thetaSegments; i ++ ) {
  16135. segment = thetaStart + i / thetaSegments * thetaLength;
  16136. // vertex
  16137. vertex.x = radius * Math.cos( segment );
  16138. vertex.y = radius * Math.sin( segment );
  16139. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16140. // normal
  16141. normals.setXYZ( index, 0, 0, 1 );
  16142. // uv
  16143. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16144. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16145. uvs.setXY( index, uv.x, uv.y );
  16146. // increase index
  16147. index++;
  16148. }
  16149. // increase the radius for next row of vertices
  16150. radius += radiusStep;
  16151. }
  16152. // generate indices
  16153. for ( j = 0; j < phiSegments; j ++ ) {
  16154. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16155. for ( i = 0; i < thetaSegments; i ++ ) {
  16156. segment = i + thetaSegmentLevel;
  16157. // indices
  16158. var a = segment;
  16159. var b = segment + thetaSegments + 1;
  16160. var c = segment + thetaSegments + 2;
  16161. var d = segment + 1;
  16162. // face one
  16163. indices.setX( indexOffset, a ); indexOffset++;
  16164. indices.setX( indexOffset, b ); indexOffset++;
  16165. indices.setX( indexOffset, c ); indexOffset++;
  16166. // face two
  16167. indices.setX( indexOffset, a ); indexOffset++;
  16168. indices.setX( indexOffset, c ); indexOffset++;
  16169. indices.setX( indexOffset, d ); indexOffset++;
  16170. }
  16171. }
  16172. // build geometry
  16173. this.setIndex( indices );
  16174. this.addAttribute( 'position', vertices );
  16175. this.addAttribute( 'normal', normals );
  16176. this.addAttribute( 'uv', uvs );
  16177. }
  16178. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16179. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16180. /**
  16181. * @author Kaleb Murphy
  16182. */
  16183. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16184. Geometry.call( this );
  16185. this.type = 'RingGeometry';
  16186. this.parameters = {
  16187. innerRadius: innerRadius,
  16188. outerRadius: outerRadius,
  16189. thetaSegments: thetaSegments,
  16190. phiSegments: phiSegments,
  16191. thetaStart: thetaStart,
  16192. thetaLength: thetaLength
  16193. };
  16194. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16195. }
  16196. RingGeometry.prototype = Object.create( Geometry.prototype );
  16197. RingGeometry.prototype.constructor = RingGeometry;
  16198. /**
  16199. * @author mrdoob / http://mrdoob.com/
  16200. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  16201. */
  16202. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  16203. Geometry.call( this );
  16204. this.type = 'PlaneGeometry';
  16205. this.parameters = {
  16206. width: width,
  16207. height: height,
  16208. widthSegments: widthSegments,
  16209. heightSegments: heightSegments
  16210. };
  16211. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  16212. }
  16213. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  16214. PlaneGeometry.prototype.constructor = PlaneGeometry;
  16215. /**
  16216. * @author Mugen87 / https://github.com/Mugen87
  16217. */
  16218. // points - to create a closed torus, one must use a set of points
  16219. // like so: [ a, b, c, d, a ], see first is the same as last.
  16220. // segments - the number of circumference segments to create
  16221. // phiStart - the starting radian
  16222. // phiLength - the radian (0 to 2PI) range of the lathed section
  16223. // 2PI is a closed lathe, less than 2PI is a portion.
  16224. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16225. BufferGeometry.call( this );
  16226. this.type = 'LatheBufferGeometry';
  16227. this.parameters = {
  16228. points: points,
  16229. segments: segments,
  16230. phiStart: phiStart,
  16231. phiLength: phiLength
  16232. };
  16233. segments = Math.floor( segments ) || 12;
  16234. phiStart = phiStart || 0;
  16235. phiLength = phiLength || Math.PI * 2;
  16236. // clamp phiLength so it's in range of [ 0, 2PI ]
  16237. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16238. // these are used to calculate buffer length
  16239. var vertexCount = ( segments + 1 ) * points.length;
  16240. var indexCount = segments * points.length * 2 * 3;
  16241. // buffers
  16242. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16243. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16244. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16245. // helper variables
  16246. var index = 0, indexOffset = 0, base;
  16247. var inverseSegments = 1.0 / segments;
  16248. var vertex = new Vector3();
  16249. var uv = new Vector2();
  16250. var i, j;
  16251. // generate vertices and uvs
  16252. for ( i = 0; i <= segments; i ++ ) {
  16253. var phi = phiStart + i * inverseSegments * phiLength;
  16254. var sin = Math.sin( phi );
  16255. var cos = Math.cos( phi );
  16256. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16257. // vertex
  16258. vertex.x = points[ j ].x * sin;
  16259. vertex.y = points[ j ].y;
  16260. vertex.z = points[ j ].x * cos;
  16261. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16262. // uv
  16263. uv.x = i / segments;
  16264. uv.y = j / ( points.length - 1 );
  16265. uvs.setXY( index, uv.x, uv.y );
  16266. // increase index
  16267. index ++;
  16268. }
  16269. }
  16270. // generate indices
  16271. for ( i = 0; i < segments; i ++ ) {
  16272. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16273. base = j + i * points.length;
  16274. // indices
  16275. var a = base;
  16276. var b = base + points.length;
  16277. var c = base + points.length + 1;
  16278. var d = base + 1;
  16279. // face one
  16280. indices.setX( indexOffset, a ); indexOffset++;
  16281. indices.setX( indexOffset, b ); indexOffset++;
  16282. indices.setX( indexOffset, d ); indexOffset++;
  16283. // face two
  16284. indices.setX( indexOffset, b ); indexOffset++;
  16285. indices.setX( indexOffset, c ); indexOffset++;
  16286. indices.setX( indexOffset, d ); indexOffset++;
  16287. }
  16288. }
  16289. // build geometry
  16290. this.setIndex( indices );
  16291. this.addAttribute( 'position', vertices );
  16292. this.addAttribute( 'uv', uvs );
  16293. // generate normals
  16294. this.computeVertexNormals();
  16295. // if the geometry is closed, we need to average the normals along the seam.
  16296. // because the corresponding vertices are identical (but still have different UVs).
  16297. if( phiLength === Math.PI * 2 ) {
  16298. var normals = this.attributes.normal.array;
  16299. var n1 = new Vector3();
  16300. var n2 = new Vector3();
  16301. var n = new Vector3();
  16302. // this is the buffer offset for the last line of vertices
  16303. base = segments * points.length * 3;
  16304. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16305. // select the normal of the vertex in the first line
  16306. n1.x = normals[ j + 0 ];
  16307. n1.y = normals[ j + 1 ];
  16308. n1.z = normals[ j + 2 ];
  16309. // select the normal of the vertex in the last line
  16310. n2.x = normals[ base + j + 0 ];
  16311. n2.y = normals[ base + j + 1 ];
  16312. n2.z = normals[ base + j + 2 ];
  16313. // average normals
  16314. n.addVectors( n1, n2 ).normalize();
  16315. // assign the new values to both normals
  16316. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16317. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16318. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16319. } // next row
  16320. }
  16321. }
  16322. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16323. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16324. /**
  16325. * @author astrodud / http://astrodud.isgreat.org/
  16326. * @author zz85 / https://github.com/zz85
  16327. * @author bhouston / http://clara.io
  16328. */
  16329. // points - to create a closed torus, one must use a set of points
  16330. // like so: [ a, b, c, d, a ], see first is the same as last.
  16331. // segments - the number of circumference segments to create
  16332. // phiStart - the starting radian
  16333. // phiLength - the radian (0 to 2PI) range of the lathed section
  16334. // 2PI is a closed lathe, less than 2PI is a portion.
  16335. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16336. Geometry.call( this );
  16337. this.type = 'LatheGeometry';
  16338. this.parameters = {
  16339. points: points,
  16340. segments: segments,
  16341. phiStart: phiStart,
  16342. phiLength: phiLength
  16343. };
  16344. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16345. this.mergeVertices();
  16346. }
  16347. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16348. LatheGeometry.prototype.constructor = LatheGeometry;
  16349. /**
  16350. * @author Mugen87 / https://github.com/Mugen87
  16351. *
  16352. * Creates a one-sided polygonal geometry from one or more shapes.
  16353. *
  16354. **/
  16355. function ShapeBufferGeometry( shapes, curveSegments ) {
  16356. BufferGeometry.call( this );
  16357. this.type = 'ShapeBufferGeometry';
  16358. this.parameters = {
  16359. shapes: shapes,
  16360. curveSegments: curveSegments
  16361. };
  16362. curveSegments = curveSegments || 12;
  16363. var vertices = [];
  16364. var normals = [];
  16365. var uvs = [];
  16366. var indices = [];
  16367. var groupStart = 0;
  16368. var groupCount = 0;
  16369. // allow single and array values for "shapes" parameter
  16370. if ( Array.isArray( shapes ) === false ) {
  16371. addShape( shapes );
  16372. } else {
  16373. for ( var i = 0; i < shapes.length; i++ ) {
  16374. addShape( shapes[ i ] );
  16375. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16376. groupStart += groupCount;
  16377. groupCount = 0;
  16378. }
  16379. }
  16380. // build geometry
  16381. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16382. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16383. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16384. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16385. // helper functions
  16386. function addShape( shape ) {
  16387. var i, l, shapeHole;
  16388. var indexOffset = vertices.length / 3;
  16389. var points = shape.extractPoints( curveSegments );
  16390. var shapeVertices = points.shape;
  16391. var shapeHoles = points.holes;
  16392. // check direction of vertices
  16393. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16394. shapeVertices = shapeVertices.reverse();
  16395. // also check if holes are in the opposite direction
  16396. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16397. shapeHole = shapeHoles[ i ];
  16398. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16399. shapeHoles[ i ] = shapeHole.reverse();
  16400. }
  16401. }
  16402. }
  16403. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16404. // join vertices of inner and outer paths to a single array
  16405. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16406. shapeHole = shapeHoles[ i ];
  16407. shapeVertices = shapeVertices.concat( shapeHole );
  16408. }
  16409. // vertices, normals, uvs
  16410. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16411. var vertex = shapeVertices[ i ];
  16412. vertices.push( vertex.x, vertex.y, 0 );
  16413. normals.push( 0, 0, 1 );
  16414. uvs.push( vertex.x, vertex.y ); // world uvs
  16415. }
  16416. // incides
  16417. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16418. var face = faces[ i ];
  16419. var a = face[ 0 ] + indexOffset;
  16420. var b = face[ 1 ] + indexOffset;
  16421. var c = face[ 2 ] + indexOffset;
  16422. indices.push( a, b, c );
  16423. groupCount += 3;
  16424. }
  16425. }
  16426. }
  16427. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16428. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16429. /**
  16430. * @author jonobr1 / http://jonobr1.com
  16431. *
  16432. * Creates a one-sided polygonal geometry from a path shape.
  16433. *
  16434. **/
  16435. function ShapeGeometry( shapes, curveSegments ) {
  16436. Geometry.call( this );
  16437. this.type = 'ShapeGeometry';
  16438. if ( typeof curveSegments === 'object' ) {
  16439. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16440. curveSegments = curveSegments.curveSegments;
  16441. }
  16442. this.parameters = {
  16443. shapes: shapes,
  16444. curveSegments: curveSegments
  16445. };
  16446. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16447. this.mergeVertices();
  16448. }
  16449. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16450. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16451. /**
  16452. * @author WestLangley / http://github.com/WestLangley
  16453. */
  16454. function EdgesGeometry( geometry, thresholdAngle ) {
  16455. BufferGeometry.call( this );
  16456. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16457. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16458. var edge = [ 0, 0 ], hash = {};
  16459. function sortFunction( a, b ) {
  16460. return a - b;
  16461. }
  16462. var keys = [ 'a', 'b', 'c' ];
  16463. var geometry2;
  16464. if ( geometry.isBufferGeometry ) {
  16465. geometry2 = new Geometry();
  16466. geometry2.fromBufferGeometry( geometry );
  16467. } else {
  16468. geometry2 = geometry.clone();
  16469. }
  16470. geometry2.mergeVertices();
  16471. geometry2.computeFaceNormals();
  16472. var vertices = geometry2.vertices;
  16473. var faces = geometry2.faces;
  16474. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16475. var face = faces[ i ];
  16476. for ( var j = 0; j < 3; j ++ ) {
  16477. edge[ 0 ] = face[ keys[ j ] ];
  16478. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  16479. edge.sort( sortFunction );
  16480. var key = edge.toString();
  16481. if ( hash[ key ] === undefined ) {
  16482. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  16483. } else {
  16484. hash[ key ].face2 = i;
  16485. }
  16486. }
  16487. }
  16488. var coords = [];
  16489. for ( var key in hash ) {
  16490. var h = hash[ key ];
  16491. // An edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16492. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  16493. var vertex = vertices[ h.vert1 ];
  16494. coords.push( vertex.x );
  16495. coords.push( vertex.y );
  16496. coords.push( vertex.z );
  16497. vertex = vertices[ h.vert2 ];
  16498. coords.push( vertex.x );
  16499. coords.push( vertex.y );
  16500. coords.push( vertex.z );
  16501. }
  16502. }
  16503. this.addAttribute( 'position', new Float32BufferAttribute( coords, 3 ) );
  16504. }
  16505. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16506. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16507. /**
  16508. * @author Mugen87 / https://github.com/Mugen87
  16509. */
  16510. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16511. BufferGeometry.call( this );
  16512. this.type = 'CylinderBufferGeometry';
  16513. this.parameters = {
  16514. radiusTop: radiusTop,
  16515. radiusBottom: radiusBottom,
  16516. height: height,
  16517. radialSegments: radialSegments,
  16518. heightSegments: heightSegments,
  16519. openEnded: openEnded,
  16520. thetaStart: thetaStart,
  16521. thetaLength: thetaLength
  16522. };
  16523. var scope = this;
  16524. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16525. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16526. height = height !== undefined ? height : 100;
  16527. radialSegments = Math.floor( radialSegments ) || 8;
  16528. heightSegments = Math.floor( heightSegments ) || 1;
  16529. openEnded = openEnded !== undefined ? openEnded : false;
  16530. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16531. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16532. // used to calculate buffer length
  16533. var nbCap = 0;
  16534. if ( openEnded === false ) {
  16535. if ( radiusTop > 0 ) nbCap ++;
  16536. if ( radiusBottom > 0 ) nbCap ++;
  16537. }
  16538. var vertexCount = calculateVertexCount();
  16539. var indexCount = calculateIndexCount();
  16540. // buffers
  16541. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  16542. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16543. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16544. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16545. // helper variables
  16546. var index = 0,
  16547. indexOffset = 0,
  16548. indexArray = [],
  16549. halfHeight = height / 2;
  16550. // group variables
  16551. var groupStart = 0;
  16552. // generate geometry
  16553. generateTorso();
  16554. if ( openEnded === false ) {
  16555. if ( radiusTop > 0 ) generateCap( true );
  16556. if ( radiusBottom > 0 ) generateCap( false );
  16557. }
  16558. // build geometry
  16559. this.setIndex( indices );
  16560. this.addAttribute( 'position', vertices );
  16561. this.addAttribute( 'normal', normals );
  16562. this.addAttribute( 'uv', uvs );
  16563. // helper functions
  16564. function calculateVertexCount() {
  16565. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  16566. if ( openEnded === false ) {
  16567. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  16568. }
  16569. return count;
  16570. }
  16571. function calculateIndexCount() {
  16572. var count = radialSegments * heightSegments * 2 * 3;
  16573. if ( openEnded === false ) {
  16574. count += radialSegments * nbCap * 3;
  16575. }
  16576. return count;
  16577. }
  16578. function generateTorso() {
  16579. var x, y;
  16580. var normal = new Vector3();
  16581. var vertex = new Vector3();
  16582. var groupCount = 0;
  16583. // this will be used to calculate the normal
  16584. var slope = ( radiusBottom - radiusTop ) / height;
  16585. // generate vertices, normals and uvs
  16586. for ( y = 0; y <= heightSegments; y ++ ) {
  16587. var indexRow = [];
  16588. var v = y / heightSegments;
  16589. // calculate the radius of the current row
  16590. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16591. for ( x = 0; x <= radialSegments; x ++ ) {
  16592. var u = x / radialSegments;
  16593. var theta = u * thetaLength + thetaStart;
  16594. var sinTheta = Math.sin( theta );
  16595. var cosTheta = Math.cos( theta );
  16596. // vertex
  16597. vertex.x = radius * sinTheta;
  16598. vertex.y = - v * height + halfHeight;
  16599. vertex.z = radius * cosTheta;
  16600. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16601. // normal
  16602. normal.set( sinTheta, slope, cosTheta ).normalize();
  16603. normals.setXYZ( index, normal.x, normal.y, normal.z );
  16604. // uv
  16605. uvs.setXY( index, u, 1 - v );
  16606. // save index of vertex in respective row
  16607. indexRow.push( index );
  16608. // increase index
  16609. index ++;
  16610. }
  16611. // now save vertices of the row in our index array
  16612. indexArray.push( indexRow );
  16613. }
  16614. // generate indices
  16615. for ( x = 0; x < radialSegments; x ++ ) {
  16616. for ( y = 0; y < heightSegments; y ++ ) {
  16617. // we use the index array to access the correct indices
  16618. var i1 = indexArray[ y ][ x ];
  16619. var i2 = indexArray[ y + 1 ][ x ];
  16620. var i3 = indexArray[ y + 1 ][ x + 1 ];
  16621. var i4 = indexArray[ y ][ x + 1 ];
  16622. // face one
  16623. indices.setX( indexOffset, i1 ); indexOffset ++;
  16624. indices.setX( indexOffset, i2 ); indexOffset ++;
  16625. indices.setX( indexOffset, i4 ); indexOffset ++;
  16626. // face two
  16627. indices.setX( indexOffset, i2 ); indexOffset ++;
  16628. indices.setX( indexOffset, i3 ); indexOffset ++;
  16629. indices.setX( indexOffset, i4 ); indexOffset ++;
  16630. // update counters
  16631. groupCount += 6;
  16632. }
  16633. }
  16634. // add a group to the geometry. this will ensure multi material support
  16635. scope.addGroup( groupStart, groupCount, 0 );
  16636. // calculate new start value for groups
  16637. groupStart += groupCount;
  16638. }
  16639. function generateCap( top ) {
  16640. var x, centerIndexStart, centerIndexEnd;
  16641. var uv = new Vector2();
  16642. var vertex = new Vector3();
  16643. var groupCount = 0;
  16644. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16645. var sign = ( top === true ) ? 1 : - 1;
  16646. // save the index of the first center vertex
  16647. centerIndexStart = index;
  16648. // first we generate the center vertex data of the cap.
  16649. // because the geometry needs one set of uvs per face,
  16650. // we must generate a center vertex per face/segment
  16651. for ( x = 1; x <= radialSegments; x ++ ) {
  16652. // vertex
  16653. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  16654. // normal
  16655. normals.setXYZ( index, 0, sign, 0 );
  16656. // uv
  16657. uv.x = 0.5;
  16658. uv.y = 0.5;
  16659. uvs.setXY( index, uv.x, uv.y );
  16660. // increase index
  16661. index ++;
  16662. }
  16663. // save the index of the last center vertex
  16664. centerIndexEnd = index;
  16665. // now we generate the surrounding vertices, normals and uvs
  16666. for ( x = 0; x <= radialSegments; x ++ ) {
  16667. var u = x / radialSegments;
  16668. var theta = u * thetaLength + thetaStart;
  16669. var cosTheta = Math.cos( theta );
  16670. var sinTheta = Math.sin( theta );
  16671. // vertex
  16672. vertex.x = radius * sinTheta;
  16673. vertex.y = halfHeight * sign;
  16674. vertex.z = radius * cosTheta;
  16675. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16676. // normal
  16677. normals.setXYZ( index, 0, sign, 0 );
  16678. // uv
  16679. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16680. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16681. uvs.setXY( index, uv.x, uv.y );
  16682. // increase index
  16683. index ++;
  16684. }
  16685. // generate indices
  16686. for ( x = 0; x < radialSegments; x ++ ) {
  16687. var c = centerIndexStart + x;
  16688. var i = centerIndexEnd + x;
  16689. if ( top === true ) {
  16690. // face top
  16691. indices.setX( indexOffset, i ); indexOffset ++;
  16692. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16693. indices.setX( indexOffset, c ); indexOffset ++;
  16694. } else {
  16695. // face bottom
  16696. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16697. indices.setX( indexOffset, i ); indexOffset ++;
  16698. indices.setX( indexOffset, c ); indexOffset ++;
  16699. }
  16700. // update counters
  16701. groupCount += 3;
  16702. }
  16703. // add a group to the geometry. this will ensure multi material support
  16704. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16705. // calculate new start value for groups
  16706. groupStart += groupCount;
  16707. }
  16708. }
  16709. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16710. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16711. /**
  16712. * @author mrdoob / http://mrdoob.com/
  16713. */
  16714. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16715. Geometry.call( this );
  16716. this.type = 'CylinderGeometry';
  16717. this.parameters = {
  16718. radiusTop: radiusTop,
  16719. radiusBottom: radiusBottom,
  16720. height: height,
  16721. radialSegments: radialSegments,
  16722. heightSegments: heightSegments,
  16723. openEnded: openEnded,
  16724. thetaStart: thetaStart,
  16725. thetaLength: thetaLength
  16726. };
  16727. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16728. this.mergeVertices();
  16729. }
  16730. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16731. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16732. /**
  16733. * @author abelnation / http://github.com/abelnation
  16734. */
  16735. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16736. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16737. this.type = 'ConeGeometry';
  16738. this.parameters = {
  16739. radius: radius,
  16740. height: height,
  16741. radialSegments: radialSegments,
  16742. heightSegments: heightSegments,
  16743. openEnded: openEnded,
  16744. thetaStart: thetaStart,
  16745. thetaLength: thetaLength
  16746. };
  16747. }
  16748. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16749. ConeGeometry.prototype.constructor = ConeGeometry;
  16750. /**
  16751. * @author: abelnation / http://github.com/abelnation
  16752. */
  16753. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16754. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16755. this.type = 'ConeBufferGeometry';
  16756. this.parameters = {
  16757. radius: radius,
  16758. height: height,
  16759. radialSegments: radialSegments,
  16760. heightSegments: heightSegments,
  16761. openEnded: openEnded,
  16762. thetaStart: thetaStart,
  16763. thetaLength: thetaLength
  16764. };
  16765. }
  16766. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16767. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16768. /**
  16769. * @author benaadams / https://twitter.com/ben_a_adams
  16770. */
  16771. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16772. BufferGeometry.call( this );
  16773. this.type = 'CircleBufferGeometry';
  16774. this.parameters = {
  16775. radius: radius,
  16776. segments: segments,
  16777. thetaStart: thetaStart,
  16778. thetaLength: thetaLength
  16779. };
  16780. radius = radius || 50;
  16781. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16782. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16783. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16784. var vertices = segments + 2;
  16785. var positions = new Float32Array( vertices * 3 );
  16786. var normals = new Float32Array( vertices * 3 );
  16787. var uvs = new Float32Array( vertices * 2 );
  16788. // center data is already zero, but need to set a few extras
  16789. normals[ 2 ] = 1.0;
  16790. uvs[ 0 ] = 0.5;
  16791. uvs[ 1 ] = 0.5;
  16792. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  16793. var segment = thetaStart + s / segments * thetaLength;
  16794. positions[ i ] = radius * Math.cos( segment );
  16795. positions[ i + 1 ] = radius * Math.sin( segment );
  16796. normals[ i + 2 ] = 1; // normal z
  16797. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  16798. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  16799. }
  16800. var indices = [];
  16801. for ( var i = 1; i <= segments; i ++ ) {
  16802. indices.push( i, i + 1, 0 );
  16803. }
  16804. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  16805. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  16806. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  16807. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  16808. this.boundingSphere = new Sphere( new Vector3(), radius );
  16809. }
  16810. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16811. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16812. /**
  16813. * @author hughes
  16814. */
  16815. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16816. Geometry.call( this );
  16817. this.type = 'CircleGeometry';
  16818. this.parameters = {
  16819. radius: radius,
  16820. segments: segments,
  16821. thetaStart: thetaStart,
  16822. thetaLength: thetaLength
  16823. };
  16824. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16825. }
  16826. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16827. CircleGeometry.prototype.constructor = CircleGeometry;
  16828. /**
  16829. * @author mrdoob / http://mrdoob.com/
  16830. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  16831. */
  16832. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  16833. Geometry.call( this );
  16834. this.type = 'BoxGeometry';
  16835. this.parameters = {
  16836. width: width,
  16837. height: height,
  16838. depth: depth,
  16839. widthSegments: widthSegments,
  16840. heightSegments: heightSegments,
  16841. depthSegments: depthSegments
  16842. };
  16843. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  16844. this.mergeVertices();
  16845. }
  16846. BoxGeometry.prototype = Object.create( Geometry.prototype );
  16847. BoxGeometry.prototype.constructor = BoxGeometry;
  16848. var Geometries = Object.freeze({
  16849. WireframeGeometry: WireframeGeometry,
  16850. ParametricGeometry: ParametricGeometry,
  16851. ParametricBufferGeometry: ParametricBufferGeometry,
  16852. TetrahedronGeometry: TetrahedronGeometry,
  16853. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16854. OctahedronGeometry: OctahedronGeometry,
  16855. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16856. IcosahedronGeometry: IcosahedronGeometry,
  16857. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16858. DodecahedronGeometry: DodecahedronGeometry,
  16859. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  16860. PolyhedronGeometry: PolyhedronGeometry,
  16861. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  16862. TubeGeometry: TubeGeometry,
  16863. TubeBufferGeometry: TubeBufferGeometry,
  16864. TorusKnotGeometry: TorusKnotGeometry,
  16865. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  16866. TorusGeometry: TorusGeometry,
  16867. TorusBufferGeometry: TorusBufferGeometry,
  16868. TextGeometry: TextGeometry,
  16869. SphereBufferGeometry: SphereBufferGeometry,
  16870. SphereGeometry: SphereGeometry,
  16871. RingGeometry: RingGeometry,
  16872. RingBufferGeometry: RingBufferGeometry,
  16873. PlaneBufferGeometry: PlaneBufferGeometry,
  16874. PlaneGeometry: PlaneGeometry,
  16875. LatheGeometry: LatheGeometry,
  16876. LatheBufferGeometry: LatheBufferGeometry,
  16877. ShapeGeometry: ShapeGeometry,
  16878. ShapeBufferGeometry: ShapeBufferGeometry,
  16879. ExtrudeGeometry: ExtrudeGeometry,
  16880. EdgesGeometry: EdgesGeometry,
  16881. ConeGeometry: ConeGeometry,
  16882. ConeBufferGeometry: ConeBufferGeometry,
  16883. CylinderGeometry: CylinderGeometry,
  16884. CylinderBufferGeometry: CylinderBufferGeometry,
  16885. CircleBufferGeometry: CircleBufferGeometry,
  16886. CircleGeometry: CircleGeometry,
  16887. BoxBufferGeometry: BoxBufferGeometry,
  16888. BoxGeometry: BoxGeometry
  16889. });
  16890. /**
  16891. * @author mrdoob / http://mrdoob.com/
  16892. */
  16893. function ShadowMaterial() {
  16894. ShaderMaterial.call( this, {
  16895. uniforms: UniformsUtils.merge( [
  16896. UniformsLib.lights,
  16897. {
  16898. opacity: { value: 1.0 }
  16899. }
  16900. ] ),
  16901. vertexShader: ShaderChunk[ 'shadow_vert' ],
  16902. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  16903. } );
  16904. this.lights = true;
  16905. this.transparent = true;
  16906. Object.defineProperties( this, {
  16907. opacity: {
  16908. enumerable: true,
  16909. get: function () {
  16910. return this.uniforms.opacity.value;
  16911. },
  16912. set: function ( value ) {
  16913. this.uniforms.opacity.value = value;
  16914. }
  16915. }
  16916. } );
  16917. }
  16918. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16919. ShadowMaterial.prototype.constructor = ShadowMaterial;
  16920. ShadowMaterial.prototype.isShadowMaterial = true;
  16921. /**
  16922. * @author mrdoob / http://mrdoob.com/
  16923. */
  16924. function RawShaderMaterial( parameters ) {
  16925. ShaderMaterial.call( this, parameters );
  16926. this.type = 'RawShaderMaterial';
  16927. }
  16928. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16929. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  16930. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  16931. /**
  16932. * @author mrdoob / http://mrdoob.com/
  16933. */
  16934. function MultiMaterial( materials ) {
  16935. this.uuid = _Math.generateUUID();
  16936. this.type = 'MultiMaterial';
  16937. this.materials = Array.isArray( materials ) ? materials : [];
  16938. this.visible = true;
  16939. }
  16940. MultiMaterial.prototype = {
  16941. constructor: MultiMaterial,
  16942. isMultiMaterial: true,
  16943. toJSON: function ( meta ) {
  16944. var output = {
  16945. metadata: {
  16946. version: 4.2,
  16947. type: 'material',
  16948. generator: 'MaterialExporter'
  16949. },
  16950. uuid: this.uuid,
  16951. type: this.type,
  16952. materials: []
  16953. };
  16954. var materials = this.materials;
  16955. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16956. var material = materials[ i ].toJSON( meta );
  16957. delete material.metadata;
  16958. output.materials.push( material );
  16959. }
  16960. output.visible = this.visible;
  16961. return output;
  16962. },
  16963. clone: function () {
  16964. var material = new this.constructor();
  16965. for ( var i = 0; i < this.materials.length; i ++ ) {
  16966. material.materials.push( this.materials[ i ].clone() );
  16967. }
  16968. material.visible = this.visible;
  16969. return material;
  16970. }
  16971. };
  16972. /**
  16973. * @author WestLangley / http://github.com/WestLangley
  16974. *
  16975. * parameters = {
  16976. * color: <hex>,
  16977. * roughness: <float>,
  16978. * metalness: <float>,
  16979. * opacity: <float>,
  16980. *
  16981. * map: new THREE.Texture( <Image> ),
  16982. *
  16983. * lightMap: new THREE.Texture( <Image> ),
  16984. * lightMapIntensity: <float>
  16985. *
  16986. * aoMap: new THREE.Texture( <Image> ),
  16987. * aoMapIntensity: <float>
  16988. *
  16989. * emissive: <hex>,
  16990. * emissiveIntensity: <float>
  16991. * emissiveMap: new THREE.Texture( <Image> ),
  16992. *
  16993. * bumpMap: new THREE.Texture( <Image> ),
  16994. * bumpScale: <float>,
  16995. *
  16996. * normalMap: new THREE.Texture( <Image> ),
  16997. * normalScale: <Vector2>,
  16998. *
  16999. * displacementMap: new THREE.Texture( <Image> ),
  17000. * displacementScale: <float>,
  17001. * displacementBias: <float>,
  17002. *
  17003. * roughnessMap: new THREE.Texture( <Image> ),
  17004. *
  17005. * metalnessMap: new THREE.Texture( <Image> ),
  17006. *
  17007. * alphaMap: new THREE.Texture( <Image> ),
  17008. *
  17009. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17010. * envMapIntensity: <float>
  17011. *
  17012. * refractionRatio: <float>,
  17013. *
  17014. * wireframe: <boolean>,
  17015. * wireframeLinewidth: <float>,
  17016. *
  17017. * skinning: <bool>,
  17018. * morphTargets: <bool>,
  17019. * morphNormals: <bool>
  17020. * }
  17021. */
  17022. function MeshStandardMaterial( parameters ) {
  17023. Material.call( this );
  17024. this.defines = { 'STANDARD': '' };
  17025. this.type = 'MeshStandardMaterial';
  17026. this.color = new Color( 0xffffff ); // diffuse
  17027. this.roughness = 0.5;
  17028. this.metalness = 0.5;
  17029. this.map = null;
  17030. this.lightMap = null;
  17031. this.lightMapIntensity = 1.0;
  17032. this.aoMap = null;
  17033. this.aoMapIntensity = 1.0;
  17034. this.emissive = new Color( 0x000000 );
  17035. this.emissiveIntensity = 1.0;
  17036. this.emissiveMap = null;
  17037. this.bumpMap = null;
  17038. this.bumpScale = 1;
  17039. this.normalMap = null;
  17040. this.normalScale = new Vector2( 1, 1 );
  17041. this.displacementMap = null;
  17042. this.displacementScale = 1;
  17043. this.displacementBias = 0;
  17044. this.roughnessMap = null;
  17045. this.metalnessMap = null;
  17046. this.alphaMap = null;
  17047. this.envMap = null;
  17048. this.envMapIntensity = 1.0;
  17049. this.refractionRatio = 0.98;
  17050. this.wireframe = false;
  17051. this.wireframeLinewidth = 1;
  17052. this.wireframeLinecap = 'round';
  17053. this.wireframeLinejoin = 'round';
  17054. this.skinning = false;
  17055. this.morphTargets = false;
  17056. this.morphNormals = false;
  17057. this.setValues( parameters );
  17058. }
  17059. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17060. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17061. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17062. MeshStandardMaterial.prototype.copy = function ( source ) {
  17063. Material.prototype.copy.call( this, source );
  17064. this.defines = { 'STANDARD': '' };
  17065. this.color.copy( source.color );
  17066. this.roughness = source.roughness;
  17067. this.metalness = source.metalness;
  17068. this.map = source.map;
  17069. this.lightMap = source.lightMap;
  17070. this.lightMapIntensity = source.lightMapIntensity;
  17071. this.aoMap = source.aoMap;
  17072. this.aoMapIntensity = source.aoMapIntensity;
  17073. this.emissive.copy( source.emissive );
  17074. this.emissiveMap = source.emissiveMap;
  17075. this.emissiveIntensity = source.emissiveIntensity;
  17076. this.bumpMap = source.bumpMap;
  17077. this.bumpScale = source.bumpScale;
  17078. this.normalMap = source.normalMap;
  17079. this.normalScale.copy( source.normalScale );
  17080. this.displacementMap = source.displacementMap;
  17081. this.displacementScale = source.displacementScale;
  17082. this.displacementBias = source.displacementBias;
  17083. this.roughnessMap = source.roughnessMap;
  17084. this.metalnessMap = source.metalnessMap;
  17085. this.alphaMap = source.alphaMap;
  17086. this.envMap = source.envMap;
  17087. this.envMapIntensity = source.envMapIntensity;
  17088. this.refractionRatio = source.refractionRatio;
  17089. this.wireframe = source.wireframe;
  17090. this.wireframeLinewidth = source.wireframeLinewidth;
  17091. this.wireframeLinecap = source.wireframeLinecap;
  17092. this.wireframeLinejoin = source.wireframeLinejoin;
  17093. this.skinning = source.skinning;
  17094. this.morphTargets = source.morphTargets;
  17095. this.morphNormals = source.morphNormals;
  17096. return this;
  17097. };
  17098. /**
  17099. * @author WestLangley / http://github.com/WestLangley
  17100. *
  17101. * parameters = {
  17102. * reflectivity: <float>
  17103. * }
  17104. */
  17105. function MeshPhysicalMaterial( parameters ) {
  17106. MeshStandardMaterial.call( this );
  17107. this.defines = { 'PHYSICAL': '' };
  17108. this.type = 'MeshPhysicalMaterial';
  17109. this.reflectivity = 0.5; // maps to F0 = 0.04
  17110. this.clearCoat = 0.0;
  17111. this.clearCoatRoughness = 0.0;
  17112. this.setValues( parameters );
  17113. }
  17114. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17115. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17116. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17117. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17118. MeshStandardMaterial.prototype.copy.call( this, source );
  17119. this.defines = { 'PHYSICAL': '' };
  17120. this.reflectivity = source.reflectivity;
  17121. this.clearCoat = source.clearCoat;
  17122. this.clearCoatRoughness = source.clearCoatRoughness;
  17123. return this;
  17124. };
  17125. /**
  17126. * @author mrdoob / http://mrdoob.com/
  17127. * @author alteredq / http://alteredqualia.com/
  17128. *
  17129. * parameters = {
  17130. * color: <hex>,
  17131. * specular: <hex>,
  17132. * shininess: <float>,
  17133. * opacity: <float>,
  17134. *
  17135. * map: new THREE.Texture( <Image> ),
  17136. *
  17137. * lightMap: new THREE.Texture( <Image> ),
  17138. * lightMapIntensity: <float>
  17139. *
  17140. * aoMap: new THREE.Texture( <Image> ),
  17141. * aoMapIntensity: <float>
  17142. *
  17143. * emissive: <hex>,
  17144. * emissiveIntensity: <float>
  17145. * emissiveMap: new THREE.Texture( <Image> ),
  17146. *
  17147. * bumpMap: new THREE.Texture( <Image> ),
  17148. * bumpScale: <float>,
  17149. *
  17150. * normalMap: new THREE.Texture( <Image> ),
  17151. * normalScale: <Vector2>,
  17152. *
  17153. * displacementMap: new THREE.Texture( <Image> ),
  17154. * displacementScale: <float>,
  17155. * displacementBias: <float>,
  17156. *
  17157. * specularMap: new THREE.Texture( <Image> ),
  17158. *
  17159. * alphaMap: new THREE.Texture( <Image> ),
  17160. *
  17161. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17162. * combine: THREE.Multiply,
  17163. * reflectivity: <float>,
  17164. * refractionRatio: <float>,
  17165. *
  17166. * wireframe: <boolean>,
  17167. * wireframeLinewidth: <float>,
  17168. *
  17169. * skinning: <bool>,
  17170. * morphTargets: <bool>,
  17171. * morphNormals: <bool>
  17172. * }
  17173. */
  17174. function MeshPhongMaterial( parameters ) {
  17175. Material.call( this );
  17176. this.type = 'MeshPhongMaterial';
  17177. this.color = new Color( 0xffffff ); // diffuse
  17178. this.specular = new Color( 0x111111 );
  17179. this.shininess = 30;
  17180. this.map = null;
  17181. this.lightMap = null;
  17182. this.lightMapIntensity = 1.0;
  17183. this.aoMap = null;
  17184. this.aoMapIntensity = 1.0;
  17185. this.emissive = new Color( 0x000000 );
  17186. this.emissiveIntensity = 1.0;
  17187. this.emissiveMap = null;
  17188. this.bumpMap = null;
  17189. this.bumpScale = 1;
  17190. this.normalMap = null;
  17191. this.normalScale = new Vector2( 1, 1 );
  17192. this.displacementMap = null;
  17193. this.displacementScale = 1;
  17194. this.displacementBias = 0;
  17195. this.specularMap = null;
  17196. this.alphaMap = null;
  17197. this.envMap = null;
  17198. this.combine = MultiplyOperation;
  17199. this.reflectivity = 1;
  17200. this.refractionRatio = 0.98;
  17201. this.wireframe = false;
  17202. this.wireframeLinewidth = 1;
  17203. this.wireframeLinecap = 'round';
  17204. this.wireframeLinejoin = 'round';
  17205. this.skinning = false;
  17206. this.morphTargets = false;
  17207. this.morphNormals = false;
  17208. this.setValues( parameters );
  17209. }
  17210. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17211. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17212. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17213. MeshPhongMaterial.prototype.copy = function ( source ) {
  17214. Material.prototype.copy.call( this, source );
  17215. this.color.copy( source.color );
  17216. this.specular.copy( source.specular );
  17217. this.shininess = source.shininess;
  17218. this.map = source.map;
  17219. this.lightMap = source.lightMap;
  17220. this.lightMapIntensity = source.lightMapIntensity;
  17221. this.aoMap = source.aoMap;
  17222. this.aoMapIntensity = source.aoMapIntensity;
  17223. this.emissive.copy( source.emissive );
  17224. this.emissiveMap = source.emissiveMap;
  17225. this.emissiveIntensity = source.emissiveIntensity;
  17226. this.bumpMap = source.bumpMap;
  17227. this.bumpScale = source.bumpScale;
  17228. this.normalMap = source.normalMap;
  17229. this.normalScale.copy( source.normalScale );
  17230. this.displacementMap = source.displacementMap;
  17231. this.displacementScale = source.displacementScale;
  17232. this.displacementBias = source.displacementBias;
  17233. this.specularMap = source.specularMap;
  17234. this.alphaMap = source.alphaMap;
  17235. this.envMap = source.envMap;
  17236. this.combine = source.combine;
  17237. this.reflectivity = source.reflectivity;
  17238. this.refractionRatio = source.refractionRatio;
  17239. this.wireframe = source.wireframe;
  17240. this.wireframeLinewidth = source.wireframeLinewidth;
  17241. this.wireframeLinecap = source.wireframeLinecap;
  17242. this.wireframeLinejoin = source.wireframeLinejoin;
  17243. this.skinning = source.skinning;
  17244. this.morphTargets = source.morphTargets;
  17245. this.morphNormals = source.morphNormals;
  17246. return this;
  17247. };
  17248. /**
  17249. * @author takahirox / http://github.com/takahirox
  17250. *
  17251. * parameters = {
  17252. * gradientMap: new THREE.Texture( <Image> )
  17253. * }
  17254. */
  17255. function MeshToonMaterial( parameters ) {
  17256. MeshPhongMaterial.call( this );
  17257. this.defines = { 'TOON': '' };
  17258. this.type = 'MeshToonMaterial';
  17259. this.gradientMap = null;
  17260. this.setValues( parameters );
  17261. }
  17262. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17263. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17264. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17265. MeshToonMaterial.prototype.copy = function ( source ) {
  17266. MeshPhongMaterial.prototype.copy.call( this, source );
  17267. this.gradientMap = source.gradientMap;
  17268. return this;
  17269. };
  17270. /**
  17271. * @author mrdoob / http://mrdoob.com/
  17272. * @author WestLangley / http://github.com/WestLangley
  17273. *
  17274. * parameters = {
  17275. * opacity: <float>,
  17276. *
  17277. * bumpMap: new THREE.Texture( <Image> ),
  17278. * bumpScale: <float>,
  17279. *
  17280. * normalMap: new THREE.Texture( <Image> ),
  17281. * normalScale: <Vector2>,
  17282. *
  17283. * displacementMap: new THREE.Texture( <Image> ),
  17284. * displacementScale: <float>,
  17285. * displacementBias: <float>,
  17286. *
  17287. * wireframe: <boolean>,
  17288. * wireframeLinewidth: <float>
  17289. *
  17290. * skinning: <bool>,
  17291. * morphTargets: <bool>,
  17292. * morphNormals: <bool>
  17293. * }
  17294. */
  17295. function MeshNormalMaterial( parameters ) {
  17296. Material.call( this, parameters );
  17297. this.type = 'MeshNormalMaterial';
  17298. this.bumpMap = null;
  17299. this.bumpScale = 1;
  17300. this.normalMap = null;
  17301. this.normalScale = new Vector2( 1, 1 );
  17302. this.displacementMap = null;
  17303. this.displacementScale = 1;
  17304. this.displacementBias = 0;
  17305. this.wireframe = false;
  17306. this.wireframeLinewidth = 1;
  17307. this.fog = false;
  17308. this.lights = false;
  17309. this.skinning = false;
  17310. this.morphTargets = false;
  17311. this.morphNormals = false;
  17312. this.setValues( parameters );
  17313. }
  17314. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17315. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17316. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17317. MeshNormalMaterial.prototype.copy = function ( source ) {
  17318. Material.prototype.copy.call( this, source );
  17319. this.bumpMap = source.bumpMap;
  17320. this.bumpScale = source.bumpScale;
  17321. this.normalMap = source.normalMap;
  17322. this.normalScale.copy( source.normalScale );
  17323. this.displacementMap = source.displacementMap;
  17324. this.displacementScale = source.displacementScale;
  17325. this.displacementBias = source.displacementBias;
  17326. this.wireframe = source.wireframe;
  17327. this.wireframeLinewidth = source.wireframeLinewidth;
  17328. this.skinning = source.skinning;
  17329. this.morphTargets = source.morphTargets;
  17330. this.morphNormals = source.morphNormals;
  17331. return this;
  17332. };
  17333. /**
  17334. * @author mrdoob / http://mrdoob.com/
  17335. * @author alteredq / http://alteredqualia.com/
  17336. *
  17337. * parameters = {
  17338. * color: <hex>,
  17339. * opacity: <float>,
  17340. *
  17341. * map: new THREE.Texture( <Image> ),
  17342. *
  17343. * lightMap: new THREE.Texture( <Image> ),
  17344. * lightMapIntensity: <float>
  17345. *
  17346. * aoMap: new THREE.Texture( <Image> ),
  17347. * aoMapIntensity: <float>
  17348. *
  17349. * emissive: <hex>,
  17350. * emissiveIntensity: <float>
  17351. * emissiveMap: new THREE.Texture( <Image> ),
  17352. *
  17353. * specularMap: new THREE.Texture( <Image> ),
  17354. *
  17355. * alphaMap: new THREE.Texture( <Image> ),
  17356. *
  17357. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17358. * combine: THREE.Multiply,
  17359. * reflectivity: <float>,
  17360. * refractionRatio: <float>,
  17361. *
  17362. * wireframe: <boolean>,
  17363. * wireframeLinewidth: <float>,
  17364. *
  17365. * skinning: <bool>,
  17366. * morphTargets: <bool>,
  17367. * morphNormals: <bool>
  17368. * }
  17369. */
  17370. function MeshLambertMaterial( parameters ) {
  17371. Material.call( this );
  17372. this.type = 'MeshLambertMaterial';
  17373. this.color = new Color( 0xffffff ); // diffuse
  17374. this.map = null;
  17375. this.lightMap = null;
  17376. this.lightMapIntensity = 1.0;
  17377. this.aoMap = null;
  17378. this.aoMapIntensity = 1.0;
  17379. this.emissive = new Color( 0x000000 );
  17380. this.emissiveIntensity = 1.0;
  17381. this.emissiveMap = null;
  17382. this.specularMap = null;
  17383. this.alphaMap = null;
  17384. this.envMap = null;
  17385. this.combine = MultiplyOperation;
  17386. this.reflectivity = 1;
  17387. this.refractionRatio = 0.98;
  17388. this.wireframe = false;
  17389. this.wireframeLinewidth = 1;
  17390. this.wireframeLinecap = 'round';
  17391. this.wireframeLinejoin = 'round';
  17392. this.skinning = false;
  17393. this.morphTargets = false;
  17394. this.morphNormals = false;
  17395. this.setValues( parameters );
  17396. }
  17397. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17398. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17399. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17400. MeshLambertMaterial.prototype.copy = function ( source ) {
  17401. Material.prototype.copy.call( this, source );
  17402. this.color.copy( source.color );
  17403. this.map = source.map;
  17404. this.lightMap = source.lightMap;
  17405. this.lightMapIntensity = source.lightMapIntensity;
  17406. this.aoMap = source.aoMap;
  17407. this.aoMapIntensity = source.aoMapIntensity;
  17408. this.emissive.copy( source.emissive );
  17409. this.emissiveMap = source.emissiveMap;
  17410. this.emissiveIntensity = source.emissiveIntensity;
  17411. this.specularMap = source.specularMap;
  17412. this.alphaMap = source.alphaMap;
  17413. this.envMap = source.envMap;
  17414. this.combine = source.combine;
  17415. this.reflectivity = source.reflectivity;
  17416. this.refractionRatio = source.refractionRatio;
  17417. this.wireframe = source.wireframe;
  17418. this.wireframeLinewidth = source.wireframeLinewidth;
  17419. this.wireframeLinecap = source.wireframeLinecap;
  17420. this.wireframeLinejoin = source.wireframeLinejoin;
  17421. this.skinning = source.skinning;
  17422. this.morphTargets = source.morphTargets;
  17423. this.morphNormals = source.morphNormals;
  17424. return this;
  17425. };
  17426. /**
  17427. * @author alteredq / http://alteredqualia.com/
  17428. *
  17429. * parameters = {
  17430. * color: <hex>,
  17431. * opacity: <float>,
  17432. *
  17433. * linewidth: <float>,
  17434. *
  17435. * scale: <float>,
  17436. * dashSize: <float>,
  17437. * gapSize: <float>
  17438. * }
  17439. */
  17440. function LineDashedMaterial( parameters ) {
  17441. Material.call( this );
  17442. this.type = 'LineDashedMaterial';
  17443. this.color = new Color( 0xffffff );
  17444. this.linewidth = 1;
  17445. this.scale = 1;
  17446. this.dashSize = 3;
  17447. this.gapSize = 1;
  17448. this.lights = false;
  17449. this.setValues( parameters );
  17450. }
  17451. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17452. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17453. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17454. LineDashedMaterial.prototype.copy = function ( source ) {
  17455. Material.prototype.copy.call( this, source );
  17456. this.color.copy( source.color );
  17457. this.linewidth = source.linewidth;
  17458. this.scale = source.scale;
  17459. this.dashSize = source.dashSize;
  17460. this.gapSize = source.gapSize;
  17461. return this;
  17462. };
  17463. var Materials = Object.freeze({
  17464. ShadowMaterial: ShadowMaterial,
  17465. SpriteMaterial: SpriteMaterial,
  17466. RawShaderMaterial: RawShaderMaterial,
  17467. ShaderMaterial: ShaderMaterial,
  17468. PointsMaterial: PointsMaterial,
  17469. MultiMaterial: MultiMaterial,
  17470. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17471. MeshStandardMaterial: MeshStandardMaterial,
  17472. MeshPhongMaterial: MeshPhongMaterial,
  17473. MeshToonMaterial: MeshToonMaterial,
  17474. MeshNormalMaterial: MeshNormalMaterial,
  17475. MeshLambertMaterial: MeshLambertMaterial,
  17476. MeshDepthMaterial: MeshDepthMaterial,
  17477. MeshBasicMaterial: MeshBasicMaterial,
  17478. LineDashedMaterial: LineDashedMaterial,
  17479. LineBasicMaterial: LineBasicMaterial,
  17480. Material: Material
  17481. });
  17482. /**
  17483. * @author mrdoob / http://mrdoob.com/
  17484. */
  17485. var Cache = {
  17486. enabled: false,
  17487. files: {},
  17488. add: function ( key, file ) {
  17489. if ( this.enabled === false ) return;
  17490. // console.log( 'THREE.Cache', 'Adding key:', key );
  17491. this.files[ key ] = file;
  17492. },
  17493. get: function ( key ) {
  17494. if ( this.enabled === false ) return;
  17495. // console.log( 'THREE.Cache', 'Checking key:', key );
  17496. return this.files[ key ];
  17497. },
  17498. remove: function ( key ) {
  17499. delete this.files[ key ];
  17500. },
  17501. clear: function () {
  17502. this.files = {};
  17503. }
  17504. };
  17505. /**
  17506. * @author mrdoob / http://mrdoob.com/
  17507. */
  17508. function LoadingManager( onLoad, onProgress, onError ) {
  17509. var scope = this;
  17510. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17511. this.onStart = undefined;
  17512. this.onLoad = onLoad;
  17513. this.onProgress = onProgress;
  17514. this.onError = onError;
  17515. this.itemStart = function ( url ) {
  17516. itemsTotal ++;
  17517. if ( isLoading === false ) {
  17518. if ( scope.onStart !== undefined ) {
  17519. scope.onStart( url, itemsLoaded, itemsTotal );
  17520. }
  17521. }
  17522. isLoading = true;
  17523. };
  17524. this.itemEnd = function ( url ) {
  17525. itemsLoaded ++;
  17526. if ( scope.onProgress !== undefined ) {
  17527. scope.onProgress( url, itemsLoaded, itemsTotal );
  17528. }
  17529. if ( itemsLoaded === itemsTotal ) {
  17530. isLoading = false;
  17531. if ( scope.onLoad !== undefined ) {
  17532. scope.onLoad();
  17533. }
  17534. }
  17535. };
  17536. this.itemError = function ( url ) {
  17537. if ( scope.onError !== undefined ) {
  17538. scope.onError( url );
  17539. }
  17540. };
  17541. }
  17542. var DefaultLoadingManager = new LoadingManager();
  17543. /**
  17544. * @author mrdoob / http://mrdoob.com/
  17545. */
  17546. function FileLoader( manager ) {
  17547. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17548. }
  17549. Object.assign( FileLoader.prototype, {
  17550. load: function ( url, onLoad, onProgress, onError ) {
  17551. if ( url === undefined ) url = '';
  17552. if ( this.path !== undefined ) url = this.path + url;
  17553. var scope = this;
  17554. var cached = Cache.get( url );
  17555. if ( cached !== undefined ) {
  17556. scope.manager.itemStart( url );
  17557. setTimeout( function () {
  17558. if ( onLoad ) onLoad( cached );
  17559. scope.manager.itemEnd( url );
  17560. }, 0 );
  17561. return cached;
  17562. }
  17563. // Check for data: URI
  17564. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17565. var dataUriRegexResult = url.match( dataUriRegex );
  17566. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17567. if ( dataUriRegexResult ) {
  17568. var mimeType = dataUriRegexResult[ 1 ];
  17569. var isBase64 = !! dataUriRegexResult[ 2 ];
  17570. var data = dataUriRegexResult[ 3 ];
  17571. data = window.decodeURIComponent( data );
  17572. if ( isBase64 ) data = window.atob( data );
  17573. try {
  17574. var response;
  17575. var responseType = ( this.responseType || '' ).toLowerCase();
  17576. switch ( responseType ) {
  17577. case 'arraybuffer':
  17578. case 'blob':
  17579. response = new ArrayBuffer( data.length );
  17580. var view = new Uint8Array( response );
  17581. for ( var i = 0; i < data.length; i ++ ) {
  17582. view[ i ] = data.charCodeAt( i );
  17583. }
  17584. if ( responseType === 'blob' ) {
  17585. response = new Blob( [ response ], { type: mimeType } );
  17586. }
  17587. break;
  17588. case 'document':
  17589. var parser = new DOMParser();
  17590. response = parser.parseFromString( data, mimeType );
  17591. break;
  17592. case 'json':
  17593. response = JSON.parse( data );
  17594. break;
  17595. default: // 'text' or other
  17596. response = data;
  17597. break;
  17598. }
  17599. // Wait for next browser tick
  17600. window.setTimeout( function () {
  17601. if ( onLoad ) onLoad( response );
  17602. scope.manager.itemEnd( url );
  17603. }, 0 );
  17604. } catch ( error ) {
  17605. // Wait for next browser tick
  17606. window.setTimeout( function () {
  17607. if ( onError ) onError( error );
  17608. scope.manager.itemError( url );
  17609. }, 0 );
  17610. }
  17611. } else {
  17612. var request = new XMLHttpRequest();
  17613. request.open( 'GET', url, true );
  17614. request.addEventListener( 'load', function ( event ) {
  17615. var response = event.target.response;
  17616. Cache.add( url, response );
  17617. if ( this.status === 200 ) {
  17618. if ( onLoad ) onLoad( response );
  17619. scope.manager.itemEnd( url );
  17620. } else if ( this.status === 0 ) {
  17621. // Some browsers return HTTP Status 0 when using non-http protocol
  17622. // e.g. 'file://' or 'data://'. Handle as success.
  17623. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17624. if ( onLoad ) onLoad( response );
  17625. scope.manager.itemEnd( url );
  17626. } else {
  17627. if ( onError ) onError( event );
  17628. scope.manager.itemError( url );
  17629. }
  17630. }, false );
  17631. if ( onProgress !== undefined ) {
  17632. request.addEventListener( 'progress', function ( event ) {
  17633. onProgress( event );
  17634. }, false );
  17635. }
  17636. request.addEventListener( 'error', function ( event ) {
  17637. if ( onError ) onError( event );
  17638. scope.manager.itemError( url );
  17639. }, false );
  17640. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17641. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17642. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17643. request.send( null );
  17644. }
  17645. scope.manager.itemStart( url );
  17646. return request;
  17647. },
  17648. setPath: function ( value ) {
  17649. this.path = value;
  17650. return this;
  17651. },
  17652. setResponseType: function ( value ) {
  17653. this.responseType = value;
  17654. return this;
  17655. },
  17656. setWithCredentials: function ( value ) {
  17657. this.withCredentials = value;
  17658. return this;
  17659. },
  17660. setMimeType: function ( value ) {
  17661. this.mimeType = value;
  17662. return this;
  17663. }
  17664. } );
  17665. /**
  17666. * @author mrdoob / http://mrdoob.com/
  17667. *
  17668. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17669. */
  17670. function CompressedTextureLoader( manager ) {
  17671. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17672. // override in sub classes
  17673. this._parser = null;
  17674. }
  17675. Object.assign( CompressedTextureLoader.prototype, {
  17676. load: function ( url, onLoad, onProgress, onError ) {
  17677. var scope = this;
  17678. var images = [];
  17679. var texture = new CompressedTexture();
  17680. texture.image = images;
  17681. var loader = new FileLoader( this.manager );
  17682. loader.setPath( this.path );
  17683. loader.setResponseType( 'arraybuffer' );
  17684. function loadTexture( i ) {
  17685. loader.load( url[ i ], function ( buffer ) {
  17686. var texDatas = scope._parser( buffer, true );
  17687. images[ i ] = {
  17688. width: texDatas.width,
  17689. height: texDatas.height,
  17690. format: texDatas.format,
  17691. mipmaps: texDatas.mipmaps
  17692. };
  17693. loaded += 1;
  17694. if ( loaded === 6 ) {
  17695. if ( texDatas.mipmapCount === 1 )
  17696. texture.minFilter = LinearFilter;
  17697. texture.format = texDatas.format;
  17698. texture.needsUpdate = true;
  17699. if ( onLoad ) onLoad( texture );
  17700. }
  17701. }, onProgress, onError );
  17702. }
  17703. if ( Array.isArray( url ) ) {
  17704. var loaded = 0;
  17705. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17706. loadTexture( i );
  17707. }
  17708. } else {
  17709. // compressed cubemap texture stored in a single DDS file
  17710. loader.load( url, function ( buffer ) {
  17711. var texDatas = scope._parser( buffer, true );
  17712. if ( texDatas.isCubemap ) {
  17713. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17714. for ( var f = 0; f < faces; f ++ ) {
  17715. images[ f ] = { mipmaps : [] };
  17716. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17717. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17718. images[ f ].format = texDatas.format;
  17719. images[ f ].width = texDatas.width;
  17720. images[ f ].height = texDatas.height;
  17721. }
  17722. }
  17723. } else {
  17724. texture.image.width = texDatas.width;
  17725. texture.image.height = texDatas.height;
  17726. texture.mipmaps = texDatas.mipmaps;
  17727. }
  17728. if ( texDatas.mipmapCount === 1 ) {
  17729. texture.minFilter = LinearFilter;
  17730. }
  17731. texture.format = texDatas.format;
  17732. texture.needsUpdate = true;
  17733. if ( onLoad ) onLoad( texture );
  17734. }, onProgress, onError );
  17735. }
  17736. return texture;
  17737. },
  17738. setPath: function ( value ) {
  17739. this.path = value;
  17740. return this;
  17741. }
  17742. } );
  17743. /**
  17744. * @author Nikos M. / https://github.com/foo123/
  17745. *
  17746. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17747. */
  17748. var DataTextureLoader = BinaryTextureLoader;
  17749. function BinaryTextureLoader( manager ) {
  17750. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17751. // override in sub classes
  17752. this._parser = null;
  17753. }
  17754. Object.assign( BinaryTextureLoader.prototype, {
  17755. load: function ( url, onLoad, onProgress, onError ) {
  17756. var scope = this;
  17757. var texture = new DataTexture();
  17758. var loader = new FileLoader( this.manager );
  17759. loader.setResponseType( 'arraybuffer' );
  17760. loader.load( url, function ( buffer ) {
  17761. var texData = scope._parser( buffer );
  17762. if ( ! texData ) return;
  17763. if ( undefined !== texData.image ) {
  17764. texture.image = texData.image;
  17765. } else if ( undefined !== texData.data ) {
  17766. texture.image.width = texData.width;
  17767. texture.image.height = texData.height;
  17768. texture.image.data = texData.data;
  17769. }
  17770. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17771. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17772. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17773. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17774. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17775. if ( undefined !== texData.format ) {
  17776. texture.format = texData.format;
  17777. }
  17778. if ( undefined !== texData.type ) {
  17779. texture.type = texData.type;
  17780. }
  17781. if ( undefined !== texData.mipmaps ) {
  17782. texture.mipmaps = texData.mipmaps;
  17783. }
  17784. if ( 1 === texData.mipmapCount ) {
  17785. texture.minFilter = LinearFilter;
  17786. }
  17787. texture.needsUpdate = true;
  17788. if ( onLoad ) onLoad( texture, texData );
  17789. }, onProgress, onError );
  17790. return texture;
  17791. }
  17792. } );
  17793. /**
  17794. * @author mrdoob / http://mrdoob.com/
  17795. */
  17796. function ImageLoader( manager ) {
  17797. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17798. }
  17799. Object.assign( ImageLoader.prototype, {
  17800. load: function ( url, onLoad, onProgress, onError ) {
  17801. var scope = this;
  17802. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17803. image.onload = function () {
  17804. image.onload = null;
  17805. URL.revokeObjectURL( image.src );
  17806. if ( onLoad ) onLoad( image );
  17807. scope.manager.itemEnd( url );
  17808. };
  17809. image.onerror = onError;
  17810. if ( url.indexOf( 'data:' ) === 0 ) {
  17811. image.src = url;
  17812. } else if ( this.crossOrigin !== undefined ) {
  17813. // crossOrigin doesn't work with URL.createObjectURL()?
  17814. image.crossOrigin = this.crossOrigin;
  17815. image.src = url;
  17816. } else {
  17817. var loader = new FileLoader();
  17818. loader.setPath( this.path );
  17819. loader.setResponseType( 'blob' );
  17820. loader.setWithCredentials( this.withCredentials );
  17821. loader.load( url, function ( blob ) {
  17822. image.src = URL.createObjectURL( blob );
  17823. }, onProgress, onError );
  17824. }
  17825. scope.manager.itemStart( url );
  17826. return image;
  17827. },
  17828. setCrossOrigin: function ( value ) {
  17829. this.crossOrigin = value;
  17830. return this;
  17831. },
  17832. setWithCredentials: function ( value ) {
  17833. this.withCredentials = value;
  17834. return this;
  17835. },
  17836. setPath: function ( value ) {
  17837. this.path = value;
  17838. return this;
  17839. }
  17840. } );
  17841. /**
  17842. * @author mrdoob / http://mrdoob.com/
  17843. */
  17844. function CubeTextureLoader( manager ) {
  17845. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17846. }
  17847. Object.assign( CubeTextureLoader.prototype, {
  17848. load: function ( urls, onLoad, onProgress, onError ) {
  17849. var texture = new CubeTexture();
  17850. var loader = new ImageLoader( this.manager );
  17851. loader.setCrossOrigin( this.crossOrigin );
  17852. loader.setPath( this.path );
  17853. var loaded = 0;
  17854. function loadTexture( i ) {
  17855. loader.load( urls[ i ], function ( image ) {
  17856. texture.images[ i ] = image;
  17857. loaded ++;
  17858. if ( loaded === 6 ) {
  17859. texture.needsUpdate = true;
  17860. if ( onLoad ) onLoad( texture );
  17861. }
  17862. }, undefined, onError );
  17863. }
  17864. for ( var i = 0; i < urls.length; ++ i ) {
  17865. loadTexture( i );
  17866. }
  17867. return texture;
  17868. },
  17869. setCrossOrigin: function ( value ) {
  17870. this.crossOrigin = value;
  17871. return this;
  17872. },
  17873. setPath: function ( value ) {
  17874. this.path = value;
  17875. return this;
  17876. }
  17877. } );
  17878. /**
  17879. * @author mrdoob / http://mrdoob.com/
  17880. */
  17881. function TextureLoader( manager ) {
  17882. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17883. }
  17884. Object.assign( TextureLoader.prototype, {
  17885. load: function ( url, onLoad, onProgress, onError ) {
  17886. var texture = new Texture();
  17887. var loader = new ImageLoader( this.manager );
  17888. loader.setCrossOrigin( this.crossOrigin );
  17889. loader.setWithCredentials( this.withCredentials );
  17890. loader.setPath( this.path );
  17891. loader.load( url, function ( image ) {
  17892. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  17893. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  17894. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  17895. texture.image = image;
  17896. texture.needsUpdate = true;
  17897. if ( onLoad !== undefined ) {
  17898. onLoad( texture );
  17899. }
  17900. }, onProgress, onError );
  17901. return texture;
  17902. },
  17903. setCrossOrigin: function ( value ) {
  17904. this.crossOrigin = value;
  17905. return this;
  17906. },
  17907. setWithCredentials: function ( value ) {
  17908. this.withCredentials = value;
  17909. return this;
  17910. },
  17911. setPath: function ( value ) {
  17912. this.path = value;
  17913. return this;
  17914. }
  17915. } );
  17916. /**
  17917. * @author mrdoob / http://mrdoob.com/
  17918. * @author alteredq / http://alteredqualia.com/
  17919. */
  17920. function Light( color, intensity ) {
  17921. Object3D.call( this );
  17922. this.type = 'Light';
  17923. this.color = new Color( color );
  17924. this.intensity = intensity !== undefined ? intensity : 1;
  17925. this.receiveShadow = undefined;
  17926. }
  17927. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17928. constructor: Light,
  17929. isLight: true,
  17930. copy: function ( source ) {
  17931. Object3D.prototype.copy.call( this, source );
  17932. this.color.copy( source.color );
  17933. this.intensity = source.intensity;
  17934. return this;
  17935. },
  17936. toJSON: function ( meta ) {
  17937. var data = Object3D.prototype.toJSON.call( this, meta );
  17938. data.object.color = this.color.getHex();
  17939. data.object.intensity = this.intensity;
  17940. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  17941. if ( this.distance !== undefined ) data.object.distance = this.distance;
  17942. if ( this.angle !== undefined ) data.object.angle = this.angle;
  17943. if ( this.decay !== undefined ) data.object.decay = this.decay;
  17944. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  17945. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  17946. return data;
  17947. }
  17948. } );
  17949. /**
  17950. * @author alteredq / http://alteredqualia.com/
  17951. */
  17952. function HemisphereLight( skyColor, groundColor, intensity ) {
  17953. Light.call( this, skyColor, intensity );
  17954. this.type = 'HemisphereLight';
  17955. this.castShadow = undefined;
  17956. this.position.copy( Object3D.DefaultUp );
  17957. this.updateMatrix();
  17958. this.groundColor = new Color( groundColor );
  17959. }
  17960. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17961. constructor: HemisphereLight,
  17962. isHemisphereLight: true,
  17963. copy: function ( source ) {
  17964. Light.prototype.copy.call( this, source );
  17965. this.groundColor.copy( source.groundColor );
  17966. return this;
  17967. }
  17968. } );
  17969. /**
  17970. * @author mrdoob / http://mrdoob.com/
  17971. */
  17972. function LightShadow( camera ) {
  17973. this.camera = camera;
  17974. this.bias = 0;
  17975. this.radius = 1;
  17976. this.mapSize = new Vector2( 512, 512 );
  17977. this.map = null;
  17978. this.matrix = new Matrix4();
  17979. }
  17980. Object.assign( LightShadow.prototype, {
  17981. copy: function ( source ) {
  17982. this.camera = source.camera.clone();
  17983. this.bias = source.bias;
  17984. this.radius = source.radius;
  17985. this.mapSize.copy( source.mapSize );
  17986. return this;
  17987. },
  17988. clone: function () {
  17989. return new this.constructor().copy( this );
  17990. },
  17991. toJSON: function () {
  17992. var object = {};
  17993. if ( this.bias !== 0 ) object.bias = this.bias;
  17994. if ( this.radius !== 1 ) object.radius = this.radius;
  17995. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  17996. object.camera = this.camera.toJSON( false ).object;
  17997. delete object.camera.matrix;
  17998. return object;
  17999. }
  18000. } );
  18001. /**
  18002. * @author mrdoob / http://mrdoob.com/
  18003. */
  18004. function SpotLightShadow() {
  18005. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18006. }
  18007. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18008. constructor: SpotLightShadow,
  18009. isSpotLightShadow: true,
  18010. update: function ( light ) {
  18011. var fov = _Math.RAD2DEG * 2 * light.angle;
  18012. var aspect = this.mapSize.width / this.mapSize.height;
  18013. var far = light.distance || 500;
  18014. var camera = this.camera;
  18015. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18016. camera.fov = fov;
  18017. camera.aspect = aspect;
  18018. camera.far = far;
  18019. camera.updateProjectionMatrix();
  18020. }
  18021. }
  18022. } );
  18023. /**
  18024. * @author alteredq / http://alteredqualia.com/
  18025. */
  18026. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18027. Light.call( this, color, intensity );
  18028. this.type = 'SpotLight';
  18029. this.position.copy( Object3D.DefaultUp );
  18030. this.updateMatrix();
  18031. this.target = new Object3D();
  18032. Object.defineProperty( this, 'power', {
  18033. get: function () {
  18034. // intensity = power per solid angle.
  18035. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18036. return this.intensity * Math.PI;
  18037. },
  18038. set: function ( power ) {
  18039. // intensity = power per solid angle.
  18040. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18041. this.intensity = power / Math.PI;
  18042. }
  18043. } );
  18044. this.distance = ( distance !== undefined ) ? distance : 0;
  18045. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18046. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18047. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18048. this.shadow = new SpotLightShadow();
  18049. }
  18050. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18051. constructor: SpotLight,
  18052. isSpotLight: true,
  18053. copy: function ( source ) {
  18054. Light.prototype.copy.call( this, source );
  18055. this.distance = source.distance;
  18056. this.angle = source.angle;
  18057. this.penumbra = source.penumbra;
  18058. this.decay = source.decay;
  18059. this.target = source.target.clone();
  18060. this.shadow = source.shadow.clone();
  18061. return this;
  18062. }
  18063. } );
  18064. /**
  18065. * @author mrdoob / http://mrdoob.com/
  18066. */
  18067. function PointLight( color, intensity, distance, decay ) {
  18068. Light.call( this, color, intensity );
  18069. this.type = 'PointLight';
  18070. Object.defineProperty( this, 'power', {
  18071. get: function () {
  18072. // intensity = power per solid angle.
  18073. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18074. return this.intensity * 4 * Math.PI;
  18075. },
  18076. set: function ( power ) {
  18077. // intensity = power per solid angle.
  18078. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18079. this.intensity = power / ( 4 * Math.PI );
  18080. }
  18081. } );
  18082. this.distance = ( distance !== undefined ) ? distance : 0;
  18083. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18084. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18085. }
  18086. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18087. constructor: PointLight,
  18088. isPointLight: true,
  18089. copy: function ( source ) {
  18090. Light.prototype.copy.call( this, source );
  18091. this.distance = source.distance;
  18092. this.decay = source.decay;
  18093. this.shadow = source.shadow.clone();
  18094. return this;
  18095. }
  18096. } );
  18097. /**
  18098. * @author mrdoob / http://mrdoob.com/
  18099. */
  18100. function DirectionalLightShadow( light ) {
  18101. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18102. }
  18103. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18104. constructor: DirectionalLightShadow
  18105. } );
  18106. /**
  18107. * @author mrdoob / http://mrdoob.com/
  18108. * @author alteredq / http://alteredqualia.com/
  18109. */
  18110. function DirectionalLight( color, intensity ) {
  18111. Light.call( this, color, intensity );
  18112. this.type = 'DirectionalLight';
  18113. this.position.copy( Object3D.DefaultUp );
  18114. this.updateMatrix();
  18115. this.target = new Object3D();
  18116. this.shadow = new DirectionalLightShadow();
  18117. }
  18118. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18119. constructor: DirectionalLight,
  18120. isDirectionalLight: true,
  18121. copy: function ( source ) {
  18122. Light.prototype.copy.call( this, source );
  18123. this.target = source.target.clone();
  18124. this.shadow = source.shadow.clone();
  18125. return this;
  18126. }
  18127. } );
  18128. /**
  18129. * @author mrdoob / http://mrdoob.com/
  18130. */
  18131. function AmbientLight( color, intensity ) {
  18132. Light.call( this, color, intensity );
  18133. this.type = 'AmbientLight';
  18134. this.castShadow = undefined;
  18135. }
  18136. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18137. constructor: AmbientLight,
  18138. isAmbientLight: true
  18139. } );
  18140. /**
  18141. * @author tschw
  18142. * @author Ben Houston / http://clara.io/
  18143. * @author David Sarno / http://lighthaus.us/
  18144. */
  18145. var AnimationUtils = {
  18146. // same as Array.prototype.slice, but also works on typed arrays
  18147. arraySlice: function( array, from, to ) {
  18148. if ( AnimationUtils.isTypedArray( array ) ) {
  18149. return new array.constructor( array.subarray( from, to ) );
  18150. }
  18151. return array.slice( from, to );
  18152. },
  18153. // converts an array to a specific type
  18154. convertArray: function( array, type, forceClone ) {
  18155. if ( ! array || // let 'undefined' and 'null' pass
  18156. ! forceClone && array.constructor === type ) return array;
  18157. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18158. return new type( array ); // create typed array
  18159. }
  18160. return Array.prototype.slice.call( array ); // create Array
  18161. },
  18162. isTypedArray: function( object ) {
  18163. return ArrayBuffer.isView( object ) &&
  18164. ! ( object instanceof DataView );
  18165. },
  18166. // returns an array by which times and values can be sorted
  18167. getKeyframeOrder: function( times ) {
  18168. function compareTime( i, j ) {
  18169. return times[ i ] - times[ j ];
  18170. }
  18171. var n = times.length;
  18172. var result = new Array( n );
  18173. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18174. result.sort( compareTime );
  18175. return result;
  18176. },
  18177. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18178. sortedArray: function( values, stride, order ) {
  18179. var nValues = values.length;
  18180. var result = new values.constructor( nValues );
  18181. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18182. var srcOffset = order[ i ] * stride;
  18183. for ( var j = 0; j !== stride; ++ j ) {
  18184. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18185. }
  18186. }
  18187. return result;
  18188. },
  18189. // function for parsing AOS keyframe formats
  18190. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  18191. var i = 1, key = jsonKeys[ 0 ];
  18192. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18193. key = jsonKeys[ i ++ ];
  18194. }
  18195. if ( key === undefined ) return; // no data
  18196. var value = key[ valuePropertyName ];
  18197. if ( value === undefined ) return; // no data
  18198. if ( Array.isArray( value ) ) {
  18199. do {
  18200. value = key[ valuePropertyName ];
  18201. if ( value !== undefined ) {
  18202. times.push( key.time );
  18203. values.push.apply( values, value ); // push all elements
  18204. }
  18205. key = jsonKeys[ i ++ ];
  18206. } while ( key !== undefined );
  18207. } else if ( value.toArray !== undefined ) {
  18208. // ...assume THREE.Math-ish
  18209. do {
  18210. value = key[ valuePropertyName ];
  18211. if ( value !== undefined ) {
  18212. times.push( key.time );
  18213. value.toArray( values, values.length );
  18214. }
  18215. key = jsonKeys[ i ++ ];
  18216. } while ( key !== undefined );
  18217. } else {
  18218. // otherwise push as-is
  18219. do {
  18220. value = key[ valuePropertyName ];
  18221. if ( value !== undefined ) {
  18222. times.push( key.time );
  18223. values.push( value );
  18224. }
  18225. key = jsonKeys[ i ++ ];
  18226. } while ( key !== undefined );
  18227. }
  18228. }
  18229. };
  18230. /**
  18231. * Abstract base class of interpolants over parametric samples.
  18232. *
  18233. * The parameter domain is one dimensional, typically the time or a path
  18234. * along a curve defined by the data.
  18235. *
  18236. * The sample values can have any dimensionality and derived classes may
  18237. * apply special interpretations to the data.
  18238. *
  18239. * This class provides the interval seek in a Template Method, deferring
  18240. * the actual interpolation to derived classes.
  18241. *
  18242. * Time complexity is O(1) for linear access crossing at most two points
  18243. * and O(log N) for random access, where N is the number of positions.
  18244. *
  18245. * References:
  18246. *
  18247. * http://www.oodesign.com/template-method-pattern.html
  18248. *
  18249. * @author tschw
  18250. */
  18251. function Interpolant(
  18252. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18253. this.parameterPositions = parameterPositions;
  18254. this._cachedIndex = 0;
  18255. this.resultBuffer = resultBuffer !== undefined ?
  18256. resultBuffer : new sampleValues.constructor( sampleSize );
  18257. this.sampleValues = sampleValues;
  18258. this.valueSize = sampleSize;
  18259. }
  18260. Interpolant.prototype = {
  18261. constructor: Interpolant,
  18262. evaluate: function( t ) {
  18263. var pp = this.parameterPositions,
  18264. i1 = this._cachedIndex,
  18265. t1 = pp[ i1 ],
  18266. t0 = pp[ i1 - 1 ];
  18267. validate_interval: {
  18268. seek: {
  18269. var right;
  18270. linear_scan: {
  18271. //- See http://jsperf.com/comparison-to-undefined/3
  18272. //- slower code:
  18273. //-
  18274. //- if ( t >= t1 || t1 === undefined ) {
  18275. forward_scan: if ( ! ( t < t1 ) ) {
  18276. for ( var giveUpAt = i1 + 2; ;) {
  18277. if ( t1 === undefined ) {
  18278. if ( t < t0 ) break forward_scan;
  18279. // after end
  18280. i1 = pp.length;
  18281. this._cachedIndex = i1;
  18282. return this.afterEnd_( i1 - 1, t, t0 );
  18283. }
  18284. if ( i1 === giveUpAt ) break; // this loop
  18285. t0 = t1;
  18286. t1 = pp[ ++ i1 ];
  18287. if ( t < t1 ) {
  18288. // we have arrived at the sought interval
  18289. break seek;
  18290. }
  18291. }
  18292. // prepare binary search on the right side of the index
  18293. right = pp.length;
  18294. break linear_scan;
  18295. }
  18296. //- slower code:
  18297. //- if ( t < t0 || t0 === undefined ) {
  18298. if ( ! ( t >= t0 ) ) {
  18299. // looping?
  18300. var t1global = pp[ 1 ];
  18301. if ( t < t1global ) {
  18302. i1 = 2; // + 1, using the scan for the details
  18303. t0 = t1global;
  18304. }
  18305. // linear reverse scan
  18306. for ( var giveUpAt = i1 - 2; ;) {
  18307. if ( t0 === undefined ) {
  18308. // before start
  18309. this._cachedIndex = 0;
  18310. return this.beforeStart_( 0, t, t1 );
  18311. }
  18312. if ( i1 === giveUpAt ) break; // this loop
  18313. t1 = t0;
  18314. t0 = pp[ -- i1 - 1 ];
  18315. if ( t >= t0 ) {
  18316. // we have arrived at the sought interval
  18317. break seek;
  18318. }
  18319. }
  18320. // prepare binary search on the left side of the index
  18321. right = i1;
  18322. i1 = 0;
  18323. break linear_scan;
  18324. }
  18325. // the interval is valid
  18326. break validate_interval;
  18327. } // linear scan
  18328. // binary search
  18329. while ( i1 < right ) {
  18330. var mid = ( i1 + right ) >>> 1;
  18331. if ( t < pp[ mid ] ) {
  18332. right = mid;
  18333. } else {
  18334. i1 = mid + 1;
  18335. }
  18336. }
  18337. t1 = pp[ i1 ];
  18338. t0 = pp[ i1 - 1 ];
  18339. // check boundary cases, again
  18340. if ( t0 === undefined ) {
  18341. this._cachedIndex = 0;
  18342. return this.beforeStart_( 0, t, t1 );
  18343. }
  18344. if ( t1 === undefined ) {
  18345. i1 = pp.length;
  18346. this._cachedIndex = i1;
  18347. return this.afterEnd_( i1 - 1, t0, t );
  18348. }
  18349. } // seek
  18350. this._cachedIndex = i1;
  18351. this.intervalChanged_( i1, t0, t1 );
  18352. } // validate_interval
  18353. return this.interpolate_( i1, t0, t, t1 );
  18354. },
  18355. settings: null, // optional, subclass-specific settings structure
  18356. // Note: The indirection allows central control of many interpolants.
  18357. // --- Protected interface
  18358. DefaultSettings_: {},
  18359. getSettings_: function() {
  18360. return this.settings || this.DefaultSettings_;
  18361. },
  18362. copySampleValue_: function( index ) {
  18363. // copies a sample value to the result buffer
  18364. var result = this.resultBuffer,
  18365. values = this.sampleValues,
  18366. stride = this.valueSize,
  18367. offset = index * stride;
  18368. for ( var i = 0; i !== stride; ++ i ) {
  18369. result[ i ] = values[ offset + i ];
  18370. }
  18371. return result;
  18372. },
  18373. // Template methods for derived classes:
  18374. interpolate_: function( i1, t0, t, t1 ) {
  18375. throw new Error( "call to abstract method" );
  18376. // implementations shall return this.resultBuffer
  18377. },
  18378. intervalChanged_: function( i1, t0, t1 ) {
  18379. // empty
  18380. }
  18381. };
  18382. Object.assign( Interpolant.prototype, {
  18383. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  18384. Interpolant.prototype.copySampleValue_,
  18385. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  18386. Interpolant.prototype.copySampleValue_
  18387. } );
  18388. /**
  18389. * Fast and simple cubic spline interpolant.
  18390. *
  18391. * It was derived from a Hermitian construction setting the first derivative
  18392. * at each sample position to the linear slope between neighboring positions
  18393. * over their parameter interval.
  18394. *
  18395. * @author tschw
  18396. */
  18397. function CubicInterpolant(
  18398. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18399. Interpolant.call(
  18400. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18401. this._weightPrev = -0;
  18402. this._offsetPrev = -0;
  18403. this._weightNext = -0;
  18404. this._offsetNext = -0;
  18405. }
  18406. CubicInterpolant.prototype =
  18407. Object.assign( Object.create( Interpolant.prototype ), {
  18408. constructor: CubicInterpolant,
  18409. DefaultSettings_: {
  18410. endingStart: ZeroCurvatureEnding,
  18411. endingEnd: ZeroCurvatureEnding
  18412. },
  18413. intervalChanged_: function( i1, t0, t1 ) {
  18414. var pp = this.parameterPositions,
  18415. iPrev = i1 - 2,
  18416. iNext = i1 + 1,
  18417. tPrev = pp[ iPrev ],
  18418. tNext = pp[ iNext ];
  18419. if ( tPrev === undefined ) {
  18420. switch ( this.getSettings_().endingStart ) {
  18421. case ZeroSlopeEnding:
  18422. // f'(t0) = 0
  18423. iPrev = i1;
  18424. tPrev = 2 * t0 - t1;
  18425. break;
  18426. case WrapAroundEnding:
  18427. // use the other end of the curve
  18428. iPrev = pp.length - 2;
  18429. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18430. break;
  18431. default: // ZeroCurvatureEnding
  18432. // f''(t0) = 0 a.k.a. Natural Spline
  18433. iPrev = i1;
  18434. tPrev = t1;
  18435. }
  18436. }
  18437. if ( tNext === undefined ) {
  18438. switch ( this.getSettings_().endingEnd ) {
  18439. case ZeroSlopeEnding:
  18440. // f'(tN) = 0
  18441. iNext = i1;
  18442. tNext = 2 * t1 - t0;
  18443. break;
  18444. case WrapAroundEnding:
  18445. // use the other end of the curve
  18446. iNext = 1;
  18447. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18448. break;
  18449. default: // ZeroCurvatureEnding
  18450. // f''(tN) = 0, a.k.a. Natural Spline
  18451. iNext = i1 - 1;
  18452. tNext = t0;
  18453. }
  18454. }
  18455. var halfDt = ( t1 - t0 ) * 0.5,
  18456. stride = this.valueSize;
  18457. this._weightPrev = halfDt / ( t0 - tPrev );
  18458. this._weightNext = halfDt / ( tNext - t1 );
  18459. this._offsetPrev = iPrev * stride;
  18460. this._offsetNext = iNext * stride;
  18461. },
  18462. interpolate_: function( i1, t0, t, t1 ) {
  18463. var result = this.resultBuffer,
  18464. values = this.sampleValues,
  18465. stride = this.valueSize,
  18466. o1 = i1 * stride, o0 = o1 - stride,
  18467. oP = this._offsetPrev, oN = this._offsetNext,
  18468. wP = this._weightPrev, wN = this._weightNext,
  18469. p = ( t - t0 ) / ( t1 - t0 ),
  18470. pp = p * p,
  18471. ppp = pp * p;
  18472. // evaluate polynomials
  18473. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18474. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18475. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18476. var sN = wN * ppp - wN * pp;
  18477. // combine data linearly
  18478. for ( var i = 0; i !== stride; ++ i ) {
  18479. result[ i ] =
  18480. sP * values[ oP + i ] +
  18481. s0 * values[ o0 + i ] +
  18482. s1 * values[ o1 + i ] +
  18483. sN * values[ oN + i ];
  18484. }
  18485. return result;
  18486. }
  18487. } );
  18488. /**
  18489. * @author tschw
  18490. */
  18491. function LinearInterpolant(
  18492. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18493. Interpolant.call(
  18494. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18495. }
  18496. LinearInterpolant.prototype =
  18497. Object.assign( Object.create( Interpolant.prototype ), {
  18498. constructor: LinearInterpolant,
  18499. interpolate_: function( i1, t0, t, t1 ) {
  18500. var result = this.resultBuffer,
  18501. values = this.sampleValues,
  18502. stride = this.valueSize,
  18503. offset1 = i1 * stride,
  18504. offset0 = offset1 - stride,
  18505. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18506. weight0 = 1 - weight1;
  18507. for ( var i = 0; i !== stride; ++ i ) {
  18508. result[ i ] =
  18509. values[ offset0 + i ] * weight0 +
  18510. values[ offset1 + i ] * weight1;
  18511. }
  18512. return result;
  18513. }
  18514. } );
  18515. /**
  18516. *
  18517. * Interpolant that evaluates to the sample value at the position preceeding
  18518. * the parameter.
  18519. *
  18520. * @author tschw
  18521. */
  18522. function DiscreteInterpolant(
  18523. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18524. Interpolant.call(
  18525. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18526. }
  18527. DiscreteInterpolant.prototype =
  18528. Object.assign( Object.create( Interpolant.prototype ), {
  18529. constructor: DiscreteInterpolant,
  18530. interpolate_: function( i1, t0, t, t1 ) {
  18531. return this.copySampleValue_( i1 - 1 );
  18532. }
  18533. } );
  18534. var KeyframeTrackPrototype;
  18535. KeyframeTrackPrototype = {
  18536. TimeBufferType: Float32Array,
  18537. ValueBufferType: Float32Array,
  18538. DefaultInterpolation: InterpolateLinear,
  18539. InterpolantFactoryMethodDiscrete: function ( result ) {
  18540. return new DiscreteInterpolant(
  18541. this.times, this.values, this.getValueSize(), result );
  18542. },
  18543. InterpolantFactoryMethodLinear: function ( result ) {
  18544. return new LinearInterpolant(
  18545. this.times, this.values, this.getValueSize(), result );
  18546. },
  18547. InterpolantFactoryMethodSmooth: function ( result ) {
  18548. return new CubicInterpolant(
  18549. this.times, this.values, this.getValueSize(), result );
  18550. },
  18551. setInterpolation: function ( interpolation ) {
  18552. var factoryMethod;
  18553. switch ( interpolation ) {
  18554. case InterpolateDiscrete:
  18555. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18556. break;
  18557. case InterpolateLinear:
  18558. factoryMethod = this.InterpolantFactoryMethodLinear;
  18559. break;
  18560. case InterpolateSmooth:
  18561. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18562. break;
  18563. }
  18564. if ( factoryMethod === undefined ) {
  18565. var message = "unsupported interpolation for " +
  18566. this.ValueTypeName + " keyframe track named " + this.name;
  18567. if ( this.createInterpolant === undefined ) {
  18568. // fall back to default, unless the default itself is messed up
  18569. if ( interpolation !== this.DefaultInterpolation ) {
  18570. this.setInterpolation( this.DefaultInterpolation );
  18571. } else {
  18572. throw new Error( message ); // fatal, in this case
  18573. }
  18574. }
  18575. console.warn( message );
  18576. return;
  18577. }
  18578. this.createInterpolant = factoryMethod;
  18579. },
  18580. getInterpolation: function () {
  18581. switch ( this.createInterpolant ) {
  18582. case this.InterpolantFactoryMethodDiscrete:
  18583. return InterpolateDiscrete;
  18584. case this.InterpolantFactoryMethodLinear:
  18585. return InterpolateLinear;
  18586. case this.InterpolantFactoryMethodSmooth:
  18587. return InterpolateSmooth;
  18588. }
  18589. },
  18590. getValueSize: function () {
  18591. return this.values.length / this.times.length;
  18592. },
  18593. // move all keyframes either forwards or backwards in time
  18594. shift: function ( timeOffset ) {
  18595. if ( timeOffset !== 0.0 ) {
  18596. var times = this.times;
  18597. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18598. times[ i ] += timeOffset;
  18599. }
  18600. }
  18601. return this;
  18602. },
  18603. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18604. scale: function ( timeScale ) {
  18605. if ( timeScale !== 1.0 ) {
  18606. var times = this.times;
  18607. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18608. times[ i ] *= timeScale;
  18609. }
  18610. }
  18611. return this;
  18612. },
  18613. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18614. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18615. trim: function ( startTime, endTime ) {
  18616. var times = this.times,
  18617. nKeys = times.length,
  18618. from = 0,
  18619. to = nKeys - 1;
  18620. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18621. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18622. ++ to; // inclusive -> exclusive bound
  18623. if ( from !== 0 || to !== nKeys ) {
  18624. // empty tracks are forbidden, so keep at least one keyframe
  18625. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18626. var stride = this.getValueSize();
  18627. this.times = AnimationUtils.arraySlice( times, from, to );
  18628. this.values = AnimationUtils.
  18629. arraySlice( this.values, from * stride, to * stride );
  18630. }
  18631. return this;
  18632. },
  18633. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18634. validate: function () {
  18635. var valid = true;
  18636. var valueSize = this.getValueSize();
  18637. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18638. console.error( "invalid value size in track", this );
  18639. valid = false;
  18640. }
  18641. var times = this.times,
  18642. values = this.values,
  18643. nKeys = times.length;
  18644. if ( nKeys === 0 ) {
  18645. console.error( "track is empty", this );
  18646. valid = false;
  18647. }
  18648. var prevTime = null;
  18649. for ( var i = 0; i !== nKeys; i ++ ) {
  18650. var currTime = times[ i ];
  18651. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18652. console.error( "time is not a valid number", this, i, currTime );
  18653. valid = false;
  18654. break;
  18655. }
  18656. if ( prevTime !== null && prevTime > currTime ) {
  18657. console.error( "out of order keys", this, i, currTime, prevTime );
  18658. valid = false;
  18659. break;
  18660. }
  18661. prevTime = currTime;
  18662. }
  18663. if ( values !== undefined ) {
  18664. if ( AnimationUtils.isTypedArray( values ) ) {
  18665. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18666. var value = values[ i ];
  18667. if ( isNaN( value ) ) {
  18668. console.error( "value is not a valid number", this, i, value );
  18669. valid = false;
  18670. break;
  18671. }
  18672. }
  18673. }
  18674. }
  18675. return valid;
  18676. },
  18677. // removes equivalent sequential keys as common in morph target sequences
  18678. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18679. optimize: function () {
  18680. var times = this.times,
  18681. values = this.values,
  18682. stride = this.getValueSize(),
  18683. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18684. writeIndex = 1,
  18685. lastIndex = times.length - 1;
  18686. for ( var i = 1; i < lastIndex; ++ i ) {
  18687. var keep = false;
  18688. var time = times[ i ];
  18689. var timeNext = times[ i + 1 ];
  18690. // remove adjacent keyframes scheduled at the same time
  18691. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18692. if ( ! smoothInterpolation ) {
  18693. // remove unnecessary keyframes same as their neighbors
  18694. var offset = i * stride,
  18695. offsetP = offset - stride,
  18696. offsetN = offset + stride;
  18697. for ( var j = 0; j !== stride; ++ j ) {
  18698. var value = values[ offset + j ];
  18699. if ( value !== values[ offsetP + j ] ||
  18700. value !== values[ offsetN + j ] ) {
  18701. keep = true;
  18702. break;
  18703. }
  18704. }
  18705. } else keep = true;
  18706. }
  18707. // in-place compaction
  18708. if ( keep ) {
  18709. if ( i !== writeIndex ) {
  18710. times[ writeIndex ] = times[ i ];
  18711. var readOffset = i * stride,
  18712. writeOffset = writeIndex * stride;
  18713. for ( var j = 0; j !== stride; ++ j )
  18714. values[ writeOffset + j ] = values[ readOffset + j ];
  18715. }
  18716. ++ writeIndex;
  18717. }
  18718. }
  18719. // flush last keyframe (compaction looks ahead)
  18720. if ( lastIndex > 0 ) {
  18721. times[ writeIndex ] = times[ lastIndex ];
  18722. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18723. values[ writeOffset + j ] = values[ readOffset + j ];
  18724. ++ writeIndex;
  18725. }
  18726. if ( writeIndex !== times.length ) {
  18727. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18728. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18729. }
  18730. return this;
  18731. }
  18732. };
  18733. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18734. if( name === undefined ) throw new Error( "track name is undefined" );
  18735. if( times === undefined || times.length === 0 ) {
  18736. throw new Error( "no keyframes in track named " + name );
  18737. }
  18738. this.name = name;
  18739. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18740. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18741. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18742. this.validate();
  18743. this.optimize();
  18744. }
  18745. /**
  18746. *
  18747. * A Track of vectored keyframe values.
  18748. *
  18749. *
  18750. * @author Ben Houston / http://clara.io/
  18751. * @author David Sarno / http://lighthaus.us/
  18752. * @author tschw
  18753. */
  18754. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18755. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18756. }
  18757. VectorKeyframeTrack.prototype =
  18758. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18759. constructor: VectorKeyframeTrack,
  18760. ValueTypeName: 'vector'
  18761. // ValueBufferType is inherited
  18762. // DefaultInterpolation is inherited
  18763. } );
  18764. /**
  18765. * Spherical linear unit quaternion interpolant.
  18766. *
  18767. * @author tschw
  18768. */
  18769. function QuaternionLinearInterpolant(
  18770. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18771. Interpolant.call(
  18772. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18773. }
  18774. QuaternionLinearInterpolant.prototype =
  18775. Object.assign( Object.create( Interpolant.prototype ), {
  18776. constructor: QuaternionLinearInterpolant,
  18777. interpolate_: function( i1, t0, t, t1 ) {
  18778. var result = this.resultBuffer,
  18779. values = this.sampleValues,
  18780. stride = this.valueSize,
  18781. offset = i1 * stride,
  18782. alpha = ( t - t0 ) / ( t1 - t0 );
  18783. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18784. Quaternion.slerpFlat( result, 0,
  18785. values, offset - stride, values, offset, alpha );
  18786. }
  18787. return result;
  18788. }
  18789. } );
  18790. /**
  18791. *
  18792. * A Track of quaternion keyframe values.
  18793. *
  18794. * @author Ben Houston / http://clara.io/
  18795. * @author David Sarno / http://lighthaus.us/
  18796. * @author tschw
  18797. */
  18798. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18799. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18800. }
  18801. QuaternionKeyframeTrack.prototype =
  18802. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18803. constructor: QuaternionKeyframeTrack,
  18804. ValueTypeName: 'quaternion',
  18805. // ValueBufferType is inherited
  18806. DefaultInterpolation: InterpolateLinear,
  18807. InterpolantFactoryMethodLinear: function( result ) {
  18808. return new QuaternionLinearInterpolant(
  18809. this.times, this.values, this.getValueSize(), result );
  18810. },
  18811. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18812. } );
  18813. /**
  18814. *
  18815. * A Track of numeric keyframe values.
  18816. *
  18817. * @author Ben Houston / http://clara.io/
  18818. * @author David Sarno / http://lighthaus.us/
  18819. * @author tschw
  18820. */
  18821. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18822. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18823. }
  18824. NumberKeyframeTrack.prototype =
  18825. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18826. constructor: NumberKeyframeTrack,
  18827. ValueTypeName: 'number'
  18828. // ValueBufferType is inherited
  18829. // DefaultInterpolation is inherited
  18830. } );
  18831. /**
  18832. *
  18833. * A Track that interpolates Strings
  18834. *
  18835. *
  18836. * @author Ben Houston / http://clara.io/
  18837. * @author David Sarno / http://lighthaus.us/
  18838. * @author tschw
  18839. */
  18840. function StringKeyframeTrack( name, times, values, interpolation ) {
  18841. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18842. }
  18843. StringKeyframeTrack.prototype =
  18844. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18845. constructor: StringKeyframeTrack,
  18846. ValueTypeName: 'string',
  18847. ValueBufferType: Array,
  18848. DefaultInterpolation: InterpolateDiscrete,
  18849. InterpolantFactoryMethodLinear: undefined,
  18850. InterpolantFactoryMethodSmooth: undefined
  18851. } );
  18852. /**
  18853. *
  18854. * A Track of Boolean keyframe values.
  18855. *
  18856. *
  18857. * @author Ben Houston / http://clara.io/
  18858. * @author David Sarno / http://lighthaus.us/
  18859. * @author tschw
  18860. */
  18861. function BooleanKeyframeTrack( name, times, values ) {
  18862. KeyframeTrackConstructor.call( this, name, times, values );
  18863. }
  18864. BooleanKeyframeTrack.prototype =
  18865. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18866. constructor: BooleanKeyframeTrack,
  18867. ValueTypeName: 'bool',
  18868. ValueBufferType: Array,
  18869. DefaultInterpolation: InterpolateDiscrete,
  18870. InterpolantFactoryMethodLinear: undefined,
  18871. InterpolantFactoryMethodSmooth: undefined
  18872. // Note: Actually this track could have a optimized / compressed
  18873. // representation of a single value and a custom interpolant that
  18874. // computes "firstValue ^ isOdd( index )".
  18875. } );
  18876. /**
  18877. *
  18878. * A Track of keyframe values that represent color.
  18879. *
  18880. *
  18881. * @author Ben Houston / http://clara.io/
  18882. * @author David Sarno / http://lighthaus.us/
  18883. * @author tschw
  18884. */
  18885. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18886. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18887. }
  18888. ColorKeyframeTrack.prototype =
  18889. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18890. constructor: ColorKeyframeTrack,
  18891. ValueTypeName: 'color'
  18892. // ValueBufferType is inherited
  18893. // DefaultInterpolation is inherited
  18894. // Note: Very basic implementation and nothing special yet.
  18895. // However, this is the place for color space parameterization.
  18896. } );
  18897. /**
  18898. *
  18899. * A timed sequence of keyframes for a specific property.
  18900. *
  18901. *
  18902. * @author Ben Houston / http://clara.io/
  18903. * @author David Sarno / http://lighthaus.us/
  18904. * @author tschw
  18905. */
  18906. function KeyframeTrack( name, times, values, interpolation ) {
  18907. KeyframeTrackConstructor.apply( this, arguments );
  18908. }
  18909. KeyframeTrack.prototype = KeyframeTrackPrototype;
  18910. KeyframeTrackPrototype.constructor = KeyframeTrack;
  18911. // Static methods:
  18912. Object.assign( KeyframeTrack, {
  18913. // Serialization (in static context, because of constructor invocation
  18914. // and automatic invocation of .toJSON):
  18915. parse: function( json ) {
  18916. if( json.type === undefined ) {
  18917. throw new Error( "track type undefined, can not parse" );
  18918. }
  18919. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  18920. if ( json.times === undefined ) {
  18921. var times = [], values = [];
  18922. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  18923. json.times = times;
  18924. json.values = values;
  18925. }
  18926. // derived classes can define a static parse method
  18927. if ( trackType.parse !== undefined ) {
  18928. return trackType.parse( json );
  18929. } else {
  18930. // by default, we asssume a constructor compatible with the base
  18931. return new trackType(
  18932. json.name, json.times, json.values, json.interpolation );
  18933. }
  18934. },
  18935. toJSON: function( track ) {
  18936. var trackType = track.constructor;
  18937. var json;
  18938. // derived classes can define a static toJSON method
  18939. if ( trackType.toJSON !== undefined ) {
  18940. json = trackType.toJSON( track );
  18941. } else {
  18942. // by default, we assume the data can be serialized as-is
  18943. json = {
  18944. 'name': track.name,
  18945. 'times': AnimationUtils.convertArray( track.times, Array ),
  18946. 'values': AnimationUtils.convertArray( track.values, Array )
  18947. };
  18948. var interpolation = track.getInterpolation();
  18949. if ( interpolation !== track.DefaultInterpolation ) {
  18950. json.interpolation = interpolation;
  18951. }
  18952. }
  18953. json.type = track.ValueTypeName; // mandatory
  18954. return json;
  18955. },
  18956. _getTrackTypeForValueTypeName: function( typeName ) {
  18957. switch( typeName.toLowerCase() ) {
  18958. case "scalar":
  18959. case "double":
  18960. case "float":
  18961. case "number":
  18962. case "integer":
  18963. return NumberKeyframeTrack;
  18964. case "vector":
  18965. case "vector2":
  18966. case "vector3":
  18967. case "vector4":
  18968. return VectorKeyframeTrack;
  18969. case "color":
  18970. return ColorKeyframeTrack;
  18971. case "quaternion":
  18972. return QuaternionKeyframeTrack;
  18973. case "bool":
  18974. case "boolean":
  18975. return BooleanKeyframeTrack;
  18976. case "string":
  18977. return StringKeyframeTrack;
  18978. }
  18979. throw new Error( "Unsupported typeName: " + typeName );
  18980. }
  18981. } );
  18982. /**
  18983. *
  18984. * Reusable set of Tracks that represent an animation.
  18985. *
  18986. * @author Ben Houston / http://clara.io/
  18987. * @author David Sarno / http://lighthaus.us/
  18988. */
  18989. function AnimationClip( name, duration, tracks ) {
  18990. this.name = name;
  18991. this.tracks = tracks;
  18992. this.duration = ( duration !== undefined ) ? duration : -1;
  18993. this.uuid = _Math.generateUUID();
  18994. // this means it should figure out its duration by scanning the tracks
  18995. if ( this.duration < 0 ) {
  18996. this.resetDuration();
  18997. }
  18998. this.optimize();
  18999. }
  19000. AnimationClip.prototype = {
  19001. constructor: AnimationClip,
  19002. resetDuration: function() {
  19003. var tracks = this.tracks,
  19004. duration = 0;
  19005. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19006. var track = this.tracks[ i ];
  19007. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19008. }
  19009. this.duration = duration;
  19010. },
  19011. trim: function() {
  19012. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19013. this.tracks[ i ].trim( 0, this.duration );
  19014. }
  19015. return this;
  19016. },
  19017. optimize: function() {
  19018. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19019. this.tracks[ i ].optimize();
  19020. }
  19021. return this;
  19022. }
  19023. };
  19024. // Static methods:
  19025. Object.assign( AnimationClip, {
  19026. parse: function( json ) {
  19027. var tracks = [],
  19028. jsonTracks = json.tracks,
  19029. frameTime = 1.0 / ( json.fps || 1.0 );
  19030. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19031. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19032. }
  19033. return new AnimationClip( json.name, json.duration, tracks );
  19034. },
  19035. toJSON: function( clip ) {
  19036. var tracks = [],
  19037. clipTracks = clip.tracks;
  19038. var json = {
  19039. 'name': clip.name,
  19040. 'duration': clip.duration,
  19041. 'tracks': tracks
  19042. };
  19043. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19044. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19045. }
  19046. return json;
  19047. },
  19048. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  19049. var numMorphTargets = morphTargetSequence.length;
  19050. var tracks = [];
  19051. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19052. var times = [];
  19053. var values = [];
  19054. times.push(
  19055. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19056. i,
  19057. ( i + 1 ) % numMorphTargets );
  19058. values.push( 0, 1, 0 );
  19059. var order = AnimationUtils.getKeyframeOrder( times );
  19060. times = AnimationUtils.sortedArray( times, 1, order );
  19061. values = AnimationUtils.sortedArray( values, 1, order );
  19062. // if there is a key at the first frame, duplicate it as the
  19063. // last frame as well for perfect loop.
  19064. if ( ! noLoop && times[ 0 ] === 0 ) {
  19065. times.push( numMorphTargets );
  19066. values.push( values[ 0 ] );
  19067. }
  19068. tracks.push(
  19069. new NumberKeyframeTrack(
  19070. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19071. times, values
  19072. ).scale( 1.0 / fps ) );
  19073. }
  19074. return new AnimationClip( name, -1, tracks );
  19075. },
  19076. findByName: function( objectOrClipArray, name ) {
  19077. var clipArray = objectOrClipArray;
  19078. if ( ! Array.isArray( objectOrClipArray ) ) {
  19079. var o = objectOrClipArray;
  19080. clipArray = o.geometry && o.geometry.animations || o.animations;
  19081. }
  19082. for ( var i = 0; i < clipArray.length; i ++ ) {
  19083. if ( clipArray[ i ].name === name ) {
  19084. return clipArray[ i ];
  19085. }
  19086. }
  19087. return null;
  19088. },
  19089. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  19090. var animationToMorphTargets = {};
  19091. // tested with https://regex101.com/ on trick sequences
  19092. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19093. var pattern = /^([\w-]*?)([\d]+)$/;
  19094. // sort morph target names into animation groups based
  19095. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19096. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19097. var morphTarget = morphTargets[ i ];
  19098. var parts = morphTarget.name.match( pattern );
  19099. if ( parts && parts.length > 1 ) {
  19100. var name = parts[ 1 ];
  19101. var animationMorphTargets = animationToMorphTargets[ name ];
  19102. if ( ! animationMorphTargets ) {
  19103. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19104. }
  19105. animationMorphTargets.push( morphTarget );
  19106. }
  19107. }
  19108. var clips = [];
  19109. for ( var name in animationToMorphTargets ) {
  19110. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19111. }
  19112. return clips;
  19113. },
  19114. // parse the animation.hierarchy format
  19115. parseAnimation: function( animation, bones ) {
  19116. if ( ! animation ) {
  19117. console.error( " no animation in JSONLoader data" );
  19118. return null;
  19119. }
  19120. var addNonemptyTrack = function(
  19121. trackType, trackName, animationKeys, propertyName, destTracks ) {
  19122. // only return track if there are actually keys.
  19123. if ( animationKeys.length !== 0 ) {
  19124. var times = [];
  19125. var values = [];
  19126. AnimationUtils.flattenJSON(
  19127. animationKeys, times, values, propertyName );
  19128. // empty keys are filtered out, so check again
  19129. if ( times.length !== 0 ) {
  19130. destTracks.push( new trackType( trackName, times, values ) );
  19131. }
  19132. }
  19133. };
  19134. var tracks = [];
  19135. var clipName = animation.name || 'default';
  19136. // automatic length determination in AnimationClip.
  19137. var duration = animation.length || -1;
  19138. var fps = animation.fps || 30;
  19139. var hierarchyTracks = animation.hierarchy || [];
  19140. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19141. var animationKeys = hierarchyTracks[ h ].keys;
  19142. // skip empty tracks
  19143. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19144. // process morph targets in a way exactly compatible
  19145. // with AnimationHandler.init( animation )
  19146. if ( animationKeys[0].morphTargets ) {
  19147. // figure out all morph targets used in this track
  19148. var morphTargetNames = {};
  19149. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19150. if ( animationKeys[k].morphTargets ) {
  19151. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  19152. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  19153. }
  19154. }
  19155. }
  19156. // create a track for each morph target with all zero
  19157. // morphTargetInfluences except for the keys in which
  19158. // the morphTarget is named.
  19159. for ( var morphTargetName in morphTargetNames ) {
  19160. var times = [];
  19161. var values = [];
  19162. for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) {
  19163. var animationKey = animationKeys[k];
  19164. times.push( animationKey.time );
  19165. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19166. }
  19167. tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19168. }
  19169. duration = morphTargetNames.length * ( fps || 1.0 );
  19170. } else {
  19171. // ...assume skeletal animation
  19172. var boneName = '.bones[' + bones[ h ].name + ']';
  19173. addNonemptyTrack(
  19174. VectorKeyframeTrack, boneName + '.position',
  19175. animationKeys, 'pos', tracks );
  19176. addNonemptyTrack(
  19177. QuaternionKeyframeTrack, boneName + '.quaternion',
  19178. animationKeys, 'rot', tracks );
  19179. addNonemptyTrack(
  19180. VectorKeyframeTrack, boneName + '.scale',
  19181. animationKeys, 'scl', tracks );
  19182. }
  19183. }
  19184. if ( tracks.length === 0 ) {
  19185. return null;
  19186. }
  19187. var clip = new AnimationClip( clipName, duration, tracks );
  19188. return clip;
  19189. }
  19190. } );
  19191. /**
  19192. * @author mrdoob / http://mrdoob.com/
  19193. */
  19194. function MaterialLoader( manager ) {
  19195. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19196. this.textures = {};
  19197. }
  19198. Object.assign( MaterialLoader.prototype, {
  19199. load: function ( url, onLoad, onProgress, onError ) {
  19200. var scope = this;
  19201. var loader = new FileLoader( scope.manager );
  19202. loader.load( url, function ( text ) {
  19203. onLoad( scope.parse( JSON.parse( text ) ) );
  19204. }, onProgress, onError );
  19205. },
  19206. setTextures: function ( value ) {
  19207. this.textures = value;
  19208. },
  19209. parse: function ( json ) {
  19210. var textures = this.textures;
  19211. function getTexture( name ) {
  19212. if ( textures[ name ] === undefined ) {
  19213. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19214. }
  19215. return textures[ name ];
  19216. }
  19217. var material = new Materials[ json.type ]();
  19218. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19219. if ( json.name !== undefined ) material.name = json.name;
  19220. if ( json.color !== undefined ) material.color.setHex( json.color );
  19221. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19222. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19223. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19224. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19225. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19226. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19227. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19228. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19229. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19230. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19231. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19232. if ( json.fog !== undefined ) material.fog = json.fog;
  19233. if ( json.shading !== undefined ) material.shading = json.shading;
  19234. if ( json.blending !== undefined ) material.blending = json.blending;
  19235. if ( json.side !== undefined ) material.side = json.side;
  19236. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19237. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19238. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19239. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19240. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19241. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19242. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19243. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19244. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19245. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19246. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19247. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19248. // for PointsMaterial
  19249. if ( json.size !== undefined ) material.size = json.size;
  19250. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19251. // maps
  19252. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19253. if ( json.alphaMap !== undefined ) {
  19254. material.alphaMap = getTexture( json.alphaMap );
  19255. material.transparent = true;
  19256. }
  19257. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19258. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19259. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19260. if ( json.normalScale !== undefined ) {
  19261. var normalScale = json.normalScale;
  19262. if ( Array.isArray( normalScale ) === false ) {
  19263. // Blender exporter used to export a scalar. See #7459
  19264. normalScale = [ normalScale, normalScale ];
  19265. }
  19266. material.normalScale = new Vector2().fromArray( normalScale );
  19267. }
  19268. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19269. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19270. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19271. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19272. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19273. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19274. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19275. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19276. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19277. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19278. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19279. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19280. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19281. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19282. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19283. // MultiMaterial
  19284. if ( json.materials !== undefined ) {
  19285. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  19286. material.materials.push( this.parse( json.materials[ i ] ) );
  19287. }
  19288. }
  19289. return material;
  19290. }
  19291. } );
  19292. /**
  19293. * @author mrdoob / http://mrdoob.com/
  19294. */
  19295. function BufferGeometryLoader( manager ) {
  19296. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19297. }
  19298. Object.assign( BufferGeometryLoader.prototype, {
  19299. load: function ( url, onLoad, onProgress, onError ) {
  19300. var scope = this;
  19301. var loader = new FileLoader( scope.manager );
  19302. loader.load( url, function ( text ) {
  19303. onLoad( scope.parse( JSON.parse( text ) ) );
  19304. }, onProgress, onError );
  19305. },
  19306. parse: function ( json ) {
  19307. var geometry = new BufferGeometry();
  19308. var index = json.data.index;
  19309. var TYPED_ARRAYS = {
  19310. 'Int8Array': Int8Array,
  19311. 'Uint8Array': Uint8Array,
  19312. 'Uint8ClampedArray': Uint8ClampedArray,
  19313. 'Int16Array': Int16Array,
  19314. 'Uint16Array': Uint16Array,
  19315. 'Int32Array': Int32Array,
  19316. 'Uint32Array': Uint32Array,
  19317. 'Float32Array': Float32Array,
  19318. 'Float64Array': Float64Array
  19319. };
  19320. if ( index !== undefined ) {
  19321. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19322. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19323. }
  19324. var attributes = json.data.attributes;
  19325. for ( var key in attributes ) {
  19326. var attribute = attributes[ key ];
  19327. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19328. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19329. }
  19330. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19331. if ( groups !== undefined ) {
  19332. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19333. var group = groups[ i ];
  19334. geometry.addGroup( group.start, group.count, group.materialIndex );
  19335. }
  19336. }
  19337. var boundingSphere = json.data.boundingSphere;
  19338. if ( boundingSphere !== undefined ) {
  19339. var center = new Vector3();
  19340. if ( boundingSphere.center !== undefined ) {
  19341. center.fromArray( boundingSphere.center );
  19342. }
  19343. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19344. }
  19345. return geometry;
  19346. }
  19347. } );
  19348. /**
  19349. * @author alteredq / http://alteredqualia.com/
  19350. */
  19351. function Loader() {
  19352. this.onLoadStart = function () {};
  19353. this.onLoadProgress = function () {};
  19354. this.onLoadComplete = function () {};
  19355. }
  19356. Loader.prototype = {
  19357. constructor: Loader,
  19358. crossOrigin: undefined,
  19359. extractUrlBase: function ( url ) {
  19360. var parts = url.split( '/' );
  19361. if ( parts.length === 1 ) return './';
  19362. parts.pop();
  19363. return parts.join( '/' ) + '/';
  19364. },
  19365. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19366. var array = [];
  19367. for ( var i = 0; i < materials.length; ++ i ) {
  19368. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19369. }
  19370. return array;
  19371. },
  19372. createMaterial: ( function () {
  19373. var color, textureLoader, materialLoader;
  19374. return function createMaterial( m, texturePath, crossOrigin ) {
  19375. if ( color === undefined ) color = new Color();
  19376. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  19377. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  19378. // convert from old material format
  19379. var textures = {};
  19380. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19381. var fullPath = texturePath + path;
  19382. var loader = Loader.Handlers.get( fullPath );
  19383. var texture;
  19384. if ( loader !== null ) {
  19385. texture = loader.load( fullPath );
  19386. } else {
  19387. textureLoader.setCrossOrigin( crossOrigin );
  19388. texture = textureLoader.load( fullPath );
  19389. }
  19390. if ( repeat !== undefined ) {
  19391. texture.repeat.fromArray( repeat );
  19392. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19393. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19394. }
  19395. if ( offset !== undefined ) {
  19396. texture.offset.fromArray( offset );
  19397. }
  19398. if ( wrap !== undefined ) {
  19399. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19400. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19401. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19402. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19403. }
  19404. if ( anisotropy !== undefined ) {
  19405. texture.anisotropy = anisotropy;
  19406. }
  19407. var uuid = _Math.generateUUID();
  19408. textures[ uuid ] = texture;
  19409. return uuid;
  19410. }
  19411. //
  19412. var json = {
  19413. uuid: _Math.generateUUID(),
  19414. type: 'MeshLambertMaterial'
  19415. };
  19416. for ( var name in m ) {
  19417. var value = m[ name ];
  19418. switch ( name ) {
  19419. case 'DbgColor':
  19420. case 'DbgIndex':
  19421. case 'opticalDensity':
  19422. case 'illumination':
  19423. break;
  19424. case 'DbgName':
  19425. json.name = value;
  19426. break;
  19427. case 'blending':
  19428. json.blending = BlendingMode[ value ];
  19429. break;
  19430. case 'colorAmbient':
  19431. case 'mapAmbient':
  19432. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19433. break;
  19434. case 'colorDiffuse':
  19435. json.color = color.fromArray( value ).getHex();
  19436. break;
  19437. case 'colorSpecular':
  19438. json.specular = color.fromArray( value ).getHex();
  19439. break;
  19440. case 'colorEmissive':
  19441. json.emissive = color.fromArray( value ).getHex();
  19442. break;
  19443. case 'specularCoef':
  19444. json.shininess = value;
  19445. break;
  19446. case 'shading':
  19447. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19448. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19449. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19450. break;
  19451. case 'mapDiffuse':
  19452. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19453. break;
  19454. case 'mapDiffuseRepeat':
  19455. case 'mapDiffuseOffset':
  19456. case 'mapDiffuseWrap':
  19457. case 'mapDiffuseAnisotropy':
  19458. break;
  19459. case 'mapEmissive':
  19460. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19461. break;
  19462. case 'mapEmissiveRepeat':
  19463. case 'mapEmissiveOffset':
  19464. case 'mapEmissiveWrap':
  19465. case 'mapEmissiveAnisotropy':
  19466. break;
  19467. case 'mapLight':
  19468. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19469. break;
  19470. case 'mapLightRepeat':
  19471. case 'mapLightOffset':
  19472. case 'mapLightWrap':
  19473. case 'mapLightAnisotropy':
  19474. break;
  19475. case 'mapAO':
  19476. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19477. break;
  19478. case 'mapAORepeat':
  19479. case 'mapAOOffset':
  19480. case 'mapAOWrap':
  19481. case 'mapAOAnisotropy':
  19482. break;
  19483. case 'mapBump':
  19484. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19485. break;
  19486. case 'mapBumpScale':
  19487. json.bumpScale = value;
  19488. break;
  19489. case 'mapBumpRepeat':
  19490. case 'mapBumpOffset':
  19491. case 'mapBumpWrap':
  19492. case 'mapBumpAnisotropy':
  19493. break;
  19494. case 'mapNormal':
  19495. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19496. break;
  19497. case 'mapNormalFactor':
  19498. json.normalScale = [ value, value ];
  19499. break;
  19500. case 'mapNormalRepeat':
  19501. case 'mapNormalOffset':
  19502. case 'mapNormalWrap':
  19503. case 'mapNormalAnisotropy':
  19504. break;
  19505. case 'mapSpecular':
  19506. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19507. break;
  19508. case 'mapSpecularRepeat':
  19509. case 'mapSpecularOffset':
  19510. case 'mapSpecularWrap':
  19511. case 'mapSpecularAnisotropy':
  19512. break;
  19513. case 'mapMetalness':
  19514. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19515. break;
  19516. case 'mapMetalnessRepeat':
  19517. case 'mapMetalnessOffset':
  19518. case 'mapMetalnessWrap':
  19519. case 'mapMetalnessAnisotropy':
  19520. break;
  19521. case 'mapRoughness':
  19522. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19523. break;
  19524. case 'mapRoughnessRepeat':
  19525. case 'mapRoughnessOffset':
  19526. case 'mapRoughnessWrap':
  19527. case 'mapRoughnessAnisotropy':
  19528. break;
  19529. case 'mapAlpha':
  19530. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19531. break;
  19532. case 'mapAlphaRepeat':
  19533. case 'mapAlphaOffset':
  19534. case 'mapAlphaWrap':
  19535. case 'mapAlphaAnisotropy':
  19536. break;
  19537. case 'flipSided':
  19538. json.side = BackSide;
  19539. break;
  19540. case 'doubleSided':
  19541. json.side = DoubleSide;
  19542. break;
  19543. case 'transparency':
  19544. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19545. json.opacity = value;
  19546. break;
  19547. case 'depthTest':
  19548. case 'depthWrite':
  19549. case 'colorWrite':
  19550. case 'opacity':
  19551. case 'reflectivity':
  19552. case 'transparent':
  19553. case 'visible':
  19554. case 'wireframe':
  19555. json[ name ] = value;
  19556. break;
  19557. case 'vertexColors':
  19558. if ( value === true ) json.vertexColors = VertexColors;
  19559. if ( value === 'face' ) json.vertexColors = FaceColors;
  19560. break;
  19561. default:
  19562. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19563. break;
  19564. }
  19565. }
  19566. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19567. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19568. if ( json.opacity < 1 ) json.transparent = true;
  19569. materialLoader.setTextures( textures );
  19570. return materialLoader.parse( json );
  19571. };
  19572. } )()
  19573. };
  19574. Loader.Handlers = {
  19575. handlers: [],
  19576. add: function ( regex, loader ) {
  19577. this.handlers.push( regex, loader );
  19578. },
  19579. get: function ( file ) {
  19580. var handlers = this.handlers;
  19581. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19582. var regex = handlers[ i ];
  19583. var loader = handlers[ i + 1 ];
  19584. if ( regex.test( file ) ) {
  19585. return loader;
  19586. }
  19587. }
  19588. return null;
  19589. }
  19590. };
  19591. /**
  19592. * @author mrdoob / http://mrdoob.com/
  19593. * @author alteredq / http://alteredqualia.com/
  19594. */
  19595. function JSONLoader( manager ) {
  19596. if ( typeof manager === 'boolean' ) {
  19597. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19598. manager = undefined;
  19599. }
  19600. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19601. this.withCredentials = false;
  19602. }
  19603. Object.assign( JSONLoader.prototype, {
  19604. load: function( url, onLoad, onProgress, onError ) {
  19605. var scope = this;
  19606. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19607. var loader = new FileLoader( this.manager );
  19608. loader.setWithCredentials( this.withCredentials );
  19609. loader.load( url, function ( text ) {
  19610. var json = JSON.parse( text );
  19611. var metadata = json.metadata;
  19612. if ( metadata !== undefined ) {
  19613. var type = metadata.type;
  19614. if ( type !== undefined ) {
  19615. if ( type.toLowerCase() === 'object' ) {
  19616. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19617. return;
  19618. }
  19619. if ( type.toLowerCase() === 'scene' ) {
  19620. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19621. return;
  19622. }
  19623. }
  19624. }
  19625. var object = scope.parse( json, texturePath );
  19626. onLoad( object.geometry, object.materials );
  19627. }, onProgress, onError );
  19628. },
  19629. setTexturePath: function ( value ) {
  19630. this.texturePath = value;
  19631. },
  19632. parse: function ( json, texturePath ) {
  19633. var geometry = new Geometry(),
  19634. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19635. parseModel( scale );
  19636. parseSkin();
  19637. parseMorphing( scale );
  19638. parseAnimations();
  19639. geometry.computeFaceNormals();
  19640. geometry.computeBoundingSphere();
  19641. function parseModel( scale ) {
  19642. function isBitSet( value, position ) {
  19643. return value & ( 1 << position );
  19644. }
  19645. var i, j, fi,
  19646. offset, zLength,
  19647. colorIndex, normalIndex, uvIndex, materialIndex,
  19648. type,
  19649. isQuad,
  19650. hasMaterial,
  19651. hasFaceVertexUv,
  19652. hasFaceNormal, hasFaceVertexNormal,
  19653. hasFaceColor, hasFaceVertexColor,
  19654. vertex, face, faceA, faceB, hex, normal,
  19655. uvLayer, uv, u, v,
  19656. faces = json.faces,
  19657. vertices = json.vertices,
  19658. normals = json.normals,
  19659. colors = json.colors,
  19660. nUvLayers = 0;
  19661. if ( json.uvs !== undefined ) {
  19662. // disregard empty arrays
  19663. for ( i = 0; i < json.uvs.length; i ++ ) {
  19664. if ( json.uvs[ i ].length ) nUvLayers ++;
  19665. }
  19666. for ( i = 0; i < nUvLayers; i ++ ) {
  19667. geometry.faceVertexUvs[ i ] = [];
  19668. }
  19669. }
  19670. offset = 0;
  19671. zLength = vertices.length;
  19672. while ( offset < zLength ) {
  19673. vertex = new Vector3();
  19674. vertex.x = vertices[ offset ++ ] * scale;
  19675. vertex.y = vertices[ offset ++ ] * scale;
  19676. vertex.z = vertices[ offset ++ ] * scale;
  19677. geometry.vertices.push( vertex );
  19678. }
  19679. offset = 0;
  19680. zLength = faces.length;
  19681. while ( offset < zLength ) {
  19682. type = faces[ offset ++ ];
  19683. isQuad = isBitSet( type, 0 );
  19684. hasMaterial = isBitSet( type, 1 );
  19685. hasFaceVertexUv = isBitSet( type, 3 );
  19686. hasFaceNormal = isBitSet( type, 4 );
  19687. hasFaceVertexNormal = isBitSet( type, 5 );
  19688. hasFaceColor = isBitSet( type, 6 );
  19689. hasFaceVertexColor = isBitSet( type, 7 );
  19690. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19691. if ( isQuad ) {
  19692. faceA = new Face3();
  19693. faceA.a = faces[ offset ];
  19694. faceA.b = faces[ offset + 1 ];
  19695. faceA.c = faces[ offset + 3 ];
  19696. faceB = new Face3();
  19697. faceB.a = faces[ offset + 1 ];
  19698. faceB.b = faces[ offset + 2 ];
  19699. faceB.c = faces[ offset + 3 ];
  19700. offset += 4;
  19701. if ( hasMaterial ) {
  19702. materialIndex = faces[ offset ++ ];
  19703. faceA.materialIndex = materialIndex;
  19704. faceB.materialIndex = materialIndex;
  19705. }
  19706. // to get face <=> uv index correspondence
  19707. fi = geometry.faces.length;
  19708. if ( hasFaceVertexUv ) {
  19709. for ( i = 0; i < nUvLayers; i ++ ) {
  19710. uvLayer = json.uvs[ i ];
  19711. geometry.faceVertexUvs[ i ][ fi ] = [];
  19712. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19713. for ( j = 0; j < 4; j ++ ) {
  19714. uvIndex = faces[ offset ++ ];
  19715. u = uvLayer[ uvIndex * 2 ];
  19716. v = uvLayer[ uvIndex * 2 + 1 ];
  19717. uv = new Vector2( u, v );
  19718. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19719. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19720. }
  19721. }
  19722. }
  19723. if ( hasFaceNormal ) {
  19724. normalIndex = faces[ offset ++ ] * 3;
  19725. faceA.normal.set(
  19726. normals[ normalIndex ++ ],
  19727. normals[ normalIndex ++ ],
  19728. normals[ normalIndex ]
  19729. );
  19730. faceB.normal.copy( faceA.normal );
  19731. }
  19732. if ( hasFaceVertexNormal ) {
  19733. for ( i = 0; i < 4; i ++ ) {
  19734. normalIndex = faces[ offset ++ ] * 3;
  19735. normal = new Vector3(
  19736. normals[ normalIndex ++ ],
  19737. normals[ normalIndex ++ ],
  19738. normals[ normalIndex ]
  19739. );
  19740. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19741. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19742. }
  19743. }
  19744. if ( hasFaceColor ) {
  19745. colorIndex = faces[ offset ++ ];
  19746. hex = colors[ colorIndex ];
  19747. faceA.color.setHex( hex );
  19748. faceB.color.setHex( hex );
  19749. }
  19750. if ( hasFaceVertexColor ) {
  19751. for ( i = 0; i < 4; i ++ ) {
  19752. colorIndex = faces[ offset ++ ];
  19753. hex = colors[ colorIndex ];
  19754. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19755. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19756. }
  19757. }
  19758. geometry.faces.push( faceA );
  19759. geometry.faces.push( faceB );
  19760. } else {
  19761. face = new Face3();
  19762. face.a = faces[ offset ++ ];
  19763. face.b = faces[ offset ++ ];
  19764. face.c = faces[ offset ++ ];
  19765. if ( hasMaterial ) {
  19766. materialIndex = faces[ offset ++ ];
  19767. face.materialIndex = materialIndex;
  19768. }
  19769. // to get face <=> uv index correspondence
  19770. fi = geometry.faces.length;
  19771. if ( hasFaceVertexUv ) {
  19772. for ( i = 0; i < nUvLayers; i ++ ) {
  19773. uvLayer = json.uvs[ i ];
  19774. geometry.faceVertexUvs[ i ][ fi ] = [];
  19775. for ( j = 0; j < 3; j ++ ) {
  19776. uvIndex = faces[ offset ++ ];
  19777. u = uvLayer[ uvIndex * 2 ];
  19778. v = uvLayer[ uvIndex * 2 + 1 ];
  19779. uv = new Vector2( u, v );
  19780. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19781. }
  19782. }
  19783. }
  19784. if ( hasFaceNormal ) {
  19785. normalIndex = faces[ offset ++ ] * 3;
  19786. face.normal.set(
  19787. normals[ normalIndex ++ ],
  19788. normals[ normalIndex ++ ],
  19789. normals[ normalIndex ]
  19790. );
  19791. }
  19792. if ( hasFaceVertexNormal ) {
  19793. for ( i = 0; i < 3; i ++ ) {
  19794. normalIndex = faces[ offset ++ ] * 3;
  19795. normal = new Vector3(
  19796. normals[ normalIndex ++ ],
  19797. normals[ normalIndex ++ ],
  19798. normals[ normalIndex ]
  19799. );
  19800. face.vertexNormals.push( normal );
  19801. }
  19802. }
  19803. if ( hasFaceColor ) {
  19804. colorIndex = faces[ offset ++ ];
  19805. face.color.setHex( colors[ colorIndex ] );
  19806. }
  19807. if ( hasFaceVertexColor ) {
  19808. for ( i = 0; i < 3; i ++ ) {
  19809. colorIndex = faces[ offset ++ ];
  19810. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19811. }
  19812. }
  19813. geometry.faces.push( face );
  19814. }
  19815. }
  19816. }
  19817. function parseSkin() {
  19818. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19819. if ( json.skinWeights ) {
  19820. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19821. var x = json.skinWeights[ i ];
  19822. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19823. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19824. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19825. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19826. }
  19827. }
  19828. if ( json.skinIndices ) {
  19829. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19830. var a = json.skinIndices[ i ];
  19831. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19832. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19833. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19834. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19835. }
  19836. }
  19837. geometry.bones = json.bones;
  19838. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19839. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19840. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19841. }
  19842. }
  19843. function parseMorphing( scale ) {
  19844. if ( json.morphTargets !== undefined ) {
  19845. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19846. geometry.morphTargets[ i ] = {};
  19847. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19848. geometry.morphTargets[ i ].vertices = [];
  19849. var dstVertices = geometry.morphTargets[ i ].vertices;
  19850. var srcVertices = json.morphTargets[ i ].vertices;
  19851. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19852. var vertex = new Vector3();
  19853. vertex.x = srcVertices[ v ] * scale;
  19854. vertex.y = srcVertices[ v + 1 ] * scale;
  19855. vertex.z = srcVertices[ v + 2 ] * scale;
  19856. dstVertices.push( vertex );
  19857. }
  19858. }
  19859. }
  19860. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19861. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19862. var faces = geometry.faces;
  19863. var morphColors = json.morphColors[ 0 ].colors;
  19864. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19865. faces[ i ].color.fromArray( morphColors, i * 3 );
  19866. }
  19867. }
  19868. }
  19869. function parseAnimations() {
  19870. var outputAnimations = [];
  19871. // parse old style Bone/Hierarchy animations
  19872. var animations = [];
  19873. if ( json.animation !== undefined ) {
  19874. animations.push( json.animation );
  19875. }
  19876. if ( json.animations !== undefined ) {
  19877. if ( json.animations.length ) {
  19878. animations = animations.concat( json.animations );
  19879. } else {
  19880. animations.push( json.animations );
  19881. }
  19882. }
  19883. for ( var i = 0; i < animations.length; i ++ ) {
  19884. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  19885. if ( clip ) outputAnimations.push( clip );
  19886. }
  19887. // parse implicit morph animations
  19888. if ( geometry.morphTargets ) {
  19889. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  19890. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  19891. outputAnimations = outputAnimations.concat( morphAnimationClips );
  19892. }
  19893. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  19894. }
  19895. if ( json.materials === undefined || json.materials.length === 0 ) {
  19896. return { geometry: geometry };
  19897. } else {
  19898. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  19899. return { geometry: geometry, materials: materials };
  19900. }
  19901. }
  19902. } );
  19903. /**
  19904. * @author mrdoob / http://mrdoob.com/
  19905. */
  19906. function ObjectLoader( manager ) {
  19907. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19908. this.texturePath = '';
  19909. }
  19910. Object.assign( ObjectLoader.prototype, {
  19911. load: function ( url, onLoad, onProgress, onError ) {
  19912. if ( this.texturePath === '' ) {
  19913. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  19914. }
  19915. var scope = this;
  19916. var loader = new FileLoader( scope.manager );
  19917. loader.load( url, function ( text ) {
  19918. var json = null;
  19919. try {
  19920. json = JSON.parse( text );
  19921. } catch ( error ) {
  19922. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  19923. return;
  19924. }
  19925. var metadata = json.metadata;
  19926. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19927. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  19928. return;
  19929. }
  19930. scope.parse( json, onLoad );
  19931. }, onProgress, onError );
  19932. },
  19933. setTexturePath: function ( value ) {
  19934. this.texturePath = value;
  19935. },
  19936. setCrossOrigin: function ( value ) {
  19937. this.crossOrigin = value;
  19938. },
  19939. parse: function ( json, onLoad ) {
  19940. var geometries = this.parseGeometries( json.geometries );
  19941. var images = this.parseImages( json.images, function () {
  19942. if ( onLoad !== undefined ) onLoad( object );
  19943. } );
  19944. var textures = this.parseTextures( json.textures, images );
  19945. var materials = this.parseMaterials( json.materials, textures );
  19946. var object = this.parseObject( json.object, geometries, materials );
  19947. if ( json.animations ) {
  19948. object.animations = this.parseAnimations( json.animations );
  19949. }
  19950. if ( json.images === undefined || json.images.length === 0 ) {
  19951. if ( onLoad !== undefined ) onLoad( object );
  19952. }
  19953. return object;
  19954. },
  19955. parseGeometries: function ( json ) {
  19956. var geometries = {};
  19957. if ( json !== undefined ) {
  19958. var geometryLoader = new JSONLoader();
  19959. var bufferGeometryLoader = new BufferGeometryLoader();
  19960. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19961. var geometry;
  19962. var data = json[ i ];
  19963. switch ( data.type ) {
  19964. case 'PlaneGeometry':
  19965. case 'PlaneBufferGeometry':
  19966. geometry = new Geometries[ data.type ](
  19967. data.width,
  19968. data.height,
  19969. data.widthSegments,
  19970. data.heightSegments
  19971. );
  19972. break;
  19973. case 'BoxGeometry':
  19974. case 'BoxBufferGeometry':
  19975. case 'CubeGeometry': // backwards compatible
  19976. geometry = new Geometries[ data.type ](
  19977. data.width,
  19978. data.height,
  19979. data.depth,
  19980. data.widthSegments,
  19981. data.heightSegments,
  19982. data.depthSegments
  19983. );
  19984. break;
  19985. case 'CircleGeometry':
  19986. case 'CircleBufferGeometry':
  19987. geometry = new Geometries[ data.type ](
  19988. data.radius,
  19989. data.segments,
  19990. data.thetaStart,
  19991. data.thetaLength
  19992. );
  19993. break;
  19994. case 'CylinderGeometry':
  19995. case 'CylinderBufferGeometry':
  19996. geometry = new Geometries[ data.type ](
  19997. data.radiusTop,
  19998. data.radiusBottom,
  19999. data.height,
  20000. data.radialSegments,
  20001. data.heightSegments,
  20002. data.openEnded,
  20003. data.thetaStart,
  20004. data.thetaLength
  20005. );
  20006. break;
  20007. case 'ConeGeometry':
  20008. case 'ConeBufferGeometry':
  20009. geometry = new Geometries[ data.type ](
  20010. data.radius,
  20011. data.height,
  20012. data.radialSegments,
  20013. data.heightSegments,
  20014. data.openEnded,
  20015. data.thetaStart,
  20016. data.thetaLength
  20017. );
  20018. break;
  20019. case 'SphereGeometry':
  20020. case 'SphereBufferGeometry':
  20021. geometry = new Geometries[ data.type ](
  20022. data.radius,
  20023. data.widthSegments,
  20024. data.heightSegments,
  20025. data.phiStart,
  20026. data.phiLength,
  20027. data.thetaStart,
  20028. data.thetaLength
  20029. );
  20030. break;
  20031. case 'DodecahedronGeometry':
  20032. case 'IcosahedronGeometry':
  20033. case 'OctahedronGeometry':
  20034. case 'TetrahedronGeometry':
  20035. geometry = new Geometries[ data.type ](
  20036. data.radius,
  20037. data.detail
  20038. );
  20039. break;
  20040. case 'RingGeometry':
  20041. case 'RingBufferGeometry':
  20042. geometry = new Geometries[ data.type ](
  20043. data.innerRadius,
  20044. data.outerRadius,
  20045. data.thetaSegments,
  20046. data.phiSegments,
  20047. data.thetaStart,
  20048. data.thetaLength
  20049. );
  20050. break;
  20051. case 'TorusGeometry':
  20052. case 'TorusBufferGeometry':
  20053. geometry = new Geometries[ data.type ](
  20054. data.radius,
  20055. data.tube,
  20056. data.radialSegments,
  20057. data.tubularSegments,
  20058. data.arc
  20059. );
  20060. break;
  20061. case 'TorusKnotGeometry':
  20062. case 'TorusKnotBufferGeometry':
  20063. geometry = new Geometries[ data.type ](
  20064. data.radius,
  20065. data.tube,
  20066. data.tubularSegments,
  20067. data.radialSegments,
  20068. data.p,
  20069. data.q
  20070. );
  20071. break;
  20072. case 'LatheGeometry':
  20073. case 'LatheBufferGeometry':
  20074. geometry = new Geometries[ data.type ](
  20075. data.points,
  20076. data.segments,
  20077. data.phiStart,
  20078. data.phiLength
  20079. );
  20080. break;
  20081. case 'BufferGeometry':
  20082. geometry = bufferGeometryLoader.parse( data );
  20083. break;
  20084. case 'Geometry':
  20085. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  20086. break;
  20087. default:
  20088. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20089. continue;
  20090. }
  20091. geometry.uuid = data.uuid;
  20092. if ( data.name !== undefined ) geometry.name = data.name;
  20093. geometries[ data.uuid ] = geometry;
  20094. }
  20095. }
  20096. return geometries;
  20097. },
  20098. parseMaterials: function ( json, textures ) {
  20099. var materials = {};
  20100. if ( json !== undefined ) {
  20101. var loader = new MaterialLoader();
  20102. loader.setTextures( textures );
  20103. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20104. var material = loader.parse( json[ i ] );
  20105. materials[ material.uuid ] = material;
  20106. }
  20107. }
  20108. return materials;
  20109. },
  20110. parseAnimations: function ( json ) {
  20111. var animations = [];
  20112. for ( var i = 0; i < json.length; i ++ ) {
  20113. var clip = AnimationClip.parse( json[ i ] );
  20114. animations.push( clip );
  20115. }
  20116. return animations;
  20117. },
  20118. parseImages: function ( json, onLoad ) {
  20119. var scope = this;
  20120. var images = {};
  20121. function loadImage( url ) {
  20122. scope.manager.itemStart( url );
  20123. return loader.load( url, function () {
  20124. scope.manager.itemEnd( url );
  20125. }, undefined, function () {
  20126. scope.manager.itemError( url );
  20127. } );
  20128. }
  20129. if ( json !== undefined && json.length > 0 ) {
  20130. var manager = new LoadingManager( onLoad );
  20131. var loader = new ImageLoader( manager );
  20132. loader.setCrossOrigin( this.crossOrigin );
  20133. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20134. var image = json[ i ];
  20135. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20136. images[ image.uuid ] = loadImage( path );
  20137. }
  20138. }
  20139. return images;
  20140. },
  20141. parseTextures: function ( json, images ) {
  20142. function parseConstant( value, type ) {
  20143. if ( typeof( value ) === 'number' ) return value;
  20144. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20145. return type[ value ];
  20146. }
  20147. var textures = {};
  20148. if ( json !== undefined ) {
  20149. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20150. var data = json[ i ];
  20151. if ( data.image === undefined ) {
  20152. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20153. }
  20154. if ( images[ data.image ] === undefined ) {
  20155. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20156. }
  20157. var texture = new Texture( images[ data.image ] );
  20158. texture.needsUpdate = true;
  20159. texture.uuid = data.uuid;
  20160. if ( data.name !== undefined ) texture.name = data.name;
  20161. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  20162. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20163. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20164. if ( data.wrap !== undefined ) {
  20165. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  20166. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  20167. }
  20168. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  20169. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  20170. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20171. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20172. textures[ data.uuid ] = texture;
  20173. }
  20174. }
  20175. return textures;
  20176. },
  20177. parseObject: function () {
  20178. var matrix = new Matrix4();
  20179. return function parseObject( data, geometries, materials ) {
  20180. var object;
  20181. function getGeometry( name ) {
  20182. if ( geometries[ name ] === undefined ) {
  20183. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20184. }
  20185. return geometries[ name ];
  20186. }
  20187. function getMaterial( name ) {
  20188. if ( name === undefined ) return undefined;
  20189. if ( materials[ name ] === undefined ) {
  20190. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20191. }
  20192. return materials[ name ];
  20193. }
  20194. switch ( data.type ) {
  20195. case 'Scene':
  20196. object = new Scene();
  20197. if ( data.background !== undefined ) {
  20198. if ( Number.isInteger( data.background ) ) {
  20199. object.background = new Color( data.background );
  20200. }
  20201. }
  20202. if ( data.fog !== undefined ) {
  20203. if ( data.fog.type === 'Fog' ) {
  20204. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20205. } else if ( data.fog.type === 'FogExp2' ) {
  20206. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20207. }
  20208. }
  20209. break;
  20210. case 'PerspectiveCamera':
  20211. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20212. if ( data.focus !== undefined ) object.focus = data.focus;
  20213. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20214. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20215. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20216. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20217. break;
  20218. case 'OrthographicCamera':
  20219. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20220. break;
  20221. case 'AmbientLight':
  20222. object = new AmbientLight( data.color, data.intensity );
  20223. break;
  20224. case 'DirectionalLight':
  20225. object = new DirectionalLight( data.color, data.intensity );
  20226. break;
  20227. case 'PointLight':
  20228. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20229. break;
  20230. case 'SpotLight':
  20231. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20232. break;
  20233. case 'HemisphereLight':
  20234. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20235. break;
  20236. case 'Mesh':
  20237. var geometry = getGeometry( data.geometry );
  20238. var material = getMaterial( data.material );
  20239. if ( geometry.bones && geometry.bones.length > 0 ) {
  20240. object = new SkinnedMesh( geometry, material );
  20241. } else {
  20242. object = new Mesh( geometry, material );
  20243. }
  20244. break;
  20245. case 'LOD':
  20246. object = new LOD();
  20247. break;
  20248. case 'Line':
  20249. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20250. break;
  20251. case 'LineSegments':
  20252. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20253. break;
  20254. case 'PointCloud':
  20255. case 'Points':
  20256. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20257. break;
  20258. case 'Sprite':
  20259. object = new Sprite( getMaterial( data.material ) );
  20260. break;
  20261. case 'Group':
  20262. object = new Group();
  20263. break;
  20264. case 'SkinnedMesh':
  20265. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.' );
  20266. default:
  20267. object = new Object3D();
  20268. }
  20269. object.uuid = data.uuid;
  20270. if ( data.name !== undefined ) object.name = data.name;
  20271. if ( data.matrix !== undefined ) {
  20272. matrix.fromArray( data.matrix );
  20273. matrix.decompose( object.position, object.quaternion, object.scale );
  20274. } else {
  20275. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20276. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20277. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20278. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20279. }
  20280. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20281. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20282. if ( data.shadow ) {
  20283. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20284. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20285. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20286. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20287. }
  20288. if ( data.visible !== undefined ) object.visible = data.visible;
  20289. if ( data.userData !== undefined ) object.userData = data.userData;
  20290. if ( data.children !== undefined ) {
  20291. for ( var child in data.children ) {
  20292. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20293. }
  20294. }
  20295. if ( data.type === 'LOD' ) {
  20296. var levels = data.levels;
  20297. for ( var l = 0; l < levels.length; l ++ ) {
  20298. var level = levels[ l ];
  20299. var child = object.getObjectByProperty( 'uuid', level.object );
  20300. if ( child !== undefined ) {
  20301. object.addLevel( child, level.distance );
  20302. }
  20303. }
  20304. }
  20305. return object;
  20306. };
  20307. }()
  20308. } );
  20309. /**
  20310. * @author zz85 / http://www.lab4games.net/zz85/blog
  20311. * Extensible curve object
  20312. *
  20313. * Some common of Curve methods
  20314. * .getPoint(t), getTangent(t)
  20315. * .getPointAt(u), getTangentAt(u)
  20316. * .getPoints(), .getSpacedPoints()
  20317. * .getLength()
  20318. * .updateArcLengths()
  20319. *
  20320. * This following classes subclasses THREE.Curve:
  20321. *
  20322. * -- 2d classes --
  20323. * THREE.LineCurve
  20324. * THREE.QuadraticBezierCurve
  20325. * THREE.CubicBezierCurve
  20326. * THREE.SplineCurve
  20327. * THREE.ArcCurve
  20328. * THREE.EllipseCurve
  20329. *
  20330. * -- 3d classes --
  20331. * THREE.LineCurve3
  20332. * THREE.QuadraticBezierCurve3
  20333. * THREE.CubicBezierCurve3
  20334. * THREE.SplineCurve3
  20335. *
  20336. * A series of curves can be represented as a THREE.CurvePath
  20337. *
  20338. **/
  20339. /**************************************************************
  20340. * Abstract Curve base class
  20341. **************************************************************/
  20342. function Curve() {}
  20343. Curve.prototype = {
  20344. constructor: Curve,
  20345. // Virtual base class method to overwrite and implement in subclasses
  20346. // - t [0 .. 1]
  20347. getPoint: function ( t ) {
  20348. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20349. return null;
  20350. },
  20351. // Get point at relative position in curve according to arc length
  20352. // - u [0 .. 1]
  20353. getPointAt: function ( u ) {
  20354. var t = this.getUtoTmapping( u );
  20355. return this.getPoint( t );
  20356. },
  20357. // Get sequence of points using getPoint( t )
  20358. getPoints: function ( divisions ) {
  20359. if ( ! divisions ) divisions = 5;
  20360. var points = [];
  20361. for ( var d = 0; d <= divisions; d ++ ) {
  20362. points.push( this.getPoint( d / divisions ) );
  20363. }
  20364. return points;
  20365. },
  20366. // Get sequence of points using getPointAt( u )
  20367. getSpacedPoints: function ( divisions ) {
  20368. if ( ! divisions ) divisions = 5;
  20369. var points = [];
  20370. for ( var d = 0; d <= divisions; d ++ ) {
  20371. points.push( this.getPointAt( d / divisions ) );
  20372. }
  20373. return points;
  20374. },
  20375. // Get total curve arc length
  20376. getLength: function () {
  20377. var lengths = this.getLengths();
  20378. return lengths[ lengths.length - 1 ];
  20379. },
  20380. // Get list of cumulative segment lengths
  20381. getLengths: function ( divisions ) {
  20382. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20383. if ( this.cacheArcLengths
  20384. && ( this.cacheArcLengths.length === divisions + 1 )
  20385. && ! this.needsUpdate ) {
  20386. //console.log( "cached", this.cacheArcLengths );
  20387. return this.cacheArcLengths;
  20388. }
  20389. this.needsUpdate = false;
  20390. var cache = [];
  20391. var current, last = this.getPoint( 0 );
  20392. var p, sum = 0;
  20393. cache.push( 0 );
  20394. for ( p = 1; p <= divisions; p ++ ) {
  20395. current = this.getPoint ( p / divisions );
  20396. sum += current.distanceTo( last );
  20397. cache.push( sum );
  20398. last = current;
  20399. }
  20400. this.cacheArcLengths = cache;
  20401. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20402. },
  20403. updateArcLengths: function() {
  20404. this.needsUpdate = true;
  20405. this.getLengths();
  20406. },
  20407. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20408. getUtoTmapping: function ( u, distance ) {
  20409. var arcLengths = this.getLengths();
  20410. var i = 0, il = arcLengths.length;
  20411. var targetArcLength; // The targeted u distance value to get
  20412. if ( distance ) {
  20413. targetArcLength = distance;
  20414. } else {
  20415. targetArcLength = u * arcLengths[ il - 1 ];
  20416. }
  20417. //var time = Date.now();
  20418. // binary search for the index with largest value smaller than target u distance
  20419. var low = 0, high = il - 1, comparison;
  20420. while ( low <= high ) {
  20421. 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
  20422. comparison = arcLengths[ i ] - targetArcLength;
  20423. if ( comparison < 0 ) {
  20424. low = i + 1;
  20425. } else if ( comparison > 0 ) {
  20426. high = i - 1;
  20427. } else {
  20428. high = i;
  20429. break;
  20430. // DONE
  20431. }
  20432. }
  20433. i = high;
  20434. //console.log('b' , i, low, high, Date.now()- time);
  20435. if ( arcLengths[ i ] === targetArcLength ) {
  20436. var t = i / ( il - 1 );
  20437. return t;
  20438. }
  20439. // we could get finer grain at lengths, or use simple interpolation between two points
  20440. var lengthBefore = arcLengths[ i ];
  20441. var lengthAfter = arcLengths[ i + 1 ];
  20442. var segmentLength = lengthAfter - lengthBefore;
  20443. // determine where we are between the 'before' and 'after' points
  20444. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20445. // add that fractional amount to t
  20446. var t = ( i + segmentFraction ) / ( il - 1 );
  20447. return t;
  20448. },
  20449. // Returns a unit vector tangent at t
  20450. // In case any sub curve does not implement its tangent derivation,
  20451. // 2 points a small delta apart will be used to find its gradient
  20452. // which seems to give a reasonable approximation
  20453. getTangent: function( t ) {
  20454. var delta = 0.0001;
  20455. var t1 = t - delta;
  20456. var t2 = t + delta;
  20457. // Capping in case of danger
  20458. if ( t1 < 0 ) t1 = 0;
  20459. if ( t2 > 1 ) t2 = 1;
  20460. var pt1 = this.getPoint( t1 );
  20461. var pt2 = this.getPoint( t2 );
  20462. var vec = pt2.clone().sub( pt1 );
  20463. return vec.normalize();
  20464. },
  20465. getTangentAt: function ( u ) {
  20466. var t = this.getUtoTmapping( u );
  20467. return this.getTangent( t );
  20468. },
  20469. computeFrenetFrames: function ( segments, closed ) {
  20470. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20471. var normal = new Vector3();
  20472. var tangents = [];
  20473. var normals = [];
  20474. var binormals = [];
  20475. var vec = new Vector3();
  20476. var mat = new Matrix4();
  20477. var i, u, theta;
  20478. // compute the tangent vectors for each segment on the curve
  20479. for ( i = 0; i <= segments; i ++ ) {
  20480. u = i / segments;
  20481. tangents[ i ] = this.getTangentAt( u );
  20482. tangents[ i ].normalize();
  20483. }
  20484. // select an initial normal vector perpendicular to the first tangent vector,
  20485. // and in the direction of the minimum tangent xyz component
  20486. normals[ 0 ] = new Vector3();
  20487. binormals[ 0 ] = new Vector3();
  20488. var min = Number.MAX_VALUE;
  20489. var tx = Math.abs( tangents[ 0 ].x );
  20490. var ty = Math.abs( tangents[ 0 ].y );
  20491. var tz = Math.abs( tangents[ 0 ].z );
  20492. if ( tx <= min ) {
  20493. min = tx;
  20494. normal.set( 1, 0, 0 );
  20495. }
  20496. if ( ty <= min ) {
  20497. min = ty;
  20498. normal.set( 0, 1, 0 );
  20499. }
  20500. if ( tz <= min ) {
  20501. normal.set( 0, 0, 1 );
  20502. }
  20503. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20504. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20505. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20506. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20507. for ( i = 1; i <= segments; i ++ ) {
  20508. normals[ i ] = normals[ i - 1 ].clone();
  20509. binormals[ i ] = binormals[ i - 1 ].clone();
  20510. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20511. if ( vec.length() > Number.EPSILON ) {
  20512. vec.normalize();
  20513. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20514. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20515. }
  20516. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20517. }
  20518. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20519. if ( closed === true ) {
  20520. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20521. theta /= segments;
  20522. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20523. theta = - theta;
  20524. }
  20525. for ( i = 1; i <= segments; i ++ ) {
  20526. // twist a little...
  20527. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20528. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20529. }
  20530. }
  20531. return {
  20532. tangents: tangents,
  20533. normals: normals,
  20534. binormals: binormals
  20535. };
  20536. }
  20537. };
  20538. // TODO: Transformation for Curves?
  20539. /**************************************************************
  20540. * 3D Curves
  20541. **************************************************************/
  20542. // A Factory method for creating new curve subclasses
  20543. Curve.create = function ( constructor, getPointFunc ) {
  20544. constructor.prototype = Object.create( Curve.prototype );
  20545. constructor.prototype.constructor = constructor;
  20546. constructor.prototype.getPoint = getPointFunc;
  20547. return constructor;
  20548. };
  20549. /**************************************************************
  20550. * Line
  20551. **************************************************************/
  20552. function LineCurve( v1, v2 ) {
  20553. this.v1 = v1;
  20554. this.v2 = v2;
  20555. }
  20556. LineCurve.prototype = Object.create( Curve.prototype );
  20557. LineCurve.prototype.constructor = LineCurve;
  20558. LineCurve.prototype.isLineCurve = true;
  20559. LineCurve.prototype.getPoint = function ( t ) {
  20560. if ( t === 1 ) {
  20561. return this.v2.clone();
  20562. }
  20563. var point = this.v2.clone().sub( this.v1 );
  20564. point.multiplyScalar( t ).add( this.v1 );
  20565. return point;
  20566. };
  20567. // Line curve is linear, so we can overwrite default getPointAt
  20568. LineCurve.prototype.getPointAt = function ( u ) {
  20569. return this.getPoint( u );
  20570. };
  20571. LineCurve.prototype.getTangent = function( t ) {
  20572. var tangent = this.v2.clone().sub( this.v1 );
  20573. return tangent.normalize();
  20574. };
  20575. /**
  20576. * @author zz85 / http://www.lab4games.net/zz85/blog
  20577. *
  20578. **/
  20579. /**************************************************************
  20580. * Curved Path - a curve path is simply a array of connected
  20581. * curves, but retains the api of a curve
  20582. **************************************************************/
  20583. function CurvePath() {
  20584. this.curves = [];
  20585. this.autoClose = false; // Automatically closes the path
  20586. }
  20587. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20588. constructor: CurvePath,
  20589. add: function ( curve ) {
  20590. this.curves.push( curve );
  20591. },
  20592. closePath: function () {
  20593. // Add a line curve if start and end of lines are not connected
  20594. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20595. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20596. if ( ! startPoint.equals( endPoint ) ) {
  20597. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20598. }
  20599. },
  20600. // To get accurate point with reference to
  20601. // entire path distance at time t,
  20602. // following has to be done:
  20603. // 1. Length of each sub path have to be known
  20604. // 2. Locate and identify type of curve
  20605. // 3. Get t for the curve
  20606. // 4. Return curve.getPointAt(t')
  20607. getPoint: function ( t ) {
  20608. var d = t * this.getLength();
  20609. var curveLengths = this.getCurveLengths();
  20610. var i = 0;
  20611. // To think about boundaries points.
  20612. while ( i < curveLengths.length ) {
  20613. if ( curveLengths[ i ] >= d ) {
  20614. var diff = curveLengths[ i ] - d;
  20615. var curve = this.curves[ i ];
  20616. var segmentLength = curve.getLength();
  20617. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20618. return curve.getPointAt( u );
  20619. }
  20620. i ++;
  20621. }
  20622. return null;
  20623. // loop where sum != 0, sum > d , sum+1 <d
  20624. },
  20625. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20626. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20627. // getPoint() depends on getLength
  20628. getLength: function () {
  20629. var lens = this.getCurveLengths();
  20630. return lens[ lens.length - 1 ];
  20631. },
  20632. // cacheLengths must be recalculated.
  20633. updateArcLengths: function () {
  20634. this.needsUpdate = true;
  20635. this.cacheLengths = null;
  20636. this.getLengths();
  20637. },
  20638. // Compute lengths and cache them
  20639. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20640. getCurveLengths: function () {
  20641. // We use cache values if curves and cache array are same length
  20642. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20643. return this.cacheLengths;
  20644. }
  20645. // Get length of sub-curve
  20646. // Push sums into cached array
  20647. var lengths = [], sums = 0;
  20648. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20649. sums += this.curves[ i ].getLength();
  20650. lengths.push( sums );
  20651. }
  20652. this.cacheLengths = lengths;
  20653. return lengths;
  20654. },
  20655. getSpacedPoints: function ( divisions ) {
  20656. if ( ! divisions ) divisions = 40;
  20657. var points = [];
  20658. for ( var i = 0; i <= divisions; i ++ ) {
  20659. points.push( this.getPoint( i / divisions ) );
  20660. }
  20661. if ( this.autoClose ) {
  20662. points.push( points[ 0 ] );
  20663. }
  20664. return points;
  20665. },
  20666. getPoints: function ( divisions ) {
  20667. divisions = divisions || 12;
  20668. var points = [], last;
  20669. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20670. var curve = curves[ i ];
  20671. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20672. : (curve && curve.isLineCurve) ? 1
  20673. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20674. : divisions;
  20675. var pts = curve.getPoints( resolution );
  20676. for ( var j = 0; j < pts.length; j++ ) {
  20677. var point = pts[ j ];
  20678. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20679. points.push( point );
  20680. last = point;
  20681. }
  20682. }
  20683. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20684. points.push( points[ 0 ] );
  20685. }
  20686. return points;
  20687. },
  20688. /**************************************************************
  20689. * Create Geometries Helpers
  20690. **************************************************************/
  20691. /// Generate geometry from path points (for Line or Points objects)
  20692. createPointsGeometry: function ( divisions ) {
  20693. var pts = this.getPoints( divisions );
  20694. return this.createGeometry( pts );
  20695. },
  20696. // Generate geometry from equidistant sampling along the path
  20697. createSpacedPointsGeometry: function ( divisions ) {
  20698. var pts = this.getSpacedPoints( divisions );
  20699. return this.createGeometry( pts );
  20700. },
  20701. createGeometry: function ( points ) {
  20702. var geometry = new Geometry();
  20703. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20704. var point = points[ i ];
  20705. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20706. }
  20707. return geometry;
  20708. }
  20709. } );
  20710. /**************************************************************
  20711. * Ellipse curve
  20712. **************************************************************/
  20713. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20714. this.aX = aX;
  20715. this.aY = aY;
  20716. this.xRadius = xRadius;
  20717. this.yRadius = yRadius;
  20718. this.aStartAngle = aStartAngle;
  20719. this.aEndAngle = aEndAngle;
  20720. this.aClockwise = aClockwise;
  20721. this.aRotation = aRotation || 0;
  20722. }
  20723. EllipseCurve.prototype = Object.create( Curve.prototype );
  20724. EllipseCurve.prototype.constructor = EllipseCurve;
  20725. EllipseCurve.prototype.isEllipseCurve = true;
  20726. EllipseCurve.prototype.getPoint = function( t ) {
  20727. var twoPi = Math.PI * 2;
  20728. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20729. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20730. // ensures that deltaAngle is 0 .. 2 PI
  20731. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20732. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20733. if ( deltaAngle < Number.EPSILON ) {
  20734. if ( samePoints ) {
  20735. deltaAngle = 0;
  20736. } else {
  20737. deltaAngle = twoPi;
  20738. }
  20739. }
  20740. if ( this.aClockwise === true && ! samePoints ) {
  20741. if ( deltaAngle === twoPi ) {
  20742. deltaAngle = - twoPi;
  20743. } else {
  20744. deltaAngle = deltaAngle - twoPi;
  20745. }
  20746. }
  20747. var angle = this.aStartAngle + t * deltaAngle;
  20748. var x = this.aX + this.xRadius * Math.cos( angle );
  20749. var y = this.aY + this.yRadius * Math.sin( angle );
  20750. if ( this.aRotation !== 0 ) {
  20751. var cos = Math.cos( this.aRotation );
  20752. var sin = Math.sin( this.aRotation );
  20753. var tx = x - this.aX;
  20754. var ty = y - this.aY;
  20755. // Rotate the point about the center of the ellipse.
  20756. x = tx * cos - ty * sin + this.aX;
  20757. y = tx * sin + ty * cos + this.aY;
  20758. }
  20759. return new Vector2( x, y );
  20760. };
  20761. /**
  20762. * @author zz85 / http://www.lab4games.net/zz85/blog
  20763. */
  20764. var CurveUtils = {
  20765. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  20766. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  20767. },
  20768. // Puay Bing, thanks for helping with this derivative!
  20769. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  20770. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  20771. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  20772. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  20773. 3 * t * t * p3;
  20774. },
  20775. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  20776. // To check if my formulas are correct
  20777. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  20778. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  20779. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  20780. var h11 = 3 * t * t - 2 * t; // t3 − t2
  20781. return h00 + h10 + h01 + h11;
  20782. },
  20783. // Catmull-Rom
  20784. interpolate: function( p0, p1, p2, p3, t ) {
  20785. var v0 = ( p2 - p0 ) * 0.5;
  20786. var v1 = ( p3 - p1 ) * 0.5;
  20787. var t2 = t * t;
  20788. var t3 = t * t2;
  20789. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20790. }
  20791. };
  20792. /**************************************************************
  20793. * Spline curve
  20794. **************************************************************/
  20795. function SplineCurve( points /* array of Vector2 */ ) {
  20796. this.points = ( points === undefined ) ? [] : points;
  20797. }
  20798. SplineCurve.prototype = Object.create( Curve.prototype );
  20799. SplineCurve.prototype.constructor = SplineCurve;
  20800. SplineCurve.prototype.isSplineCurve = true;
  20801. SplineCurve.prototype.getPoint = function ( t ) {
  20802. var points = this.points;
  20803. var point = ( points.length - 1 ) * t;
  20804. var intPoint = Math.floor( point );
  20805. var weight = point - intPoint;
  20806. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20807. var point1 = points[ intPoint ];
  20808. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20809. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20810. var interpolate = CurveUtils.interpolate;
  20811. return new Vector2(
  20812. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20813. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20814. );
  20815. };
  20816. /**************************************************************
  20817. * Cubic Bezier curve
  20818. **************************************************************/
  20819. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20820. this.v0 = v0;
  20821. this.v1 = v1;
  20822. this.v2 = v2;
  20823. this.v3 = v3;
  20824. }
  20825. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20826. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20827. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20828. var b3 = ShapeUtils.b3;
  20829. return new Vector2(
  20830. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20831. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20832. );
  20833. };
  20834. CubicBezierCurve.prototype.getTangent = function( t ) {
  20835. var tangentCubicBezier = CurveUtils.tangentCubicBezier;
  20836. return new Vector2(
  20837. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20838. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20839. ).normalize();
  20840. };
  20841. /**************************************************************
  20842. * Quadratic Bezier curve
  20843. **************************************************************/
  20844. function QuadraticBezierCurve( v0, v1, v2 ) {
  20845. this.v0 = v0;
  20846. this.v1 = v1;
  20847. this.v2 = v2;
  20848. }
  20849. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20850. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20851. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20852. var b2 = ShapeUtils.b2;
  20853. return new Vector2(
  20854. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20855. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20856. );
  20857. };
  20858. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20859. var tangentQuadraticBezier = CurveUtils.tangentQuadraticBezier;
  20860. return new Vector2(
  20861. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20862. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20863. ).normalize();
  20864. };
  20865. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  20866. fromPoints: function ( vectors ) {
  20867. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20868. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20869. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20870. }
  20871. },
  20872. moveTo: function ( x, y ) {
  20873. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20874. },
  20875. lineTo: function ( x, y ) {
  20876. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20877. this.curves.push( curve );
  20878. this.currentPoint.set( x, y );
  20879. },
  20880. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20881. var curve = new QuadraticBezierCurve(
  20882. this.currentPoint.clone(),
  20883. new Vector2( aCPx, aCPy ),
  20884. new Vector2( aX, aY )
  20885. );
  20886. this.curves.push( curve );
  20887. this.currentPoint.set( aX, aY );
  20888. },
  20889. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20890. var curve = new CubicBezierCurve(
  20891. this.currentPoint.clone(),
  20892. new Vector2( aCP1x, aCP1y ),
  20893. new Vector2( aCP2x, aCP2y ),
  20894. new Vector2( aX, aY )
  20895. );
  20896. this.curves.push( curve );
  20897. this.currentPoint.set( aX, aY );
  20898. },
  20899. splineThru: function ( pts /*Array of Vector*/ ) {
  20900. var npts = [ this.currentPoint.clone() ].concat( pts );
  20901. var curve = new SplineCurve( npts );
  20902. this.curves.push( curve );
  20903. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20904. },
  20905. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20906. var x0 = this.currentPoint.x;
  20907. var y0 = this.currentPoint.y;
  20908. this.absarc( aX + x0, aY + y0, aRadius,
  20909. aStartAngle, aEndAngle, aClockwise );
  20910. },
  20911. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20912. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20913. },
  20914. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20915. var x0 = this.currentPoint.x;
  20916. var y0 = this.currentPoint.y;
  20917. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20918. },
  20919. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20920. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20921. if ( this.curves.length > 0 ) {
  20922. // if a previous curve is present, attempt to join
  20923. var firstPoint = curve.getPoint( 0 );
  20924. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20925. this.lineTo( firstPoint.x, firstPoint.y );
  20926. }
  20927. }
  20928. this.curves.push( curve );
  20929. var lastPoint = curve.getPoint( 1 );
  20930. this.currentPoint.copy( lastPoint );
  20931. }
  20932. } );
  20933. /**
  20934. * @author zz85 / http://www.lab4games.net/zz85/blog
  20935. * Defines a 2d shape plane using paths.
  20936. **/
  20937. // STEP 1 Create a path.
  20938. // STEP 2 Turn path into shape.
  20939. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20940. // STEP 3a - Extract points from each shape, turn to vertices
  20941. // STEP 3b - Triangulate each shape, add faces.
  20942. function Shape() {
  20943. Path.apply( this, arguments );
  20944. this.holes = [];
  20945. }
  20946. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  20947. constructor: Shape,
  20948. getPointsHoles: function ( divisions ) {
  20949. var holesPts = [];
  20950. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20951. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20952. }
  20953. return holesPts;
  20954. },
  20955. // Get points of shape and holes (keypoints based on segments parameter)
  20956. extractAllPoints: function ( divisions ) {
  20957. return {
  20958. shape: this.getPoints( divisions ),
  20959. holes: this.getPointsHoles( divisions )
  20960. };
  20961. },
  20962. extractPoints: function ( divisions ) {
  20963. return this.extractAllPoints( divisions );
  20964. }
  20965. } );
  20966. /**
  20967. * @author zz85 / http://www.lab4games.net/zz85/blog
  20968. * Creates free form 2d path using series of points, lines or curves.
  20969. *
  20970. **/
  20971. function Path( points ) {
  20972. CurvePath.call( this );
  20973. this.currentPoint = new Vector2();
  20974. if ( points ) {
  20975. this.fromPoints( points );
  20976. }
  20977. }
  20978. Path.prototype = PathPrototype;
  20979. PathPrototype.constructor = Path;
  20980. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  20981. function ShapePath() {
  20982. this.subPaths = [];
  20983. this.currentPath = null;
  20984. }
  20985. ShapePath.prototype = {
  20986. moveTo: function ( x, y ) {
  20987. this.currentPath = new Path();
  20988. this.subPaths.push(this.currentPath);
  20989. this.currentPath.moveTo( x, y );
  20990. },
  20991. lineTo: function ( x, y ) {
  20992. this.currentPath.lineTo( x, y );
  20993. },
  20994. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20995. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  20996. },
  20997. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20998. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  20999. },
  21000. splineThru: function ( pts ) {
  21001. this.currentPath.splineThru( pts );
  21002. },
  21003. toShapes: function ( isCCW, noHoles ) {
  21004. function toShapesNoHoles( inSubpaths ) {
  21005. var shapes = [];
  21006. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21007. var tmpPath = inSubpaths[ i ];
  21008. var tmpShape = new Shape();
  21009. tmpShape.curves = tmpPath.curves;
  21010. shapes.push( tmpShape );
  21011. }
  21012. return shapes;
  21013. }
  21014. function isPointInsidePolygon( inPt, inPolygon ) {
  21015. var polyLen = inPolygon.length;
  21016. // inPt on polygon contour => immediate success or
  21017. // toggling of inside/outside at every single! intersection point of an edge
  21018. // with the horizontal line through inPt, left of inPt
  21019. // not counting lowerY endpoints of edges and whole edges on that line
  21020. var inside = false;
  21021. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21022. var edgeLowPt = inPolygon[ p ];
  21023. var edgeHighPt = inPolygon[ q ];
  21024. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21025. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21026. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21027. // not parallel
  21028. if ( edgeDy < 0 ) {
  21029. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21030. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21031. }
  21032. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21033. if ( inPt.y === edgeLowPt.y ) {
  21034. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21035. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21036. } else {
  21037. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21038. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21039. if ( perpEdge < 0 ) continue;
  21040. inside = ! inside; // true intersection left of inPt
  21041. }
  21042. } else {
  21043. // parallel or collinear
  21044. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21045. // edge lies on the same horizontal line as inPt
  21046. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21047. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21048. // continue;
  21049. }
  21050. }
  21051. return inside;
  21052. }
  21053. var isClockWise = ShapeUtils.isClockWise;
  21054. var subPaths = this.subPaths;
  21055. if ( subPaths.length === 0 ) return [];
  21056. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21057. var solid, tmpPath, tmpShape, shapes = [];
  21058. if ( subPaths.length === 1 ) {
  21059. tmpPath = subPaths[ 0 ];
  21060. tmpShape = new Shape();
  21061. tmpShape.curves = tmpPath.curves;
  21062. shapes.push( tmpShape );
  21063. return shapes;
  21064. }
  21065. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21066. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21067. // console.log("Holes first", holesFirst);
  21068. var betterShapeHoles = [];
  21069. var newShapes = [];
  21070. var newShapeHoles = [];
  21071. var mainIdx = 0;
  21072. var tmpPoints;
  21073. newShapes[ mainIdx ] = undefined;
  21074. newShapeHoles[ mainIdx ] = [];
  21075. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21076. tmpPath = subPaths[ i ];
  21077. tmpPoints = tmpPath.getPoints();
  21078. solid = isClockWise( tmpPoints );
  21079. solid = isCCW ? ! solid : solid;
  21080. if ( solid ) {
  21081. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21082. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21083. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21084. if ( holesFirst ) mainIdx ++;
  21085. newShapeHoles[ mainIdx ] = [];
  21086. //console.log('cw', i);
  21087. } else {
  21088. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21089. //console.log('ccw', i);
  21090. }
  21091. }
  21092. // only Holes? -> probably all Shapes with wrong orientation
  21093. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21094. if ( newShapes.length > 1 ) {
  21095. var ambiguous = false;
  21096. var toChange = [];
  21097. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21098. betterShapeHoles[ sIdx ] = [];
  21099. }
  21100. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21101. var sho = newShapeHoles[ sIdx ];
  21102. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21103. var ho = sho[ hIdx ];
  21104. var hole_unassigned = true;
  21105. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21106. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21107. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21108. if ( hole_unassigned ) {
  21109. hole_unassigned = false;
  21110. betterShapeHoles[ s2Idx ].push( ho );
  21111. } else {
  21112. ambiguous = true;
  21113. }
  21114. }
  21115. }
  21116. if ( hole_unassigned ) {
  21117. betterShapeHoles[ sIdx ].push( ho );
  21118. }
  21119. }
  21120. }
  21121. // console.log("ambiguous: ", ambiguous);
  21122. if ( toChange.length > 0 ) {
  21123. // console.log("to change: ", toChange);
  21124. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21125. }
  21126. }
  21127. var tmpHoles;
  21128. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21129. tmpShape = newShapes[ i ].s;
  21130. shapes.push( tmpShape );
  21131. tmpHoles = newShapeHoles[ i ];
  21132. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21133. tmpShape.holes.push( tmpHoles[ j ].h );
  21134. }
  21135. }
  21136. //console.log("shape", shapes);
  21137. return shapes;
  21138. }
  21139. };
  21140. /**
  21141. * @author zz85 / http://www.lab4games.net/zz85/blog
  21142. * @author mrdoob / http://mrdoob.com/
  21143. */
  21144. function Font( data ) {
  21145. this.data = data;
  21146. }
  21147. Object.assign( Font.prototype, {
  21148. isFont: true,
  21149. generateShapes: function ( text, size, divisions ) {
  21150. function createPaths( text ) {
  21151. var chars = String( text ).split( '' );
  21152. var scale = size / data.resolution;
  21153. var offset = 0;
  21154. var paths = [];
  21155. for ( var i = 0; i < chars.length; i ++ ) {
  21156. var ret = createPath( chars[ i ], scale, offset );
  21157. offset += ret.offset;
  21158. paths.push( ret.path );
  21159. }
  21160. return paths;
  21161. }
  21162. function createPath( c, scale, offset ) {
  21163. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21164. if ( ! glyph ) return;
  21165. var path = new ShapePath();
  21166. var pts = [], b2 = ShapeUtils.b2, b3 = ShapeUtils.b3;
  21167. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21168. if ( glyph.o ) {
  21169. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21170. for ( var i = 0, l = outline.length; i < l; ) {
  21171. var action = outline[ i ++ ];
  21172. switch ( action ) {
  21173. case 'm': // moveTo
  21174. x = outline[ i ++ ] * scale + offset;
  21175. y = outline[ i ++ ] * scale;
  21176. path.moveTo( x, y );
  21177. break;
  21178. case 'l': // lineTo
  21179. x = outline[ i ++ ] * scale + offset;
  21180. y = outline[ i ++ ] * scale;
  21181. path.lineTo( x, y );
  21182. break;
  21183. case 'q': // quadraticCurveTo
  21184. cpx = outline[ i ++ ] * scale + offset;
  21185. cpy = outline[ i ++ ] * scale;
  21186. cpx1 = outline[ i ++ ] * scale + offset;
  21187. cpy1 = outline[ i ++ ] * scale;
  21188. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21189. laste = pts[ pts.length - 1 ];
  21190. if ( laste ) {
  21191. cpx0 = laste.x;
  21192. cpy0 = laste.y;
  21193. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21194. var t = i2 / divisions;
  21195. b2( t, cpx0, cpx1, cpx );
  21196. b2( t, cpy0, cpy1, cpy );
  21197. }
  21198. }
  21199. break;
  21200. case 'b': // bezierCurveTo
  21201. cpx = outline[ i ++ ] * scale + offset;
  21202. cpy = outline[ i ++ ] * scale;
  21203. cpx1 = outline[ i ++ ] * scale + offset;
  21204. cpy1 = outline[ i ++ ] * scale;
  21205. cpx2 = outline[ i ++ ] * scale + offset;
  21206. cpy2 = outline[ i ++ ] * scale;
  21207. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21208. laste = pts[ pts.length - 1 ];
  21209. if ( laste ) {
  21210. cpx0 = laste.x;
  21211. cpy0 = laste.y;
  21212. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21213. var t = i2 / divisions;
  21214. b3( t, cpx0, cpx1, cpx2, cpx );
  21215. b3( t, cpy0, cpy1, cpy2, cpy );
  21216. }
  21217. }
  21218. break;
  21219. }
  21220. }
  21221. }
  21222. return { offset: glyph.ha * scale, path: path };
  21223. }
  21224. //
  21225. if ( size === undefined ) size = 100;
  21226. if ( divisions === undefined ) divisions = 4;
  21227. var data = this.data;
  21228. var paths = createPaths( text );
  21229. var shapes = [];
  21230. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21231. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21232. }
  21233. return shapes;
  21234. }
  21235. } );
  21236. /**
  21237. * @author mrdoob / http://mrdoob.com/
  21238. */
  21239. function FontLoader( manager ) {
  21240. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21241. }
  21242. Object.assign( FontLoader.prototype, {
  21243. load: function ( url, onLoad, onProgress, onError ) {
  21244. var scope = this;
  21245. var loader = new FileLoader( this.manager );
  21246. loader.load( url, function ( text ) {
  21247. var json;
  21248. try {
  21249. json = JSON.parse( text );
  21250. } catch ( e ) {
  21251. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21252. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21253. }
  21254. var font = scope.parse( json );
  21255. if ( onLoad ) onLoad( font );
  21256. }, onProgress, onError );
  21257. },
  21258. parse: function ( json ) {
  21259. return new Font( json );
  21260. }
  21261. } );
  21262. var context;
  21263. var AudioContext = {
  21264. getContext: function () {
  21265. if ( context === undefined ) {
  21266. context = new ( window.AudioContext || window.webkitAudioContext )();
  21267. }
  21268. return context;
  21269. },
  21270. setContext: function ( value ) {
  21271. context = value;
  21272. }
  21273. };
  21274. /**
  21275. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21276. */
  21277. function AudioLoader( manager ) {
  21278. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21279. }
  21280. Object.assign( AudioLoader.prototype, {
  21281. load: function ( url, onLoad, onProgress, onError ) {
  21282. var loader = new FileLoader( this.manager );
  21283. loader.setResponseType( 'arraybuffer' );
  21284. loader.load( url, function ( buffer ) {
  21285. var context = AudioContext.getContext();
  21286. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21287. onLoad( audioBuffer );
  21288. } );
  21289. }, onProgress, onError );
  21290. }
  21291. } );
  21292. /**
  21293. * @author abelnation / http://github.com/abelnation
  21294. */
  21295. function RectAreaLight ( color, intensity, width, height ) {
  21296. Light.call( this, color, intensity );
  21297. this.type = 'RectAreaLight';
  21298. this.position.set( 0, 1, 0 );
  21299. this.updateMatrix();
  21300. this.width = ( width !== undefined ) ? width : 10;
  21301. this.height = ( height !== undefined ) ? height : 10;
  21302. // TODO (abelnation): distance/decay
  21303. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  21304. // TODO (abelnation): shadows
  21305. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  21306. }
  21307. // TODO (abelnation): RectAreaLight update when light shape is changed
  21308. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  21309. constructor: RectAreaLight,
  21310. isRectAreaLight: true,
  21311. copy: function ( source ) {
  21312. Light.prototype.copy.call( this, source );
  21313. this.width = source.width;
  21314. this.height = source.height;
  21315. // this.shadow = source.shadow.clone();
  21316. return this;
  21317. }
  21318. } );
  21319. /**
  21320. * @author mrdoob / http://mrdoob.com/
  21321. */
  21322. function StereoCamera() {
  21323. this.type = 'StereoCamera';
  21324. this.aspect = 1;
  21325. this.eyeSep = 0.064;
  21326. this.cameraL = new PerspectiveCamera();
  21327. this.cameraL.layers.enable( 1 );
  21328. this.cameraL.matrixAutoUpdate = false;
  21329. this.cameraR = new PerspectiveCamera();
  21330. this.cameraR.layers.enable( 2 );
  21331. this.cameraR.matrixAutoUpdate = false;
  21332. }
  21333. Object.assign( StereoCamera.prototype, {
  21334. update: ( function () {
  21335. var instance, focus, fov, aspect, near, far, zoom;
  21336. var eyeRight = new Matrix4();
  21337. var eyeLeft = new Matrix4();
  21338. return function update( camera ) {
  21339. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21340. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21341. far !== camera.far || zoom !== camera.zoom;
  21342. if ( needsUpdate ) {
  21343. instance = this;
  21344. focus = camera.focus;
  21345. fov = camera.fov;
  21346. aspect = camera.aspect * this.aspect;
  21347. near = camera.near;
  21348. far = camera.far;
  21349. zoom = camera.zoom;
  21350. // Off-axis stereoscopic effect based on
  21351. // http://paulbourke.net/stereographics/stereorender/
  21352. var projectionMatrix = camera.projectionMatrix.clone();
  21353. var eyeSep = this.eyeSep / 2;
  21354. var eyeSepOnProjection = eyeSep * near / focus;
  21355. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21356. var xmin, xmax;
  21357. // translate xOffset
  21358. eyeLeft.elements[ 12 ] = - eyeSep;
  21359. eyeRight.elements[ 12 ] = eyeSep;
  21360. // for left eye
  21361. xmin = - ymax * aspect + eyeSepOnProjection;
  21362. xmax = ymax * aspect + eyeSepOnProjection;
  21363. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21364. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21365. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21366. // for right eye
  21367. xmin = - ymax * aspect - eyeSepOnProjection;
  21368. xmax = ymax * aspect - eyeSepOnProjection;
  21369. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21370. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21371. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21372. }
  21373. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21374. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21375. };
  21376. } )()
  21377. } );
  21378. /**
  21379. * Camera for rendering cube maps
  21380. * - renders scene into axis-aligned cube
  21381. *
  21382. * @author alteredq / http://alteredqualia.com/
  21383. */
  21384. function CubeCamera( near, far, cubeResolution ) {
  21385. Object3D.call( this );
  21386. this.type = 'CubeCamera';
  21387. var fov = 90, aspect = 1;
  21388. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21389. cameraPX.up.set( 0, - 1, 0 );
  21390. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21391. this.add( cameraPX );
  21392. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21393. cameraNX.up.set( 0, - 1, 0 );
  21394. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21395. this.add( cameraNX );
  21396. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21397. cameraPY.up.set( 0, 0, 1 );
  21398. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21399. this.add( cameraPY );
  21400. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21401. cameraNY.up.set( 0, 0, - 1 );
  21402. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21403. this.add( cameraNY );
  21404. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21405. cameraPZ.up.set( 0, - 1, 0 );
  21406. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21407. this.add( cameraPZ );
  21408. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21409. cameraNZ.up.set( 0, - 1, 0 );
  21410. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21411. this.add( cameraNZ );
  21412. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21413. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21414. this.updateCubeMap = function ( renderer, scene ) {
  21415. if ( this.parent === null ) this.updateMatrixWorld();
  21416. var renderTarget = this.renderTarget;
  21417. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21418. renderTarget.texture.generateMipmaps = false;
  21419. renderTarget.activeCubeFace = 0;
  21420. renderer.render( scene, cameraPX, renderTarget );
  21421. renderTarget.activeCubeFace = 1;
  21422. renderer.render( scene, cameraNX, renderTarget );
  21423. renderTarget.activeCubeFace = 2;
  21424. renderer.render( scene, cameraPY, renderTarget );
  21425. renderTarget.activeCubeFace = 3;
  21426. renderer.render( scene, cameraNY, renderTarget );
  21427. renderTarget.activeCubeFace = 4;
  21428. renderer.render( scene, cameraPZ, renderTarget );
  21429. renderTarget.texture.generateMipmaps = generateMipmaps;
  21430. renderTarget.activeCubeFace = 5;
  21431. renderer.render( scene, cameraNZ, renderTarget );
  21432. renderer.setRenderTarget( null );
  21433. };
  21434. }
  21435. CubeCamera.prototype = Object.create( Object3D.prototype );
  21436. CubeCamera.prototype.constructor = CubeCamera;
  21437. /**
  21438. * @author mrdoob / http://mrdoob.com/
  21439. */
  21440. function AudioListener() {
  21441. Object3D.call( this );
  21442. this.type = 'AudioListener';
  21443. this.context = AudioContext.getContext();
  21444. this.gain = this.context.createGain();
  21445. this.gain.connect( this.context.destination );
  21446. this.filter = null;
  21447. }
  21448. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21449. constructor: AudioListener,
  21450. getInput: function () {
  21451. return this.gain;
  21452. },
  21453. removeFilter: function ( ) {
  21454. if ( this.filter !== null ) {
  21455. this.gain.disconnect( this.filter );
  21456. this.filter.disconnect( this.context.destination );
  21457. this.gain.connect( this.context.destination );
  21458. this.filter = null;
  21459. }
  21460. },
  21461. getFilter: function () {
  21462. return this.filter;
  21463. },
  21464. setFilter: function ( value ) {
  21465. if ( this.filter !== null ) {
  21466. this.gain.disconnect( this.filter );
  21467. this.filter.disconnect( this.context.destination );
  21468. } else {
  21469. this.gain.disconnect( this.context.destination );
  21470. }
  21471. this.filter = value;
  21472. this.gain.connect( this.filter );
  21473. this.filter.connect( this.context.destination );
  21474. },
  21475. getMasterVolume: function () {
  21476. return this.gain.gain.value;
  21477. },
  21478. setMasterVolume: function ( value ) {
  21479. this.gain.gain.value = value;
  21480. },
  21481. updateMatrixWorld: ( function () {
  21482. var position = new Vector3();
  21483. var quaternion = new Quaternion();
  21484. var scale = new Vector3();
  21485. var orientation = new Vector3();
  21486. return function updateMatrixWorld( force ) {
  21487. Object3D.prototype.updateMatrixWorld.call( this, force );
  21488. var listener = this.context.listener;
  21489. var up = this.up;
  21490. this.matrixWorld.decompose( position, quaternion, scale );
  21491. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21492. if ( listener.positionX ) {
  21493. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21494. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21495. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21496. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21497. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21498. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21499. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21500. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21501. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21502. } else {
  21503. listener.setPosition( position.x, position.y, position.z );
  21504. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21505. }
  21506. };
  21507. } )()
  21508. } );
  21509. /**
  21510. * @author mrdoob / http://mrdoob.com/
  21511. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21512. */
  21513. function Audio( listener ) {
  21514. Object3D.call( this );
  21515. this.type = 'Audio';
  21516. this.context = listener.context;
  21517. this.gain = this.context.createGain();
  21518. this.gain.connect( listener.getInput() );
  21519. this.autoplay = false;
  21520. this.buffer = null;
  21521. this.loop = false;
  21522. this.startTime = 0;
  21523. this.playbackRate = 1;
  21524. this.isPlaying = false;
  21525. this.hasPlaybackControl = true;
  21526. this.sourceType = 'empty';
  21527. this.filters = [];
  21528. }
  21529. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21530. constructor: Audio,
  21531. getOutput: function () {
  21532. return this.gain;
  21533. },
  21534. setNodeSource: function ( audioNode ) {
  21535. this.hasPlaybackControl = false;
  21536. this.sourceType = 'audioNode';
  21537. this.source = audioNode;
  21538. this.connect();
  21539. return this;
  21540. },
  21541. setBuffer: function ( audioBuffer ) {
  21542. this.buffer = audioBuffer;
  21543. this.sourceType = 'buffer';
  21544. if ( this.autoplay ) this.play();
  21545. return this;
  21546. },
  21547. play: function () {
  21548. if ( this.isPlaying === true ) {
  21549. console.warn( 'THREE.Audio: Audio is already playing.' );
  21550. return;
  21551. }
  21552. if ( this.hasPlaybackControl === false ) {
  21553. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21554. return;
  21555. }
  21556. var source = this.context.createBufferSource();
  21557. source.buffer = this.buffer;
  21558. source.loop = this.loop;
  21559. source.onended = this.onEnded.bind( this );
  21560. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21561. source.start( 0, this.startTime );
  21562. this.isPlaying = true;
  21563. this.source = source;
  21564. return this.connect();
  21565. },
  21566. pause: function () {
  21567. if ( this.hasPlaybackControl === false ) {
  21568. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21569. return;
  21570. }
  21571. this.source.stop();
  21572. this.startTime = this.context.currentTime;
  21573. this.isPlaying = false;
  21574. return this;
  21575. },
  21576. stop: function () {
  21577. if ( this.hasPlaybackControl === false ) {
  21578. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21579. return;
  21580. }
  21581. this.source.stop();
  21582. this.startTime = 0;
  21583. this.isPlaying = false;
  21584. return this;
  21585. },
  21586. connect: function () {
  21587. if ( this.filters.length > 0 ) {
  21588. this.source.connect( this.filters[ 0 ] );
  21589. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21590. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21591. }
  21592. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21593. } else {
  21594. this.source.connect( this.getOutput() );
  21595. }
  21596. return this;
  21597. },
  21598. disconnect: function () {
  21599. if ( this.filters.length > 0 ) {
  21600. this.source.disconnect( this.filters[ 0 ] );
  21601. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21602. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21603. }
  21604. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21605. } else {
  21606. this.source.disconnect( this.getOutput() );
  21607. }
  21608. return this;
  21609. },
  21610. getFilters: function () {
  21611. return this.filters;
  21612. },
  21613. setFilters: function ( value ) {
  21614. if ( ! value ) value = [];
  21615. if ( this.isPlaying === true ) {
  21616. this.disconnect();
  21617. this.filters = value;
  21618. this.connect();
  21619. } else {
  21620. this.filters = value;
  21621. }
  21622. return this;
  21623. },
  21624. getFilter: function () {
  21625. return this.getFilters()[ 0 ];
  21626. },
  21627. setFilter: function ( filter ) {
  21628. return this.setFilters( filter ? [ filter ] : [] );
  21629. },
  21630. setPlaybackRate: function ( value ) {
  21631. if ( this.hasPlaybackControl === false ) {
  21632. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21633. return;
  21634. }
  21635. this.playbackRate = value;
  21636. if ( this.isPlaying === true ) {
  21637. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21638. }
  21639. return this;
  21640. },
  21641. getPlaybackRate: function () {
  21642. return this.playbackRate;
  21643. },
  21644. onEnded: function () {
  21645. this.isPlaying = false;
  21646. },
  21647. getLoop: function () {
  21648. if ( this.hasPlaybackControl === false ) {
  21649. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21650. return false;
  21651. }
  21652. return this.loop;
  21653. },
  21654. setLoop: function ( value ) {
  21655. if ( this.hasPlaybackControl === false ) {
  21656. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21657. return;
  21658. }
  21659. this.loop = value;
  21660. if ( this.isPlaying === true ) {
  21661. this.source.loop = this.loop;
  21662. }
  21663. return this;
  21664. },
  21665. getVolume: function () {
  21666. return this.gain.gain.value;
  21667. },
  21668. setVolume: function ( value ) {
  21669. this.gain.gain.value = value;
  21670. return this;
  21671. }
  21672. } );
  21673. /**
  21674. * @author mrdoob / http://mrdoob.com/
  21675. */
  21676. function PositionalAudio( listener ) {
  21677. Audio.call( this, listener );
  21678. this.panner = this.context.createPanner();
  21679. this.panner.connect( this.gain );
  21680. }
  21681. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21682. constructor: PositionalAudio,
  21683. getOutput: function () {
  21684. return this.panner;
  21685. },
  21686. getRefDistance: function () {
  21687. return this.panner.refDistance;
  21688. },
  21689. setRefDistance: function ( value ) {
  21690. this.panner.refDistance = value;
  21691. },
  21692. getRolloffFactor: function () {
  21693. return this.panner.rolloffFactor;
  21694. },
  21695. setRolloffFactor: function ( value ) {
  21696. this.panner.rolloffFactor = value;
  21697. },
  21698. getDistanceModel: function () {
  21699. return this.panner.distanceModel;
  21700. },
  21701. setDistanceModel: function ( value ) {
  21702. this.panner.distanceModel = value;
  21703. },
  21704. getMaxDistance: function () {
  21705. return this.panner.maxDistance;
  21706. },
  21707. setMaxDistance: function ( value ) {
  21708. this.panner.maxDistance = value;
  21709. },
  21710. updateMatrixWorld: ( function () {
  21711. var position = new Vector3();
  21712. return function updateMatrixWorld( force ) {
  21713. Object3D.prototype.updateMatrixWorld.call( this, force );
  21714. position.setFromMatrixPosition( this.matrixWorld );
  21715. this.panner.setPosition( position.x, position.y, position.z );
  21716. };
  21717. } )()
  21718. } );
  21719. /**
  21720. * @author mrdoob / http://mrdoob.com/
  21721. */
  21722. function AudioAnalyser( audio, fftSize ) {
  21723. this.analyser = audio.context.createAnalyser();
  21724. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21725. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21726. audio.getOutput().connect( this.analyser );
  21727. }
  21728. Object.assign( AudioAnalyser.prototype, {
  21729. getFrequencyData: function () {
  21730. this.analyser.getByteFrequencyData( this.data );
  21731. return this.data;
  21732. },
  21733. getAverageFrequency: function () {
  21734. var value = 0, data = this.getFrequencyData();
  21735. for ( var i = 0; i < data.length; i ++ ) {
  21736. value += data[ i ];
  21737. }
  21738. return value / data.length;
  21739. }
  21740. } );
  21741. /**
  21742. *
  21743. * Buffered scene graph property that allows weighted accumulation.
  21744. *
  21745. *
  21746. * @author Ben Houston / http://clara.io/
  21747. * @author David Sarno / http://lighthaus.us/
  21748. * @author tschw
  21749. */
  21750. function PropertyMixer( binding, typeName, valueSize ) {
  21751. this.binding = binding;
  21752. this.valueSize = valueSize;
  21753. var bufferType = Float64Array,
  21754. mixFunction;
  21755. switch ( typeName ) {
  21756. case 'quaternion':
  21757. mixFunction = this._slerp;
  21758. break;
  21759. case 'string':
  21760. case 'bool':
  21761. bufferType = Array;
  21762. mixFunction = this._select;
  21763. break;
  21764. default:
  21765. mixFunction = this._lerp;
  21766. }
  21767. this.buffer = new bufferType( valueSize * 4 );
  21768. // layout: [ incoming | accu0 | accu1 | orig ]
  21769. //
  21770. // interpolators can use .buffer as their .result
  21771. // the data then goes to 'incoming'
  21772. //
  21773. // 'accu0' and 'accu1' are used frame-interleaved for
  21774. // the cumulative result and are compared to detect
  21775. // changes
  21776. //
  21777. // 'orig' stores the original state of the property
  21778. this._mixBufferRegion = mixFunction;
  21779. this.cumulativeWeight = 0;
  21780. this.useCount = 0;
  21781. this.referenceCount = 0;
  21782. }
  21783. PropertyMixer.prototype = {
  21784. constructor: PropertyMixer,
  21785. // accumulate data in the 'incoming' region into 'accu<i>'
  21786. accumulate: function( accuIndex, weight ) {
  21787. // note: happily accumulating nothing when weight = 0, the caller knows
  21788. // the weight and shouldn't have made the call in the first place
  21789. var buffer = this.buffer,
  21790. stride = this.valueSize,
  21791. offset = accuIndex * stride + stride,
  21792. currentWeight = this.cumulativeWeight;
  21793. if ( currentWeight === 0 ) {
  21794. // accuN := incoming * weight
  21795. for ( var i = 0; i !== stride; ++ i ) {
  21796. buffer[ offset + i ] = buffer[ i ];
  21797. }
  21798. currentWeight = weight;
  21799. } else {
  21800. // accuN := accuN + incoming * weight
  21801. currentWeight += weight;
  21802. var mix = weight / currentWeight;
  21803. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21804. }
  21805. this.cumulativeWeight = currentWeight;
  21806. },
  21807. // apply the state of 'accu<i>' to the binding when accus differ
  21808. apply: function( accuIndex ) {
  21809. var stride = this.valueSize,
  21810. buffer = this.buffer,
  21811. offset = accuIndex * stride + stride,
  21812. weight = this.cumulativeWeight,
  21813. binding = this.binding;
  21814. this.cumulativeWeight = 0;
  21815. if ( weight < 1 ) {
  21816. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21817. var originalValueOffset = stride * 3;
  21818. this._mixBufferRegion(
  21819. buffer, offset, originalValueOffset, 1 - weight, stride );
  21820. }
  21821. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21822. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21823. // value has changed -> update scene graph
  21824. binding.setValue( buffer, offset );
  21825. break;
  21826. }
  21827. }
  21828. },
  21829. // remember the state of the bound property and copy it to both accus
  21830. saveOriginalState: function() {
  21831. var binding = this.binding;
  21832. var buffer = this.buffer,
  21833. stride = this.valueSize,
  21834. originalValueOffset = stride * 3;
  21835. binding.getValue( buffer, originalValueOffset );
  21836. // accu[0..1] := orig -- initially detect changes against the original
  21837. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21838. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21839. }
  21840. this.cumulativeWeight = 0;
  21841. },
  21842. // apply the state previously taken via 'saveOriginalState' to the binding
  21843. restoreOriginalState: function() {
  21844. var originalValueOffset = this.valueSize * 3;
  21845. this.binding.setValue( this.buffer, originalValueOffset );
  21846. },
  21847. // mix functions
  21848. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  21849. if ( t >= 0.5 ) {
  21850. for ( var i = 0; i !== stride; ++ i ) {
  21851. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21852. }
  21853. }
  21854. },
  21855. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21856. Quaternion.slerpFlat( buffer, dstOffset,
  21857. buffer, dstOffset, buffer, srcOffset, t );
  21858. },
  21859. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21860. var s = 1 - t;
  21861. for ( var i = 0; i !== stride; ++ i ) {
  21862. var j = dstOffset + i;
  21863. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21864. }
  21865. }
  21866. };
  21867. /**
  21868. *
  21869. * A reference to a real property in the scene graph.
  21870. *
  21871. *
  21872. * @author Ben Houston / http://clara.io/
  21873. * @author David Sarno / http://lighthaus.us/
  21874. * @author tschw
  21875. */
  21876. function PropertyBinding( rootNode, path, parsedPath ) {
  21877. this.path = path;
  21878. this.parsedPath = parsedPath ||
  21879. PropertyBinding.parseTrackName( path );
  21880. this.node = PropertyBinding.findNode(
  21881. rootNode, this.parsedPath.nodeName ) || rootNode;
  21882. this.rootNode = rootNode;
  21883. }
  21884. PropertyBinding.prototype = {
  21885. constructor: PropertyBinding,
  21886. getValue: function getValue_unbound( targetArray, offset ) {
  21887. this.bind();
  21888. this.getValue( targetArray, offset );
  21889. // Note: This class uses a State pattern on a per-method basis:
  21890. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  21891. // prototype version of these methods with one that represents
  21892. // the bound state. When the property is not found, the methods
  21893. // become no-ops.
  21894. },
  21895. setValue: function getValue_unbound( sourceArray, offset ) {
  21896. this.bind();
  21897. this.setValue( sourceArray, offset );
  21898. },
  21899. // create getter / setter pair for a property in the scene graph
  21900. bind: function() {
  21901. var targetObject = this.node,
  21902. parsedPath = this.parsedPath,
  21903. objectName = parsedPath.objectName,
  21904. propertyName = parsedPath.propertyName,
  21905. propertyIndex = parsedPath.propertyIndex;
  21906. if ( ! targetObject ) {
  21907. targetObject = PropertyBinding.findNode(
  21908. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  21909. this.node = targetObject;
  21910. }
  21911. // set fail state so we can just 'return' on error
  21912. this.getValue = this._getValue_unavailable;
  21913. this.setValue = this._setValue_unavailable;
  21914. // ensure there is a value node
  21915. if ( ! targetObject ) {
  21916. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  21917. return;
  21918. }
  21919. if ( objectName ) {
  21920. var objectIndex = parsedPath.objectIndex;
  21921. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  21922. switch ( objectName ) {
  21923. case 'materials':
  21924. if ( ! targetObject.material ) {
  21925. console.error( ' can not bind to material as node does not have a material', this );
  21926. return;
  21927. }
  21928. if ( ! targetObject.material.materials ) {
  21929. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  21930. return;
  21931. }
  21932. targetObject = targetObject.material.materials;
  21933. break;
  21934. case 'bones':
  21935. if ( ! targetObject.skeleton ) {
  21936. console.error( ' can not bind to bones as node does not have a skeleton', this );
  21937. return;
  21938. }
  21939. // potential future optimization: skip this if propertyIndex is already an integer
  21940. // and convert the integer string to a true integer.
  21941. targetObject = targetObject.skeleton.bones;
  21942. // support resolving morphTarget names into indices.
  21943. for ( var i = 0; i < targetObject.length; i ++ ) {
  21944. if ( targetObject[ i ].name === objectIndex ) {
  21945. objectIndex = i;
  21946. break;
  21947. }
  21948. }
  21949. break;
  21950. default:
  21951. if ( targetObject[ objectName ] === undefined ) {
  21952. console.error( ' can not bind to objectName of node, undefined', this );
  21953. return;
  21954. }
  21955. targetObject = targetObject[ objectName ];
  21956. }
  21957. if ( objectIndex !== undefined ) {
  21958. if ( targetObject[ objectIndex ] === undefined ) {
  21959. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  21960. return;
  21961. }
  21962. targetObject = targetObject[ objectIndex ];
  21963. }
  21964. }
  21965. // resolve property
  21966. var nodeProperty = targetObject[ propertyName ];
  21967. if ( nodeProperty === undefined ) {
  21968. var nodeName = parsedPath.nodeName;
  21969. console.error( " trying to update property for track: " + nodeName +
  21970. '.' + propertyName + " but it wasn't found.", targetObject );
  21971. return;
  21972. }
  21973. // determine versioning scheme
  21974. var versioning = this.Versioning.None;
  21975. if ( targetObject.needsUpdate !== undefined ) { // material
  21976. versioning = this.Versioning.NeedsUpdate;
  21977. this.targetObject = targetObject;
  21978. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  21979. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  21980. this.targetObject = targetObject;
  21981. }
  21982. // determine how the property gets bound
  21983. var bindingType = this.BindingType.Direct;
  21984. if ( propertyIndex !== undefined ) {
  21985. // access a sub element of the property array (only primitives are supported right now)
  21986. if ( propertyName === "morphTargetInfluences" ) {
  21987. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  21988. // support resolving morphTarget names into indices.
  21989. if ( ! targetObject.geometry ) {
  21990. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  21991. return;
  21992. }
  21993. if ( ! targetObject.geometry.morphTargets ) {
  21994. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  21995. return;
  21996. }
  21997. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  21998. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  21999. propertyIndex = i;
  22000. break;
  22001. }
  22002. }
  22003. }
  22004. bindingType = this.BindingType.ArrayElement;
  22005. this.resolvedProperty = nodeProperty;
  22006. this.propertyIndex = propertyIndex;
  22007. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22008. // must use copy for Object3D.Euler/Quaternion
  22009. bindingType = this.BindingType.HasFromToArray;
  22010. this.resolvedProperty = nodeProperty;
  22011. } else if ( nodeProperty.length !== undefined ) {
  22012. bindingType = this.BindingType.EntireArray;
  22013. this.resolvedProperty = nodeProperty;
  22014. } else {
  22015. this.propertyName = propertyName;
  22016. }
  22017. // select getter / setter
  22018. this.getValue = this.GetterByBindingType[ bindingType ];
  22019. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22020. },
  22021. unbind: function() {
  22022. this.node = null;
  22023. // back to the prototype version of getValue / setValue
  22024. // note: avoiding to mutate the shape of 'this' via 'delete'
  22025. this.getValue = this._getValue_unbound;
  22026. this.setValue = this._setValue_unbound;
  22027. }
  22028. };
  22029. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22030. // these are used to "bind" a nonexistent property
  22031. _getValue_unavailable: function() {},
  22032. _setValue_unavailable: function() {},
  22033. // initial state of these methods that calls 'bind'
  22034. _getValue_unbound: PropertyBinding.prototype.getValue,
  22035. _setValue_unbound: PropertyBinding.prototype.setValue,
  22036. BindingType: {
  22037. Direct: 0,
  22038. EntireArray: 1,
  22039. ArrayElement: 2,
  22040. HasFromToArray: 3
  22041. },
  22042. Versioning: {
  22043. None: 0,
  22044. NeedsUpdate: 1,
  22045. MatrixWorldNeedsUpdate: 2
  22046. },
  22047. GetterByBindingType: [
  22048. function getValue_direct( buffer, offset ) {
  22049. buffer[ offset ] = this.node[ this.propertyName ];
  22050. },
  22051. function getValue_array( buffer, offset ) {
  22052. var source = this.resolvedProperty;
  22053. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22054. buffer[ offset ++ ] = source[ i ];
  22055. }
  22056. },
  22057. function getValue_arrayElement( buffer, offset ) {
  22058. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22059. },
  22060. function getValue_toArray( buffer, offset ) {
  22061. this.resolvedProperty.toArray( buffer, offset );
  22062. }
  22063. ],
  22064. SetterByBindingTypeAndVersioning: [
  22065. [
  22066. // Direct
  22067. function setValue_direct( buffer, offset ) {
  22068. this.node[ this.propertyName ] = buffer[ offset ];
  22069. },
  22070. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22071. this.node[ this.propertyName ] = buffer[ offset ];
  22072. this.targetObject.needsUpdate = true;
  22073. },
  22074. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22075. this.node[ this.propertyName ] = buffer[ offset ];
  22076. this.targetObject.matrixWorldNeedsUpdate = true;
  22077. }
  22078. ], [
  22079. // EntireArray
  22080. function setValue_array( buffer, offset ) {
  22081. var dest = this.resolvedProperty;
  22082. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22083. dest[ i ] = buffer[ offset ++ ];
  22084. }
  22085. },
  22086. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22087. var dest = this.resolvedProperty;
  22088. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22089. dest[ i ] = buffer[ offset ++ ];
  22090. }
  22091. this.targetObject.needsUpdate = true;
  22092. },
  22093. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22094. var dest = this.resolvedProperty;
  22095. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22096. dest[ i ] = buffer[ offset ++ ];
  22097. }
  22098. this.targetObject.matrixWorldNeedsUpdate = true;
  22099. }
  22100. ], [
  22101. // ArrayElement
  22102. function setValue_arrayElement( buffer, offset ) {
  22103. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22104. },
  22105. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22106. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22107. this.targetObject.needsUpdate = true;
  22108. },
  22109. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22110. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22111. this.targetObject.matrixWorldNeedsUpdate = true;
  22112. }
  22113. ], [
  22114. // HasToFromArray
  22115. function setValue_fromArray( buffer, offset ) {
  22116. this.resolvedProperty.fromArray( buffer, offset );
  22117. },
  22118. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22119. this.resolvedProperty.fromArray( buffer, offset );
  22120. this.targetObject.needsUpdate = true;
  22121. },
  22122. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22123. this.resolvedProperty.fromArray( buffer, offset );
  22124. this.targetObject.matrixWorldNeedsUpdate = true;
  22125. }
  22126. ]
  22127. ]
  22128. } );
  22129. PropertyBinding.Composite =
  22130. function( targetGroup, path, optionalParsedPath ) {
  22131. var parsedPath = optionalParsedPath ||
  22132. PropertyBinding.parseTrackName( path );
  22133. this._targetGroup = targetGroup;
  22134. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22135. };
  22136. PropertyBinding.Composite.prototype = {
  22137. constructor: PropertyBinding.Composite,
  22138. getValue: function( array, offset ) {
  22139. this.bind(); // bind all binding
  22140. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22141. binding = this._bindings[ firstValidIndex ];
  22142. // and only call .getValue on the first
  22143. if ( binding !== undefined ) binding.getValue( array, offset );
  22144. },
  22145. setValue: function( array, offset ) {
  22146. var bindings = this._bindings;
  22147. for ( var i = this._targetGroup.nCachedObjects_,
  22148. n = bindings.length; i !== n; ++ i ) {
  22149. bindings[ i ].setValue( array, offset );
  22150. }
  22151. },
  22152. bind: function() {
  22153. var bindings = this._bindings;
  22154. for ( var i = this._targetGroup.nCachedObjects_,
  22155. n = bindings.length; i !== n; ++ i ) {
  22156. bindings[ i ].bind();
  22157. }
  22158. },
  22159. unbind: function() {
  22160. var bindings = this._bindings;
  22161. for ( var i = this._targetGroup.nCachedObjects_,
  22162. n = bindings.length; i !== n; ++ i ) {
  22163. bindings[ i ].unbind();
  22164. }
  22165. }
  22166. };
  22167. PropertyBinding.create = function( root, path, parsedPath ) {
  22168. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22169. return new PropertyBinding( root, path, parsedPath );
  22170. } else {
  22171. return new PropertyBinding.Composite( root, path, parsedPath );
  22172. }
  22173. };
  22174. PropertyBinding.parseTrackName = function( trackName ) {
  22175. // matches strings in the form of:
  22176. // nodeName.property
  22177. // nodeName.property[accessor]
  22178. // nodeName.material.property[accessor]
  22179. // uuid.property[accessor]
  22180. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  22181. // parentName/nodeName.property
  22182. // parentName/parentName/nodeName.property[index]
  22183. // .bone[Armature.DEF_cog].position
  22184. // scene:helium_balloon_model:helium_balloon_model.position
  22185. // created and tested via https://regex101.com/#javascript
  22186. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  22187. var matches = re.exec( trackName );
  22188. if ( ! matches ) {
  22189. throw new Error( "cannot parse trackName at all: " + trackName );
  22190. }
  22191. var results = {
  22192. // directoryName: matches[ 1 ], // (tschw) currently unused
  22193. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  22194. objectName: matches[ 3 ],
  22195. objectIndex: matches[ 4 ],
  22196. propertyName: matches[ 5 ],
  22197. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  22198. };
  22199. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22200. throw new Error( "can not parse propertyName from trackName: " + trackName );
  22201. }
  22202. return results;
  22203. };
  22204. PropertyBinding.findNode = function( root, nodeName ) {
  22205. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  22206. return root;
  22207. }
  22208. // search into skeleton bones.
  22209. if ( root.skeleton ) {
  22210. var searchSkeleton = function( skeleton ) {
  22211. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  22212. var bone = skeleton.bones[ i ];
  22213. if ( bone.name === nodeName ) {
  22214. return bone;
  22215. }
  22216. }
  22217. return null;
  22218. };
  22219. var bone = searchSkeleton( root.skeleton );
  22220. if ( bone ) {
  22221. return bone;
  22222. }
  22223. }
  22224. // search into node subtree.
  22225. if ( root.children ) {
  22226. var searchNodeSubtree = function( children ) {
  22227. for( var i = 0; i < children.length; i ++ ) {
  22228. var childNode = children[ i ];
  22229. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22230. return childNode;
  22231. }
  22232. var result = searchNodeSubtree( childNode.children );
  22233. if ( result ) return result;
  22234. }
  22235. return null;
  22236. };
  22237. var subTreeNode = searchNodeSubtree( root.children );
  22238. if ( subTreeNode ) {
  22239. return subTreeNode;
  22240. }
  22241. }
  22242. return null;
  22243. };
  22244. /**
  22245. *
  22246. * A group of objects that receives a shared animation state.
  22247. *
  22248. * Usage:
  22249. *
  22250. * - Add objects you would otherwise pass as 'root' to the
  22251. * constructor or the .clipAction method of AnimationMixer.
  22252. *
  22253. * - Instead pass this object as 'root'.
  22254. *
  22255. * - You can also add and remove objects later when the mixer
  22256. * is running.
  22257. *
  22258. * Note:
  22259. *
  22260. * Objects of this class appear as one object to the mixer,
  22261. * so cache control of the individual objects must be done
  22262. * on the group.
  22263. *
  22264. * Limitation:
  22265. *
  22266. * - The animated properties must be compatible among the
  22267. * all objects in the group.
  22268. *
  22269. * - A single property can either be controlled through a
  22270. * target group or directly, but not both.
  22271. *
  22272. * @author tschw
  22273. */
  22274. function AnimationObjectGroup( var_args ) {
  22275. this.uuid = _Math.generateUUID();
  22276. // cached objects followed by the active ones
  22277. this._objects = Array.prototype.slice.call( arguments );
  22278. this.nCachedObjects_ = 0; // threshold
  22279. // note: read by PropertyBinding.Composite
  22280. var indices = {};
  22281. this._indicesByUUID = indices; // for bookkeeping
  22282. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22283. indices[ arguments[ i ].uuid ] = i;
  22284. }
  22285. this._paths = []; // inside: string
  22286. this._parsedPaths = []; // inside: { we don't care, here }
  22287. this._bindings = []; // inside: Array< PropertyBinding >
  22288. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22289. var scope = this;
  22290. this.stats = {
  22291. objects: {
  22292. get total() { return scope._objects.length; },
  22293. get inUse() { return this.total - scope.nCachedObjects_; }
  22294. },
  22295. get bindingsPerObject() { return scope._bindings.length; }
  22296. };
  22297. }
  22298. AnimationObjectGroup.prototype = {
  22299. constructor: AnimationObjectGroup,
  22300. isAnimationObjectGroup: true,
  22301. add: function( var_args ) {
  22302. var objects = this._objects,
  22303. nObjects = objects.length,
  22304. nCachedObjects = this.nCachedObjects_,
  22305. indicesByUUID = this._indicesByUUID,
  22306. paths = this._paths,
  22307. parsedPaths = this._parsedPaths,
  22308. bindings = this._bindings,
  22309. nBindings = bindings.length;
  22310. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22311. var object = arguments[ i ],
  22312. uuid = object.uuid,
  22313. index = indicesByUUID[ uuid ],
  22314. knownObject = undefined;
  22315. if ( index === undefined ) {
  22316. // unknown object -> add it to the ACTIVE region
  22317. index = nObjects ++;
  22318. indicesByUUID[ uuid ] = index;
  22319. objects.push( object );
  22320. // accounting is done, now do the same for all bindings
  22321. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22322. bindings[ j ].push(
  22323. new PropertyBinding(
  22324. object, paths[ j ], parsedPaths[ j ] ) );
  22325. }
  22326. } else if ( index < nCachedObjects ) {
  22327. knownObject = objects[ index ];
  22328. // move existing object to the ACTIVE region
  22329. var firstActiveIndex = -- nCachedObjects,
  22330. lastCachedObject = objects[ firstActiveIndex ];
  22331. indicesByUUID[ lastCachedObject.uuid ] = index;
  22332. objects[ index ] = lastCachedObject;
  22333. indicesByUUID[ uuid ] = firstActiveIndex;
  22334. objects[ firstActiveIndex ] = object;
  22335. // accounting is done, now do the same for all bindings
  22336. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22337. var bindingsForPath = bindings[ j ],
  22338. lastCached = bindingsForPath[ firstActiveIndex ],
  22339. binding = bindingsForPath[ index ];
  22340. bindingsForPath[ index ] = lastCached;
  22341. if ( binding === undefined ) {
  22342. // since we do not bother to create new bindings
  22343. // for objects that are cached, the binding may
  22344. // or may not exist
  22345. binding = new PropertyBinding(
  22346. object, paths[ j ], parsedPaths[ j ] );
  22347. }
  22348. bindingsForPath[ firstActiveIndex ] = binding;
  22349. }
  22350. } else if ( objects[ index ] !== knownObject) {
  22351. console.error( "Different objects with the same UUID " +
  22352. "detected. Clean the caches or recreate your " +
  22353. "infrastructure when reloading scenes..." );
  22354. } // else the object is already where we want it to be
  22355. } // for arguments
  22356. this.nCachedObjects_ = nCachedObjects;
  22357. },
  22358. remove: function( var_args ) {
  22359. var objects = this._objects,
  22360. nCachedObjects = this.nCachedObjects_,
  22361. indicesByUUID = this._indicesByUUID,
  22362. bindings = this._bindings,
  22363. nBindings = bindings.length;
  22364. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22365. var object = arguments[ i ],
  22366. uuid = object.uuid,
  22367. index = indicesByUUID[ uuid ];
  22368. if ( index !== undefined && index >= nCachedObjects ) {
  22369. // move existing object into the CACHED region
  22370. var lastCachedIndex = nCachedObjects ++,
  22371. firstActiveObject = objects[ lastCachedIndex ];
  22372. indicesByUUID[ firstActiveObject.uuid ] = index;
  22373. objects[ index ] = firstActiveObject;
  22374. indicesByUUID[ uuid ] = lastCachedIndex;
  22375. objects[ lastCachedIndex ] = object;
  22376. // accounting is done, now do the same for all bindings
  22377. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22378. var bindingsForPath = bindings[ j ],
  22379. firstActive = bindingsForPath[ lastCachedIndex ],
  22380. binding = bindingsForPath[ index ];
  22381. bindingsForPath[ index ] = firstActive;
  22382. bindingsForPath[ lastCachedIndex ] = binding;
  22383. }
  22384. }
  22385. } // for arguments
  22386. this.nCachedObjects_ = nCachedObjects;
  22387. },
  22388. // remove & forget
  22389. uncache: function( var_args ) {
  22390. var objects = this._objects,
  22391. nObjects = objects.length,
  22392. nCachedObjects = this.nCachedObjects_,
  22393. indicesByUUID = this._indicesByUUID,
  22394. bindings = this._bindings,
  22395. nBindings = bindings.length;
  22396. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22397. var object = arguments[ i ],
  22398. uuid = object.uuid,
  22399. index = indicesByUUID[ uuid ];
  22400. if ( index !== undefined ) {
  22401. delete indicesByUUID[ uuid ];
  22402. if ( index < nCachedObjects ) {
  22403. // object is cached, shrink the CACHED region
  22404. var firstActiveIndex = -- nCachedObjects,
  22405. lastCachedObject = objects[ firstActiveIndex ],
  22406. lastIndex = -- nObjects,
  22407. lastObject = objects[ lastIndex ];
  22408. // last cached object takes this object's place
  22409. indicesByUUID[ lastCachedObject.uuid ] = index;
  22410. objects[ index ] = lastCachedObject;
  22411. // last object goes to the activated slot and pop
  22412. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22413. objects[ firstActiveIndex ] = lastObject;
  22414. objects.pop();
  22415. // accounting is done, now do the same for all bindings
  22416. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22417. var bindingsForPath = bindings[ j ],
  22418. lastCached = bindingsForPath[ firstActiveIndex ],
  22419. last = bindingsForPath[ lastIndex ];
  22420. bindingsForPath[ index ] = lastCached;
  22421. bindingsForPath[ firstActiveIndex ] = last;
  22422. bindingsForPath.pop();
  22423. }
  22424. } else {
  22425. // object is active, just swap with the last and pop
  22426. var lastIndex = -- nObjects,
  22427. lastObject = objects[ lastIndex ];
  22428. indicesByUUID[ lastObject.uuid ] = index;
  22429. objects[ index ] = lastObject;
  22430. objects.pop();
  22431. // accounting is done, now do the same for all bindings
  22432. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22433. var bindingsForPath = bindings[ j ];
  22434. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22435. bindingsForPath.pop();
  22436. }
  22437. } // cached or active
  22438. } // if object is known
  22439. } // for arguments
  22440. this.nCachedObjects_ = nCachedObjects;
  22441. },
  22442. // Internal interface used by befriended PropertyBinding.Composite:
  22443. subscribe_: function( path, parsedPath ) {
  22444. // returns an array of bindings for the given path that is changed
  22445. // according to the contained objects in the group
  22446. var indicesByPath = this._bindingsIndicesByPath,
  22447. index = indicesByPath[ path ],
  22448. bindings = this._bindings;
  22449. if ( index !== undefined ) return bindings[ index ];
  22450. var paths = this._paths,
  22451. parsedPaths = this._parsedPaths,
  22452. objects = this._objects,
  22453. nObjects = objects.length,
  22454. nCachedObjects = this.nCachedObjects_,
  22455. bindingsForPath = new Array( nObjects );
  22456. index = bindings.length;
  22457. indicesByPath[ path ] = index;
  22458. paths.push( path );
  22459. parsedPaths.push( parsedPath );
  22460. bindings.push( bindingsForPath );
  22461. for ( var i = nCachedObjects,
  22462. n = objects.length; i !== n; ++ i ) {
  22463. var object = objects[ i ];
  22464. bindingsForPath[ i ] =
  22465. new PropertyBinding( object, path, parsedPath );
  22466. }
  22467. return bindingsForPath;
  22468. },
  22469. unsubscribe_: function( path ) {
  22470. // tells the group to forget about a property path and no longer
  22471. // update the array previously obtained with 'subscribe_'
  22472. var indicesByPath = this._bindingsIndicesByPath,
  22473. index = indicesByPath[ path ];
  22474. if ( index !== undefined ) {
  22475. var paths = this._paths,
  22476. parsedPaths = this._parsedPaths,
  22477. bindings = this._bindings,
  22478. lastBindingsIndex = bindings.length - 1,
  22479. lastBindings = bindings[ lastBindingsIndex ],
  22480. lastBindingsPath = path[ lastBindingsIndex ];
  22481. indicesByPath[ lastBindingsPath ] = index;
  22482. bindings[ index ] = lastBindings;
  22483. bindings.pop();
  22484. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22485. parsedPaths.pop();
  22486. paths[ index ] = paths[ lastBindingsIndex ];
  22487. paths.pop();
  22488. }
  22489. }
  22490. };
  22491. /**
  22492. *
  22493. * Action provided by AnimationMixer for scheduling clip playback on specific
  22494. * objects.
  22495. *
  22496. * @author Ben Houston / http://clara.io/
  22497. * @author David Sarno / http://lighthaus.us/
  22498. * @author tschw
  22499. *
  22500. */
  22501. function AnimationAction( mixer, clip, localRoot ) {
  22502. this._mixer = mixer;
  22503. this._clip = clip;
  22504. this._localRoot = localRoot || null;
  22505. var tracks = clip.tracks,
  22506. nTracks = tracks.length,
  22507. interpolants = new Array( nTracks );
  22508. var interpolantSettings = {
  22509. endingStart: ZeroCurvatureEnding,
  22510. endingEnd: ZeroCurvatureEnding
  22511. };
  22512. for ( var i = 0; i !== nTracks; ++ i ) {
  22513. var interpolant = tracks[ i ].createInterpolant( null );
  22514. interpolants[ i ] = interpolant;
  22515. interpolant.settings = interpolantSettings;
  22516. }
  22517. this._interpolantSettings = interpolantSettings;
  22518. this._interpolants = interpolants; // bound by the mixer
  22519. // inside: PropertyMixer (managed by the mixer)
  22520. this._propertyBindings = new Array( nTracks );
  22521. this._cacheIndex = null; // for the memory manager
  22522. this._byClipCacheIndex = null; // for the memory manager
  22523. this._timeScaleInterpolant = null;
  22524. this._weightInterpolant = null;
  22525. this.loop = LoopRepeat;
  22526. this._loopCount = -1;
  22527. // global mixer time when the action is to be started
  22528. // it's set back to 'null' upon start of the action
  22529. this._startTime = null;
  22530. // scaled local time of the action
  22531. // gets clamped or wrapped to 0..clip.duration according to loop
  22532. this.time = 0;
  22533. this.timeScale = 1;
  22534. this._effectiveTimeScale = 1;
  22535. this.weight = 1;
  22536. this._effectiveWeight = 1;
  22537. this.repetitions = Infinity; // no. of repetitions when looping
  22538. this.paused = false; // false -> zero effective time scale
  22539. this.enabled = true; // true -> zero effective weight
  22540. this.clampWhenFinished = false; // keep feeding the last frame?
  22541. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22542. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22543. }
  22544. AnimationAction.prototype = {
  22545. constructor: AnimationAction,
  22546. // State & Scheduling
  22547. play: function() {
  22548. this._mixer._activateAction( this );
  22549. return this;
  22550. },
  22551. stop: function() {
  22552. this._mixer._deactivateAction( this );
  22553. return this.reset();
  22554. },
  22555. reset: function() {
  22556. this.paused = false;
  22557. this.enabled = true;
  22558. this.time = 0; // restart clip
  22559. this._loopCount = -1; // forget previous loops
  22560. this._startTime = null; // forget scheduling
  22561. return this.stopFading().stopWarping();
  22562. },
  22563. isRunning: function() {
  22564. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22565. this._startTime === null && this._mixer._isActiveAction( this );
  22566. },
  22567. // return true when play has been called
  22568. isScheduled: function() {
  22569. return this._mixer._isActiveAction( this );
  22570. },
  22571. startAt: function( time ) {
  22572. this._startTime = time;
  22573. return this;
  22574. },
  22575. setLoop: function( mode, repetitions ) {
  22576. this.loop = mode;
  22577. this.repetitions = repetitions;
  22578. return this;
  22579. },
  22580. // Weight
  22581. // set the weight stopping any scheduled fading
  22582. // although .enabled = false yields an effective weight of zero, this
  22583. // method does *not* change .enabled, because it would be confusing
  22584. setEffectiveWeight: function( weight ) {
  22585. this.weight = weight;
  22586. // note: same logic as when updated at runtime
  22587. this._effectiveWeight = this.enabled ? weight : 0;
  22588. return this.stopFading();
  22589. },
  22590. // return the weight considering fading and .enabled
  22591. getEffectiveWeight: function() {
  22592. return this._effectiveWeight;
  22593. },
  22594. fadeIn: function( duration ) {
  22595. return this._scheduleFading( duration, 0, 1 );
  22596. },
  22597. fadeOut: function( duration ) {
  22598. return this._scheduleFading( duration, 1, 0 );
  22599. },
  22600. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22601. fadeOutAction.fadeOut( duration );
  22602. this.fadeIn( duration );
  22603. if( warp ) {
  22604. var fadeInDuration = this._clip.duration,
  22605. fadeOutDuration = fadeOutAction._clip.duration,
  22606. startEndRatio = fadeOutDuration / fadeInDuration,
  22607. endStartRatio = fadeInDuration / fadeOutDuration;
  22608. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22609. this.warp( endStartRatio, 1.0, duration );
  22610. }
  22611. return this;
  22612. },
  22613. crossFadeTo: function( fadeInAction, duration, warp ) {
  22614. return fadeInAction.crossFadeFrom( this, duration, warp );
  22615. },
  22616. stopFading: function() {
  22617. var weightInterpolant = this._weightInterpolant;
  22618. if ( weightInterpolant !== null ) {
  22619. this._weightInterpolant = null;
  22620. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22621. }
  22622. return this;
  22623. },
  22624. // Time Scale Control
  22625. // set the weight stopping any scheduled warping
  22626. // although .paused = true yields an effective time scale of zero, this
  22627. // method does *not* change .paused, because it would be confusing
  22628. setEffectiveTimeScale: function( timeScale ) {
  22629. this.timeScale = timeScale;
  22630. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22631. return this.stopWarping();
  22632. },
  22633. // return the time scale considering warping and .paused
  22634. getEffectiveTimeScale: function() {
  22635. return this._effectiveTimeScale;
  22636. },
  22637. setDuration: function( duration ) {
  22638. this.timeScale = this._clip.duration / duration;
  22639. return this.stopWarping();
  22640. },
  22641. syncWith: function( action ) {
  22642. this.time = action.time;
  22643. this.timeScale = action.timeScale;
  22644. return this.stopWarping();
  22645. },
  22646. halt: function( duration ) {
  22647. return this.warp( this._effectiveTimeScale, 0, duration );
  22648. },
  22649. warp: function( startTimeScale, endTimeScale, duration ) {
  22650. var mixer = this._mixer, now = mixer.time,
  22651. interpolant = this._timeScaleInterpolant,
  22652. timeScale = this.timeScale;
  22653. if ( interpolant === null ) {
  22654. interpolant = mixer._lendControlInterpolant();
  22655. this._timeScaleInterpolant = interpolant;
  22656. }
  22657. var times = interpolant.parameterPositions,
  22658. values = interpolant.sampleValues;
  22659. times[ 0 ] = now;
  22660. times[ 1 ] = now + duration;
  22661. values[ 0 ] = startTimeScale / timeScale;
  22662. values[ 1 ] = endTimeScale / timeScale;
  22663. return this;
  22664. },
  22665. stopWarping: function() {
  22666. var timeScaleInterpolant = this._timeScaleInterpolant;
  22667. if ( timeScaleInterpolant !== null ) {
  22668. this._timeScaleInterpolant = null;
  22669. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22670. }
  22671. return this;
  22672. },
  22673. // Object Accessors
  22674. getMixer: function() {
  22675. return this._mixer;
  22676. },
  22677. getClip: function() {
  22678. return this._clip;
  22679. },
  22680. getRoot: function() {
  22681. return this._localRoot || this._mixer._root;
  22682. },
  22683. // Interna
  22684. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22685. // called by the mixer
  22686. var startTime = this._startTime;
  22687. if ( startTime !== null ) {
  22688. // check for scheduled start of action
  22689. var timeRunning = ( time - startTime ) * timeDirection;
  22690. if ( timeRunning < 0 || timeDirection === 0 ) {
  22691. return; // yet to come / don't decide when delta = 0
  22692. }
  22693. // start
  22694. this._startTime = null; // unschedule
  22695. deltaTime = timeDirection * timeRunning;
  22696. }
  22697. // apply time scale and advance time
  22698. deltaTime *= this._updateTimeScale( time );
  22699. var clipTime = this._updateTime( deltaTime );
  22700. // note: _updateTime may disable the action resulting in
  22701. // an effective weight of 0
  22702. var weight = this._updateWeight( time );
  22703. if ( weight > 0 ) {
  22704. var interpolants = this._interpolants;
  22705. var propertyMixers = this._propertyBindings;
  22706. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22707. interpolants[ j ].evaluate( clipTime );
  22708. propertyMixers[ j ].accumulate( accuIndex, weight );
  22709. }
  22710. }
  22711. },
  22712. _updateWeight: function( time ) {
  22713. var weight = 0;
  22714. if ( this.enabled ) {
  22715. weight = this.weight;
  22716. var interpolant = this._weightInterpolant;
  22717. if ( interpolant !== null ) {
  22718. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22719. weight *= interpolantValue;
  22720. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22721. this.stopFading();
  22722. if ( interpolantValue === 0 ) {
  22723. // faded out, disable
  22724. this.enabled = false;
  22725. }
  22726. }
  22727. }
  22728. }
  22729. this._effectiveWeight = weight;
  22730. return weight;
  22731. },
  22732. _updateTimeScale: function( time ) {
  22733. var timeScale = 0;
  22734. if ( ! this.paused ) {
  22735. timeScale = this.timeScale;
  22736. var interpolant = this._timeScaleInterpolant;
  22737. if ( interpolant !== null ) {
  22738. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22739. timeScale *= interpolantValue;
  22740. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22741. this.stopWarping();
  22742. if ( timeScale === 0 ) {
  22743. // motion has halted, pause
  22744. this.paused = true;
  22745. } else {
  22746. // warp done - apply final time scale
  22747. this.timeScale = timeScale;
  22748. }
  22749. }
  22750. }
  22751. }
  22752. this._effectiveTimeScale = timeScale;
  22753. return timeScale;
  22754. },
  22755. _updateTime: function( deltaTime ) {
  22756. var time = this.time + deltaTime;
  22757. if ( deltaTime === 0 ) return time;
  22758. var duration = this._clip.duration,
  22759. loop = this.loop,
  22760. loopCount = this._loopCount;
  22761. if ( loop === LoopOnce ) {
  22762. if ( loopCount === -1 ) {
  22763. // just started
  22764. this._loopCount = 0;
  22765. this._setEndings( true, true, false );
  22766. }
  22767. handle_stop: {
  22768. if ( time >= duration ) {
  22769. time = duration;
  22770. } else if ( time < 0 ) {
  22771. time = 0;
  22772. } else break handle_stop;
  22773. if ( this.clampWhenFinished ) this.paused = true;
  22774. else this.enabled = false;
  22775. this._mixer.dispatchEvent( {
  22776. type: 'finished', action: this,
  22777. direction: deltaTime < 0 ? -1 : 1
  22778. } );
  22779. }
  22780. } else { // repetitive Repeat or PingPong
  22781. var pingPong = ( loop === LoopPingPong );
  22782. if ( loopCount === -1 ) {
  22783. // just started
  22784. if ( deltaTime >= 0 ) {
  22785. loopCount = 0;
  22786. this._setEndings(
  22787. true, this.repetitions === 0, pingPong );
  22788. } else {
  22789. // when looping in reverse direction, the initial
  22790. // transition through zero counts as a repetition,
  22791. // so leave loopCount at -1
  22792. this._setEndings(
  22793. this.repetitions === 0, true, pingPong );
  22794. }
  22795. }
  22796. if ( time >= duration || time < 0 ) {
  22797. // wrap around
  22798. var loopDelta = Math.floor( time / duration ); // signed
  22799. time -= duration * loopDelta;
  22800. loopCount += Math.abs( loopDelta );
  22801. var pending = this.repetitions - loopCount;
  22802. if ( pending < 0 ) {
  22803. // have to stop (switch state, clamp time, fire event)
  22804. if ( this.clampWhenFinished ) this.paused = true;
  22805. else this.enabled = false;
  22806. time = deltaTime > 0 ? duration : 0;
  22807. this._mixer.dispatchEvent( {
  22808. type: 'finished', action: this,
  22809. direction: deltaTime > 0 ? 1 : -1
  22810. } );
  22811. } else {
  22812. // keep running
  22813. if ( pending === 0 ) {
  22814. // entering the last round
  22815. var atStart = deltaTime < 0;
  22816. this._setEndings( atStart, ! atStart, pingPong );
  22817. } else {
  22818. this._setEndings( false, false, pingPong );
  22819. }
  22820. this._loopCount = loopCount;
  22821. this._mixer.dispatchEvent( {
  22822. type: 'loop', action: this, loopDelta: loopDelta
  22823. } );
  22824. }
  22825. }
  22826. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22827. // invert time for the "pong round"
  22828. this.time = time;
  22829. return duration - time;
  22830. }
  22831. }
  22832. this.time = time;
  22833. return time;
  22834. },
  22835. _setEndings: function( atStart, atEnd, pingPong ) {
  22836. var settings = this._interpolantSettings;
  22837. if ( pingPong ) {
  22838. settings.endingStart = ZeroSlopeEnding;
  22839. settings.endingEnd = ZeroSlopeEnding;
  22840. } else {
  22841. // assuming for LoopOnce atStart == atEnd == true
  22842. if ( atStart ) {
  22843. settings.endingStart = this.zeroSlopeAtStart ?
  22844. ZeroSlopeEnding : ZeroCurvatureEnding;
  22845. } else {
  22846. settings.endingStart = WrapAroundEnding;
  22847. }
  22848. if ( atEnd ) {
  22849. settings.endingEnd = this.zeroSlopeAtEnd ?
  22850. ZeroSlopeEnding : ZeroCurvatureEnding;
  22851. } else {
  22852. settings.endingEnd = WrapAroundEnding;
  22853. }
  22854. }
  22855. },
  22856. _scheduleFading: function( duration, weightNow, weightThen ) {
  22857. var mixer = this._mixer, now = mixer.time,
  22858. interpolant = this._weightInterpolant;
  22859. if ( interpolant === null ) {
  22860. interpolant = mixer._lendControlInterpolant();
  22861. this._weightInterpolant = interpolant;
  22862. }
  22863. var times = interpolant.parameterPositions,
  22864. values = interpolant.sampleValues;
  22865. times[ 0 ] = now; values[ 0 ] = weightNow;
  22866. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  22867. return this;
  22868. }
  22869. };
  22870. /**
  22871. *
  22872. * Player for AnimationClips.
  22873. *
  22874. *
  22875. * @author Ben Houston / http://clara.io/
  22876. * @author David Sarno / http://lighthaus.us/
  22877. * @author tschw
  22878. */
  22879. function AnimationMixer( root ) {
  22880. this._root = root;
  22881. this._initMemoryManager();
  22882. this._accuIndex = 0;
  22883. this.time = 0;
  22884. this.timeScale = 1.0;
  22885. }
  22886. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  22887. // return an action for a clip optionally using a custom root target
  22888. // object (this method allocates a lot of dynamic memory in case a
  22889. // previously unknown clip/root combination is specified)
  22890. clipAction: function( clip, optionalRoot ) {
  22891. var root = optionalRoot || this._root,
  22892. rootUuid = root.uuid,
  22893. clipObject = typeof clip === 'string' ?
  22894. AnimationClip.findByName( root, clip ) : clip,
  22895. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  22896. actionsForClip = this._actionsByClip[ clipUuid ],
  22897. prototypeAction = null;
  22898. if ( actionsForClip !== undefined ) {
  22899. var existingAction =
  22900. actionsForClip.actionByRoot[ rootUuid ];
  22901. if ( existingAction !== undefined ) {
  22902. return existingAction;
  22903. }
  22904. // we know the clip, so we don't have to parse all
  22905. // the bindings again but can just copy
  22906. prototypeAction = actionsForClip.knownActions[ 0 ];
  22907. // also, take the clip from the prototype action
  22908. if ( clipObject === null )
  22909. clipObject = prototypeAction._clip;
  22910. }
  22911. // clip must be known when specified via string
  22912. if ( clipObject === null ) return null;
  22913. // allocate all resources required to run it
  22914. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  22915. this._bindAction( newAction, prototypeAction );
  22916. // and make the action known to the memory manager
  22917. this._addInactiveAction( newAction, clipUuid, rootUuid );
  22918. return newAction;
  22919. },
  22920. // get an existing action
  22921. existingAction: function( clip, optionalRoot ) {
  22922. var root = optionalRoot || this._root,
  22923. rootUuid = root.uuid,
  22924. clipObject = typeof clip === 'string' ?
  22925. AnimationClip.findByName( root, clip ) : clip,
  22926. clipUuid = clipObject ? clipObject.uuid : clip,
  22927. actionsForClip = this._actionsByClip[ clipUuid ];
  22928. if ( actionsForClip !== undefined ) {
  22929. return actionsForClip.actionByRoot[ rootUuid ] || null;
  22930. }
  22931. return null;
  22932. },
  22933. // deactivates all previously scheduled actions
  22934. stopAllAction: function() {
  22935. var actions = this._actions,
  22936. nActions = this._nActiveActions,
  22937. bindings = this._bindings,
  22938. nBindings = this._nActiveBindings;
  22939. this._nActiveActions = 0;
  22940. this._nActiveBindings = 0;
  22941. for ( var i = 0; i !== nActions; ++ i ) {
  22942. actions[ i ].reset();
  22943. }
  22944. for ( var i = 0; i !== nBindings; ++ i ) {
  22945. bindings[ i ].useCount = 0;
  22946. }
  22947. return this;
  22948. },
  22949. // advance the time and update apply the animation
  22950. update: function( deltaTime ) {
  22951. deltaTime *= this.timeScale;
  22952. var actions = this._actions,
  22953. nActions = this._nActiveActions,
  22954. time = this.time += deltaTime,
  22955. timeDirection = Math.sign( deltaTime ),
  22956. accuIndex = this._accuIndex ^= 1;
  22957. // run active actions
  22958. for ( var i = 0; i !== nActions; ++ i ) {
  22959. var action = actions[ i ];
  22960. if ( action.enabled ) {
  22961. action._update( time, deltaTime, timeDirection, accuIndex );
  22962. }
  22963. }
  22964. // update scene graph
  22965. var bindings = this._bindings,
  22966. nBindings = this._nActiveBindings;
  22967. for ( var i = 0; i !== nBindings; ++ i ) {
  22968. bindings[ i ].apply( accuIndex );
  22969. }
  22970. return this;
  22971. },
  22972. // return this mixer's root target object
  22973. getRoot: function() {
  22974. return this._root;
  22975. },
  22976. // free all resources specific to a particular clip
  22977. uncacheClip: function( clip ) {
  22978. var actions = this._actions,
  22979. clipUuid = clip.uuid,
  22980. actionsByClip = this._actionsByClip,
  22981. actionsForClip = actionsByClip[ clipUuid ];
  22982. if ( actionsForClip !== undefined ) {
  22983. // note: just calling _removeInactiveAction would mess up the
  22984. // iteration state and also require updating the state we can
  22985. // just throw away
  22986. var actionsToRemove = actionsForClip.knownActions;
  22987. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22988. var action = actionsToRemove[ i ];
  22989. this._deactivateAction( action );
  22990. var cacheIndex = action._cacheIndex,
  22991. lastInactiveAction = actions[ actions.length - 1 ];
  22992. action._cacheIndex = null;
  22993. action._byClipCacheIndex = null;
  22994. lastInactiveAction._cacheIndex = cacheIndex;
  22995. actions[ cacheIndex ] = lastInactiveAction;
  22996. actions.pop();
  22997. this._removeInactiveBindingsForAction( action );
  22998. }
  22999. delete actionsByClip[ clipUuid ];
  23000. }
  23001. },
  23002. // free all resources specific to a particular root target object
  23003. uncacheRoot: function( root ) {
  23004. var rootUuid = root.uuid,
  23005. actionsByClip = this._actionsByClip;
  23006. for ( var clipUuid in actionsByClip ) {
  23007. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23008. action = actionByRoot[ rootUuid ];
  23009. if ( action !== undefined ) {
  23010. this._deactivateAction( action );
  23011. this._removeInactiveAction( action );
  23012. }
  23013. }
  23014. var bindingsByRoot = this._bindingsByRootAndName,
  23015. bindingByName = bindingsByRoot[ rootUuid ];
  23016. if ( bindingByName !== undefined ) {
  23017. for ( var trackName in bindingByName ) {
  23018. var binding = bindingByName[ trackName ];
  23019. binding.restoreOriginalState();
  23020. this._removeInactiveBinding( binding );
  23021. }
  23022. }
  23023. },
  23024. // remove a targeted clip from the cache
  23025. uncacheAction: function( clip, optionalRoot ) {
  23026. var action = this.existingAction( clip, optionalRoot );
  23027. if ( action !== null ) {
  23028. this._deactivateAction( action );
  23029. this._removeInactiveAction( action );
  23030. }
  23031. }
  23032. } );
  23033. // Implementation details:
  23034. Object.assign( AnimationMixer.prototype, {
  23035. _bindAction: function( action, prototypeAction ) {
  23036. var root = action._localRoot || this._root,
  23037. tracks = action._clip.tracks,
  23038. nTracks = tracks.length,
  23039. bindings = action._propertyBindings,
  23040. interpolants = action._interpolants,
  23041. rootUuid = root.uuid,
  23042. bindingsByRoot = this._bindingsByRootAndName,
  23043. bindingsByName = bindingsByRoot[ rootUuid ];
  23044. if ( bindingsByName === undefined ) {
  23045. bindingsByName = {};
  23046. bindingsByRoot[ rootUuid ] = bindingsByName;
  23047. }
  23048. for ( var i = 0; i !== nTracks; ++ i ) {
  23049. var track = tracks[ i ],
  23050. trackName = track.name,
  23051. binding = bindingsByName[ trackName ];
  23052. if ( binding !== undefined ) {
  23053. bindings[ i ] = binding;
  23054. } else {
  23055. binding = bindings[ i ];
  23056. if ( binding !== undefined ) {
  23057. // existing binding, make sure the cache knows
  23058. if ( binding._cacheIndex === null ) {
  23059. ++ binding.referenceCount;
  23060. this._addInactiveBinding( binding, rootUuid, trackName );
  23061. }
  23062. continue;
  23063. }
  23064. var path = prototypeAction && prototypeAction.
  23065. _propertyBindings[ i ].binding.parsedPath;
  23066. binding = new PropertyMixer(
  23067. PropertyBinding.create( root, trackName, path ),
  23068. track.ValueTypeName, track.getValueSize() );
  23069. ++ binding.referenceCount;
  23070. this._addInactiveBinding( binding, rootUuid, trackName );
  23071. bindings[ i ] = binding;
  23072. }
  23073. interpolants[ i ].resultBuffer = binding.buffer;
  23074. }
  23075. },
  23076. _activateAction: function( action ) {
  23077. if ( ! this._isActiveAction( action ) ) {
  23078. if ( action._cacheIndex === null ) {
  23079. // this action has been forgotten by the cache, but the user
  23080. // appears to be still using it -> rebind
  23081. var rootUuid = ( action._localRoot || this._root ).uuid,
  23082. clipUuid = action._clip.uuid,
  23083. actionsForClip = this._actionsByClip[ clipUuid ];
  23084. this._bindAction( action,
  23085. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23086. this._addInactiveAction( action, clipUuid, rootUuid );
  23087. }
  23088. var bindings = action._propertyBindings;
  23089. // increment reference counts / sort out state
  23090. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23091. var binding = bindings[ i ];
  23092. if ( binding.useCount ++ === 0 ) {
  23093. this._lendBinding( binding );
  23094. binding.saveOriginalState();
  23095. }
  23096. }
  23097. this._lendAction( action );
  23098. }
  23099. },
  23100. _deactivateAction: function( action ) {
  23101. if ( this._isActiveAction( action ) ) {
  23102. var bindings = action._propertyBindings;
  23103. // decrement reference counts / sort out state
  23104. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23105. var binding = bindings[ i ];
  23106. if ( -- binding.useCount === 0 ) {
  23107. binding.restoreOriginalState();
  23108. this._takeBackBinding( binding );
  23109. }
  23110. }
  23111. this._takeBackAction( action );
  23112. }
  23113. },
  23114. // Memory manager
  23115. _initMemoryManager: function() {
  23116. this._actions = []; // 'nActiveActions' followed by inactive ones
  23117. this._nActiveActions = 0;
  23118. this._actionsByClip = {};
  23119. // inside:
  23120. // {
  23121. // knownActions: Array< AnimationAction > - used as prototypes
  23122. // actionByRoot: AnimationAction - lookup
  23123. // }
  23124. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23125. this._nActiveBindings = 0;
  23126. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23127. this._controlInterpolants = []; // same game as above
  23128. this._nActiveControlInterpolants = 0;
  23129. var scope = this;
  23130. this.stats = {
  23131. actions: {
  23132. get total() { return scope._actions.length; },
  23133. get inUse() { return scope._nActiveActions; }
  23134. },
  23135. bindings: {
  23136. get total() { return scope._bindings.length; },
  23137. get inUse() { return scope._nActiveBindings; }
  23138. },
  23139. controlInterpolants: {
  23140. get total() { return scope._controlInterpolants.length; },
  23141. get inUse() { return scope._nActiveControlInterpolants; }
  23142. }
  23143. };
  23144. },
  23145. // Memory management for AnimationAction objects
  23146. _isActiveAction: function( action ) {
  23147. var index = action._cacheIndex;
  23148. return index !== null && index < this._nActiveActions;
  23149. },
  23150. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  23151. var actions = this._actions,
  23152. actionsByClip = this._actionsByClip,
  23153. actionsForClip = actionsByClip[ clipUuid ];
  23154. if ( actionsForClip === undefined ) {
  23155. actionsForClip = {
  23156. knownActions: [ action ],
  23157. actionByRoot: {}
  23158. };
  23159. action._byClipCacheIndex = 0;
  23160. actionsByClip[ clipUuid ] = actionsForClip;
  23161. } else {
  23162. var knownActions = actionsForClip.knownActions;
  23163. action._byClipCacheIndex = knownActions.length;
  23164. knownActions.push( action );
  23165. }
  23166. action._cacheIndex = actions.length;
  23167. actions.push( action );
  23168. actionsForClip.actionByRoot[ rootUuid ] = action;
  23169. },
  23170. _removeInactiveAction: function( action ) {
  23171. var actions = this._actions,
  23172. lastInactiveAction = actions[ actions.length - 1 ],
  23173. cacheIndex = action._cacheIndex;
  23174. lastInactiveAction._cacheIndex = cacheIndex;
  23175. actions[ cacheIndex ] = lastInactiveAction;
  23176. actions.pop();
  23177. action._cacheIndex = null;
  23178. var clipUuid = action._clip.uuid,
  23179. actionsByClip = this._actionsByClip,
  23180. actionsForClip = actionsByClip[ clipUuid ],
  23181. knownActionsForClip = actionsForClip.knownActions,
  23182. lastKnownAction =
  23183. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23184. byClipCacheIndex = action._byClipCacheIndex;
  23185. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23186. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23187. knownActionsForClip.pop();
  23188. action._byClipCacheIndex = null;
  23189. var actionByRoot = actionsForClip.actionByRoot,
  23190. rootUuid = ( actions._localRoot || this._root ).uuid;
  23191. delete actionByRoot[ rootUuid ];
  23192. if ( knownActionsForClip.length === 0 ) {
  23193. delete actionsByClip[ clipUuid ];
  23194. }
  23195. this._removeInactiveBindingsForAction( action );
  23196. },
  23197. _removeInactiveBindingsForAction: function( action ) {
  23198. var bindings = action._propertyBindings;
  23199. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23200. var binding = bindings[ i ];
  23201. if ( -- binding.referenceCount === 0 ) {
  23202. this._removeInactiveBinding( binding );
  23203. }
  23204. }
  23205. },
  23206. _lendAction: function( action ) {
  23207. // [ active actions | inactive actions ]
  23208. // [ active actions >| inactive actions ]
  23209. // s a
  23210. // <-swap->
  23211. // a s
  23212. var actions = this._actions,
  23213. prevIndex = action._cacheIndex,
  23214. lastActiveIndex = this._nActiveActions ++,
  23215. firstInactiveAction = actions[ lastActiveIndex ];
  23216. action._cacheIndex = lastActiveIndex;
  23217. actions[ lastActiveIndex ] = action;
  23218. firstInactiveAction._cacheIndex = prevIndex;
  23219. actions[ prevIndex ] = firstInactiveAction;
  23220. },
  23221. _takeBackAction: function( action ) {
  23222. // [ active actions | inactive actions ]
  23223. // [ active actions |< inactive actions ]
  23224. // a s
  23225. // <-swap->
  23226. // s a
  23227. var actions = this._actions,
  23228. prevIndex = action._cacheIndex,
  23229. firstInactiveIndex = -- this._nActiveActions,
  23230. lastActiveAction = actions[ firstInactiveIndex ];
  23231. action._cacheIndex = firstInactiveIndex;
  23232. actions[ firstInactiveIndex ] = action;
  23233. lastActiveAction._cacheIndex = prevIndex;
  23234. actions[ prevIndex ] = lastActiveAction;
  23235. },
  23236. // Memory management for PropertyMixer objects
  23237. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  23238. var bindingsByRoot = this._bindingsByRootAndName,
  23239. bindingByName = bindingsByRoot[ rootUuid ],
  23240. bindings = this._bindings;
  23241. if ( bindingByName === undefined ) {
  23242. bindingByName = {};
  23243. bindingsByRoot[ rootUuid ] = bindingByName;
  23244. }
  23245. bindingByName[ trackName ] = binding;
  23246. binding._cacheIndex = bindings.length;
  23247. bindings.push( binding );
  23248. },
  23249. _removeInactiveBinding: function( binding ) {
  23250. var bindings = this._bindings,
  23251. propBinding = binding.binding,
  23252. rootUuid = propBinding.rootNode.uuid,
  23253. trackName = propBinding.path,
  23254. bindingsByRoot = this._bindingsByRootAndName,
  23255. bindingByName = bindingsByRoot[ rootUuid ],
  23256. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23257. cacheIndex = binding._cacheIndex;
  23258. lastInactiveBinding._cacheIndex = cacheIndex;
  23259. bindings[ cacheIndex ] = lastInactiveBinding;
  23260. bindings.pop();
  23261. delete bindingByName[ trackName ];
  23262. remove_empty_map: {
  23263. for ( var _ in bindingByName ) break remove_empty_map;
  23264. delete bindingsByRoot[ rootUuid ];
  23265. }
  23266. },
  23267. _lendBinding: function( binding ) {
  23268. var bindings = this._bindings,
  23269. prevIndex = binding._cacheIndex,
  23270. lastActiveIndex = this._nActiveBindings ++,
  23271. firstInactiveBinding = bindings[ lastActiveIndex ];
  23272. binding._cacheIndex = lastActiveIndex;
  23273. bindings[ lastActiveIndex ] = binding;
  23274. firstInactiveBinding._cacheIndex = prevIndex;
  23275. bindings[ prevIndex ] = firstInactiveBinding;
  23276. },
  23277. _takeBackBinding: function( binding ) {
  23278. var bindings = this._bindings,
  23279. prevIndex = binding._cacheIndex,
  23280. firstInactiveIndex = -- this._nActiveBindings,
  23281. lastActiveBinding = bindings[ firstInactiveIndex ];
  23282. binding._cacheIndex = firstInactiveIndex;
  23283. bindings[ firstInactiveIndex ] = binding;
  23284. lastActiveBinding._cacheIndex = prevIndex;
  23285. bindings[ prevIndex ] = lastActiveBinding;
  23286. },
  23287. // Memory management of Interpolants for weight and time scale
  23288. _lendControlInterpolant: function() {
  23289. var interpolants = this._controlInterpolants,
  23290. lastActiveIndex = this._nActiveControlInterpolants ++,
  23291. interpolant = interpolants[ lastActiveIndex ];
  23292. if ( interpolant === undefined ) {
  23293. interpolant = new LinearInterpolant(
  23294. new Float32Array( 2 ), new Float32Array( 2 ),
  23295. 1, this._controlInterpolantsResultBuffer );
  23296. interpolant.__cacheIndex = lastActiveIndex;
  23297. interpolants[ lastActiveIndex ] = interpolant;
  23298. }
  23299. return interpolant;
  23300. },
  23301. _takeBackControlInterpolant: function( interpolant ) {
  23302. var interpolants = this._controlInterpolants,
  23303. prevIndex = interpolant.__cacheIndex,
  23304. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23305. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23306. interpolant.__cacheIndex = firstInactiveIndex;
  23307. interpolants[ firstInactiveIndex ] = interpolant;
  23308. lastActiveInterpolant.__cacheIndex = prevIndex;
  23309. interpolants[ prevIndex ] = lastActiveInterpolant;
  23310. },
  23311. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  23312. } );
  23313. /**
  23314. * @author mrdoob / http://mrdoob.com/
  23315. */
  23316. function Uniform( value ) {
  23317. if ( typeof value === 'string' ) {
  23318. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23319. value = arguments[ 1 ];
  23320. }
  23321. this.value = value;
  23322. }
  23323. Uniform.prototype.clone = function () {
  23324. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23325. };
  23326. /**
  23327. * @author benaadams / https://twitter.com/ben_a_adams
  23328. */
  23329. function InstancedBufferGeometry() {
  23330. BufferGeometry.call( this );
  23331. this.type = 'InstancedBufferGeometry';
  23332. this.maxInstancedCount = undefined;
  23333. }
  23334. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23335. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  23336. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23337. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  23338. this.groups.push( {
  23339. start: start,
  23340. count: count,
  23341. materialIndex: materialIndex
  23342. } );
  23343. };
  23344. InstancedBufferGeometry.prototype.copy = function ( source ) {
  23345. var index = source.index;
  23346. if ( index !== null ) {
  23347. this.setIndex( index.clone() );
  23348. }
  23349. var attributes = source.attributes;
  23350. for ( var name in attributes ) {
  23351. var attribute = attributes[ name ];
  23352. this.addAttribute( name, attribute.clone() );
  23353. }
  23354. var groups = source.groups;
  23355. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23356. var group = groups[ i ];
  23357. this.addGroup( group.start, group.count, group.materialIndex );
  23358. }
  23359. return this;
  23360. };
  23361. /**
  23362. * @author benaadams / https://twitter.com/ben_a_adams
  23363. */
  23364. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23365. this.uuid = _Math.generateUUID();
  23366. this.data = interleavedBuffer;
  23367. this.itemSize = itemSize;
  23368. this.offset = offset;
  23369. this.normalized = normalized === true;
  23370. }
  23371. InterleavedBufferAttribute.prototype = {
  23372. constructor: InterleavedBufferAttribute,
  23373. isInterleavedBufferAttribute: true,
  23374. get count() {
  23375. return this.data.count;
  23376. },
  23377. get array() {
  23378. return this.data.array;
  23379. },
  23380. setX: function ( index, x ) {
  23381. this.data.array[ index * this.data.stride + this.offset ] = x;
  23382. return this;
  23383. },
  23384. setY: function ( index, y ) {
  23385. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23386. return this;
  23387. },
  23388. setZ: function ( index, z ) {
  23389. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23390. return this;
  23391. },
  23392. setW: function ( index, w ) {
  23393. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23394. return this;
  23395. },
  23396. getX: function ( index ) {
  23397. return this.data.array[ index * this.data.stride + this.offset ];
  23398. },
  23399. getY: function ( index ) {
  23400. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23401. },
  23402. getZ: function ( index ) {
  23403. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23404. },
  23405. getW: function ( index ) {
  23406. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23407. },
  23408. setXY: function ( index, x, y ) {
  23409. index = index * this.data.stride + this.offset;
  23410. this.data.array[ index + 0 ] = x;
  23411. this.data.array[ index + 1 ] = y;
  23412. return this;
  23413. },
  23414. setXYZ: function ( index, x, y, z ) {
  23415. index = index * this.data.stride + this.offset;
  23416. this.data.array[ index + 0 ] = x;
  23417. this.data.array[ index + 1 ] = y;
  23418. this.data.array[ index + 2 ] = z;
  23419. return this;
  23420. },
  23421. setXYZW: function ( index, x, y, z, w ) {
  23422. index = index * this.data.stride + this.offset;
  23423. this.data.array[ index + 0 ] = x;
  23424. this.data.array[ index + 1 ] = y;
  23425. this.data.array[ index + 2 ] = z;
  23426. this.data.array[ index + 3 ] = w;
  23427. return this;
  23428. }
  23429. };
  23430. /**
  23431. * @author benaadams / https://twitter.com/ben_a_adams
  23432. */
  23433. function InterleavedBuffer( array, stride ) {
  23434. this.uuid = _Math.generateUUID();
  23435. this.array = array;
  23436. this.stride = stride;
  23437. this.count = array !== undefined ? array.length / stride : 0;
  23438. this.dynamic = false;
  23439. this.updateRange = { offset: 0, count: - 1 };
  23440. this.onUploadCallback = function () {};
  23441. this.version = 0;
  23442. }
  23443. InterleavedBuffer.prototype = {
  23444. constructor: InterleavedBuffer,
  23445. isInterleavedBuffer: true,
  23446. set needsUpdate( value ) {
  23447. if ( value === true ) this.version ++;
  23448. },
  23449. setArray: function ( array ) {
  23450. if ( Array.isArray( array ) ) {
  23451. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23452. }
  23453. this.count = array !== undefined ? array.length / this.stride : 0;
  23454. this.array = array;
  23455. },
  23456. setDynamic: function ( value ) {
  23457. this.dynamic = value;
  23458. return this;
  23459. },
  23460. copy: function ( source ) {
  23461. this.array = new source.array.constructor( source.array );
  23462. this.count = source.count;
  23463. this.stride = source.stride;
  23464. this.dynamic = source.dynamic;
  23465. return this;
  23466. },
  23467. copyAt: function ( index1, attribute, index2 ) {
  23468. index1 *= this.stride;
  23469. index2 *= attribute.stride;
  23470. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23471. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23472. }
  23473. return this;
  23474. },
  23475. set: function ( value, offset ) {
  23476. if ( offset === undefined ) offset = 0;
  23477. this.array.set( value, offset );
  23478. return this;
  23479. },
  23480. clone: function () {
  23481. return new this.constructor().copy( this );
  23482. },
  23483. onUpload: function ( callback ) {
  23484. this.onUploadCallback = callback;
  23485. return this;
  23486. }
  23487. };
  23488. /**
  23489. * @author benaadams / https://twitter.com/ben_a_adams
  23490. */
  23491. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23492. InterleavedBuffer.call( this, array, stride );
  23493. this.meshPerAttribute = meshPerAttribute || 1;
  23494. }
  23495. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  23496. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  23497. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  23498. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  23499. InterleavedBuffer.prototype.copy.call( this, source );
  23500. this.meshPerAttribute = source.meshPerAttribute;
  23501. return this;
  23502. };
  23503. /**
  23504. * @author benaadams / https://twitter.com/ben_a_adams
  23505. */
  23506. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23507. BufferAttribute.call( this, array, itemSize );
  23508. this.meshPerAttribute = meshPerAttribute || 1;
  23509. }
  23510. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  23511. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  23512. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23513. InstancedBufferAttribute.prototype.copy = function ( source ) {
  23514. BufferAttribute.prototype.copy.call( this, source );
  23515. this.meshPerAttribute = source.meshPerAttribute;
  23516. return this;
  23517. };
  23518. /**
  23519. * @author mrdoob / http://mrdoob.com/
  23520. * @author bhouston / http://clara.io/
  23521. * @author stephomi / http://stephaneginier.com/
  23522. */
  23523. function Raycaster( origin, direction, near, far ) {
  23524. this.ray = new Ray( origin, direction );
  23525. // direction is assumed to be normalized (for accurate distance calculations)
  23526. this.near = near || 0;
  23527. this.far = far || Infinity;
  23528. this.params = {
  23529. Mesh: {},
  23530. Line: {},
  23531. LOD: {},
  23532. Points: { threshold: 1 },
  23533. Sprite: {}
  23534. };
  23535. Object.defineProperties( this.params, {
  23536. PointCloud: {
  23537. get: function () {
  23538. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23539. return this.Points;
  23540. }
  23541. }
  23542. } );
  23543. }
  23544. function ascSort( a, b ) {
  23545. return a.distance - b.distance;
  23546. }
  23547. function intersectObject( object, raycaster, intersects, recursive ) {
  23548. if ( object.visible === false ) return;
  23549. object.raycast( raycaster, intersects );
  23550. if ( recursive === true ) {
  23551. var children = object.children;
  23552. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23553. intersectObject( children[ i ], raycaster, intersects, true );
  23554. }
  23555. }
  23556. }
  23557. //
  23558. Raycaster.prototype = {
  23559. constructor: Raycaster,
  23560. linePrecision: 1,
  23561. set: function ( origin, direction ) {
  23562. // direction is assumed to be normalized (for accurate distance calculations)
  23563. this.ray.set( origin, direction );
  23564. },
  23565. setFromCamera: function ( coords, camera ) {
  23566. if ( (camera && camera.isPerspectiveCamera) ) {
  23567. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23568. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23569. } else if ( (camera && camera.isOrthographicCamera) ) {
  23570. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23571. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23572. } else {
  23573. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23574. }
  23575. },
  23576. intersectObject: function ( object, recursive ) {
  23577. var intersects = [];
  23578. intersectObject( object, this, intersects, recursive );
  23579. intersects.sort( ascSort );
  23580. return intersects;
  23581. },
  23582. intersectObjects: function ( objects, recursive ) {
  23583. var intersects = [];
  23584. if ( Array.isArray( objects ) === false ) {
  23585. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23586. return intersects;
  23587. }
  23588. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23589. intersectObject( objects[ i ], this, intersects, recursive );
  23590. }
  23591. intersects.sort( ascSort );
  23592. return intersects;
  23593. }
  23594. };
  23595. /**
  23596. * @author alteredq / http://alteredqualia.com/
  23597. */
  23598. function Clock( autoStart ) {
  23599. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23600. this.startTime = 0;
  23601. this.oldTime = 0;
  23602. this.elapsedTime = 0;
  23603. this.running = false;
  23604. }
  23605. Clock.prototype = {
  23606. constructor: Clock,
  23607. start: function () {
  23608. this.startTime = ( performance || Date ).now();
  23609. this.oldTime = this.startTime;
  23610. this.elapsedTime = 0;
  23611. this.running = true;
  23612. },
  23613. stop: function () {
  23614. this.getElapsedTime();
  23615. this.running = false;
  23616. },
  23617. getElapsedTime: function () {
  23618. this.getDelta();
  23619. return this.elapsedTime;
  23620. },
  23621. getDelta: function () {
  23622. var diff = 0;
  23623. if ( this.autoStart && ! this.running ) {
  23624. this.start();
  23625. }
  23626. if ( this.running ) {
  23627. var newTime = ( performance || Date ).now();
  23628. diff = ( newTime - this.oldTime ) / 1000;
  23629. this.oldTime = newTime;
  23630. this.elapsedTime += diff;
  23631. }
  23632. return diff;
  23633. }
  23634. };
  23635. /**
  23636. * Spline from Tween.js, slightly optimized (and trashed)
  23637. * http://sole.github.com/tween.js/examples/05_spline.html
  23638. *
  23639. * @author mrdoob / http://mrdoob.com/
  23640. * @author alteredq / http://alteredqualia.com/
  23641. */
  23642. function Spline( points ) {
  23643. this.points = points;
  23644. var c = [], v3 = { x: 0, y: 0, z: 0 },
  23645. point, intPoint, weight, w2, w3,
  23646. pa, pb, pc, pd;
  23647. this.initFromArray = function ( a ) {
  23648. this.points = [];
  23649. for ( var i = 0; i < a.length; i ++ ) {
  23650. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  23651. }
  23652. };
  23653. this.getPoint = function ( k ) {
  23654. point = ( this.points.length - 1 ) * k;
  23655. intPoint = Math.floor( point );
  23656. weight = point - intPoint;
  23657. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  23658. c[ 1 ] = intPoint;
  23659. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  23660. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  23661. pa = this.points[ c[ 0 ] ];
  23662. pb = this.points[ c[ 1 ] ];
  23663. pc = this.points[ c[ 2 ] ];
  23664. pd = this.points[ c[ 3 ] ];
  23665. w2 = weight * weight;
  23666. w3 = weight * w2;
  23667. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  23668. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  23669. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  23670. return v3;
  23671. };
  23672. this.getControlPointsArray = function () {
  23673. var i, p, l = this.points.length,
  23674. coords = [];
  23675. for ( i = 0; i < l; i ++ ) {
  23676. p = this.points[ i ];
  23677. coords[ i ] = [ p.x, p.y, p.z ];
  23678. }
  23679. return coords;
  23680. };
  23681. // approximate length by summing linear segments
  23682. this.getLength = function ( nSubDivisions ) {
  23683. var i, index, nSamples, position,
  23684. point = 0, intPoint = 0, oldIntPoint = 0,
  23685. oldPosition = new Vector3(),
  23686. tmpVec = new Vector3(),
  23687. chunkLengths = [],
  23688. totalLength = 0;
  23689. // first point has 0 length
  23690. chunkLengths[ 0 ] = 0;
  23691. if ( ! nSubDivisions ) nSubDivisions = 100;
  23692. nSamples = this.points.length * nSubDivisions;
  23693. oldPosition.copy( this.points[ 0 ] );
  23694. for ( i = 1; i < nSamples; i ++ ) {
  23695. index = i / nSamples;
  23696. position = this.getPoint( index );
  23697. tmpVec.copy( position );
  23698. totalLength += tmpVec.distanceTo( oldPosition );
  23699. oldPosition.copy( position );
  23700. point = ( this.points.length - 1 ) * index;
  23701. intPoint = Math.floor( point );
  23702. if ( intPoint !== oldIntPoint ) {
  23703. chunkLengths[ intPoint ] = totalLength;
  23704. oldIntPoint = intPoint;
  23705. }
  23706. }
  23707. // last point ends with total length
  23708. chunkLengths[ chunkLengths.length ] = totalLength;
  23709. return { chunks: chunkLengths, total: totalLength };
  23710. };
  23711. this.reparametrizeByArcLength = function ( samplingCoef ) {
  23712. var i, j,
  23713. index, indexCurrent, indexNext,
  23714. realDistance,
  23715. sampling, position,
  23716. newpoints = [],
  23717. tmpVec = new Vector3(),
  23718. sl = this.getLength();
  23719. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  23720. for ( i = 1; i < this.points.length; i ++ ) {
  23721. //tmpVec.copy( this.points[ i - 1 ] );
  23722. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  23723. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  23724. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  23725. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  23726. indexNext = i / ( this.points.length - 1 );
  23727. for ( j = 1; j < sampling - 1; j ++ ) {
  23728. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  23729. position = this.getPoint( index );
  23730. newpoints.push( tmpVec.copy( position ).clone() );
  23731. }
  23732. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  23733. }
  23734. this.points = newpoints;
  23735. };
  23736. // Catmull-Rom
  23737. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  23738. var v0 = ( p2 - p0 ) * 0.5,
  23739. v1 = ( p3 - p1 ) * 0.5;
  23740. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23741. }
  23742. }
  23743. /**
  23744. * @author bhouston / http://clara.io
  23745. * @author WestLangley / http://github.com/WestLangley
  23746. *
  23747. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23748. *
  23749. * The poles (phi) are at the positive and negative y axis.
  23750. * The equator starts at positive z.
  23751. */
  23752. function Spherical( radius, phi, theta ) {
  23753. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23754. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23755. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23756. return this;
  23757. }
  23758. Spherical.prototype = {
  23759. constructor: Spherical,
  23760. set: function ( radius, phi, theta ) {
  23761. this.radius = radius;
  23762. this.phi = phi;
  23763. this.theta = theta;
  23764. return this;
  23765. },
  23766. clone: function () {
  23767. return new this.constructor().copy( this );
  23768. },
  23769. copy: function ( other ) {
  23770. this.radius = other.radius;
  23771. this.phi = other.phi;
  23772. this.theta = other.theta;
  23773. return this;
  23774. },
  23775. // restrict phi to be betwee EPS and PI-EPS
  23776. makeSafe: function() {
  23777. var EPS = 0.000001;
  23778. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23779. return this;
  23780. },
  23781. setFromVector3: function( vec3 ) {
  23782. this.radius = vec3.length();
  23783. if ( this.radius === 0 ) {
  23784. this.theta = 0;
  23785. this.phi = 0;
  23786. } else {
  23787. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23788. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23789. }
  23790. return this;
  23791. }
  23792. };
  23793. /**
  23794. * @author Mugen87 / https://github.com/Mugen87
  23795. *
  23796. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  23797. *
  23798. */
  23799. function Cylindrical( radius, theta, y ) {
  23800. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  23801. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  23802. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  23803. return this;
  23804. }
  23805. Cylindrical.prototype = {
  23806. constructor: Cylindrical,
  23807. set: function ( radius, theta, y ) {
  23808. this.radius = radius;
  23809. this.theta = theta;
  23810. this.y = y;
  23811. return this;
  23812. },
  23813. clone: function () {
  23814. return new this.constructor().copy( this );
  23815. },
  23816. copy: function ( other ) {
  23817. this.radius = other.radius;
  23818. this.theta = other.theta;
  23819. this.y = other.y;
  23820. return this;
  23821. },
  23822. setFromVector3: function( vec3 ) {
  23823. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  23824. this.theta = Math.atan2( vec3.x, vec3.z );
  23825. this.y = vec3.y;
  23826. return this;
  23827. }
  23828. };
  23829. /**
  23830. * @author alteredq / http://alteredqualia.com/
  23831. */
  23832. function MorphBlendMesh( geometry, material ) {
  23833. Mesh.call( this, geometry, material );
  23834. this.animationsMap = {};
  23835. this.animationsList = [];
  23836. // prepare default animation
  23837. // (all frames played together in 1 second)
  23838. var numFrames = this.geometry.morphTargets.length;
  23839. var name = "__default";
  23840. var startFrame = 0;
  23841. var endFrame = numFrames - 1;
  23842. var fps = numFrames / 1;
  23843. this.createAnimation( name, startFrame, endFrame, fps );
  23844. this.setAnimationWeight( name, 1 );
  23845. }
  23846. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23847. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23848. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23849. var animation = {
  23850. start: start,
  23851. end: end,
  23852. length: end - start + 1,
  23853. fps: fps,
  23854. duration: ( end - start ) / fps,
  23855. lastFrame: 0,
  23856. currentFrame: 0,
  23857. active: false,
  23858. time: 0,
  23859. direction: 1,
  23860. weight: 1,
  23861. directionBackwards: false,
  23862. mirroredLoop: false
  23863. };
  23864. this.animationsMap[ name ] = animation;
  23865. this.animationsList.push( animation );
  23866. };
  23867. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23868. var pattern = /([a-z]+)_?(\d+)/i;
  23869. var firstAnimation, frameRanges = {};
  23870. var geometry = this.geometry;
  23871. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23872. var morph = geometry.morphTargets[ i ];
  23873. var chunks = morph.name.match( pattern );
  23874. if ( chunks && chunks.length > 1 ) {
  23875. var name = chunks[ 1 ];
  23876. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23877. var range = frameRanges[ name ];
  23878. if ( i < range.start ) range.start = i;
  23879. if ( i > range.end ) range.end = i;
  23880. if ( ! firstAnimation ) firstAnimation = name;
  23881. }
  23882. }
  23883. for ( var name in frameRanges ) {
  23884. var range = frameRanges[ name ];
  23885. this.createAnimation( name, range.start, range.end, fps );
  23886. }
  23887. this.firstAnimation = firstAnimation;
  23888. };
  23889. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23890. var animation = this.animationsMap[ name ];
  23891. if ( animation ) {
  23892. animation.direction = 1;
  23893. animation.directionBackwards = false;
  23894. }
  23895. };
  23896. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23897. var animation = this.animationsMap[ name ];
  23898. if ( animation ) {
  23899. animation.direction = - 1;
  23900. animation.directionBackwards = true;
  23901. }
  23902. };
  23903. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23904. var animation = this.animationsMap[ name ];
  23905. if ( animation ) {
  23906. animation.fps = fps;
  23907. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23908. }
  23909. };
  23910. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23911. var animation = this.animationsMap[ name ];
  23912. if ( animation ) {
  23913. animation.duration = duration;
  23914. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23915. }
  23916. };
  23917. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23918. var animation = this.animationsMap[ name ];
  23919. if ( animation ) {
  23920. animation.weight = weight;
  23921. }
  23922. };
  23923. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23924. var animation = this.animationsMap[ name ];
  23925. if ( animation ) {
  23926. animation.time = time;
  23927. }
  23928. };
  23929. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23930. var time = 0;
  23931. var animation = this.animationsMap[ name ];
  23932. if ( animation ) {
  23933. time = animation.time;
  23934. }
  23935. return time;
  23936. };
  23937. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23938. var duration = - 1;
  23939. var animation = this.animationsMap[ name ];
  23940. if ( animation ) {
  23941. duration = animation.duration;
  23942. }
  23943. return duration;
  23944. };
  23945. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23946. var animation = this.animationsMap[ name ];
  23947. if ( animation ) {
  23948. animation.time = 0;
  23949. animation.active = true;
  23950. } else {
  23951. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23952. }
  23953. };
  23954. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23955. var animation = this.animationsMap[ name ];
  23956. if ( animation ) {
  23957. animation.active = false;
  23958. }
  23959. };
  23960. MorphBlendMesh.prototype.update = function ( delta ) {
  23961. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23962. var animation = this.animationsList[ i ];
  23963. if ( ! animation.active ) continue;
  23964. var frameTime = animation.duration / animation.length;
  23965. animation.time += animation.direction * delta;
  23966. if ( animation.mirroredLoop ) {
  23967. if ( animation.time > animation.duration || animation.time < 0 ) {
  23968. animation.direction *= - 1;
  23969. if ( animation.time > animation.duration ) {
  23970. animation.time = animation.duration;
  23971. animation.directionBackwards = true;
  23972. }
  23973. if ( animation.time < 0 ) {
  23974. animation.time = 0;
  23975. animation.directionBackwards = false;
  23976. }
  23977. }
  23978. } else {
  23979. animation.time = animation.time % animation.duration;
  23980. if ( animation.time < 0 ) animation.time += animation.duration;
  23981. }
  23982. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23983. var weight = animation.weight;
  23984. if ( keyframe !== animation.currentFrame ) {
  23985. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23986. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23987. this.morphTargetInfluences[ keyframe ] = 0;
  23988. animation.lastFrame = animation.currentFrame;
  23989. animation.currentFrame = keyframe;
  23990. }
  23991. var mix = ( animation.time % frameTime ) / frameTime;
  23992. if ( animation.directionBackwards ) mix = 1 - mix;
  23993. if ( animation.currentFrame !== animation.lastFrame ) {
  23994. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23995. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23996. } else {
  23997. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23998. }
  23999. }
  24000. };
  24001. /**
  24002. * @author alteredq / http://alteredqualia.com/
  24003. */
  24004. function ImmediateRenderObject( material ) {
  24005. Object3D.call( this );
  24006. this.material = material;
  24007. this.render = function ( renderCallback ) {};
  24008. }
  24009. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24010. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24011. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24012. /**
  24013. * @author mrdoob / http://mrdoob.com/
  24014. * @author WestLangley / http://github.com/WestLangley
  24015. */
  24016. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24017. this.object = object;
  24018. this.size = ( size !== undefined ) ? size : 1;
  24019. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24020. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24021. //
  24022. var nNormals = 0;
  24023. var objGeometry = this.object.geometry;
  24024. if ( objGeometry && objGeometry.isGeometry ) {
  24025. nNormals = objGeometry.faces.length * 3;
  24026. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24027. nNormals = objGeometry.attributes.normal.count;
  24028. }
  24029. //
  24030. var geometry = new BufferGeometry();
  24031. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24032. geometry.addAttribute( 'position', positions );
  24033. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24034. //
  24035. this.matrixAutoUpdate = false;
  24036. this.update();
  24037. }
  24038. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24039. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24040. VertexNormalsHelper.prototype.update = ( function () {
  24041. var v1 = new Vector3();
  24042. var v2 = new Vector3();
  24043. var normalMatrix = new Matrix3();
  24044. return function update() {
  24045. var keys = [ 'a', 'b', 'c' ];
  24046. this.object.updateMatrixWorld( true );
  24047. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24048. var matrixWorld = this.object.matrixWorld;
  24049. var position = this.geometry.attributes.position;
  24050. //
  24051. var objGeometry = this.object.geometry;
  24052. if ( objGeometry && objGeometry.isGeometry ) {
  24053. var vertices = objGeometry.vertices;
  24054. var faces = objGeometry.faces;
  24055. var idx = 0;
  24056. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24057. var face = faces[ i ];
  24058. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24059. var vertex = vertices[ face[ keys[ j ] ] ];
  24060. var normal = face.vertexNormals[ j ];
  24061. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24062. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24063. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24064. idx = idx + 1;
  24065. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24066. idx = idx + 1;
  24067. }
  24068. }
  24069. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24070. var objPos = objGeometry.attributes.position;
  24071. var objNorm = objGeometry.attributes.normal;
  24072. var idx = 0;
  24073. // for simplicity, ignore index and drawcalls, and render every normal
  24074. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24075. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24076. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24077. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24078. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24079. idx = idx + 1;
  24080. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24081. idx = idx + 1;
  24082. }
  24083. }
  24084. position.needsUpdate = true;
  24085. return this;
  24086. };
  24087. }() );
  24088. /**
  24089. * @author alteredq / http://alteredqualia.com/
  24090. * @author mrdoob / http://mrdoob.com/
  24091. * @author WestLangley / http://github.com/WestLangley
  24092. */
  24093. function SpotLightHelper( light ) {
  24094. Object3D.call( this );
  24095. this.light = light;
  24096. this.light.updateMatrixWorld();
  24097. this.matrix = light.matrixWorld;
  24098. this.matrixAutoUpdate = false;
  24099. var geometry = new BufferGeometry();
  24100. var positions = [
  24101. 0, 0, 0, 0, 0, 1,
  24102. 0, 0, 0, 1, 0, 1,
  24103. 0, 0, 0, - 1, 0, 1,
  24104. 0, 0, 0, 0, 1, 1,
  24105. 0, 0, 0, 0, - 1, 1
  24106. ];
  24107. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24108. var p1 = ( i / l ) * Math.PI * 2;
  24109. var p2 = ( j / l ) * Math.PI * 2;
  24110. positions.push(
  24111. Math.cos( p1 ), Math.sin( p1 ), 1,
  24112. Math.cos( p2 ), Math.sin( p2 ), 1
  24113. );
  24114. }
  24115. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24116. var material = new LineBasicMaterial( { fog: false } );
  24117. this.cone = new LineSegments( geometry, material );
  24118. this.add( this.cone );
  24119. this.update();
  24120. }
  24121. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24122. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24123. SpotLightHelper.prototype.dispose = function () {
  24124. this.cone.geometry.dispose();
  24125. this.cone.material.dispose();
  24126. };
  24127. SpotLightHelper.prototype.update = function () {
  24128. var vector = new Vector3();
  24129. var vector2 = new Vector3();
  24130. return function update() {
  24131. var coneLength = this.light.distance ? this.light.distance : 1000;
  24132. var coneWidth = coneLength * Math.tan( this.light.angle );
  24133. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24134. vector.setFromMatrixPosition( this.light.matrixWorld );
  24135. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24136. this.cone.lookAt( vector2.sub( vector ) );
  24137. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24138. };
  24139. }();
  24140. /**
  24141. * @author Sean Griffin / http://twitter.com/sgrif
  24142. * @author Michael Guerrero / http://realitymeltdown.com
  24143. * @author mrdoob / http://mrdoob.com/
  24144. * @author ikerr / http://verold.com
  24145. * @author Mugen87 / https://github.com/Mugen87
  24146. */
  24147. function SkeletonHelper( object ) {
  24148. this.bones = this.getBoneList( object );
  24149. var geometry = new BufferGeometry();
  24150. var vertices = [];
  24151. var colors = [];
  24152. var color1 = new Color( 0, 0, 1 );
  24153. var color2 = new Color( 0, 1, 0 );
  24154. for ( var i = 0; i < this.bones.length; i ++ ) {
  24155. var bone = this.bones[ i ];
  24156. if ( bone.parent && bone.parent.isBone ) {
  24157. vertices.push( 0, 0, 0 );
  24158. vertices.push( 0, 0, 0 );
  24159. colors.push( color1.r, color1.g, color1.b );
  24160. colors.push( color2.r, color2.g, color2.b );
  24161. }
  24162. }
  24163. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24164. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24165. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24166. LineSegments.call( this, geometry, material );
  24167. this.root = object;
  24168. this.matrix = object.matrixWorld;
  24169. this.matrixAutoUpdate = false;
  24170. this.update();
  24171. }
  24172. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24173. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24174. SkeletonHelper.prototype.getBoneList = function( object ) {
  24175. var boneList = [];
  24176. if ( object && object.isBone ) {
  24177. boneList.push( object );
  24178. }
  24179. for ( var i = 0; i < object.children.length; i ++ ) {
  24180. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24181. }
  24182. return boneList;
  24183. };
  24184. SkeletonHelper.prototype.update = function () {
  24185. var vector = new Vector3();
  24186. var boneMatrix = new Matrix4();
  24187. var matrixWorldInv = new Matrix4();
  24188. return function update() {
  24189. var geometry = this.geometry;
  24190. var position = geometry.getAttribute( 'position' );
  24191. matrixWorldInv.getInverse( this.root.matrixWorld );
  24192. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  24193. var bone = this.bones[ i ];
  24194. if ( bone.parent && bone.parent.isBone ) {
  24195. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24196. vector.setFromMatrixPosition( boneMatrix );
  24197. position.setXYZ( j, vector.x, vector.y, vector.z );
  24198. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24199. vector.setFromMatrixPosition( boneMatrix );
  24200. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24201. j += 2;
  24202. }
  24203. }
  24204. geometry.getAttribute( 'position' ).needsUpdate = true;
  24205. };
  24206. }();
  24207. /**
  24208. * @author alteredq / http://alteredqualia.com/
  24209. * @author mrdoob / http://mrdoob.com/
  24210. */
  24211. function PointLightHelper( light, sphereSize ) {
  24212. this.light = light;
  24213. this.light.updateMatrixWorld();
  24214. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24215. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24216. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24217. Mesh.call( this, geometry, material );
  24218. this.matrix = this.light.matrixWorld;
  24219. this.matrixAutoUpdate = false;
  24220. /*
  24221. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24222. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24223. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24224. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24225. var d = light.distance;
  24226. if ( d === 0.0 ) {
  24227. this.lightDistance.visible = false;
  24228. } else {
  24229. this.lightDistance.scale.set( d, d, d );
  24230. }
  24231. this.add( this.lightDistance );
  24232. */
  24233. }
  24234. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24235. PointLightHelper.prototype.constructor = PointLightHelper;
  24236. PointLightHelper.prototype.dispose = function () {
  24237. this.geometry.dispose();
  24238. this.material.dispose();
  24239. };
  24240. PointLightHelper.prototype.update = function () {
  24241. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24242. /*
  24243. var d = this.light.distance;
  24244. if ( d === 0.0 ) {
  24245. this.lightDistance.visible = false;
  24246. } else {
  24247. this.lightDistance.visible = true;
  24248. this.lightDistance.scale.set( d, d, d );
  24249. }
  24250. */
  24251. };
  24252. /**
  24253. * @author abelnation / http://github.com/abelnation
  24254. * @author Mugen87 / http://github.com/Mugen87
  24255. */
  24256. function RectAreaLightHelper( light ) {
  24257. Object3D.call( this );
  24258. this.light = light;
  24259. this.light.updateMatrixWorld();
  24260. var materialFront = new MeshBasicMaterial( {
  24261. color: light.color,
  24262. fog: false
  24263. } );
  24264. var materialBack = new MeshBasicMaterial( {
  24265. color: light.color,
  24266. fog: false,
  24267. wireframe: true
  24268. } );
  24269. var geometry = new BufferGeometry();
  24270. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  24271. // shows the "front" of the light, e.g. where light comes from
  24272. this.add( new Mesh( geometry, materialFront ) );
  24273. // shows the "back" of the light, which does not emit light
  24274. this.add( new Mesh( geometry, materialBack ) );
  24275. this.update();
  24276. }
  24277. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24278. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24279. RectAreaLightHelper.prototype.dispose = function () {
  24280. this.children[ 0 ].geometry.dispose();
  24281. this.children[ 0 ].material.dispose();
  24282. this.children[ 1 ].geometry.dispose();
  24283. this.children[ 1 ].material.dispose();
  24284. };
  24285. RectAreaLightHelper.prototype.update = function () {
  24286. var vector1 = new Vector3();
  24287. var vector2 = new Vector3();
  24288. return function update() {
  24289. var mesh1 = this.children[ 0 ];
  24290. var mesh2 = this.children[ 1 ];
  24291. if ( this.light.target ) {
  24292. vector1.setFromMatrixPosition( this.light.matrixWorld );
  24293. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24294. var lookVec = vector2.clone().sub( vector1 );
  24295. mesh1.lookAt( lookVec );
  24296. mesh2.lookAt( lookVec );
  24297. }
  24298. // update materials
  24299. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24300. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24301. // calculate new dimensions of the helper
  24302. var hx = this.light.width * 0.5;
  24303. var hy = this.light.height * 0.5;
  24304. // because the buffer attribute is shared over both geometries, we only have to update once
  24305. var position = mesh1.geometry.getAttribute( 'position' );
  24306. var array = position.array;
  24307. // first face
  24308. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24309. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24310. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24311. // second face
  24312. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  24313. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24314. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  24315. position.needsUpdate = true;
  24316. };
  24317. }();
  24318. /**
  24319. * @author alteredq / http://alteredqualia.com/
  24320. * @author mrdoob / http://mrdoob.com/
  24321. * @author Mugen87 / https://github.com/Mugen87
  24322. */
  24323. function HemisphereLightHelper( light, size ) {
  24324. Object3D.call( this );
  24325. this.light = light;
  24326. this.light.updateMatrixWorld();
  24327. this.matrix = light.matrixWorld;
  24328. this.matrixAutoUpdate = false;
  24329. var geometry = new OctahedronBufferGeometry( size );
  24330. geometry.rotateY( Math.PI * 0.5 );
  24331. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24332. var position = geometry.getAttribute( 'position' );
  24333. var colors = new Float32Array( position.count * 3 );
  24334. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24335. this.add( new Mesh( geometry, material ) );
  24336. this.update();
  24337. }
  24338. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24339. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24340. HemisphereLightHelper.prototype.dispose = function () {
  24341. this.children[ 0 ].geometry.dispose();
  24342. this.children[ 0 ].material.dispose();
  24343. };
  24344. HemisphereLightHelper.prototype.update = function () {
  24345. var vector = new Vector3();
  24346. var color1 = new Color();
  24347. var color2 = new Color();
  24348. return function update() {
  24349. var mesh = this.children[ 0 ];
  24350. var colors = mesh.geometry.getAttribute( 'color' );
  24351. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24352. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24353. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24354. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24355. colors.setXYZ( i, color.r, color.g, color.b );
  24356. }
  24357. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24358. colors.needsUpdate = true;
  24359. };
  24360. }();
  24361. /**
  24362. * @author mrdoob / http://mrdoob.com/
  24363. */
  24364. function GridHelper( size, divisions, color1, color2 ) {
  24365. size = size || 10;
  24366. divisions = divisions || 10;
  24367. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24368. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24369. var center = divisions / 2;
  24370. var step = ( size * 2 ) / divisions;
  24371. var vertices = [], colors = [];
  24372. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  24373. vertices.push( - size, 0, k, size, 0, k );
  24374. vertices.push( k, 0, - size, k, 0, size );
  24375. var color = i === center ? color1 : color2;
  24376. color.toArray( colors, j ); j += 3;
  24377. color.toArray( colors, j ); j += 3;
  24378. color.toArray( colors, j ); j += 3;
  24379. color.toArray( colors, j ); j += 3;
  24380. }
  24381. var geometry = new BufferGeometry();
  24382. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24383. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24384. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24385. LineSegments.call( this, geometry, material );
  24386. }
  24387. GridHelper.prototype = Object.create( LineSegments.prototype );
  24388. GridHelper.prototype.constructor = GridHelper;
  24389. /**
  24390. * @author mrdoob / http://mrdoob.com/
  24391. * @author Mugen87 / http://github.com/Mugen87
  24392. * @author Hectate / http://www.github.com/Hectate
  24393. */
  24394. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24395. radius = radius || 10;
  24396. radials = radials || 16;
  24397. circles = circles || 8;
  24398. divisions = divisions || 64;
  24399. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24400. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24401. var vertices = [];
  24402. var colors = [];
  24403. var x, z;
  24404. var v, i, j, r, color;
  24405. // create the radials
  24406. for ( i = 0; i <= radials; i ++ ) {
  24407. v = ( i / radials ) * ( Math.PI * 2 );
  24408. x = Math.sin( v ) * radius;
  24409. z = Math.cos( v ) * radius;
  24410. vertices.push( 0, 0, 0 );
  24411. vertices.push( x, 0, z );
  24412. color = ( i & 1 ) ? color1 : color2;
  24413. colors.push( color.r, color.g, color.b );
  24414. colors.push( color.r, color.g, color.b );
  24415. }
  24416. // create the circles
  24417. for ( i = 0; i <= circles; i ++ ) {
  24418. color = ( i & 1 ) ? color1 : color2;
  24419. r = radius - ( radius / circles * i );
  24420. for ( j = 0; j < divisions; j ++ ) {
  24421. // first vertex
  24422. v = ( j / divisions ) * ( Math.PI * 2 );
  24423. x = Math.sin( v ) * r;
  24424. z = Math.cos( v ) * r;
  24425. vertices.push( x, 0, z );
  24426. colors.push( color.r, color.g, color.b );
  24427. // second vertex
  24428. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24429. x = Math.sin( v ) * r;
  24430. z = Math.cos( v ) * r;
  24431. vertices.push( x, 0, z );
  24432. colors.push( color.r, color.g, color.b );
  24433. }
  24434. }
  24435. var geometry = new BufferGeometry();
  24436. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24437. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24438. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24439. LineSegments.call( this, geometry, material );
  24440. }
  24441. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24442. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24443. /**
  24444. * @author mrdoob / http://mrdoob.com/
  24445. * @author WestLangley / http://github.com/WestLangley
  24446. */
  24447. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24448. // FaceNormalsHelper only supports THREE.Geometry
  24449. this.object = object;
  24450. this.size = ( size !== undefined ) ? size : 1;
  24451. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24452. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24453. //
  24454. var nNormals = 0;
  24455. var objGeometry = this.object.geometry;
  24456. if ( objGeometry && objGeometry.isGeometry ) {
  24457. nNormals = objGeometry.faces.length;
  24458. } else {
  24459. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24460. }
  24461. //
  24462. var geometry = new BufferGeometry();
  24463. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24464. geometry.addAttribute( 'position', positions );
  24465. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24466. //
  24467. this.matrixAutoUpdate = false;
  24468. this.update();
  24469. }
  24470. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24471. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24472. FaceNormalsHelper.prototype.update = ( function () {
  24473. var v1 = new Vector3();
  24474. var v2 = new Vector3();
  24475. var normalMatrix = new Matrix3();
  24476. return function update() {
  24477. this.object.updateMatrixWorld( true );
  24478. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24479. var matrixWorld = this.object.matrixWorld;
  24480. var position = this.geometry.attributes.position;
  24481. //
  24482. var objGeometry = this.object.geometry;
  24483. var vertices = objGeometry.vertices;
  24484. var faces = objGeometry.faces;
  24485. var idx = 0;
  24486. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24487. var face = faces[ i ];
  24488. var normal = face.normal;
  24489. v1.copy( vertices[ face.a ] )
  24490. .add( vertices[ face.b ] )
  24491. .add( vertices[ face.c ] )
  24492. .divideScalar( 3 )
  24493. .applyMatrix4( matrixWorld );
  24494. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24495. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24496. idx = idx + 1;
  24497. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24498. idx = idx + 1;
  24499. }
  24500. position.needsUpdate = true;
  24501. return this;
  24502. };
  24503. }() );
  24504. /**
  24505. * @author alteredq / http://alteredqualia.com/
  24506. * @author mrdoob / http://mrdoob.com/
  24507. * @author WestLangley / http://github.com/WestLangley
  24508. */
  24509. function DirectionalLightHelper( light, size ) {
  24510. Object3D.call( this );
  24511. this.light = light;
  24512. this.light.updateMatrixWorld();
  24513. this.matrix = light.matrixWorld;
  24514. this.matrixAutoUpdate = false;
  24515. if ( size === undefined ) size = 1;
  24516. var geometry = new BufferGeometry();
  24517. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24518. - size, size, 0,
  24519. size, size, 0,
  24520. size, - size, 0,
  24521. - size, - size, 0,
  24522. - size, size, 0
  24523. ], 3 ) );
  24524. var material = new LineBasicMaterial( { fog: false } );
  24525. this.add( new Line( geometry, material ) );
  24526. geometry = new BufferGeometry();
  24527. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24528. this.add( new Line( geometry, material ));
  24529. this.update();
  24530. }
  24531. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24532. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24533. DirectionalLightHelper.prototype.dispose = function () {
  24534. var lightPlane = this.children[ 0 ];
  24535. var targetLine = this.children[ 1 ];
  24536. lightPlane.geometry.dispose();
  24537. lightPlane.material.dispose();
  24538. targetLine.geometry.dispose();
  24539. targetLine.material.dispose();
  24540. };
  24541. DirectionalLightHelper.prototype.update = function () {
  24542. var v1 = new Vector3();
  24543. var v2 = new Vector3();
  24544. var v3 = new Vector3();
  24545. return function update() {
  24546. v1.setFromMatrixPosition( this.light.matrixWorld );
  24547. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24548. v3.subVectors( v2, v1 );
  24549. var lightPlane = this.children[ 0 ];
  24550. var targetLine = this.children[ 1 ];
  24551. lightPlane.lookAt( v3 );
  24552. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24553. targetLine.lookAt( v3 );
  24554. targetLine.scale.z = v3.length();
  24555. };
  24556. }();
  24557. /**
  24558. * @author alteredq / http://alteredqualia.com/
  24559. * @author Mugen87 / https://github.com/Mugen87
  24560. *
  24561. * - shows frustum, line of sight and up of the camera
  24562. * - suitable for fast updates
  24563. * - based on frustum visualization in lightgl.js shadowmap example
  24564. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24565. */
  24566. function CameraHelper( camera ) {
  24567. var geometry = new BufferGeometry();
  24568. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24569. var vertices = [];
  24570. var colors = [];
  24571. var pointMap = {};
  24572. // colors
  24573. var colorFrustum = new Color( 0xffaa00 );
  24574. var colorCone = new Color( 0xff0000 );
  24575. var colorUp = new Color( 0x00aaff );
  24576. var colorTarget = new Color( 0xffffff );
  24577. var colorCross = new Color( 0x333333 );
  24578. // near
  24579. addLine( "n1", "n2", colorFrustum );
  24580. addLine( "n2", "n4", colorFrustum );
  24581. addLine( "n4", "n3", colorFrustum );
  24582. addLine( "n3", "n1", colorFrustum );
  24583. // far
  24584. addLine( "f1", "f2", colorFrustum );
  24585. addLine( "f2", "f4", colorFrustum );
  24586. addLine( "f4", "f3", colorFrustum );
  24587. addLine( "f3", "f1", colorFrustum );
  24588. // sides
  24589. addLine( "n1", "f1", colorFrustum );
  24590. addLine( "n2", "f2", colorFrustum );
  24591. addLine( "n3", "f3", colorFrustum );
  24592. addLine( "n4", "f4", colorFrustum );
  24593. // cone
  24594. addLine( "p", "n1", colorCone );
  24595. addLine( "p", "n2", colorCone );
  24596. addLine( "p", "n3", colorCone );
  24597. addLine( "p", "n4", colorCone );
  24598. // up
  24599. addLine( "u1", "u2", colorUp );
  24600. addLine( "u2", "u3", colorUp );
  24601. addLine( "u3", "u1", colorUp );
  24602. // target
  24603. addLine( "c", "t", colorTarget );
  24604. addLine( "p", "c", colorCross );
  24605. // cross
  24606. addLine( "cn1", "cn2", colorCross );
  24607. addLine( "cn3", "cn4", colorCross );
  24608. addLine( "cf1", "cf2", colorCross );
  24609. addLine( "cf3", "cf4", colorCross );
  24610. function addLine( a, b, color ) {
  24611. addPoint( a, color );
  24612. addPoint( b, color );
  24613. }
  24614. function addPoint( id, color ) {
  24615. vertices.push( 0, 0, 0 );
  24616. colors.push( color.r, color.g, color.b );
  24617. if ( pointMap[ id ] === undefined ) {
  24618. pointMap[ id ] = [];
  24619. }
  24620. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24621. }
  24622. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24623. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24624. LineSegments.call( this, geometry, material );
  24625. this.camera = camera;
  24626. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24627. this.matrix = camera.matrixWorld;
  24628. this.matrixAutoUpdate = false;
  24629. this.pointMap = pointMap;
  24630. this.update();
  24631. }
  24632. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24633. CameraHelper.prototype.constructor = CameraHelper;
  24634. CameraHelper.prototype.update = function () {
  24635. var geometry, pointMap;
  24636. var vector = new Vector3();
  24637. var camera = new Camera();
  24638. function setPoint( point, x, y, z ) {
  24639. vector.set( x, y, z ).unproject( camera );
  24640. var points = pointMap[ point ];
  24641. if ( points !== undefined ) {
  24642. var position = geometry.getAttribute( 'position' );
  24643. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24644. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24645. }
  24646. }
  24647. }
  24648. return function update() {
  24649. geometry = this.geometry;
  24650. pointMap = this.pointMap;
  24651. var w = 1, h = 1;
  24652. // we need just camera projection matrix
  24653. // world matrix must be identity
  24654. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24655. // center / target
  24656. setPoint( "c", 0, 0, - 1 );
  24657. setPoint( "t", 0, 0, 1 );
  24658. // near
  24659. setPoint( "n1", - w, - h, - 1 );
  24660. setPoint( "n2", w, - h, - 1 );
  24661. setPoint( "n3", - w, h, - 1 );
  24662. setPoint( "n4", w, h, - 1 );
  24663. // far
  24664. setPoint( "f1", - w, - h, 1 );
  24665. setPoint( "f2", w, - h, 1 );
  24666. setPoint( "f3", - w, h, 1 );
  24667. setPoint( "f4", w, h, 1 );
  24668. // up
  24669. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24670. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24671. setPoint( "u3", 0, h * 2, - 1 );
  24672. // cross
  24673. setPoint( "cf1", - w, 0, 1 );
  24674. setPoint( "cf2", w, 0, 1 );
  24675. setPoint( "cf3", 0, - h, 1 );
  24676. setPoint( "cf4", 0, h, 1 );
  24677. setPoint( "cn1", - w, 0, - 1 );
  24678. setPoint( "cn2", w, 0, - 1 );
  24679. setPoint( "cn3", 0, - h, - 1 );
  24680. setPoint( "cn4", 0, h, - 1 );
  24681. geometry.getAttribute( 'position' ).needsUpdate = true;
  24682. };
  24683. }();
  24684. /**
  24685. * @author mrdoob / http://mrdoob.com/
  24686. */
  24687. function BoxHelper( object, color ) {
  24688. if ( color === undefined ) color = 0xffff00;
  24689. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  24690. var positions = new Float32Array( 8 * 3 );
  24691. var geometry = new BufferGeometry();
  24692. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24693. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24694. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24695. if ( object !== undefined ) {
  24696. this.update( object );
  24697. }
  24698. }
  24699. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24700. BoxHelper.prototype.constructor = BoxHelper;
  24701. BoxHelper.prototype.update = ( function () {
  24702. var box = new Box3();
  24703. return function update( object ) {
  24704. if ( object && object.isBox3 ) {
  24705. box.copy( object );
  24706. } else {
  24707. box.setFromObject( object );
  24708. }
  24709. if ( box.isEmpty() ) return;
  24710. var min = box.min;
  24711. var max = box.max;
  24712. /*
  24713. 5____4
  24714. 1/___0/|
  24715. | 6__|_7
  24716. 2/___3/
  24717. 0: max.x, max.y, max.z
  24718. 1: min.x, max.y, max.z
  24719. 2: min.x, min.y, max.z
  24720. 3: max.x, min.y, max.z
  24721. 4: max.x, max.y, min.z
  24722. 5: min.x, max.y, min.z
  24723. 6: min.x, min.y, min.z
  24724. 7: max.x, min.y, min.z
  24725. */
  24726. var position = this.geometry.attributes.position;
  24727. var array = position.array;
  24728. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24729. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24730. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24731. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24732. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24733. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24734. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24735. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24736. position.needsUpdate = true;
  24737. this.geometry.computeBoundingSphere();
  24738. };
  24739. } )();
  24740. /**
  24741. * @author WestLangley / http://github.com/WestLangley
  24742. * @author zz85 / http://github.com/zz85
  24743. * @author bhouston / http://clara.io
  24744. *
  24745. * Creates an arrow for visualizing directions
  24746. *
  24747. * Parameters:
  24748. * dir - Vector3
  24749. * origin - Vector3
  24750. * length - Number
  24751. * color - color in hex value
  24752. * headLength - Number
  24753. * headWidth - Number
  24754. */
  24755. var lineGeometry = new BufferGeometry();
  24756. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24757. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24758. coneGeometry.translate( 0, - 0.5, 0 );
  24759. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24760. // dir is assumed to be normalized
  24761. Object3D.call( this );
  24762. if ( color === undefined ) color = 0xffff00;
  24763. if ( length === undefined ) length = 1;
  24764. if ( headLength === undefined ) headLength = 0.2 * length;
  24765. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24766. this.position.copy( origin );
  24767. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24768. this.line.matrixAutoUpdate = false;
  24769. this.add( this.line );
  24770. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24771. this.cone.matrixAutoUpdate = false;
  24772. this.add( this.cone );
  24773. this.setDirection( dir );
  24774. this.setLength( length, headLength, headWidth );
  24775. }
  24776. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24777. ArrowHelper.prototype.constructor = ArrowHelper;
  24778. ArrowHelper.prototype.setDirection = ( function () {
  24779. var axis = new Vector3();
  24780. var radians;
  24781. return function setDirection( dir ) {
  24782. // dir is assumed to be normalized
  24783. if ( dir.y > 0.99999 ) {
  24784. this.quaternion.set( 0, 0, 0, 1 );
  24785. } else if ( dir.y < - 0.99999 ) {
  24786. this.quaternion.set( 1, 0, 0, 0 );
  24787. } else {
  24788. axis.set( dir.z, 0, - dir.x ).normalize();
  24789. radians = Math.acos( dir.y );
  24790. this.quaternion.setFromAxisAngle( axis, radians );
  24791. }
  24792. };
  24793. }() );
  24794. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24795. if ( headLength === undefined ) headLength = 0.2 * length;
  24796. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24797. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24798. this.line.updateMatrix();
  24799. this.cone.scale.set( headWidth, headLength, headWidth );
  24800. this.cone.position.y = length;
  24801. this.cone.updateMatrix();
  24802. };
  24803. ArrowHelper.prototype.setColor = function ( color ) {
  24804. this.line.material.color.copy( color );
  24805. this.cone.material.color.copy( color );
  24806. };
  24807. /**
  24808. * @author sroucheray / http://sroucheray.org/
  24809. * @author mrdoob / http://mrdoob.com/
  24810. */
  24811. function AxisHelper( size ) {
  24812. size = size || 1;
  24813. var vertices = [
  24814. 0, 0, 0, size, 0, 0,
  24815. 0, 0, 0, 0, size, 0,
  24816. 0, 0, 0, 0, 0, size
  24817. ];
  24818. var colors = [
  24819. 1, 0, 0, 1, 0.6, 0,
  24820. 0, 1, 0, 0.6, 1, 0,
  24821. 0, 0, 1, 0, 0.6, 1
  24822. ];
  24823. var geometry = new BufferGeometry();
  24824. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24825. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24826. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24827. LineSegments.call( this, geometry, material );
  24828. }
  24829. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24830. AxisHelper.prototype.constructor = AxisHelper;
  24831. /**
  24832. * @author zz85 https://github.com/zz85
  24833. *
  24834. * Centripetal CatmullRom Curve - which is useful for avoiding
  24835. * cusps and self-intersections in non-uniform catmull rom curves.
  24836. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24837. *
  24838. * curve.type accepts centripetal(default), chordal and catmullrom
  24839. * curve.tension is used for catmullrom which defaults to 0.5
  24840. */
  24841. var CatmullRomCurve3 = ( function() {
  24842. var
  24843. tmp = new Vector3(),
  24844. px = new CubicPoly(),
  24845. py = new CubicPoly(),
  24846. pz = new CubicPoly();
  24847. /*
  24848. Based on an optimized c++ solution in
  24849. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24850. - http://ideone.com/NoEbVM
  24851. This CubicPoly class could be used for reusing some variables and calculations,
  24852. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24853. which can be placed in CurveUtils.
  24854. */
  24855. function CubicPoly() {}
  24856. /*
  24857. * Compute coefficients for a cubic polynomial
  24858. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24859. * such that
  24860. * p(0) = x0, p(1) = x1
  24861. * and
  24862. * p'(0) = t0, p'(1) = t1.
  24863. */
  24864. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24865. this.c0 = x0;
  24866. this.c1 = t0;
  24867. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24868. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24869. };
  24870. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24871. // compute tangents when parameterized in [t1,t2]
  24872. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24873. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24874. // rescale tangents for parametrization in [0,1]
  24875. t1 *= dt1;
  24876. t2 *= dt1;
  24877. // initCubicPoly
  24878. this.init( x1, x2, t1, t2 );
  24879. };
  24880. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24881. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24882. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24883. };
  24884. CubicPoly.prototype.calc = function( t ) {
  24885. var t2 = t * t;
  24886. var t3 = t2 * t;
  24887. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24888. };
  24889. // Subclass Three.js curve
  24890. return Curve.create(
  24891. function ( p /* array of Vector3 */ ) {
  24892. this.points = p || [];
  24893. this.closed = false;
  24894. },
  24895. function ( t ) {
  24896. var points = this.points,
  24897. point, intPoint, weight, l;
  24898. l = points.length;
  24899. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24900. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24901. intPoint = Math.floor( point );
  24902. weight = point - intPoint;
  24903. if ( this.closed ) {
  24904. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24905. } else if ( weight === 0 && intPoint === l - 1 ) {
  24906. intPoint = l - 2;
  24907. weight = 1;
  24908. }
  24909. var p0, p1, p2, p3; // 4 points
  24910. if ( this.closed || intPoint > 0 ) {
  24911. p0 = points[ ( intPoint - 1 ) % l ];
  24912. } else {
  24913. // extrapolate first point
  24914. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24915. p0 = tmp;
  24916. }
  24917. p1 = points[ intPoint % l ];
  24918. p2 = points[ ( intPoint + 1 ) % l ];
  24919. if ( this.closed || intPoint + 2 < l ) {
  24920. p3 = points[ ( intPoint + 2 ) % l ];
  24921. } else {
  24922. // extrapolate last point
  24923. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24924. p3 = tmp;
  24925. }
  24926. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24927. // init Centripetal / Chordal Catmull-Rom
  24928. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24929. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24930. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24931. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24932. // safety check for repeated points
  24933. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24934. if ( dt0 < 1e-4 ) dt0 = dt1;
  24935. if ( dt2 < 1e-4 ) dt2 = dt1;
  24936. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24937. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24938. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24939. } else if ( this.type === 'catmullrom' ) {
  24940. var tension = this.tension !== undefined ? this.tension : 0.5;
  24941. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24942. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24943. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24944. }
  24945. var v = new Vector3(
  24946. px.calc( weight ),
  24947. py.calc( weight ),
  24948. pz.calc( weight )
  24949. );
  24950. return v;
  24951. }
  24952. );
  24953. } )();
  24954. /**************************************************************
  24955. * Spline 3D curve
  24956. **************************************************************/
  24957. var SplineCurve3 = Curve.create(
  24958. function ( points /* array of Vector3 */ ) {
  24959. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24960. this.points = ( points === undefined ) ? [] : points;
  24961. },
  24962. function ( t ) {
  24963. var points = this.points;
  24964. var point = ( points.length - 1 ) * t;
  24965. var intPoint = Math.floor( point );
  24966. var weight = point - intPoint;
  24967. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24968. var point1 = points[ intPoint ];
  24969. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24970. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24971. var interpolate = CurveUtils.interpolate;
  24972. return new Vector3(
  24973. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24974. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24975. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24976. );
  24977. }
  24978. );
  24979. /**************************************************************
  24980. * Cubic Bezier 3D curve
  24981. **************************************************************/
  24982. var CubicBezierCurve3 = Curve.create(
  24983. function ( v0, v1, v2, v3 ) {
  24984. this.v0 = v0;
  24985. this.v1 = v1;
  24986. this.v2 = v2;
  24987. this.v3 = v3;
  24988. },
  24989. function ( t ) {
  24990. var b3 = ShapeUtils.b3;
  24991. return new Vector3(
  24992. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24993. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24994. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24995. );
  24996. }
  24997. );
  24998. /**************************************************************
  24999. * Quadratic Bezier 3D curve
  25000. **************************************************************/
  25001. var QuadraticBezierCurve3 = Curve.create(
  25002. function ( v0, v1, v2 ) {
  25003. this.v0 = v0;
  25004. this.v1 = v1;
  25005. this.v2 = v2;
  25006. },
  25007. function ( t ) {
  25008. var b2 = ShapeUtils.b2;
  25009. return new Vector3(
  25010. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  25011. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  25012. b2( t, this.v0.z, this.v1.z, this.v2.z )
  25013. );
  25014. }
  25015. );
  25016. /**************************************************************
  25017. * Line3D
  25018. **************************************************************/
  25019. var LineCurve3 = Curve.create(
  25020. function ( v1, v2 ) {
  25021. this.v1 = v1;
  25022. this.v2 = v2;
  25023. },
  25024. function ( t ) {
  25025. if ( t === 1 ) {
  25026. return this.v2.clone();
  25027. }
  25028. var vector = new Vector3();
  25029. vector.subVectors( this.v2, this.v1 ); // diff
  25030. vector.multiplyScalar( t );
  25031. vector.add( this.v1 );
  25032. return vector;
  25033. }
  25034. );
  25035. /**************************************************************
  25036. * Arc curve
  25037. **************************************************************/
  25038. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25039. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25040. }
  25041. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25042. ArcCurve.prototype.constructor = ArcCurve;
  25043. /**
  25044. * @author alteredq / http://alteredqualia.com/
  25045. */
  25046. var SceneUtils = {
  25047. createMultiMaterialObject: function ( geometry, materials ) {
  25048. var group = new Group();
  25049. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25050. group.add( new Mesh( geometry, materials[ i ] ) );
  25051. }
  25052. return group;
  25053. },
  25054. detach: function ( child, parent, scene ) {
  25055. child.applyMatrix( parent.matrixWorld );
  25056. parent.remove( child );
  25057. scene.add( child );
  25058. },
  25059. attach: function ( child, scene, parent ) {
  25060. var matrixWorldInverse = new Matrix4();
  25061. matrixWorldInverse.getInverse( parent.matrixWorld );
  25062. child.applyMatrix( matrixWorldInverse );
  25063. scene.remove( child );
  25064. parent.add( child );
  25065. }
  25066. };
  25067. /**
  25068. * @author mrdoob / http://mrdoob.com/
  25069. */
  25070. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25071. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25072. return new Face3( a, b, c, normal, color, materialIndex );
  25073. }
  25074. var LineStrip = 0;
  25075. var LinePieces = 1;
  25076. function MeshFaceMaterial( materials ) {
  25077. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  25078. return new MultiMaterial( materials );
  25079. }
  25080. function PointCloud( geometry, material ) {
  25081. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25082. return new Points( geometry, material );
  25083. }
  25084. function Particle( material ) {
  25085. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25086. return new Sprite( material );
  25087. }
  25088. function ParticleSystem( geometry, material ) {
  25089. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25090. return new Points( geometry, material );
  25091. }
  25092. function PointCloudMaterial( parameters ) {
  25093. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25094. return new PointsMaterial( parameters );
  25095. }
  25096. function ParticleBasicMaterial( parameters ) {
  25097. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25098. return new PointsMaterial( parameters );
  25099. }
  25100. function ParticleSystemMaterial( parameters ) {
  25101. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25102. return new PointsMaterial( parameters );
  25103. }
  25104. function Vertex( x, y, z ) {
  25105. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25106. return new Vector3( x, y, z );
  25107. }
  25108. //
  25109. function DynamicBufferAttribute( array, itemSize ) {
  25110. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25111. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25112. }
  25113. function Int8Attribute( array, itemSize ) {
  25114. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25115. return new Int8BufferAttribute( array, itemSize );
  25116. }
  25117. function Uint8Attribute( array, itemSize ) {
  25118. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25119. return new Uint8BufferAttribute( array, itemSize );
  25120. }
  25121. function Uint8ClampedAttribute( array, itemSize ) {
  25122. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25123. return new Uint8ClampedBufferAttribute( array, itemSize );
  25124. }
  25125. function Int16Attribute( array, itemSize ) {
  25126. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25127. return new Int16BufferAttribute( array, itemSize );
  25128. }
  25129. function Uint16Attribute( array, itemSize ) {
  25130. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25131. return new Uint16BufferAttribute( array, itemSize );
  25132. }
  25133. function Int32Attribute( array, itemSize ) {
  25134. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25135. return new Int32BufferAttribute( array, itemSize );
  25136. }
  25137. function Uint32Attribute( array, itemSize ) {
  25138. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25139. return new Uint32BufferAttribute( array, itemSize );
  25140. }
  25141. function Float32Attribute( array, itemSize ) {
  25142. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25143. return new Float32BufferAttribute( array, itemSize );
  25144. }
  25145. function Float64Attribute( array, itemSize ) {
  25146. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25147. return new Float64BufferAttribute( array, itemSize );
  25148. }
  25149. //
  25150. function ClosedSplineCurve3( points ) {
  25151. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25152. CatmullRomCurve3.call( this, points );
  25153. this.type = 'catmullrom';
  25154. this.closed = true;
  25155. }
  25156. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25157. //
  25158. function BoundingBoxHelper( object, color ) {
  25159. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25160. return new BoxHelper( object, color );
  25161. }
  25162. function EdgesHelper( object, hex ) {
  25163. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25164. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25165. }
  25166. GridHelper.prototype.setColors = function () {
  25167. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25168. };
  25169. function WireframeHelper( object, hex ) {
  25170. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25171. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25172. }
  25173. //
  25174. function XHRLoader( manager ) {
  25175. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25176. return new FileLoader( manager );
  25177. }
  25178. //
  25179. Object.assign( Box2.prototype, {
  25180. center: function ( optionalTarget ) {
  25181. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25182. return this.getCenter( optionalTarget );
  25183. },
  25184. empty: function () {
  25185. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25186. return this.isEmpty();
  25187. },
  25188. isIntersectionBox: function ( box ) {
  25189. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25190. return this.intersectsBox( box );
  25191. },
  25192. size: function ( optionalTarget ) {
  25193. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25194. return this.getSize( optionalTarget );
  25195. }
  25196. } );
  25197. Object.assign( Box3.prototype, {
  25198. center: function ( optionalTarget ) {
  25199. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25200. return this.getCenter( optionalTarget );
  25201. },
  25202. empty: function () {
  25203. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25204. return this.isEmpty();
  25205. },
  25206. isIntersectionBox: function ( box ) {
  25207. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25208. return this.intersectsBox( box );
  25209. },
  25210. isIntersectionSphere: function ( sphere ) {
  25211. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25212. return this.intersectsSphere( sphere );
  25213. },
  25214. size: function ( optionalTarget ) {
  25215. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25216. return this.getSize( optionalTarget );
  25217. }
  25218. } );
  25219. Line3.prototype.center = function ( optionalTarget ) {
  25220. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25221. return this.getCenter( optionalTarget );
  25222. };
  25223. _Math.random16 = function () {
  25224. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25225. return Math.random();
  25226. };
  25227. Object.assign( Matrix3.prototype, {
  25228. flattenToArrayOffset: function ( array, offset ) {
  25229. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25230. return this.toArray( array, offset );
  25231. },
  25232. multiplyVector3: function ( vector ) {
  25233. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25234. return vector.applyMatrix3( this );
  25235. },
  25236. multiplyVector3Array: function ( a ) {
  25237. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25238. return this.applyToVector3Array( a );
  25239. },
  25240. applyToBuffer: function( buffer, offset, length ) {
  25241. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25242. return this.applyToBufferAttribute( buffer );
  25243. }
  25244. } );
  25245. Object.assign( Matrix4.prototype, {
  25246. extractPosition: function ( m ) {
  25247. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25248. return this.copyPosition( m );
  25249. },
  25250. flattenToArrayOffset: function ( array, offset ) {
  25251. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25252. return this.toArray( array, offset );
  25253. },
  25254. getPosition: function () {
  25255. var v1;
  25256. return function getPosition() {
  25257. if ( v1 === undefined ) v1 = new Vector3();
  25258. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25259. return v1.setFromMatrixColumn( this, 3 );
  25260. };
  25261. }(),
  25262. setRotationFromQuaternion: function ( q ) {
  25263. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25264. return this.makeRotationFromQuaternion( q );
  25265. },
  25266. multiplyVector3: function ( vector ) {
  25267. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  25268. return vector.applyProjection( this );
  25269. },
  25270. multiplyVector4: function ( vector ) {
  25271. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25272. return vector.applyMatrix4( this );
  25273. },
  25274. multiplyVector3Array: function ( a ) {
  25275. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25276. return this.applyToVector3Array( a );
  25277. },
  25278. rotateAxis: function ( v ) {
  25279. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25280. v.transformDirection( this );
  25281. },
  25282. crossVector: function ( vector ) {
  25283. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25284. return vector.applyMatrix4( this );
  25285. },
  25286. translate: function () {
  25287. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25288. },
  25289. rotateX: function () {
  25290. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25291. },
  25292. rotateY: function () {
  25293. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25294. },
  25295. rotateZ: function () {
  25296. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25297. },
  25298. rotateByAxis: function () {
  25299. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25300. },
  25301. applyToBuffer: function( buffer, offset, length ) {
  25302. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25303. return this.applyToBufferAttribute( buffer );
  25304. }
  25305. } );
  25306. Plane.prototype.isIntersectionLine = function ( line ) {
  25307. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25308. return this.intersectsLine( line );
  25309. };
  25310. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25311. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25312. return vector.applyQuaternion( this );
  25313. };
  25314. Object.assign( Ray.prototype, {
  25315. isIntersectionBox: function ( box ) {
  25316. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25317. return this.intersectsBox( box );
  25318. },
  25319. isIntersectionPlane: function ( plane ) {
  25320. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25321. return this.intersectsPlane( plane );
  25322. },
  25323. isIntersectionSphere: function ( sphere ) {
  25324. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25325. return this.intersectsSphere( sphere );
  25326. }
  25327. } );
  25328. Object.assign( Shape.prototype, {
  25329. extrude: function ( options ) {
  25330. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25331. return new ExtrudeGeometry( this, options );
  25332. },
  25333. makeGeometry: function ( options ) {
  25334. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25335. return new ShapeGeometry( this, options );
  25336. }
  25337. } );
  25338. Object.assign( Vector3.prototype, {
  25339. setEulerFromRotationMatrix: function () {
  25340. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25341. },
  25342. setEulerFromQuaternion: function () {
  25343. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25344. },
  25345. getPositionFromMatrix: function ( m ) {
  25346. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25347. return this.setFromMatrixPosition( m );
  25348. },
  25349. getScaleFromMatrix: function ( m ) {
  25350. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25351. return this.setFromMatrixScale( m );
  25352. },
  25353. getColumnFromMatrix: function ( index, matrix ) {
  25354. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25355. return this.setFromMatrixColumn( matrix, index );
  25356. }
  25357. } );
  25358. //
  25359. Geometry.prototype.computeTangents = function () {
  25360. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25361. };
  25362. Object.assign( Object3D.prototype, {
  25363. getChildByName: function ( name ) {
  25364. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25365. return this.getObjectByName( name );
  25366. },
  25367. renderDepth: function () {
  25368. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25369. },
  25370. translate: function ( distance, axis ) {
  25371. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25372. return this.translateOnAxis( axis, distance );
  25373. }
  25374. } );
  25375. Object.defineProperties( Object3D.prototype, {
  25376. eulerOrder: {
  25377. get: function () {
  25378. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25379. return this.rotation.order;
  25380. },
  25381. set: function ( value ) {
  25382. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25383. this.rotation.order = value;
  25384. }
  25385. },
  25386. useQuaternion: {
  25387. get: function () {
  25388. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25389. },
  25390. set: function () {
  25391. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25392. }
  25393. }
  25394. } );
  25395. Object.defineProperties( LOD.prototype, {
  25396. objects: {
  25397. get: function () {
  25398. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25399. return this.levels;
  25400. }
  25401. }
  25402. } );
  25403. //
  25404. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25405. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25406. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25407. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25408. this.setFocalLength( focalLength );
  25409. };
  25410. //
  25411. Object.defineProperties( Light.prototype, {
  25412. onlyShadow: {
  25413. set: function () {
  25414. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25415. }
  25416. },
  25417. shadowCameraFov: {
  25418. set: function ( value ) {
  25419. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25420. this.shadow.camera.fov = value;
  25421. }
  25422. },
  25423. shadowCameraLeft: {
  25424. set: function ( value ) {
  25425. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25426. this.shadow.camera.left = value;
  25427. }
  25428. },
  25429. shadowCameraRight: {
  25430. set: function ( value ) {
  25431. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25432. this.shadow.camera.right = value;
  25433. }
  25434. },
  25435. shadowCameraTop: {
  25436. set: function ( value ) {
  25437. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25438. this.shadow.camera.top = value;
  25439. }
  25440. },
  25441. shadowCameraBottom: {
  25442. set: function ( value ) {
  25443. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25444. this.shadow.camera.bottom = value;
  25445. }
  25446. },
  25447. shadowCameraNear: {
  25448. set: function ( value ) {
  25449. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25450. this.shadow.camera.near = value;
  25451. }
  25452. },
  25453. shadowCameraFar: {
  25454. set: function ( value ) {
  25455. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25456. this.shadow.camera.far = value;
  25457. }
  25458. },
  25459. shadowCameraVisible: {
  25460. set: function () {
  25461. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25462. }
  25463. },
  25464. shadowBias: {
  25465. set: function ( value ) {
  25466. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25467. this.shadow.bias = value;
  25468. }
  25469. },
  25470. shadowDarkness: {
  25471. set: function () {
  25472. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25473. }
  25474. },
  25475. shadowMapWidth: {
  25476. set: function ( value ) {
  25477. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25478. this.shadow.mapSize.width = value;
  25479. }
  25480. },
  25481. shadowMapHeight: {
  25482. set: function ( value ) {
  25483. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25484. this.shadow.mapSize.height = value;
  25485. }
  25486. }
  25487. } );
  25488. //
  25489. Object.defineProperties( BufferAttribute.prototype, {
  25490. length: {
  25491. get: function () {
  25492. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25493. return this.array.length;
  25494. }
  25495. }
  25496. } );
  25497. Object.assign( BufferGeometry.prototype, {
  25498. addIndex: function ( index ) {
  25499. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25500. this.setIndex( index );
  25501. },
  25502. addDrawCall: function ( start, count, indexOffset ) {
  25503. if ( indexOffset !== undefined ) {
  25504. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25505. }
  25506. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25507. this.addGroup( start, count );
  25508. },
  25509. clearDrawCalls: function () {
  25510. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25511. this.clearGroups();
  25512. },
  25513. computeTangents: function () {
  25514. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25515. },
  25516. computeOffsets: function () {
  25517. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25518. }
  25519. } );
  25520. Object.defineProperties( BufferGeometry.prototype, {
  25521. drawcalls: {
  25522. get: function () {
  25523. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25524. return this.groups;
  25525. }
  25526. },
  25527. offsets: {
  25528. get: function () {
  25529. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25530. return this.groups;
  25531. }
  25532. }
  25533. } );
  25534. //
  25535. Object.defineProperties( Uniform.prototype, {
  25536. dynamic: {
  25537. set: function () {
  25538. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25539. }
  25540. },
  25541. onUpdate: {
  25542. value: function () {
  25543. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25544. return this;
  25545. }
  25546. }
  25547. } );
  25548. //
  25549. Object.defineProperties( Material.prototype, {
  25550. wrapAround: {
  25551. get: function () {
  25552. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25553. },
  25554. set: function () {
  25555. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25556. }
  25557. },
  25558. wrapRGB: {
  25559. get: function () {
  25560. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  25561. return new Color();
  25562. }
  25563. }
  25564. } );
  25565. Object.defineProperties( MeshPhongMaterial.prototype, {
  25566. metal: {
  25567. get: function () {
  25568. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25569. return false;
  25570. },
  25571. set: function () {
  25572. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25573. }
  25574. }
  25575. } );
  25576. Object.defineProperties( ShaderMaterial.prototype, {
  25577. derivatives: {
  25578. get: function () {
  25579. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25580. return this.extensions.derivatives;
  25581. },
  25582. set: function ( value ) {
  25583. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25584. this.extensions.derivatives = value;
  25585. }
  25586. }
  25587. } );
  25588. //
  25589. EventDispatcher.prototype = Object.assign( Object.create( {
  25590. // Note: Extra base ensures these properties are not 'assign'ed.
  25591. constructor: EventDispatcher,
  25592. apply: function ( target ) {
  25593. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  25594. "just inherit or Object.assign the prototype to mix-in." );
  25595. Object.assign( target, this );
  25596. }
  25597. } ), EventDispatcher.prototype );
  25598. //
  25599. Object.assign( WebGLRenderer.prototype, {
  25600. supportsFloatTextures: function () {
  25601. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25602. return this.extensions.get( 'OES_texture_float' );
  25603. },
  25604. supportsHalfFloatTextures: function () {
  25605. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25606. return this.extensions.get( 'OES_texture_half_float' );
  25607. },
  25608. supportsStandardDerivatives: function () {
  25609. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25610. return this.extensions.get( 'OES_standard_derivatives' );
  25611. },
  25612. supportsCompressedTextureS3TC: function () {
  25613. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25614. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25615. },
  25616. supportsCompressedTexturePVRTC: function () {
  25617. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25618. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25619. },
  25620. supportsBlendMinMax: function () {
  25621. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25622. return this.extensions.get( 'EXT_blend_minmax' );
  25623. },
  25624. supportsVertexTextures: function () {
  25625. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25626. return this.capabilities.vertexTextures;
  25627. },
  25628. supportsInstancedArrays: function () {
  25629. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25630. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25631. },
  25632. enableScissorTest: function ( boolean ) {
  25633. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25634. this.setScissorTest( boolean );
  25635. },
  25636. initMaterial: function () {
  25637. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25638. },
  25639. addPrePlugin: function () {
  25640. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25641. },
  25642. addPostPlugin: function () {
  25643. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25644. },
  25645. updateShadowMap: function () {
  25646. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25647. }
  25648. } );
  25649. Object.defineProperties( WebGLRenderer.prototype, {
  25650. shadowMapEnabled: {
  25651. get: function () {
  25652. return this.shadowMap.enabled;
  25653. },
  25654. set: function ( value ) {
  25655. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25656. this.shadowMap.enabled = value;
  25657. }
  25658. },
  25659. shadowMapType: {
  25660. get: function () {
  25661. return this.shadowMap.type;
  25662. },
  25663. set: function ( value ) {
  25664. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25665. this.shadowMap.type = value;
  25666. }
  25667. },
  25668. shadowMapCullFace: {
  25669. get: function () {
  25670. return this.shadowMap.cullFace;
  25671. },
  25672. set: function ( value ) {
  25673. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25674. this.shadowMap.cullFace = value;
  25675. }
  25676. }
  25677. } );
  25678. Object.defineProperties( WebGLShadowMap.prototype, {
  25679. cullFace: {
  25680. get: function () {
  25681. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25682. },
  25683. set: function ( cullFace ) {
  25684. var value = ( cullFace !== CullFaceBack );
  25685. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25686. this.renderReverseSided = value;
  25687. }
  25688. }
  25689. } );
  25690. //
  25691. Object.defineProperties( WebGLRenderTarget.prototype, {
  25692. wrapS: {
  25693. get: function () {
  25694. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25695. return this.texture.wrapS;
  25696. },
  25697. set: function ( value ) {
  25698. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25699. this.texture.wrapS = value;
  25700. }
  25701. },
  25702. wrapT: {
  25703. get: function () {
  25704. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25705. return this.texture.wrapT;
  25706. },
  25707. set: function ( value ) {
  25708. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25709. this.texture.wrapT = value;
  25710. }
  25711. },
  25712. magFilter: {
  25713. get: function () {
  25714. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25715. return this.texture.magFilter;
  25716. },
  25717. set: function ( value ) {
  25718. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25719. this.texture.magFilter = value;
  25720. }
  25721. },
  25722. minFilter: {
  25723. get: function () {
  25724. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25725. return this.texture.minFilter;
  25726. },
  25727. set: function ( value ) {
  25728. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25729. this.texture.minFilter = value;
  25730. }
  25731. },
  25732. anisotropy: {
  25733. get: function () {
  25734. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25735. return this.texture.anisotropy;
  25736. },
  25737. set: function ( value ) {
  25738. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25739. this.texture.anisotropy = value;
  25740. }
  25741. },
  25742. offset: {
  25743. get: function () {
  25744. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25745. return this.texture.offset;
  25746. },
  25747. set: function ( value ) {
  25748. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25749. this.texture.offset = value;
  25750. }
  25751. },
  25752. repeat: {
  25753. get: function () {
  25754. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25755. return this.texture.repeat;
  25756. },
  25757. set: function ( value ) {
  25758. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25759. this.texture.repeat = value;
  25760. }
  25761. },
  25762. format: {
  25763. get: function () {
  25764. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25765. return this.texture.format;
  25766. },
  25767. set: function ( value ) {
  25768. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25769. this.texture.format = value;
  25770. }
  25771. },
  25772. type: {
  25773. get: function () {
  25774. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25775. return this.texture.type;
  25776. },
  25777. set: function ( value ) {
  25778. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25779. this.texture.type = value;
  25780. }
  25781. },
  25782. generateMipmaps: {
  25783. get: function () {
  25784. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25785. return this.texture.generateMipmaps;
  25786. },
  25787. set: function ( value ) {
  25788. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25789. this.texture.generateMipmaps = value;
  25790. }
  25791. }
  25792. } );
  25793. //
  25794. Audio.prototype.load = function ( file ) {
  25795. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25796. var scope = this;
  25797. var audioLoader = new AudioLoader();
  25798. audioLoader.load( file, function ( buffer ) {
  25799. scope.setBuffer( buffer );
  25800. } );
  25801. return this;
  25802. };
  25803. AudioAnalyser.prototype.getData = function () {
  25804. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25805. return this.getFrequencyData();
  25806. };
  25807. //
  25808. var GeometryUtils = {
  25809. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25810. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25811. var matrix;
  25812. if ( geometry2.isMesh ) {
  25813. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25814. matrix = geometry2.matrix;
  25815. geometry2 = geometry2.geometry;
  25816. }
  25817. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25818. },
  25819. center: function ( geometry ) {
  25820. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25821. return geometry.center();
  25822. }
  25823. };
  25824. var ImageUtils = {
  25825. crossOrigin: undefined,
  25826. loadTexture: function ( url, mapping, onLoad, onError ) {
  25827. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25828. var loader = new TextureLoader();
  25829. loader.setCrossOrigin( this.crossOrigin );
  25830. var texture = loader.load( url, onLoad, undefined, onError );
  25831. if ( mapping ) texture.mapping = mapping;
  25832. return texture;
  25833. },
  25834. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25835. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25836. var loader = new CubeTextureLoader();
  25837. loader.setCrossOrigin( this.crossOrigin );
  25838. var texture = loader.load( urls, onLoad, undefined, onError );
  25839. if ( mapping ) texture.mapping = mapping;
  25840. return texture;
  25841. },
  25842. loadCompressedTexture: function () {
  25843. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25844. },
  25845. loadCompressedTextureCube: function () {
  25846. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25847. }
  25848. };
  25849. //
  25850. function Projector() {
  25851. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25852. this.projectVector = function ( vector, camera ) {
  25853. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25854. vector.project( camera );
  25855. };
  25856. this.unprojectVector = function ( vector, camera ) {
  25857. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25858. vector.unproject( camera );
  25859. };
  25860. this.pickingRay = function () {
  25861. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25862. };
  25863. }
  25864. //
  25865. function CanvasRenderer() {
  25866. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25867. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25868. this.clear = function () {};
  25869. this.render = function () {};
  25870. this.setClearColor = function () {};
  25871. this.setSize = function () {};
  25872. }
  25873. export { WebGLRenderTargetCube, WebGLRenderTarget, WebGLRenderer, ShaderLib, UniformsLib, UniformsUtils, ShaderChunk, FogExp2, Fog, Scene, LensFlare, Sprite, LOD, SkinnedMesh, Skeleton, Bone, Mesh, LineSegments, Line, Points, Group, VideoTexture, DataTexture, CompressedTexture, CubeTexture, CanvasTexture, DepthTexture, Texture, CompressedTextureLoader, BinaryTextureLoader, DataTextureLoader, CubeTextureLoader, TextureLoader, ObjectLoader, MaterialLoader, BufferGeometryLoader, DefaultLoadingManager, LoadingManager, JSONLoader, ImageLoader, FontLoader, FileLoader, Loader, Cache, AudioLoader, SpotLightShadow, SpotLight, PointLight, RectAreaLight, HemisphereLight, DirectionalLightShadow, DirectionalLight, AmbientLight, LightShadow, Light, StereoCamera, PerspectiveCamera, OrthographicCamera, CubeCamera, Camera, AudioListener, PositionalAudio, AudioContext, AudioAnalyser, Audio, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, PropertyMixer, PropertyBinding, KeyframeTrack, AnimationUtils, AnimationObjectGroup, AnimationMixer, AnimationClip, Uniform, InstancedBufferGeometry, BufferGeometry, GeometryIdCount, Geometry, InterleavedBufferAttribute, InstancedInterleavedBuffer, InterleavedBuffer, InstancedBufferAttribute, Face3, Object3D, Raycaster, Layers, EventDispatcher, Clock, QuaternionLinearInterpolant, LinearInterpolant, DiscreteInterpolant, CubicInterpolant, Interpolant, Triangle, Spline, _Math as Math, Spherical, Cylindrical, Plane, Frustum, Sphere, Ray, Matrix4, Matrix3, Box3, Box2, Line3, Euler, Vector4, Vector3, Vector2, Quaternion, Color, MorphBlendMesh, ImmediateRenderObject, VertexNormalsHelper, SpotLightHelper, SkeletonHelper, PointLightHelper, RectAreaLightHelper, HemisphereLightHelper, GridHelper, PolarGridHelper, FaceNormalsHelper, DirectionalLightHelper, CameraHelper, BoxHelper, ArrowHelper, AxisHelper, CatmullRomCurve3, SplineCurve3, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, ShapePath, Path, Font, CurvePath, Curve, ShapeUtils, SceneUtils, CurveUtils, WireframeGeometry, ParametricGeometry, ParametricBufferGeometry, TetrahedronGeometry, TetrahedronBufferGeometry, OctahedronGeometry, OctahedronBufferGeometry, IcosahedronGeometry, IcosahedronBufferGeometry, DodecahedronGeometry, DodecahedronBufferGeometry, PolyhedronGeometry, PolyhedronBufferGeometry, TubeGeometry, TubeBufferGeometry, TorusKnotGeometry, TorusKnotBufferGeometry, TorusGeometry, TorusBufferGeometry, TextGeometry, SphereBufferGeometry, SphereGeometry, RingGeometry, RingBufferGeometry, PlaneBufferGeometry, PlaneGeometry, LatheGeometry, LatheBufferGeometry, ShapeGeometry, ShapeBufferGeometry, ExtrudeGeometry, EdgesGeometry, ConeGeometry, ConeBufferGeometry, CylinderGeometry, CylinderBufferGeometry, CircleBufferGeometry, CircleGeometry, BoxBufferGeometry, BoxGeometry, ShadowMaterial, SpriteMaterial, RawShaderMaterial, ShaderMaterial, PointsMaterial, MultiMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshPhongMaterial, MeshToonMaterial, MeshNormalMaterial, MeshLambertMaterial, MeshDepthMaterial, MeshBasicMaterial, LineDashedMaterial, LineBasicMaterial, Material, Float64BufferAttribute, Float32BufferAttribute, Uint32BufferAttribute, Int32BufferAttribute, Uint16BufferAttribute, Int16BufferAttribute, Uint8ClampedBufferAttribute, Uint8BufferAttribute, Int8BufferAttribute, BufferAttribute, REVISION, MOUSE, CullFaceNone, CullFaceBack, CullFaceFront, CullFaceFrontBack, FrontFaceDirectionCW, FrontFaceDirectionCCW, BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, FrontSide, BackSide, DoubleSide, FlatShading, SmoothShading, NoColors, FaceColors, VertexColors, NoBlending, NormalBlending, AdditiveBlending, SubtractiveBlending, MultiplyBlending, CustomBlending, BlendingMode, AddEquation, SubtractEquation, ReverseSubtractEquation, MinEquation, MaxEquation, ZeroFactor, OneFactor, SrcColorFactor, OneMinusSrcColorFactor, SrcAlphaFactor, OneMinusSrcAlphaFactor, DstAlphaFactor, OneMinusDstAlphaFactor, DstColorFactor, OneMinusDstColorFactor, SrcAlphaSaturateFactor, NeverDepth, AlwaysDepth, LessDepth, LessEqualDepth, EqualDepth, GreaterEqualDepth, GreaterDepth, NotEqualDepth, MultiplyOperation, MixOperation, AddOperation, NoToneMapping, LinearToneMapping, ReinhardToneMapping, Uncharted2ToneMapping, CineonToneMapping, UVMapping, CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping, SphericalReflectionMapping, CubeUVReflectionMapping, CubeUVRefractionMapping, TextureMapping, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, TextureWrapping, NearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter, LinearFilter, LinearMipMapNearestFilter, LinearMipMapLinearFilter, TextureFilter, UnsignedByteType, ByteType, ShortType, UnsignedShortType, IntType, UnsignedIntType, FloatType, HalfFloatType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedInt248Type, AlphaFormat, RGBFormat, RGBAFormat, LuminanceFormat, LuminanceAlphaFormat, RGBEFormat, DepthFormat, DepthStencilFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, LoopOnce, LoopRepeat, LoopPingPong, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, ZeroCurvatureEnding, ZeroSlopeEnding, WrapAroundEnding, TrianglesDrawMode, TriangleStripDrawMode, TriangleFanDrawMode, LinearEncoding, sRGBEncoding, GammaEncoding, RGBEEncoding, LogLuvEncoding, RGBM7Encoding, RGBM16Encoding, RGBDEncoding, BasicDepthPacking, RGBADepthPacking, BoxGeometry as CubeGeometry, Face4, LineStrip, LinePieces, MeshFaceMaterial, PointCloud, Particle, ParticleSystem, PointCloudMaterial, ParticleBasicMaterial, ParticleSystemMaterial, Vertex, DynamicBufferAttribute, Int8Attribute, Uint8Attribute, Uint8ClampedAttribute, Int16Attribute, Uint16Attribute, Int32Attribute, Uint32Attribute, Float32Attribute, Float64Attribute, ClosedSplineCurve3, BoundingBoxHelper, EdgesHelper, WireframeHelper, XHRLoader, GeometryUtils, ImageUtils, Projector, CanvasRenderer };