three.module.js 980 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721
  1. // Polyfills
  2. if ( Number.EPSILON === undefined ) {
  3. Number.EPSILON = Math.pow( 2, - 52 );
  4. }
  5. if ( Number.isInteger === undefined ) {
  6. // Missing in IE
  7. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  8. Number.isInteger = function ( value ) {
  9. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  10. };
  11. }
  12. //
  13. if ( Math.sign === undefined ) {
  14. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  15. Math.sign = function ( x ) {
  16. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  17. };
  18. }
  19. if ( Function.prototype.name === undefined ) {
  20. // Missing in IE
  21. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  22. Object.defineProperty( Function.prototype, 'name', {
  23. get: function () {
  24. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  25. }
  26. } );
  27. }
  28. if ( Object.assign === undefined ) {
  29. // Missing in IE
  30. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  31. ( function () {
  32. Object.assign = function ( target ) {
  33. 'use strict';
  34. if ( target === undefined || target === null ) {
  35. throw new TypeError( 'Cannot convert undefined or null to object' );
  36. }
  37. var output = Object( target );
  38. for ( var index = 1; index < arguments.length; index ++ ) {
  39. var source = arguments[ index ];
  40. if ( source !== undefined && source !== null ) {
  41. for ( var nextKey in source ) {
  42. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  43. output[ nextKey ] = source[ nextKey ];
  44. }
  45. }
  46. }
  47. }
  48. return output;
  49. };
  50. } )();
  51. }
  52. /**
  53. * https://github.com/mrdoob/eventdispatcher.js/
  54. */
  55. function EventDispatcher() {}
  56. Object.assign( EventDispatcher.prototype, {
  57. addEventListener: function ( type, listener ) {
  58. if ( this._listeners === undefined ) this._listeners = {};
  59. var listeners = this._listeners;
  60. if ( listeners[ type ] === undefined ) {
  61. listeners[ type ] = [];
  62. }
  63. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  64. listeners[ type ].push( listener );
  65. }
  66. },
  67. hasEventListener: function ( type, listener ) {
  68. if ( this._listeners === undefined ) return false;
  69. var listeners = this._listeners;
  70. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  71. },
  72. removeEventListener: function ( type, listener ) {
  73. if ( this._listeners === undefined ) return;
  74. var listeners = this._listeners;
  75. var listenerArray = listeners[ type ];
  76. if ( listenerArray !== undefined ) {
  77. var index = listenerArray.indexOf( listener );
  78. if ( index !== - 1 ) {
  79. listenerArray.splice( index, 1 );
  80. }
  81. }
  82. },
  83. dispatchEvent: function ( event ) {
  84. if ( this._listeners === undefined ) return;
  85. var listeners = this._listeners;
  86. var listenerArray = listeners[ event.type ];
  87. if ( listenerArray !== undefined ) {
  88. event.target = this;
  89. var array = listenerArray.slice( 0 );
  90. for ( var i = 0, l = array.length; i < l; i ++ ) {
  91. array[ i ].call( this, event );
  92. }
  93. }
  94. }
  95. } );
  96. var REVISION = '86';
  97. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  98. var CullFaceNone = 0;
  99. var CullFaceBack = 1;
  100. var CullFaceFront = 2;
  101. var CullFaceFrontBack = 3;
  102. var FrontFaceDirectionCW = 0;
  103. var FrontFaceDirectionCCW = 1;
  104. var BasicShadowMap = 0;
  105. var PCFShadowMap = 1;
  106. var PCFSoftShadowMap = 2;
  107. var FrontSide = 0;
  108. var BackSide = 1;
  109. var DoubleSide = 2;
  110. var FlatShading = 1;
  111. var SmoothShading = 2;
  112. var NoColors = 0;
  113. var FaceColors = 1;
  114. var VertexColors = 2;
  115. var NoBlending = 0;
  116. var NormalBlending = 1;
  117. var AdditiveBlending = 2;
  118. var SubtractiveBlending = 3;
  119. var MultiplyBlending = 4;
  120. var CustomBlending = 5;
  121. var AddEquation = 100;
  122. var SubtractEquation = 101;
  123. var ReverseSubtractEquation = 102;
  124. var MinEquation = 103;
  125. var MaxEquation = 104;
  126. var ZeroFactor = 200;
  127. var OneFactor = 201;
  128. var SrcColorFactor = 202;
  129. var OneMinusSrcColorFactor = 203;
  130. var SrcAlphaFactor = 204;
  131. var OneMinusSrcAlphaFactor = 205;
  132. var DstAlphaFactor = 206;
  133. var OneMinusDstAlphaFactor = 207;
  134. var DstColorFactor = 208;
  135. var OneMinusDstColorFactor = 209;
  136. var SrcAlphaSaturateFactor = 210;
  137. var NeverDepth = 0;
  138. var AlwaysDepth = 1;
  139. var LessDepth = 2;
  140. var LessEqualDepth = 3;
  141. var EqualDepth = 4;
  142. var GreaterEqualDepth = 5;
  143. var GreaterDepth = 6;
  144. var NotEqualDepth = 7;
  145. var MultiplyOperation = 0;
  146. var MixOperation = 1;
  147. var AddOperation = 2;
  148. var NoToneMapping = 0;
  149. var LinearToneMapping = 1;
  150. var ReinhardToneMapping = 2;
  151. var Uncharted2ToneMapping = 3;
  152. var CineonToneMapping = 4;
  153. var UVMapping = 300;
  154. var CubeReflectionMapping = 301;
  155. var CubeRefractionMapping = 302;
  156. var EquirectangularReflectionMapping = 303;
  157. var EquirectangularRefractionMapping = 304;
  158. var SphericalReflectionMapping = 305;
  159. var CubeUVReflectionMapping = 306;
  160. var CubeUVRefractionMapping = 307;
  161. var RepeatWrapping = 1000;
  162. var ClampToEdgeWrapping = 1001;
  163. var MirroredRepeatWrapping = 1002;
  164. var NearestFilter = 1003;
  165. var NearestMipMapNearestFilter = 1004;
  166. var NearestMipMapLinearFilter = 1005;
  167. var LinearFilter = 1006;
  168. var LinearMipMapNearestFilter = 1007;
  169. var LinearMipMapLinearFilter = 1008;
  170. var UnsignedByteType = 1009;
  171. var ByteType = 1010;
  172. var ShortType = 1011;
  173. var UnsignedShortType = 1012;
  174. var IntType = 1013;
  175. var UnsignedIntType = 1014;
  176. var FloatType = 1015;
  177. var HalfFloatType = 1016;
  178. var UnsignedShort4444Type = 1017;
  179. var UnsignedShort5551Type = 1018;
  180. var UnsignedShort565Type = 1019;
  181. var UnsignedInt248Type = 1020;
  182. var AlphaFormat = 1021;
  183. var RGBFormat = 1022;
  184. var RGBAFormat = 1023;
  185. var LuminanceFormat = 1024;
  186. var LuminanceAlphaFormat = 1025;
  187. var RGBEFormat = RGBAFormat;
  188. var DepthFormat = 1026;
  189. var DepthStencilFormat = 1027;
  190. var RGB_S3TC_DXT1_Format = 2001;
  191. var RGBA_S3TC_DXT1_Format = 2002;
  192. var RGBA_S3TC_DXT3_Format = 2003;
  193. var RGBA_S3TC_DXT5_Format = 2004;
  194. var RGB_PVRTC_4BPPV1_Format = 2100;
  195. var RGB_PVRTC_2BPPV1_Format = 2101;
  196. var RGBA_PVRTC_4BPPV1_Format = 2102;
  197. var RGBA_PVRTC_2BPPV1_Format = 2103;
  198. var RGB_ETC1_Format = 2151;
  199. var LoopOnce = 2200;
  200. var LoopRepeat = 2201;
  201. var LoopPingPong = 2202;
  202. var InterpolateDiscrete = 2300;
  203. var InterpolateLinear = 2301;
  204. var InterpolateSmooth = 2302;
  205. var ZeroCurvatureEnding = 2400;
  206. var ZeroSlopeEnding = 2401;
  207. var WrapAroundEnding = 2402;
  208. var TrianglesDrawMode = 0;
  209. var TriangleStripDrawMode = 1;
  210. var TriangleFanDrawMode = 2;
  211. var LinearEncoding = 3000;
  212. var sRGBEncoding = 3001;
  213. var GammaEncoding = 3007;
  214. var RGBEEncoding = 3002;
  215. var LogLuvEncoding = 3003;
  216. var RGBM7Encoding = 3004;
  217. var RGBM16Encoding = 3005;
  218. var RGBDEncoding = 3006;
  219. var BasicDepthPacking = 3200;
  220. var RGBADepthPacking = 3201;
  221. /**
  222. * @author alteredq / http://alteredqualia.com/
  223. * @author mrdoob / http://mrdoob.com/
  224. */
  225. var _Math = {
  226. DEG2RAD: Math.PI / 180,
  227. RAD2DEG: 180 / Math.PI,
  228. generateUUID: function () {
  229. // http://www.broofa.com/Tools/Math.uuid.htm
  230. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  231. var uuid = new Array( 36 );
  232. var rnd = 0, r;
  233. return function generateUUID() {
  234. for ( var i = 0; i < 36; i ++ ) {
  235. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  236. uuid[ i ] = '-';
  237. } else if ( i === 14 ) {
  238. uuid[ i ] = '4';
  239. } else {
  240. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  241. r = rnd & 0xf;
  242. rnd = rnd >> 4;
  243. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  244. }
  245. }
  246. return uuid.join( '' );
  247. };
  248. }(),
  249. clamp: function ( value, min, max ) {
  250. return Math.max( min, Math.min( max, value ) );
  251. },
  252. // compute euclidian modulo of m % n
  253. // https://en.wikipedia.org/wiki/Modulo_operation
  254. euclideanModulo: function ( n, m ) {
  255. return ( ( n % m ) + m ) % m;
  256. },
  257. // Linear mapping from range <a1, a2> to range <b1, b2>
  258. mapLinear: function ( x, a1, a2, b1, b2 ) {
  259. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  260. },
  261. // https://en.wikipedia.org/wiki/Linear_interpolation
  262. lerp: function ( x, y, t ) {
  263. return ( 1 - t ) * x + t * y;
  264. },
  265. // http://en.wikipedia.org/wiki/Smoothstep
  266. smoothstep: function ( x, min, max ) {
  267. if ( x <= min ) return 0;
  268. if ( x >= max ) return 1;
  269. x = ( x - min ) / ( max - min );
  270. return x * x * ( 3 - 2 * x );
  271. },
  272. smootherstep: function ( x, min, max ) {
  273. if ( x <= min ) return 0;
  274. if ( x >= max ) return 1;
  275. x = ( x - min ) / ( max - min );
  276. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  277. },
  278. // Random integer from <low, high> interval
  279. randInt: function ( low, high ) {
  280. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  281. },
  282. // Random float from <low, high> interval
  283. randFloat: function ( low, high ) {
  284. return low + Math.random() * ( high - low );
  285. },
  286. // Random float from <-range/2, range/2> interval
  287. randFloatSpread: function ( range ) {
  288. return range * ( 0.5 - Math.random() );
  289. },
  290. degToRad: function ( degrees ) {
  291. return degrees * _Math.DEG2RAD;
  292. },
  293. radToDeg: function ( radians ) {
  294. return radians * _Math.RAD2DEG;
  295. },
  296. isPowerOfTwo: function ( value ) {
  297. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  298. },
  299. nearestPowerOfTwo: function ( value ) {
  300. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  301. },
  302. nextPowerOfTwo: function ( value ) {
  303. value --;
  304. value |= value >> 1;
  305. value |= value >> 2;
  306. value |= value >> 4;
  307. value |= value >> 8;
  308. value |= value >> 16;
  309. value ++;
  310. return value;
  311. }
  312. };
  313. /**
  314. * @author mrdoob / http://mrdoob.com/
  315. * @author philogb / http://blog.thejit.org/
  316. * @author egraether / http://egraether.com/
  317. * @author zz85 / http://www.lab4games.net/zz85/blog
  318. */
  319. function Vector2( x, y ) {
  320. this.x = x || 0;
  321. this.y = y || 0;
  322. }
  323. Object.defineProperties( Vector2.prototype, {
  324. "width" : {
  325. get: function () {
  326. return this.x;
  327. },
  328. set: function ( value ) {
  329. this.x = value;
  330. }
  331. },
  332. "height" : {
  333. get: function () {
  334. return this.y;
  335. },
  336. set: function ( value ) {
  337. this.y = value;
  338. }
  339. }
  340. } );
  341. Object.assign( Vector2.prototype, {
  342. isVector2: true,
  343. set: function ( x, y ) {
  344. this.x = x;
  345. this.y = y;
  346. return this;
  347. },
  348. setScalar: function ( scalar ) {
  349. this.x = scalar;
  350. this.y = scalar;
  351. return this;
  352. },
  353. setX: function ( x ) {
  354. this.x = x;
  355. return this;
  356. },
  357. setY: function ( y ) {
  358. this.y = y;
  359. return this;
  360. },
  361. setComponent: function ( index, value ) {
  362. switch ( index ) {
  363. case 0: this.x = value; break;
  364. case 1: this.y = value; break;
  365. default: throw new Error( 'index is out of range: ' + index );
  366. }
  367. return this;
  368. },
  369. getComponent: function ( index ) {
  370. switch ( index ) {
  371. case 0: return this.x;
  372. case 1: return this.y;
  373. default: throw new Error( 'index is out of range: ' + index );
  374. }
  375. },
  376. clone: function () {
  377. return new this.constructor( this.x, this.y );
  378. },
  379. copy: function ( v ) {
  380. this.x = v.x;
  381. this.y = v.y;
  382. return this;
  383. },
  384. add: function ( v, w ) {
  385. if ( w !== undefined ) {
  386. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  387. return this.addVectors( v, w );
  388. }
  389. this.x += v.x;
  390. this.y += v.y;
  391. return this;
  392. },
  393. addScalar: function ( s ) {
  394. this.x += s;
  395. this.y += s;
  396. return this;
  397. },
  398. addVectors: function ( a, b ) {
  399. this.x = a.x + b.x;
  400. this.y = a.y + b.y;
  401. return this;
  402. },
  403. addScaledVector: function ( v, s ) {
  404. this.x += v.x * s;
  405. this.y += v.y * s;
  406. return this;
  407. },
  408. sub: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  411. return this.subVectors( v, w );
  412. }
  413. this.x -= v.x;
  414. this.y -= v.y;
  415. return this;
  416. },
  417. subScalar: function ( s ) {
  418. this.x -= s;
  419. this.y -= s;
  420. return this;
  421. },
  422. subVectors: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. multiply: function ( v ) {
  428. this.x *= v.x;
  429. this.y *= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( scalar ) {
  433. this.x *= scalar;
  434. this.y *= scalar;
  435. return this;
  436. },
  437. divide: function ( v ) {
  438. this.x /= v.x;
  439. this.y /= v.y;
  440. return this;
  441. },
  442. divideScalar: function ( scalar ) {
  443. return this.multiplyScalar( 1 / scalar );
  444. },
  445. min: function ( v ) {
  446. this.x = Math.min( this.x, v.x );
  447. this.y = Math.min( this.y, v.y );
  448. return this;
  449. },
  450. max: function ( v ) {
  451. this.x = Math.max( this.x, v.x );
  452. this.y = Math.max( this.y, v.y );
  453. return this;
  454. },
  455. clamp: function ( min, max ) {
  456. // assumes min < max, componentwise
  457. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  458. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  459. return this;
  460. },
  461. clampScalar: function () {
  462. var min = new Vector2();
  463. var max = new Vector2();
  464. return function clampScalar( minVal, maxVal ) {
  465. min.set( minVal, minVal );
  466. max.set( maxVal, maxVal );
  467. return this.clamp( min, max );
  468. };
  469. }(),
  470. clampLength: function ( min, max ) {
  471. var length = this.length();
  472. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  473. },
  474. floor: function () {
  475. this.x = Math.floor( this.x );
  476. this.y = Math.floor( this.y );
  477. return this;
  478. },
  479. ceil: function () {
  480. this.x = Math.ceil( this.x );
  481. this.y = Math.ceil( this.y );
  482. return this;
  483. },
  484. round: function () {
  485. this.x = Math.round( this.x );
  486. this.y = Math.round( this.y );
  487. return this;
  488. },
  489. roundToZero: function () {
  490. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  491. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  492. return this;
  493. },
  494. negate: function () {
  495. this.x = - this.x;
  496. this.y = - this.y;
  497. return this;
  498. },
  499. dot: function ( v ) {
  500. return this.x * v.x + this.y * v.y;
  501. },
  502. lengthSq: function () {
  503. return this.x * this.x + this.y * this.y;
  504. },
  505. length: function () {
  506. return Math.sqrt( this.x * this.x + this.y * this.y );
  507. },
  508. lengthManhattan: function() {
  509. return Math.abs( this.x ) + Math.abs( this.y );
  510. },
  511. normalize: function () {
  512. return this.divideScalar( this.length() || 1 );
  513. },
  514. angle: function () {
  515. // computes the angle in radians with respect to the positive x-axis
  516. var angle = Math.atan2( this.y, this.x );
  517. if ( angle < 0 ) angle += 2 * Math.PI;
  518. return angle;
  519. },
  520. distanceTo: function ( v ) {
  521. return Math.sqrt( this.distanceToSquared( v ) );
  522. },
  523. distanceToSquared: function ( v ) {
  524. var dx = this.x - v.x, dy = this.y - v.y;
  525. return dx * dx + dy * dy;
  526. },
  527. distanceToManhattan: function ( v ) {
  528. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  529. },
  530. setLength: function ( length ) {
  531. return this.normalize().multiplyScalar( length );
  532. },
  533. lerp: function ( v, alpha ) {
  534. this.x += ( v.x - this.x ) * alpha;
  535. this.y += ( v.y - this.y ) * alpha;
  536. return this;
  537. },
  538. lerpVectors: function ( v1, v2, alpha ) {
  539. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  540. },
  541. equals: function ( v ) {
  542. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  543. },
  544. fromArray: function ( array, offset ) {
  545. if ( offset === undefined ) offset = 0;
  546. this.x = array[ offset ];
  547. this.y = array[ offset + 1 ];
  548. return this;
  549. },
  550. toArray: function ( array, offset ) {
  551. if ( array === undefined ) array = [];
  552. if ( offset === undefined ) offset = 0;
  553. array[ offset ] = this.x;
  554. array[ offset + 1 ] = this.y;
  555. return array;
  556. },
  557. fromBufferAttribute: function ( attribute, index, offset ) {
  558. if ( offset !== undefined ) {
  559. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  560. }
  561. this.x = attribute.getX( index );
  562. this.y = attribute.getY( index );
  563. return this;
  564. },
  565. rotateAround: function ( center, angle ) {
  566. var c = Math.cos( angle ), s = Math.sin( angle );
  567. var x = this.x - center.x;
  568. var y = this.y - center.y;
  569. this.x = x * c - y * s + center.x;
  570. this.y = x * s + y * c + center.y;
  571. return this;
  572. }
  573. } );
  574. /**
  575. * @author mrdoob / http://mrdoob.com/
  576. * @author alteredq / http://alteredqualia.com/
  577. * @author szimek / https://github.com/szimek/
  578. */
  579. var textureId = 0;
  580. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  581. Object.defineProperty( this, 'id', { value: textureId ++ } );
  582. this.uuid = _Math.generateUUID();
  583. this.name = '';
  584. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  585. this.mipmaps = [];
  586. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  587. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  588. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  589. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  590. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  591. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  592. this.format = format !== undefined ? format : RGBAFormat;
  593. this.type = type !== undefined ? type : UnsignedByteType;
  594. this.offset = new Vector2( 0, 0 );
  595. this.repeat = new Vector2( 1, 1 );
  596. this.generateMipmaps = true;
  597. this.premultiplyAlpha = false;
  598. this.flipY = true;
  599. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  600. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  601. //
  602. // Also changing the encoding after already used by a Material will not automatically make the Material
  603. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  604. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  605. this.version = 0;
  606. this.onUpdate = null;
  607. }
  608. Texture.DEFAULT_IMAGE = undefined;
  609. Texture.DEFAULT_MAPPING = UVMapping;
  610. Object.defineProperty( Texture.prototype, "needsUpdate", {
  611. set: function ( value ) {
  612. if ( value === true ) this.version ++;
  613. }
  614. } );
  615. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  616. constructor: Texture,
  617. isTexture: true,
  618. clone: function () {
  619. return new this.constructor().copy( this );
  620. },
  621. copy: function ( source ) {
  622. this.name = source.name;
  623. this.image = source.image;
  624. this.mipmaps = source.mipmaps.slice( 0 );
  625. this.mapping = source.mapping;
  626. this.wrapS = source.wrapS;
  627. this.wrapT = source.wrapT;
  628. this.magFilter = source.magFilter;
  629. this.minFilter = source.minFilter;
  630. this.anisotropy = source.anisotropy;
  631. this.format = source.format;
  632. this.type = source.type;
  633. this.offset.copy( source.offset );
  634. this.repeat.copy( source.repeat );
  635. this.generateMipmaps = source.generateMipmaps;
  636. this.premultiplyAlpha = source.premultiplyAlpha;
  637. this.flipY = source.flipY;
  638. this.unpackAlignment = source.unpackAlignment;
  639. this.encoding = source.encoding;
  640. return this;
  641. },
  642. toJSON: function ( meta ) {
  643. if ( meta.textures[ this.uuid ] !== undefined ) {
  644. return meta.textures[ this.uuid ];
  645. }
  646. function getDataURL( image ) {
  647. var canvas;
  648. if ( image.toDataURL !== undefined ) {
  649. canvas = image;
  650. } else {
  651. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  652. canvas.width = image.width;
  653. canvas.height = image.height;
  654. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  655. }
  656. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  657. return canvas.toDataURL( 'image/jpeg', 0.6 );
  658. } else {
  659. return canvas.toDataURL( 'image/png' );
  660. }
  661. }
  662. var output = {
  663. metadata: {
  664. version: 4.5,
  665. type: 'Texture',
  666. generator: 'Texture.toJSON'
  667. },
  668. uuid: this.uuid,
  669. name: this.name,
  670. mapping: this.mapping,
  671. repeat: [ this.repeat.x, this.repeat.y ],
  672. offset: [ this.offset.x, this.offset.y ],
  673. wrap: [ this.wrapS, this.wrapT ],
  674. minFilter: this.minFilter,
  675. magFilter: this.magFilter,
  676. anisotropy: this.anisotropy,
  677. flipY: this.flipY
  678. };
  679. if ( this.image !== undefined ) {
  680. // TODO: Move to THREE.Image
  681. var image = this.image;
  682. if ( image.uuid === undefined ) {
  683. image.uuid = _Math.generateUUID(); // UGH
  684. }
  685. if ( meta.images[ image.uuid ] === undefined ) {
  686. meta.images[ image.uuid ] = {
  687. uuid: image.uuid,
  688. url: getDataURL( image )
  689. };
  690. }
  691. output.image = image.uuid;
  692. }
  693. meta.textures[ this.uuid ] = output;
  694. return output;
  695. },
  696. dispose: function () {
  697. this.dispatchEvent( { type: 'dispose' } );
  698. },
  699. transformUv: function ( uv ) {
  700. if ( this.mapping !== UVMapping ) return;
  701. uv.multiply( this.repeat );
  702. uv.add( this.offset );
  703. if ( uv.x < 0 || uv.x > 1 ) {
  704. switch ( this.wrapS ) {
  705. case RepeatWrapping:
  706. uv.x = uv.x - Math.floor( uv.x );
  707. break;
  708. case ClampToEdgeWrapping:
  709. uv.x = uv.x < 0 ? 0 : 1;
  710. break;
  711. case MirroredRepeatWrapping:
  712. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  713. uv.x = Math.ceil( uv.x ) - uv.x;
  714. } else {
  715. uv.x = uv.x - Math.floor( uv.x );
  716. }
  717. break;
  718. }
  719. }
  720. if ( uv.y < 0 || uv.y > 1 ) {
  721. switch ( this.wrapT ) {
  722. case RepeatWrapping:
  723. uv.y = uv.y - Math.floor( uv.y );
  724. break;
  725. case ClampToEdgeWrapping:
  726. uv.y = uv.y < 0 ? 0 : 1;
  727. break;
  728. case MirroredRepeatWrapping:
  729. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  730. uv.y = Math.ceil( uv.y ) - uv.y;
  731. } else {
  732. uv.y = uv.y - Math.floor( uv.y );
  733. }
  734. break;
  735. }
  736. }
  737. if ( this.flipY ) {
  738. uv.y = 1 - uv.y;
  739. }
  740. }
  741. } );
  742. /**
  743. * @author supereggbert / http://www.paulbrunt.co.uk/
  744. * @author philogb / http://blog.thejit.org/
  745. * @author mikael emtinger / http://gomo.se/
  746. * @author egraether / http://egraether.com/
  747. * @author WestLangley / http://github.com/WestLangley
  748. */
  749. function Vector4( x, y, z, w ) {
  750. this.x = x || 0;
  751. this.y = y || 0;
  752. this.z = z || 0;
  753. this.w = ( w !== undefined ) ? w : 1;
  754. }
  755. Object.assign( Vector4.prototype, {
  756. isVector4: true,
  757. set: function ( x, y, z, w ) {
  758. this.x = x;
  759. this.y = y;
  760. this.z = z;
  761. this.w = w;
  762. return this;
  763. },
  764. setScalar: function ( scalar ) {
  765. this.x = scalar;
  766. this.y = scalar;
  767. this.z = scalar;
  768. this.w = scalar;
  769. return this;
  770. },
  771. setX: function ( x ) {
  772. this.x = x;
  773. return this;
  774. },
  775. setY: function ( y ) {
  776. this.y = y;
  777. return this;
  778. },
  779. setZ: function ( z ) {
  780. this.z = z;
  781. return this;
  782. },
  783. setW: function ( w ) {
  784. this.w = w;
  785. return this;
  786. },
  787. setComponent: function ( index, value ) {
  788. switch ( index ) {
  789. case 0: this.x = value; break;
  790. case 1: this.y = value; break;
  791. case 2: this.z = value; break;
  792. case 3: this.w = value; break;
  793. default: throw new Error( 'index is out of range: ' + index );
  794. }
  795. return this;
  796. },
  797. getComponent: function ( index ) {
  798. switch ( index ) {
  799. case 0: return this.x;
  800. case 1: return this.y;
  801. case 2: return this.z;
  802. case 3: return this.w;
  803. default: throw new Error( 'index is out of range: ' + index );
  804. }
  805. },
  806. clone: function () {
  807. return new this.constructor( this.x, this.y, this.z, this.w );
  808. },
  809. copy: function ( v ) {
  810. this.x = v.x;
  811. this.y = v.y;
  812. this.z = v.z;
  813. this.w = ( v.w !== undefined ) ? v.w : 1;
  814. return this;
  815. },
  816. add: function ( v, w ) {
  817. if ( w !== undefined ) {
  818. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  819. return this.addVectors( v, w );
  820. }
  821. this.x += v.x;
  822. this.y += v.y;
  823. this.z += v.z;
  824. this.w += v.w;
  825. return this;
  826. },
  827. addScalar: function ( s ) {
  828. this.x += s;
  829. this.y += s;
  830. this.z += s;
  831. this.w += s;
  832. return this;
  833. },
  834. addVectors: function ( a, b ) {
  835. this.x = a.x + b.x;
  836. this.y = a.y + b.y;
  837. this.z = a.z + b.z;
  838. this.w = a.w + b.w;
  839. return this;
  840. },
  841. addScaledVector: function ( v, s ) {
  842. this.x += v.x * s;
  843. this.y += v.y * s;
  844. this.z += v.z * s;
  845. this.w += v.w * s;
  846. return this;
  847. },
  848. sub: function ( v, w ) {
  849. if ( w !== undefined ) {
  850. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  851. return this.subVectors( v, w );
  852. }
  853. this.x -= v.x;
  854. this.y -= v.y;
  855. this.z -= v.z;
  856. this.w -= v.w;
  857. return this;
  858. },
  859. subScalar: function ( s ) {
  860. this.x -= s;
  861. this.y -= s;
  862. this.z -= s;
  863. this.w -= s;
  864. return this;
  865. },
  866. subVectors: function ( a, b ) {
  867. this.x = a.x - b.x;
  868. this.y = a.y - b.y;
  869. this.z = a.z - b.z;
  870. this.w = a.w - b.w;
  871. return this;
  872. },
  873. multiplyScalar: function ( scalar ) {
  874. this.x *= scalar;
  875. this.y *= scalar;
  876. this.z *= scalar;
  877. this.w *= scalar;
  878. return this;
  879. },
  880. applyMatrix4: function ( m ) {
  881. var x = this.x, y = this.y, z = this.z, w = this.w;
  882. var e = m.elements;
  883. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  884. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  885. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  886. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  887. return this;
  888. },
  889. divideScalar: function ( scalar ) {
  890. return this.multiplyScalar( 1 / scalar );
  891. },
  892. setAxisAngleFromQuaternion: function ( q ) {
  893. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  894. // q is assumed to be normalized
  895. this.w = 2 * Math.acos( q.w );
  896. var s = Math.sqrt( 1 - q.w * q.w );
  897. if ( s < 0.0001 ) {
  898. this.x = 1;
  899. this.y = 0;
  900. this.z = 0;
  901. } else {
  902. this.x = q.x / s;
  903. this.y = q.y / s;
  904. this.z = q.z / s;
  905. }
  906. return this;
  907. },
  908. setAxisAngleFromRotationMatrix: function ( m ) {
  909. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  910. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  911. var angle, x, y, z, // variables for result
  912. epsilon = 0.01, // margin to allow for rounding errors
  913. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  914. te = m.elements,
  915. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  916. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  917. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  918. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  919. ( Math.abs( m13 - m31 ) < epsilon ) &&
  920. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  921. // singularity found
  922. // first check for identity matrix which must have +1 for all terms
  923. // in leading diagonal and zero in other terms
  924. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  925. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  926. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  927. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  928. // this singularity is identity matrix so angle = 0
  929. this.set( 1, 0, 0, 0 );
  930. return this; // zero angle, arbitrary axis
  931. }
  932. // otherwise this singularity is angle = 180
  933. angle = Math.PI;
  934. var xx = ( m11 + 1 ) / 2;
  935. var yy = ( m22 + 1 ) / 2;
  936. var zz = ( m33 + 1 ) / 2;
  937. var xy = ( m12 + m21 ) / 4;
  938. var xz = ( m13 + m31 ) / 4;
  939. var yz = ( m23 + m32 ) / 4;
  940. if ( ( xx > yy ) && ( xx > zz ) ) {
  941. // m11 is the largest diagonal term
  942. if ( xx < epsilon ) {
  943. x = 0;
  944. y = 0.707106781;
  945. z = 0.707106781;
  946. } else {
  947. x = Math.sqrt( xx );
  948. y = xy / x;
  949. z = xz / x;
  950. }
  951. } else if ( yy > zz ) {
  952. // m22 is the largest diagonal term
  953. if ( yy < epsilon ) {
  954. x = 0.707106781;
  955. y = 0;
  956. z = 0.707106781;
  957. } else {
  958. y = Math.sqrt( yy );
  959. x = xy / y;
  960. z = yz / y;
  961. }
  962. } else {
  963. // m33 is the largest diagonal term so base result on this
  964. if ( zz < epsilon ) {
  965. x = 0.707106781;
  966. y = 0.707106781;
  967. z = 0;
  968. } else {
  969. z = Math.sqrt( zz );
  970. x = xz / z;
  971. y = yz / z;
  972. }
  973. }
  974. this.set( x, y, z, angle );
  975. return this; // return 180 deg rotation
  976. }
  977. // as we have reached here there are no singularities so we can handle normally
  978. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  979. ( m13 - m31 ) * ( m13 - m31 ) +
  980. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  981. if ( Math.abs( s ) < 0.001 ) s = 1;
  982. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  983. // caught by singularity test above, but I've left it in just in case
  984. this.x = ( m32 - m23 ) / s;
  985. this.y = ( m13 - m31 ) / s;
  986. this.z = ( m21 - m12 ) / s;
  987. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  988. return this;
  989. },
  990. min: function ( v ) {
  991. this.x = Math.min( this.x, v.x );
  992. this.y = Math.min( this.y, v.y );
  993. this.z = Math.min( this.z, v.z );
  994. this.w = Math.min( this.w, v.w );
  995. return this;
  996. },
  997. max: function ( v ) {
  998. this.x = Math.max( this.x, v.x );
  999. this.y = Math.max( this.y, v.y );
  1000. this.z = Math.max( this.z, v.z );
  1001. this.w = Math.max( this.w, v.w );
  1002. return this;
  1003. },
  1004. clamp: function ( min, max ) {
  1005. // assumes min < max, componentwise
  1006. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1007. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1008. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1009. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1010. return this;
  1011. },
  1012. clampScalar: function () {
  1013. var min, max;
  1014. return function clampScalar( minVal, maxVal ) {
  1015. if ( min === undefined ) {
  1016. min = new Vector4();
  1017. max = new Vector4();
  1018. }
  1019. min.set( minVal, minVal, minVal, minVal );
  1020. max.set( maxVal, maxVal, maxVal, maxVal );
  1021. return this.clamp( min, max );
  1022. };
  1023. }(),
  1024. clampLength: function ( min, max ) {
  1025. var length = this.length();
  1026. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1027. },
  1028. floor: function () {
  1029. this.x = Math.floor( this.x );
  1030. this.y = Math.floor( this.y );
  1031. this.z = Math.floor( this.z );
  1032. this.w = Math.floor( this.w );
  1033. return this;
  1034. },
  1035. ceil: function () {
  1036. this.x = Math.ceil( this.x );
  1037. this.y = Math.ceil( this.y );
  1038. this.z = Math.ceil( this.z );
  1039. this.w = Math.ceil( this.w );
  1040. return this;
  1041. },
  1042. round: function () {
  1043. this.x = Math.round( this.x );
  1044. this.y = Math.round( this.y );
  1045. this.z = Math.round( this.z );
  1046. this.w = Math.round( this.w );
  1047. return this;
  1048. },
  1049. roundToZero: function () {
  1050. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1051. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1052. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1053. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1054. return this;
  1055. },
  1056. negate: function () {
  1057. this.x = - this.x;
  1058. this.y = - this.y;
  1059. this.z = - this.z;
  1060. this.w = - this.w;
  1061. return this;
  1062. },
  1063. dot: function ( v ) {
  1064. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1065. },
  1066. lengthSq: function () {
  1067. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1068. },
  1069. length: function () {
  1070. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1071. },
  1072. lengthManhattan: function () {
  1073. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1074. },
  1075. normalize: function () {
  1076. return this.divideScalar( this.length() || 1 );
  1077. },
  1078. setLength: function ( length ) {
  1079. return this.normalize().multiplyScalar( length );
  1080. },
  1081. lerp: function ( v, alpha ) {
  1082. this.x += ( v.x - this.x ) * alpha;
  1083. this.y += ( v.y - this.y ) * alpha;
  1084. this.z += ( v.z - this.z ) * alpha;
  1085. this.w += ( v.w - this.w ) * alpha;
  1086. return this;
  1087. },
  1088. lerpVectors: function ( v1, v2, alpha ) {
  1089. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1090. },
  1091. equals: function ( v ) {
  1092. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1093. },
  1094. fromArray: function ( array, offset ) {
  1095. if ( offset === undefined ) offset = 0;
  1096. this.x = array[ offset ];
  1097. this.y = array[ offset + 1 ];
  1098. this.z = array[ offset + 2 ];
  1099. this.w = array[ offset + 3 ];
  1100. return this;
  1101. },
  1102. toArray: function ( array, offset ) {
  1103. if ( array === undefined ) array = [];
  1104. if ( offset === undefined ) offset = 0;
  1105. array[ offset ] = this.x;
  1106. array[ offset + 1 ] = this.y;
  1107. array[ offset + 2 ] = this.z;
  1108. array[ offset + 3 ] = this.w;
  1109. return array;
  1110. },
  1111. fromBufferAttribute: function ( attribute, index, offset ) {
  1112. if ( offset !== undefined ) {
  1113. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1114. }
  1115. this.x = attribute.getX( index );
  1116. this.y = attribute.getY( index );
  1117. this.z = attribute.getZ( index );
  1118. this.w = attribute.getW( index );
  1119. return this;
  1120. }
  1121. } );
  1122. /**
  1123. * @author szimek / https://github.com/szimek/
  1124. * @author alteredq / http://alteredqualia.com/
  1125. * @author Marius Kintel / https://github.com/kintel
  1126. */
  1127. /*
  1128. In options, we can specify:
  1129. * Texture parameters for an auto-generated target texture
  1130. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1131. */
  1132. function WebGLRenderTarget( width, height, options ) {
  1133. this.uuid = _Math.generateUUID();
  1134. this.width = width;
  1135. this.height = height;
  1136. this.scissor = new Vector4( 0, 0, width, height );
  1137. this.scissorTest = false;
  1138. this.viewport = new Vector4( 0, 0, width, height );
  1139. options = options || {};
  1140. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1141. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1142. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1143. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1144. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1145. }
  1146. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1147. isWebGLRenderTarget: true,
  1148. setSize: function ( width, height ) {
  1149. if ( this.width !== width || this.height !== height ) {
  1150. this.width = width;
  1151. this.height = height;
  1152. this.dispose();
  1153. }
  1154. this.viewport.set( 0, 0, width, height );
  1155. this.scissor.set( 0, 0, width, height );
  1156. },
  1157. clone: function () {
  1158. return new this.constructor().copy( this );
  1159. },
  1160. copy: function ( source ) {
  1161. this.width = source.width;
  1162. this.height = source.height;
  1163. this.viewport.copy( source.viewport );
  1164. this.texture = source.texture.clone();
  1165. this.depthBuffer = source.depthBuffer;
  1166. this.stencilBuffer = source.stencilBuffer;
  1167. this.depthTexture = source.depthTexture;
  1168. return this;
  1169. },
  1170. dispose: function () {
  1171. this.dispatchEvent( { type: 'dispose' } );
  1172. }
  1173. } );
  1174. /**
  1175. * @author alteredq / http://alteredqualia.com
  1176. */
  1177. function WebGLRenderTargetCube( width, height, options ) {
  1178. WebGLRenderTarget.call( this, width, height, options );
  1179. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1180. this.activeMipMapLevel = 0;
  1181. }
  1182. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1183. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1184. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1185. /**
  1186. * @author mikael emtinger / http://gomo.se/
  1187. * @author alteredq / http://alteredqualia.com/
  1188. * @author WestLangley / http://github.com/WestLangley
  1189. * @author bhouston / http://clara.io
  1190. */
  1191. function Quaternion( x, y, z, w ) {
  1192. this._x = x || 0;
  1193. this._y = y || 0;
  1194. this._z = z || 0;
  1195. this._w = ( w !== undefined ) ? w : 1;
  1196. }
  1197. Object.assign( Quaternion, {
  1198. slerp: function ( qa, qb, qm, t ) {
  1199. return qm.copy( qa ).slerp( qb, t );
  1200. },
  1201. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1202. // fuzz-free, array-based Quaternion SLERP operation
  1203. var x0 = src0[ srcOffset0 + 0 ],
  1204. y0 = src0[ srcOffset0 + 1 ],
  1205. z0 = src0[ srcOffset0 + 2 ],
  1206. w0 = src0[ srcOffset0 + 3 ],
  1207. x1 = src1[ srcOffset1 + 0 ],
  1208. y1 = src1[ srcOffset1 + 1 ],
  1209. z1 = src1[ srcOffset1 + 2 ],
  1210. w1 = src1[ srcOffset1 + 3 ];
  1211. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1212. var s = 1 - t,
  1213. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1214. dir = ( cos >= 0 ? 1 : - 1 ),
  1215. sqrSin = 1 - cos * cos;
  1216. // Skip the Slerp for tiny steps to avoid numeric problems:
  1217. if ( sqrSin > Number.EPSILON ) {
  1218. var sin = Math.sqrt( sqrSin ),
  1219. len = Math.atan2( sin, cos * dir );
  1220. s = Math.sin( s * len ) / sin;
  1221. t = Math.sin( t * len ) / sin;
  1222. }
  1223. var tDir = t * dir;
  1224. x0 = x0 * s + x1 * tDir;
  1225. y0 = y0 * s + y1 * tDir;
  1226. z0 = z0 * s + z1 * tDir;
  1227. w0 = w0 * s + w1 * tDir;
  1228. // Normalize in case we just did a lerp:
  1229. if ( s === 1 - t ) {
  1230. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1231. x0 *= f;
  1232. y0 *= f;
  1233. z0 *= f;
  1234. w0 *= f;
  1235. }
  1236. }
  1237. dst[ dstOffset ] = x0;
  1238. dst[ dstOffset + 1 ] = y0;
  1239. dst[ dstOffset + 2 ] = z0;
  1240. dst[ dstOffset + 3 ] = w0;
  1241. }
  1242. } );
  1243. Object.defineProperties( Quaternion.prototype, {
  1244. x: {
  1245. get: function () {
  1246. return this._x;
  1247. },
  1248. set: function ( value ) {
  1249. this._x = value;
  1250. this.onChangeCallback();
  1251. }
  1252. },
  1253. y: {
  1254. get: function () {
  1255. return this._y;
  1256. },
  1257. set: function ( value ) {
  1258. this._y = value;
  1259. this.onChangeCallback();
  1260. }
  1261. },
  1262. z: {
  1263. get: function () {
  1264. return this._z;
  1265. },
  1266. set: function ( value ) {
  1267. this._z = value;
  1268. this.onChangeCallback();
  1269. }
  1270. },
  1271. w: {
  1272. get: function () {
  1273. return this._w;
  1274. },
  1275. set: function ( value ) {
  1276. this._w = value;
  1277. this.onChangeCallback();
  1278. }
  1279. }
  1280. } );
  1281. Object.assign( Quaternion.prototype, {
  1282. set: function ( x, y, z, w ) {
  1283. this._x = x;
  1284. this._y = y;
  1285. this._z = z;
  1286. this._w = w;
  1287. this.onChangeCallback();
  1288. return this;
  1289. },
  1290. clone: function () {
  1291. return new this.constructor( this._x, this._y, this._z, this._w );
  1292. },
  1293. copy: function ( quaternion ) {
  1294. this._x = quaternion.x;
  1295. this._y = quaternion.y;
  1296. this._z = quaternion.z;
  1297. this._w = quaternion.w;
  1298. this.onChangeCallback();
  1299. return this;
  1300. },
  1301. setFromEuler: function ( euler, update ) {
  1302. if ( ! ( euler && euler.isEuler ) ) {
  1303. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1304. }
  1305. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1306. // http://www.mathworks.com/matlabcentral/fileexchange/
  1307. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1308. // content/SpinCalc.m
  1309. var cos = Math.cos;
  1310. var sin = Math.sin;
  1311. var c1 = cos( x / 2 );
  1312. var c2 = cos( y / 2 );
  1313. var c3 = cos( z / 2 );
  1314. var s1 = sin( x / 2 );
  1315. var s2 = sin( y / 2 );
  1316. var s3 = sin( z / 2 );
  1317. if ( order === 'XYZ' ) {
  1318. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1319. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1320. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1321. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1322. } else if ( order === 'YXZ' ) {
  1323. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1324. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1325. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1326. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1327. } else if ( order === 'ZXY' ) {
  1328. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1329. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1330. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1331. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1332. } else if ( order === 'ZYX' ) {
  1333. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1334. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1335. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1336. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1337. } else if ( order === 'YZX' ) {
  1338. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1339. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1340. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1341. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1342. } else if ( order === 'XZY' ) {
  1343. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1344. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1345. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1346. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1347. }
  1348. if ( update !== false ) this.onChangeCallback();
  1349. return this;
  1350. },
  1351. setFromAxisAngle: function ( axis, angle ) {
  1352. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1353. // assumes axis is normalized
  1354. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1355. this._x = axis.x * s;
  1356. this._y = axis.y * s;
  1357. this._z = axis.z * s;
  1358. this._w = Math.cos( halfAngle );
  1359. this.onChangeCallback();
  1360. return this;
  1361. },
  1362. setFromRotationMatrix: function ( m ) {
  1363. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1364. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1365. var te = m.elements,
  1366. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1367. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1368. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1369. trace = m11 + m22 + m33,
  1370. s;
  1371. if ( trace > 0 ) {
  1372. s = 0.5 / Math.sqrt( trace + 1.0 );
  1373. this._w = 0.25 / s;
  1374. this._x = ( m32 - m23 ) * s;
  1375. this._y = ( m13 - m31 ) * s;
  1376. this._z = ( m21 - m12 ) * s;
  1377. } else if ( m11 > m22 && m11 > m33 ) {
  1378. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1379. this._w = ( m32 - m23 ) / s;
  1380. this._x = 0.25 * s;
  1381. this._y = ( m12 + m21 ) / s;
  1382. this._z = ( m13 + m31 ) / s;
  1383. } else if ( m22 > m33 ) {
  1384. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1385. this._w = ( m13 - m31 ) / s;
  1386. this._x = ( m12 + m21 ) / s;
  1387. this._y = 0.25 * s;
  1388. this._z = ( m23 + m32 ) / s;
  1389. } else {
  1390. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1391. this._w = ( m21 - m12 ) / s;
  1392. this._x = ( m13 + m31 ) / s;
  1393. this._y = ( m23 + m32 ) / s;
  1394. this._z = 0.25 * s;
  1395. }
  1396. this.onChangeCallback();
  1397. return this;
  1398. },
  1399. setFromUnitVectors: function () {
  1400. // assumes direction vectors vFrom and vTo are normalized
  1401. var v1 = new Vector3();
  1402. var r;
  1403. var EPS = 0.000001;
  1404. return function setFromUnitVectors( vFrom, vTo ) {
  1405. if ( v1 === undefined ) v1 = new Vector3();
  1406. r = vFrom.dot( vTo ) + 1;
  1407. if ( r < EPS ) {
  1408. r = 0;
  1409. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1410. v1.set( - vFrom.y, vFrom.x, 0 );
  1411. } else {
  1412. v1.set( 0, - vFrom.z, vFrom.y );
  1413. }
  1414. } else {
  1415. v1.crossVectors( vFrom, vTo );
  1416. }
  1417. this._x = v1.x;
  1418. this._y = v1.y;
  1419. this._z = v1.z;
  1420. this._w = r;
  1421. return this.normalize();
  1422. };
  1423. }(),
  1424. inverse: function () {
  1425. return this.conjugate().normalize();
  1426. },
  1427. conjugate: function () {
  1428. this._x *= - 1;
  1429. this._y *= - 1;
  1430. this._z *= - 1;
  1431. this.onChangeCallback();
  1432. return this;
  1433. },
  1434. dot: function ( v ) {
  1435. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1436. },
  1437. lengthSq: function () {
  1438. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1439. },
  1440. length: function () {
  1441. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1442. },
  1443. normalize: function () {
  1444. var l = this.length();
  1445. if ( l === 0 ) {
  1446. this._x = 0;
  1447. this._y = 0;
  1448. this._z = 0;
  1449. this._w = 1;
  1450. } else {
  1451. l = 1 / l;
  1452. this._x = this._x * l;
  1453. this._y = this._y * l;
  1454. this._z = this._z * l;
  1455. this._w = this._w * l;
  1456. }
  1457. this.onChangeCallback();
  1458. return this;
  1459. },
  1460. multiply: function ( q, p ) {
  1461. if ( p !== undefined ) {
  1462. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1463. return this.multiplyQuaternions( q, p );
  1464. }
  1465. return this.multiplyQuaternions( this, q );
  1466. },
  1467. premultiply: function ( q ) {
  1468. return this.multiplyQuaternions( q, this );
  1469. },
  1470. multiplyQuaternions: function ( a, b ) {
  1471. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1472. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1473. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1474. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1475. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1476. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1477. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1478. this.onChangeCallback();
  1479. return this;
  1480. },
  1481. slerp: function ( qb, t ) {
  1482. if ( t === 0 ) return this;
  1483. if ( t === 1 ) return this.copy( qb );
  1484. var x = this._x, y = this._y, z = this._z, w = this._w;
  1485. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1486. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1487. if ( cosHalfTheta < 0 ) {
  1488. this._w = - qb._w;
  1489. this._x = - qb._x;
  1490. this._y = - qb._y;
  1491. this._z = - qb._z;
  1492. cosHalfTheta = - cosHalfTheta;
  1493. } else {
  1494. this.copy( qb );
  1495. }
  1496. if ( cosHalfTheta >= 1.0 ) {
  1497. this._w = w;
  1498. this._x = x;
  1499. this._y = y;
  1500. this._z = z;
  1501. return this;
  1502. }
  1503. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1504. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1505. this._w = 0.5 * ( w + this._w );
  1506. this._x = 0.5 * ( x + this._x );
  1507. this._y = 0.5 * ( y + this._y );
  1508. this._z = 0.5 * ( z + this._z );
  1509. return this;
  1510. }
  1511. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1512. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1513. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1514. this._w = ( w * ratioA + this._w * ratioB );
  1515. this._x = ( x * ratioA + this._x * ratioB );
  1516. this._y = ( y * ratioA + this._y * ratioB );
  1517. this._z = ( z * ratioA + this._z * ratioB );
  1518. this.onChangeCallback();
  1519. return this;
  1520. },
  1521. equals: function ( quaternion ) {
  1522. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1523. },
  1524. fromArray: function ( array, offset ) {
  1525. if ( offset === undefined ) offset = 0;
  1526. this._x = array[ offset ];
  1527. this._y = array[ offset + 1 ];
  1528. this._z = array[ offset + 2 ];
  1529. this._w = array[ offset + 3 ];
  1530. this.onChangeCallback();
  1531. return this;
  1532. },
  1533. toArray: function ( array, offset ) {
  1534. if ( array === undefined ) array = [];
  1535. if ( offset === undefined ) offset = 0;
  1536. array[ offset ] = this._x;
  1537. array[ offset + 1 ] = this._y;
  1538. array[ offset + 2 ] = this._z;
  1539. array[ offset + 3 ] = this._w;
  1540. return array;
  1541. },
  1542. onChange: function ( callback ) {
  1543. this.onChangeCallback = callback;
  1544. return this;
  1545. },
  1546. onChangeCallback: function () {}
  1547. } );
  1548. /**
  1549. * @author mrdoob / http://mrdoob.com/
  1550. * @author kile / http://kile.stravaganza.org/
  1551. * @author philogb / http://blog.thejit.org/
  1552. * @author mikael emtinger / http://gomo.se/
  1553. * @author egraether / http://egraether.com/
  1554. * @author WestLangley / http://github.com/WestLangley
  1555. */
  1556. function Vector3( x, y, z ) {
  1557. this.x = x || 0;
  1558. this.y = y || 0;
  1559. this.z = z || 0;
  1560. }
  1561. Object.assign( Vector3.prototype, {
  1562. isVector3: true,
  1563. set: function ( x, y, z ) {
  1564. this.x = x;
  1565. this.y = y;
  1566. this.z = z;
  1567. return this;
  1568. },
  1569. setScalar: function ( scalar ) {
  1570. this.x = scalar;
  1571. this.y = scalar;
  1572. this.z = scalar;
  1573. return this;
  1574. },
  1575. setX: function ( x ) {
  1576. this.x = x;
  1577. return this;
  1578. },
  1579. setY: function ( y ) {
  1580. this.y = y;
  1581. return this;
  1582. },
  1583. setZ: function ( z ) {
  1584. this.z = z;
  1585. return this;
  1586. },
  1587. setComponent: function ( index, value ) {
  1588. switch ( index ) {
  1589. case 0: this.x = value; break;
  1590. case 1: this.y = value; break;
  1591. case 2: this.z = value; break;
  1592. default: throw new Error( 'index is out of range: ' + index );
  1593. }
  1594. return this;
  1595. },
  1596. getComponent: function ( index ) {
  1597. switch ( index ) {
  1598. case 0: return this.x;
  1599. case 1: return this.y;
  1600. case 2: return this.z;
  1601. default: throw new Error( 'index is out of range: ' + index );
  1602. }
  1603. },
  1604. clone: function () {
  1605. return new this.constructor( this.x, this.y, this.z );
  1606. },
  1607. copy: function ( v ) {
  1608. this.x = v.x;
  1609. this.y = v.y;
  1610. this.z = v.z;
  1611. return this;
  1612. },
  1613. add: function ( v, w ) {
  1614. if ( w !== undefined ) {
  1615. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1616. return this.addVectors( v, w );
  1617. }
  1618. this.x += v.x;
  1619. this.y += v.y;
  1620. this.z += v.z;
  1621. return this;
  1622. },
  1623. addScalar: function ( s ) {
  1624. this.x += s;
  1625. this.y += s;
  1626. this.z += s;
  1627. return this;
  1628. },
  1629. addVectors: function ( a, b ) {
  1630. this.x = a.x + b.x;
  1631. this.y = a.y + b.y;
  1632. this.z = a.z + b.z;
  1633. return this;
  1634. },
  1635. addScaledVector: function ( v, s ) {
  1636. this.x += v.x * s;
  1637. this.y += v.y * s;
  1638. this.z += v.z * s;
  1639. return this;
  1640. },
  1641. sub: function ( v, w ) {
  1642. if ( w !== undefined ) {
  1643. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1644. return this.subVectors( v, w );
  1645. }
  1646. this.x -= v.x;
  1647. this.y -= v.y;
  1648. this.z -= v.z;
  1649. return this;
  1650. },
  1651. subScalar: function ( s ) {
  1652. this.x -= s;
  1653. this.y -= s;
  1654. this.z -= s;
  1655. return this;
  1656. },
  1657. subVectors: function ( a, b ) {
  1658. this.x = a.x - b.x;
  1659. this.y = a.y - b.y;
  1660. this.z = a.z - b.z;
  1661. return this;
  1662. },
  1663. multiply: function ( v, w ) {
  1664. if ( w !== undefined ) {
  1665. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1666. return this.multiplyVectors( v, w );
  1667. }
  1668. this.x *= v.x;
  1669. this.y *= v.y;
  1670. this.z *= v.z;
  1671. return this;
  1672. },
  1673. multiplyScalar: function ( scalar ) {
  1674. this.x *= scalar;
  1675. this.y *= scalar;
  1676. this.z *= scalar;
  1677. return this;
  1678. },
  1679. multiplyVectors: function ( a, b ) {
  1680. this.x = a.x * b.x;
  1681. this.y = a.y * b.y;
  1682. this.z = a.z * b.z;
  1683. return this;
  1684. },
  1685. applyEuler: function () {
  1686. var quaternion = new Quaternion();
  1687. return function applyEuler( euler ) {
  1688. if ( ! ( euler && euler.isEuler ) ) {
  1689. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1690. }
  1691. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1692. };
  1693. }(),
  1694. applyAxisAngle: function () {
  1695. var quaternion = new Quaternion();
  1696. return function applyAxisAngle( axis, angle ) {
  1697. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1698. };
  1699. }(),
  1700. applyMatrix3: function ( m ) {
  1701. var x = this.x, y = this.y, z = this.z;
  1702. var e = m.elements;
  1703. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1704. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1705. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1706. return this;
  1707. },
  1708. applyMatrix4: function ( m ) {
  1709. var x = this.x, y = this.y, z = this.z;
  1710. var e = m.elements;
  1711. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1712. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1713. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1714. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1715. return this;
  1716. },
  1717. applyQuaternion: function ( q ) {
  1718. var x = this.x, y = this.y, z = this.z;
  1719. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1720. // calculate quat * vector
  1721. var ix = qw * x + qy * z - qz * y;
  1722. var iy = qw * y + qz * x - qx * z;
  1723. var iz = qw * z + qx * y - qy * x;
  1724. var iw = - qx * x - qy * y - qz * z;
  1725. // calculate result * inverse quat
  1726. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1727. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1728. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1729. return this;
  1730. },
  1731. project: function () {
  1732. var matrix = new Matrix4();
  1733. return function project( camera ) {
  1734. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1735. return this.applyMatrix4( matrix );
  1736. };
  1737. }(),
  1738. unproject: function () {
  1739. var matrix = new Matrix4();
  1740. return function unproject( camera ) {
  1741. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1742. return this.applyMatrix4( matrix );
  1743. };
  1744. }(),
  1745. transformDirection: function ( m ) {
  1746. // input: THREE.Matrix4 affine matrix
  1747. // vector interpreted as a direction
  1748. var x = this.x, y = this.y, z = this.z;
  1749. var e = m.elements;
  1750. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1751. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1752. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1753. return this.normalize();
  1754. },
  1755. divide: function ( v ) {
  1756. this.x /= v.x;
  1757. this.y /= v.y;
  1758. this.z /= v.z;
  1759. return this;
  1760. },
  1761. divideScalar: function ( scalar ) {
  1762. return this.multiplyScalar( 1 / scalar );
  1763. },
  1764. min: function ( v ) {
  1765. this.x = Math.min( this.x, v.x );
  1766. this.y = Math.min( this.y, v.y );
  1767. this.z = Math.min( this.z, v.z );
  1768. return this;
  1769. },
  1770. max: function ( v ) {
  1771. this.x = Math.max( this.x, v.x );
  1772. this.y = Math.max( this.y, v.y );
  1773. this.z = Math.max( this.z, v.z );
  1774. return this;
  1775. },
  1776. clamp: function ( min, max ) {
  1777. // assumes min < max, componentwise
  1778. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1779. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1780. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1781. return this;
  1782. },
  1783. clampScalar: function () {
  1784. var min = new Vector3();
  1785. var max = new Vector3();
  1786. return function clampScalar( minVal, maxVal ) {
  1787. min.set( minVal, minVal, minVal );
  1788. max.set( maxVal, maxVal, maxVal );
  1789. return this.clamp( min, max );
  1790. };
  1791. }(),
  1792. clampLength: function ( min, max ) {
  1793. var length = this.length();
  1794. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1795. },
  1796. floor: function () {
  1797. this.x = Math.floor( this.x );
  1798. this.y = Math.floor( this.y );
  1799. this.z = Math.floor( this.z );
  1800. return this;
  1801. },
  1802. ceil: function () {
  1803. this.x = Math.ceil( this.x );
  1804. this.y = Math.ceil( this.y );
  1805. this.z = Math.ceil( this.z );
  1806. return this;
  1807. },
  1808. round: function () {
  1809. this.x = Math.round( this.x );
  1810. this.y = Math.round( this.y );
  1811. this.z = Math.round( this.z );
  1812. return this;
  1813. },
  1814. roundToZero: function () {
  1815. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1816. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1817. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1818. return this;
  1819. },
  1820. negate: function () {
  1821. this.x = - this.x;
  1822. this.y = - this.y;
  1823. this.z = - this.z;
  1824. return this;
  1825. },
  1826. dot: function ( v ) {
  1827. return this.x * v.x + this.y * v.y + this.z * v.z;
  1828. },
  1829. // TODO lengthSquared?
  1830. lengthSq: function () {
  1831. return this.x * this.x + this.y * this.y + this.z * this.z;
  1832. },
  1833. length: function () {
  1834. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1835. },
  1836. lengthManhattan: function () {
  1837. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1838. },
  1839. normalize: function () {
  1840. return this.divideScalar( this.length() || 1 );
  1841. },
  1842. setLength: function ( length ) {
  1843. return this.normalize().multiplyScalar( length );
  1844. },
  1845. lerp: function ( v, alpha ) {
  1846. this.x += ( v.x - this.x ) * alpha;
  1847. this.y += ( v.y - this.y ) * alpha;
  1848. this.z += ( v.z - this.z ) * alpha;
  1849. return this;
  1850. },
  1851. lerpVectors: function ( v1, v2, alpha ) {
  1852. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1853. },
  1854. cross: function ( v, w ) {
  1855. if ( w !== undefined ) {
  1856. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1857. return this.crossVectors( v, w );
  1858. }
  1859. var x = this.x, y = this.y, z = this.z;
  1860. this.x = y * v.z - z * v.y;
  1861. this.y = z * v.x - x * v.z;
  1862. this.z = x * v.y - y * v.x;
  1863. return this;
  1864. },
  1865. crossVectors: function ( a, b ) {
  1866. var ax = a.x, ay = a.y, az = a.z;
  1867. var bx = b.x, by = b.y, bz = b.z;
  1868. this.x = ay * bz - az * by;
  1869. this.y = az * bx - ax * bz;
  1870. this.z = ax * by - ay * bx;
  1871. return this;
  1872. },
  1873. projectOnVector: function ( vector ) {
  1874. var scalar = vector.dot( this ) / vector.lengthSq();
  1875. return this.copy( vector ).multiplyScalar( scalar );
  1876. },
  1877. projectOnPlane: function () {
  1878. var v1 = new Vector3();
  1879. return function projectOnPlane( planeNormal ) {
  1880. v1.copy( this ).projectOnVector( planeNormal );
  1881. return this.sub( v1 );
  1882. };
  1883. }(),
  1884. reflect: function () {
  1885. // reflect incident vector off plane orthogonal to normal
  1886. // normal is assumed to have unit length
  1887. var v1 = new Vector3();
  1888. return function reflect( normal ) {
  1889. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1890. };
  1891. }(),
  1892. angleTo: function ( v ) {
  1893. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1894. // clamp, to handle numerical problems
  1895. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1896. },
  1897. distanceTo: function ( v ) {
  1898. return Math.sqrt( this.distanceToSquared( v ) );
  1899. },
  1900. distanceToSquared: function ( v ) {
  1901. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1902. return dx * dx + dy * dy + dz * dz;
  1903. },
  1904. distanceToManhattan: function ( v ) {
  1905. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1906. },
  1907. setFromSpherical: function ( s ) {
  1908. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1909. this.x = sinPhiRadius * Math.sin( s.theta );
  1910. this.y = Math.cos( s.phi ) * s.radius;
  1911. this.z = sinPhiRadius * Math.cos( s.theta );
  1912. return this;
  1913. },
  1914. setFromCylindrical: function ( c ) {
  1915. this.x = c.radius * Math.sin( c.theta );
  1916. this.y = c.y;
  1917. this.z = c.radius * Math.cos( c.theta );
  1918. return this;
  1919. },
  1920. setFromMatrixPosition: function ( m ) {
  1921. var e = m.elements;
  1922. this.x = e[ 12 ];
  1923. this.y = e[ 13 ];
  1924. this.z = e[ 14 ];
  1925. return this;
  1926. },
  1927. setFromMatrixScale: function ( m ) {
  1928. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1929. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1930. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1931. this.x = sx;
  1932. this.y = sy;
  1933. this.z = sz;
  1934. return this;
  1935. },
  1936. setFromMatrixColumn: function ( m, index ) {
  1937. return this.fromArray( m.elements, index * 4 );
  1938. },
  1939. equals: function ( v ) {
  1940. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1941. },
  1942. fromArray: function ( array, offset ) {
  1943. if ( offset === undefined ) offset = 0;
  1944. this.x = array[ offset ];
  1945. this.y = array[ offset + 1 ];
  1946. this.z = array[ offset + 2 ];
  1947. return this;
  1948. },
  1949. toArray: function ( array, offset ) {
  1950. if ( array === undefined ) array = [];
  1951. if ( offset === undefined ) offset = 0;
  1952. array[ offset ] = this.x;
  1953. array[ offset + 1 ] = this.y;
  1954. array[ offset + 2 ] = this.z;
  1955. return array;
  1956. },
  1957. fromBufferAttribute: function ( attribute, index, offset ) {
  1958. if ( offset !== undefined ) {
  1959. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1960. }
  1961. this.x = attribute.getX( index );
  1962. this.y = attribute.getY( index );
  1963. this.z = attribute.getZ( index );
  1964. return this;
  1965. }
  1966. } );
  1967. /**
  1968. * @author mrdoob / http://mrdoob.com/
  1969. * @author supereggbert / http://www.paulbrunt.co.uk/
  1970. * @author philogb / http://blog.thejit.org/
  1971. * @author jordi_ros / http://plattsoft.com
  1972. * @author D1plo1d / http://github.com/D1plo1d
  1973. * @author alteredq / http://alteredqualia.com/
  1974. * @author mikael emtinger / http://gomo.se/
  1975. * @author timknip / http://www.floorplanner.com/
  1976. * @author bhouston / http://clara.io
  1977. * @author WestLangley / http://github.com/WestLangley
  1978. */
  1979. function Matrix4() {
  1980. this.elements = [
  1981. 1, 0, 0, 0,
  1982. 0, 1, 0, 0,
  1983. 0, 0, 1, 0,
  1984. 0, 0, 0, 1
  1985. ];
  1986. if ( arguments.length > 0 ) {
  1987. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  1988. }
  1989. }
  1990. Object.assign( Matrix4.prototype, {
  1991. isMatrix4: true,
  1992. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1993. var te = this.elements;
  1994. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  1995. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  1996. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  1997. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  1998. return this;
  1999. },
  2000. identity: function () {
  2001. this.set(
  2002. 1, 0, 0, 0,
  2003. 0, 1, 0, 0,
  2004. 0, 0, 1, 0,
  2005. 0, 0, 0, 1
  2006. );
  2007. return this;
  2008. },
  2009. clone: function () {
  2010. return new Matrix4().fromArray( this.elements );
  2011. },
  2012. copy: function ( m ) {
  2013. var te = this.elements;
  2014. var me = m.elements;
  2015. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  2016. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  2017. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  2018. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  2019. return this;
  2020. },
  2021. copyPosition: function ( m ) {
  2022. var te = this.elements, me = m.elements;
  2023. te[ 12 ] = me[ 12 ];
  2024. te[ 13 ] = me[ 13 ];
  2025. te[ 14 ] = me[ 14 ];
  2026. return this;
  2027. },
  2028. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2029. xAxis.setFromMatrixColumn( this, 0 );
  2030. yAxis.setFromMatrixColumn( this, 1 );
  2031. zAxis.setFromMatrixColumn( this, 2 );
  2032. return this;
  2033. },
  2034. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2035. this.set(
  2036. xAxis.x, yAxis.x, zAxis.x, 0,
  2037. xAxis.y, yAxis.y, zAxis.y, 0,
  2038. xAxis.z, yAxis.z, zAxis.z, 0,
  2039. 0, 0, 0, 1
  2040. );
  2041. return this;
  2042. },
  2043. extractRotation: function () {
  2044. var v1 = new Vector3();
  2045. return function extractRotation( m ) {
  2046. var te = this.elements;
  2047. var me = m.elements;
  2048. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2049. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2050. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2051. te[ 0 ] = me[ 0 ] * scaleX;
  2052. te[ 1 ] = me[ 1 ] * scaleX;
  2053. te[ 2 ] = me[ 2 ] * scaleX;
  2054. te[ 4 ] = me[ 4 ] * scaleY;
  2055. te[ 5 ] = me[ 5 ] * scaleY;
  2056. te[ 6 ] = me[ 6 ] * scaleY;
  2057. te[ 8 ] = me[ 8 ] * scaleZ;
  2058. te[ 9 ] = me[ 9 ] * scaleZ;
  2059. te[ 10 ] = me[ 10 ] * scaleZ;
  2060. return this;
  2061. };
  2062. }(),
  2063. makeRotationFromEuler: function ( euler ) {
  2064. if ( ! ( euler && euler.isEuler ) ) {
  2065. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2066. }
  2067. var te = this.elements;
  2068. var x = euler.x, y = euler.y, z = euler.z;
  2069. var a = Math.cos( x ), b = Math.sin( x );
  2070. var c = Math.cos( y ), d = Math.sin( y );
  2071. var e = Math.cos( z ), f = Math.sin( z );
  2072. if ( euler.order === 'XYZ' ) {
  2073. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2074. te[ 0 ] = c * e;
  2075. te[ 4 ] = - c * f;
  2076. te[ 8 ] = d;
  2077. te[ 1 ] = af + be * d;
  2078. te[ 5 ] = ae - bf * d;
  2079. te[ 9 ] = - b * c;
  2080. te[ 2 ] = bf - ae * d;
  2081. te[ 6 ] = be + af * d;
  2082. te[ 10 ] = a * c;
  2083. } else if ( euler.order === 'YXZ' ) {
  2084. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2085. te[ 0 ] = ce + df * b;
  2086. te[ 4 ] = de * b - cf;
  2087. te[ 8 ] = a * d;
  2088. te[ 1 ] = a * f;
  2089. te[ 5 ] = a * e;
  2090. te[ 9 ] = - b;
  2091. te[ 2 ] = cf * b - de;
  2092. te[ 6 ] = df + ce * b;
  2093. te[ 10 ] = a * c;
  2094. } else if ( euler.order === 'ZXY' ) {
  2095. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2096. te[ 0 ] = ce - df * b;
  2097. te[ 4 ] = - a * f;
  2098. te[ 8 ] = de + cf * b;
  2099. te[ 1 ] = cf + de * b;
  2100. te[ 5 ] = a * e;
  2101. te[ 9 ] = df - ce * b;
  2102. te[ 2 ] = - a * d;
  2103. te[ 6 ] = b;
  2104. te[ 10 ] = a * c;
  2105. } else if ( euler.order === 'ZYX' ) {
  2106. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2107. te[ 0 ] = c * e;
  2108. te[ 4 ] = be * d - af;
  2109. te[ 8 ] = ae * d + bf;
  2110. te[ 1 ] = c * f;
  2111. te[ 5 ] = bf * d + ae;
  2112. te[ 9 ] = af * d - be;
  2113. te[ 2 ] = - d;
  2114. te[ 6 ] = b * c;
  2115. te[ 10 ] = a * c;
  2116. } else if ( euler.order === 'YZX' ) {
  2117. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2118. te[ 0 ] = c * e;
  2119. te[ 4 ] = bd - ac * f;
  2120. te[ 8 ] = bc * f + ad;
  2121. te[ 1 ] = f;
  2122. te[ 5 ] = a * e;
  2123. te[ 9 ] = - b * e;
  2124. te[ 2 ] = - d * e;
  2125. te[ 6 ] = ad * f + bc;
  2126. te[ 10 ] = ac - bd * f;
  2127. } else if ( euler.order === 'XZY' ) {
  2128. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2129. te[ 0 ] = c * e;
  2130. te[ 4 ] = - f;
  2131. te[ 8 ] = d * e;
  2132. te[ 1 ] = ac * f + bd;
  2133. te[ 5 ] = a * e;
  2134. te[ 9 ] = ad * f - bc;
  2135. te[ 2 ] = bc * f - ad;
  2136. te[ 6 ] = b * e;
  2137. te[ 10 ] = bd * f + ac;
  2138. }
  2139. // last column
  2140. te[ 3 ] = 0;
  2141. te[ 7 ] = 0;
  2142. te[ 11 ] = 0;
  2143. // bottom row
  2144. te[ 12 ] = 0;
  2145. te[ 13 ] = 0;
  2146. te[ 14 ] = 0;
  2147. te[ 15 ] = 1;
  2148. return this;
  2149. },
  2150. makeRotationFromQuaternion: function ( q ) {
  2151. var te = this.elements;
  2152. var x = q._x, y = q._y, z = q._z, w = q._w;
  2153. var x2 = x + x, y2 = y + y, z2 = z + z;
  2154. var xx = x * x2, xy = x * y2, xz = x * z2;
  2155. var yy = y * y2, yz = y * z2, zz = z * z2;
  2156. var wx = w * x2, wy = w * y2, wz = w * z2;
  2157. te[ 0 ] = 1 - ( yy + zz );
  2158. te[ 4 ] = xy - wz;
  2159. te[ 8 ] = xz + wy;
  2160. te[ 1 ] = xy + wz;
  2161. te[ 5 ] = 1 - ( xx + zz );
  2162. te[ 9 ] = yz - wx;
  2163. te[ 2 ] = xz - wy;
  2164. te[ 6 ] = yz + wx;
  2165. te[ 10 ] = 1 - ( xx + yy );
  2166. // last column
  2167. te[ 3 ] = 0;
  2168. te[ 7 ] = 0;
  2169. te[ 11 ] = 0;
  2170. // bottom row
  2171. te[ 12 ] = 0;
  2172. te[ 13 ] = 0;
  2173. te[ 14 ] = 0;
  2174. te[ 15 ] = 1;
  2175. return this;
  2176. },
  2177. lookAt: function () {
  2178. var x = new Vector3();
  2179. var y = new Vector3();
  2180. var z = new Vector3();
  2181. return function lookAt( eye, target, up ) {
  2182. var te = this.elements;
  2183. z.subVectors( eye, target );
  2184. if ( z.lengthSq() === 0 ) {
  2185. // eye and target are in the same position
  2186. z.z = 1;
  2187. }
  2188. z.normalize();
  2189. x.crossVectors( up, z );
  2190. if ( x.lengthSq() === 0 ) {
  2191. // up and z are parallel
  2192. if ( Math.abs( up.z ) === 1 ) {
  2193. z.x += 0.0001;
  2194. } else {
  2195. z.z += 0.0001;
  2196. }
  2197. z.normalize();
  2198. x.crossVectors( up, z );
  2199. }
  2200. x.normalize();
  2201. y.crossVectors( z, x );
  2202. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2203. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2204. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2205. return this;
  2206. };
  2207. }(),
  2208. multiply: function ( m, n ) {
  2209. if ( n !== undefined ) {
  2210. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2211. return this.multiplyMatrices( m, n );
  2212. }
  2213. return this.multiplyMatrices( this, m );
  2214. },
  2215. premultiply: function ( m ) {
  2216. return this.multiplyMatrices( m, this );
  2217. },
  2218. multiplyMatrices: function ( a, b ) {
  2219. var ae = a.elements;
  2220. var be = b.elements;
  2221. var te = this.elements;
  2222. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2223. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2224. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2225. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2226. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2227. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2228. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2229. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2230. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2231. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2232. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2233. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2234. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2235. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2236. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2237. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2238. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2239. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2240. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2241. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2242. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2243. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2244. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2245. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2246. return this;
  2247. },
  2248. multiplyScalar: function ( s ) {
  2249. var te = this.elements;
  2250. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2251. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2252. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2253. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2254. return this;
  2255. },
  2256. applyToBufferAttribute: function () {
  2257. var v1 = new Vector3();
  2258. return function applyToBufferAttribute( attribute ) {
  2259. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2260. v1.x = attribute.getX( i );
  2261. v1.y = attribute.getY( i );
  2262. v1.z = attribute.getZ( i );
  2263. v1.applyMatrix4( this );
  2264. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2265. }
  2266. return attribute;
  2267. };
  2268. }(),
  2269. determinant: function () {
  2270. var te = this.elements;
  2271. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2272. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2273. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2274. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2275. //TODO: make this more efficient
  2276. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2277. return (
  2278. n41 * (
  2279. + n14 * n23 * n32
  2280. - n13 * n24 * n32
  2281. - n14 * n22 * n33
  2282. + n12 * n24 * n33
  2283. + n13 * n22 * n34
  2284. - n12 * n23 * n34
  2285. ) +
  2286. n42 * (
  2287. + n11 * n23 * n34
  2288. - n11 * n24 * n33
  2289. + n14 * n21 * n33
  2290. - n13 * n21 * n34
  2291. + n13 * n24 * n31
  2292. - n14 * n23 * n31
  2293. ) +
  2294. n43 * (
  2295. + n11 * n24 * n32
  2296. - n11 * n22 * n34
  2297. - n14 * n21 * n32
  2298. + n12 * n21 * n34
  2299. + n14 * n22 * n31
  2300. - n12 * n24 * n31
  2301. ) +
  2302. n44 * (
  2303. - n13 * n22 * n31
  2304. - n11 * n23 * n32
  2305. + n11 * n22 * n33
  2306. + n13 * n21 * n32
  2307. - n12 * n21 * n33
  2308. + n12 * n23 * n31
  2309. )
  2310. );
  2311. },
  2312. transpose: function () {
  2313. var te = this.elements;
  2314. var tmp;
  2315. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2316. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2317. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2318. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2319. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2320. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2321. return this;
  2322. },
  2323. setPosition: function ( v ) {
  2324. var te = this.elements;
  2325. te[ 12 ] = v.x;
  2326. te[ 13 ] = v.y;
  2327. te[ 14 ] = v.z;
  2328. return this;
  2329. },
  2330. getInverse: function ( m, throwOnDegenerate ) {
  2331. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2332. var te = this.elements,
  2333. me = m.elements,
  2334. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2335. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2336. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2337. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2338. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2339. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2340. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2341. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2342. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2343. if ( det === 0 ) {
  2344. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2345. if ( throwOnDegenerate === true ) {
  2346. throw new Error( msg );
  2347. } else {
  2348. console.warn( msg );
  2349. }
  2350. return this.identity();
  2351. }
  2352. var detInv = 1 / det;
  2353. te[ 0 ] = t11 * detInv;
  2354. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2355. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2356. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2357. te[ 4 ] = t12 * detInv;
  2358. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2359. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2360. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2361. te[ 8 ] = t13 * detInv;
  2362. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2363. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2364. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2365. te[ 12 ] = t14 * detInv;
  2366. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2367. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2368. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2369. return this;
  2370. },
  2371. scale: function ( v ) {
  2372. var te = this.elements;
  2373. var x = v.x, y = v.y, z = v.z;
  2374. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2375. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2376. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2377. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2378. return this;
  2379. },
  2380. getMaxScaleOnAxis: function () {
  2381. var te = this.elements;
  2382. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2383. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2384. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2385. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2386. },
  2387. makeTranslation: function ( x, y, z ) {
  2388. this.set(
  2389. 1, 0, 0, x,
  2390. 0, 1, 0, y,
  2391. 0, 0, 1, z,
  2392. 0, 0, 0, 1
  2393. );
  2394. return this;
  2395. },
  2396. makeRotationX: function ( theta ) {
  2397. var c = Math.cos( theta ), s = Math.sin( theta );
  2398. this.set(
  2399. 1, 0, 0, 0,
  2400. 0, c, - s, 0,
  2401. 0, s, c, 0,
  2402. 0, 0, 0, 1
  2403. );
  2404. return this;
  2405. },
  2406. makeRotationY: function ( theta ) {
  2407. var c = Math.cos( theta ), s = Math.sin( theta );
  2408. this.set(
  2409. c, 0, s, 0,
  2410. 0, 1, 0, 0,
  2411. - s, 0, c, 0,
  2412. 0, 0, 0, 1
  2413. );
  2414. return this;
  2415. },
  2416. makeRotationZ: function ( theta ) {
  2417. var c = Math.cos( theta ), s = Math.sin( theta );
  2418. this.set(
  2419. c, - s, 0, 0,
  2420. s, c, 0, 0,
  2421. 0, 0, 1, 0,
  2422. 0, 0, 0, 1
  2423. );
  2424. return this;
  2425. },
  2426. makeRotationAxis: function ( axis, angle ) {
  2427. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2428. var c = Math.cos( angle );
  2429. var s = Math.sin( angle );
  2430. var t = 1 - c;
  2431. var x = axis.x, y = axis.y, z = axis.z;
  2432. var tx = t * x, ty = t * y;
  2433. this.set(
  2434. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2435. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2436. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2437. 0, 0, 0, 1
  2438. );
  2439. return this;
  2440. },
  2441. makeScale: function ( x, y, z ) {
  2442. this.set(
  2443. x, 0, 0, 0,
  2444. 0, y, 0, 0,
  2445. 0, 0, z, 0,
  2446. 0, 0, 0, 1
  2447. );
  2448. return this;
  2449. },
  2450. makeShear: function ( x, y, z ) {
  2451. this.set(
  2452. 1, y, z, 0,
  2453. x, 1, z, 0,
  2454. x, y, 1, 0,
  2455. 0, 0, 0, 1
  2456. );
  2457. return this;
  2458. },
  2459. compose: function ( position, quaternion, scale ) {
  2460. this.makeRotationFromQuaternion( quaternion );
  2461. this.scale( scale );
  2462. this.setPosition( position );
  2463. return this;
  2464. },
  2465. decompose: function () {
  2466. var vector = new Vector3();
  2467. var matrix = new Matrix4();
  2468. return function decompose( position, quaternion, scale ) {
  2469. var te = this.elements;
  2470. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2471. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2472. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2473. // if determine is negative, we need to invert one scale
  2474. var det = this.determinant();
  2475. if ( det < 0 ) sx = - sx;
  2476. position.x = te[ 12 ];
  2477. position.y = te[ 13 ];
  2478. position.z = te[ 14 ];
  2479. // scale the rotation part
  2480. matrix.copy( this );
  2481. var invSX = 1 / sx;
  2482. var invSY = 1 / sy;
  2483. var invSZ = 1 / sz;
  2484. matrix.elements[ 0 ] *= invSX;
  2485. matrix.elements[ 1 ] *= invSX;
  2486. matrix.elements[ 2 ] *= invSX;
  2487. matrix.elements[ 4 ] *= invSY;
  2488. matrix.elements[ 5 ] *= invSY;
  2489. matrix.elements[ 6 ] *= invSY;
  2490. matrix.elements[ 8 ] *= invSZ;
  2491. matrix.elements[ 9 ] *= invSZ;
  2492. matrix.elements[ 10 ] *= invSZ;
  2493. quaternion.setFromRotationMatrix( matrix );
  2494. scale.x = sx;
  2495. scale.y = sy;
  2496. scale.z = sz;
  2497. return this;
  2498. };
  2499. }(),
  2500. makePerspective: function ( left, right, top, bottom, near, far ) {
  2501. if ( far === undefined ) {
  2502. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2503. }
  2504. var te = this.elements;
  2505. var x = 2 * near / ( right - left );
  2506. var y = 2 * near / ( top - bottom );
  2507. var a = ( right + left ) / ( right - left );
  2508. var b = ( top + bottom ) / ( top - bottom );
  2509. var c = - ( far + near ) / ( far - near );
  2510. var d = - 2 * far * near / ( far - near );
  2511. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2512. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2513. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2514. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2515. return this;
  2516. },
  2517. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2518. var te = this.elements;
  2519. var w = 1.0 / ( right - left );
  2520. var h = 1.0 / ( top - bottom );
  2521. var p = 1.0 / ( far - near );
  2522. var x = ( right + left ) * w;
  2523. var y = ( top + bottom ) * h;
  2524. var z = ( far + near ) * p;
  2525. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2526. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2527. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2528. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2529. return this;
  2530. },
  2531. equals: function ( matrix ) {
  2532. var te = this.elements;
  2533. var me = matrix.elements;
  2534. for ( var i = 0; i < 16; i ++ ) {
  2535. if ( te[ i ] !== me[ i ] ) return false;
  2536. }
  2537. return true;
  2538. },
  2539. fromArray: function ( array, offset ) {
  2540. if ( offset === undefined ) offset = 0;
  2541. for ( var i = 0; i < 16; i ++ ) {
  2542. this.elements[ i ] = array[ i + offset ];
  2543. }
  2544. return this;
  2545. },
  2546. toArray: function ( array, offset ) {
  2547. if ( array === undefined ) array = [];
  2548. if ( offset === undefined ) offset = 0;
  2549. var te = this.elements;
  2550. array[ offset ] = te[ 0 ];
  2551. array[ offset + 1 ] = te[ 1 ];
  2552. array[ offset + 2 ] = te[ 2 ];
  2553. array[ offset + 3 ] = te[ 3 ];
  2554. array[ offset + 4 ] = te[ 4 ];
  2555. array[ offset + 5 ] = te[ 5 ];
  2556. array[ offset + 6 ] = te[ 6 ];
  2557. array[ offset + 7 ] = te[ 7 ];
  2558. array[ offset + 8 ] = te[ 8 ];
  2559. array[ offset + 9 ] = te[ 9 ];
  2560. array[ offset + 10 ] = te[ 10 ];
  2561. array[ offset + 11 ] = te[ 11 ];
  2562. array[ offset + 12 ] = te[ 12 ];
  2563. array[ offset + 13 ] = te[ 13 ];
  2564. array[ offset + 14 ] = te[ 14 ];
  2565. array[ offset + 15 ] = te[ 15 ];
  2566. return array;
  2567. }
  2568. } );
  2569. /**
  2570. * @author alteredq / http://alteredqualia.com/
  2571. */
  2572. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2573. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2574. this.image = { data: data, width: width, height: height };
  2575. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2576. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2577. this.generateMipmaps = false;
  2578. this.flipY = false;
  2579. this.unpackAlignment = 1;
  2580. }
  2581. DataTexture.prototype = Object.create( Texture.prototype );
  2582. DataTexture.prototype.constructor = DataTexture;
  2583. DataTexture.prototype.isDataTexture = true;
  2584. /**
  2585. * @author mrdoob / http://mrdoob.com/
  2586. */
  2587. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2588. images = images !== undefined ? images : [];
  2589. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2590. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2591. this.flipY = false;
  2592. }
  2593. CubeTexture.prototype = Object.create( Texture.prototype );
  2594. CubeTexture.prototype.constructor = CubeTexture;
  2595. CubeTexture.prototype.isCubeTexture = true;
  2596. Object.defineProperty( CubeTexture.prototype, 'images', {
  2597. get: function () {
  2598. return this.image;
  2599. },
  2600. set: function ( value ) {
  2601. this.image = value;
  2602. }
  2603. } );
  2604. /**
  2605. * @author tschw
  2606. *
  2607. * Uniforms of a program.
  2608. * Those form a tree structure with a special top-level container for the root,
  2609. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2610. *
  2611. *
  2612. * Properties of inner nodes including the top-level container:
  2613. *
  2614. * .seq - array of nested uniforms
  2615. * .map - nested uniforms by name
  2616. *
  2617. *
  2618. * Methods of all nodes except the top-level container:
  2619. *
  2620. * .setValue( gl, value, [renderer] )
  2621. *
  2622. * uploads a uniform value(s)
  2623. * the 'renderer' parameter is needed for sampler uniforms
  2624. *
  2625. *
  2626. * Static methods of the top-level container (renderer factorizations):
  2627. *
  2628. * .upload( gl, seq, values, renderer )
  2629. *
  2630. * sets uniforms in 'seq' to 'values[id].value'
  2631. *
  2632. * .seqWithValue( seq, values ) : filteredSeq
  2633. *
  2634. * filters 'seq' entries with corresponding entry in values
  2635. *
  2636. *
  2637. * Methods of the top-level container (renderer factorizations):
  2638. *
  2639. * .setValue( gl, name, value )
  2640. *
  2641. * sets uniform with name 'name' to 'value'
  2642. *
  2643. * .set( gl, obj, prop )
  2644. *
  2645. * sets uniform from object and property with same name than uniform
  2646. *
  2647. * .setOptional( gl, obj, prop )
  2648. *
  2649. * like .set for an optional property of the object
  2650. *
  2651. */
  2652. var emptyTexture = new Texture();
  2653. var emptyCubeTexture = new CubeTexture();
  2654. // --- Base for inner nodes (including the root) ---
  2655. function UniformContainer() {
  2656. this.seq = [];
  2657. this.map = {};
  2658. }
  2659. // --- Utilities ---
  2660. // Array Caches (provide typed arrays for temporary by size)
  2661. var arrayCacheF32 = [];
  2662. var arrayCacheI32 = [];
  2663. // Float32Array caches used for uploading Matrix uniforms
  2664. var mat4array = new Float32Array( 16 );
  2665. var mat3array = new Float32Array( 9 );
  2666. // Flattening for arrays of vectors and matrices
  2667. function flatten( array, nBlocks, blockSize ) {
  2668. var firstElem = array[ 0 ];
  2669. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2670. // unoptimized: ! isNaN( firstElem )
  2671. // see http://jacksondunstan.com/articles/983
  2672. var n = nBlocks * blockSize,
  2673. r = arrayCacheF32[ n ];
  2674. if ( r === undefined ) {
  2675. r = new Float32Array( n );
  2676. arrayCacheF32[ n ] = r;
  2677. }
  2678. if ( nBlocks !== 0 ) {
  2679. firstElem.toArray( r, 0 );
  2680. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2681. offset += blockSize;
  2682. array[ i ].toArray( r, offset );
  2683. }
  2684. }
  2685. return r;
  2686. }
  2687. // Texture unit allocation
  2688. function allocTexUnits( renderer, n ) {
  2689. var r = arrayCacheI32[ n ];
  2690. if ( r === undefined ) {
  2691. r = new Int32Array( n );
  2692. arrayCacheI32[ n ] = r;
  2693. }
  2694. for ( var i = 0; i !== n; ++ i )
  2695. r[ i ] = renderer.allocTextureUnit();
  2696. return r;
  2697. }
  2698. // --- Setters ---
  2699. // Note: Defining these methods externally, because they come in a bunch
  2700. // and this way their names minify.
  2701. // Single scalar
  2702. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2703. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2704. // Single float vector (from flat array or THREE.VectorN)
  2705. function setValue2fv( gl, v ) {
  2706. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2707. else gl.uniform2f( this.addr, v.x, v.y );
  2708. }
  2709. function setValue3fv( gl, v ) {
  2710. if ( v.x !== undefined )
  2711. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2712. else if ( v.r !== undefined )
  2713. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2714. else
  2715. gl.uniform3fv( this.addr, v );
  2716. }
  2717. function setValue4fv( gl, v ) {
  2718. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2719. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2720. }
  2721. // Single matrix (from flat array or MatrixN)
  2722. function setValue2fm( gl, v ) {
  2723. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2724. }
  2725. function setValue3fm( gl, v ) {
  2726. if ( v.elements === undefined ) {
  2727. gl.uniformMatrix3fv( this.addr, false, v );
  2728. } else {
  2729. mat3array.set( v.elements );
  2730. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2731. }
  2732. }
  2733. function setValue4fm( gl, v ) {
  2734. if ( v.elements === undefined ) {
  2735. gl.uniformMatrix4fv( this.addr, false, v );
  2736. } else {
  2737. mat4array.set( v.elements );
  2738. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2739. }
  2740. }
  2741. // Single texture (2D / Cube)
  2742. function setValueT1( gl, v, renderer ) {
  2743. var unit = renderer.allocTextureUnit();
  2744. gl.uniform1i( this.addr, unit );
  2745. renderer.setTexture2D( v || emptyTexture, unit );
  2746. }
  2747. function setValueT6( gl, v, renderer ) {
  2748. var unit = renderer.allocTextureUnit();
  2749. gl.uniform1i( this.addr, unit );
  2750. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2751. }
  2752. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2753. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2754. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2755. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2756. // Helper to pick the right setter for the singular case
  2757. function getSingularSetter( type ) {
  2758. switch ( type ) {
  2759. case 0x1406: return setValue1f; // FLOAT
  2760. case 0x8b50: return setValue2fv; // _VEC2
  2761. case 0x8b51: return setValue3fv; // _VEC3
  2762. case 0x8b52: return setValue4fv; // _VEC4
  2763. case 0x8b5a: return setValue2fm; // _MAT2
  2764. case 0x8b5b: return setValue3fm; // _MAT3
  2765. case 0x8b5c: return setValue4fm; // _MAT4
  2766. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  2767. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2768. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2769. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2770. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2771. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2772. }
  2773. }
  2774. // Array of scalars
  2775. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2776. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2777. // Array of vectors (flat or from THREE classes)
  2778. function setValueV2a( gl, v ) {
  2779. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2780. }
  2781. function setValueV3a( gl, v ) {
  2782. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2783. }
  2784. function setValueV4a( gl, v ) {
  2785. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2786. }
  2787. // Array of matrices (flat or from THREE clases)
  2788. function setValueM2a( gl, v ) {
  2789. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2790. }
  2791. function setValueM3a( gl, v ) {
  2792. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2793. }
  2794. function setValueM4a( gl, v ) {
  2795. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2796. }
  2797. // Array of textures (2D / Cube)
  2798. function setValueT1a( gl, v, renderer ) {
  2799. var n = v.length,
  2800. units = allocTexUnits( renderer, n );
  2801. gl.uniform1iv( this.addr, units );
  2802. for ( var i = 0; i !== n; ++ i ) {
  2803. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2804. }
  2805. }
  2806. function setValueT6a( gl, v, renderer ) {
  2807. var n = v.length,
  2808. units = allocTexUnits( renderer, n );
  2809. gl.uniform1iv( this.addr, units );
  2810. for ( var i = 0; i !== n; ++ i ) {
  2811. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2812. }
  2813. }
  2814. // Helper to pick the right setter for a pure (bottom-level) array
  2815. function getPureArraySetter( type ) {
  2816. switch ( type ) {
  2817. case 0x1406: return setValue1fv; // FLOAT
  2818. case 0x8b50: return setValueV2a; // _VEC2
  2819. case 0x8b51: return setValueV3a; // _VEC3
  2820. case 0x8b52: return setValueV4a; // _VEC4
  2821. case 0x8b5a: return setValueM2a; // _MAT2
  2822. case 0x8b5b: return setValueM3a; // _MAT3
  2823. case 0x8b5c: return setValueM4a; // _MAT4
  2824. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2825. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2826. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2827. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2828. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2829. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2830. }
  2831. }
  2832. // --- Uniform Classes ---
  2833. function SingleUniform( id, activeInfo, addr ) {
  2834. this.id = id;
  2835. this.addr = addr;
  2836. this.setValue = getSingularSetter( activeInfo.type );
  2837. // this.path = activeInfo.name; // DEBUG
  2838. }
  2839. function PureArrayUniform( id, activeInfo, addr ) {
  2840. this.id = id;
  2841. this.addr = addr;
  2842. this.size = activeInfo.size;
  2843. this.setValue = getPureArraySetter( activeInfo.type );
  2844. // this.path = activeInfo.name; // DEBUG
  2845. }
  2846. function StructuredUniform( id ) {
  2847. this.id = id;
  2848. UniformContainer.call( this ); // mix-in
  2849. }
  2850. StructuredUniform.prototype.setValue = function ( gl, value ) {
  2851. // Note: Don't need an extra 'renderer' parameter, since samplers
  2852. // are not allowed in structured uniforms.
  2853. var seq = this.seq;
  2854. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2855. var u = seq[ i ];
  2856. u.setValue( gl, value[ u.id ] );
  2857. }
  2858. };
  2859. // --- Top-level ---
  2860. // Parser - builds up the property tree from the path strings
  2861. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2862. // extracts
  2863. // - the identifier (member name or array index)
  2864. // - followed by an optional right bracket (found when array index)
  2865. // - followed by an optional left bracket or dot (type of subscript)
  2866. //
  2867. // Note: These portions can be read in a non-overlapping fashion and
  2868. // allow straightforward parsing of the hierarchy that WebGL encodes
  2869. // in the uniform names.
  2870. function addUniform( container, uniformObject ) {
  2871. container.seq.push( uniformObject );
  2872. container.map[ uniformObject.id ] = uniformObject;
  2873. }
  2874. function parseUniform( activeInfo, addr, container ) {
  2875. var path = activeInfo.name,
  2876. pathLength = path.length;
  2877. // reset RegExp object, because of the early exit of a previous run
  2878. RePathPart.lastIndex = 0;
  2879. for ( ; ; ) {
  2880. var match = RePathPart.exec( path ),
  2881. matchEnd = RePathPart.lastIndex,
  2882. id = match[ 1 ],
  2883. idIsIndex = match[ 2 ] === ']',
  2884. subscript = match[ 3 ];
  2885. if ( idIsIndex ) id = id | 0; // convert to integer
  2886. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  2887. // bare name or "pure" bottom-level array "[0]" suffix
  2888. addUniform( container, subscript === undefined ?
  2889. new SingleUniform( id, activeInfo, addr ) :
  2890. new PureArrayUniform( id, activeInfo, addr ) );
  2891. break;
  2892. } else {
  2893. // step into inner node / create it in case it doesn't exist
  2894. var map = container.map, next = map[ id ];
  2895. if ( next === undefined ) {
  2896. next = new StructuredUniform( id );
  2897. addUniform( container, next );
  2898. }
  2899. container = next;
  2900. }
  2901. }
  2902. }
  2903. // Root Container
  2904. function WebGLUniforms( gl, program, renderer ) {
  2905. UniformContainer.call( this );
  2906. this.renderer = renderer;
  2907. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2908. for ( var i = 0; i < n; ++ i ) {
  2909. var info = gl.getActiveUniform( program, i ),
  2910. path = info.name,
  2911. addr = gl.getUniformLocation( program, path );
  2912. parseUniform( info, addr, this );
  2913. }
  2914. }
  2915. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  2916. var u = this.map[ name ];
  2917. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2918. };
  2919. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  2920. var v = object[ name ];
  2921. if ( v !== undefined ) this.setValue( gl, name, v );
  2922. };
  2923. // Static interface
  2924. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  2925. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2926. var u = seq[ i ],
  2927. v = values[ u.id ];
  2928. if ( v.needsUpdate !== false ) {
  2929. // note: always updating when .needsUpdate is undefined
  2930. u.setValue( gl, v.value, renderer );
  2931. }
  2932. }
  2933. };
  2934. WebGLUniforms.seqWithValue = function ( seq, values ) {
  2935. var r = [];
  2936. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2937. var u = seq[ i ];
  2938. if ( u.id in values ) r.push( u );
  2939. }
  2940. return r;
  2941. };
  2942. /**
  2943. * @author mrdoob / http://mrdoob.com/
  2944. */
  2945. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  2946. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  2947. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  2948. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  2949. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  2950. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  2951. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  2952. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  2953. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  2954. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  2955. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  2956. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  2957. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  2958. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  2959. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  2960. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  2961. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  2962. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  2963. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  2964. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  2965. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  2966. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  2967. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  2968. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  2969. function Color( r, g, b ) {
  2970. if ( g === undefined && b === undefined ) {
  2971. // r is THREE.Color, hex or string
  2972. return this.set( r );
  2973. }
  2974. return this.setRGB( r, g, b );
  2975. }
  2976. Object.assign( Color.prototype, {
  2977. isColor: true,
  2978. r: 1, g: 1, b: 1,
  2979. set: function ( value ) {
  2980. if ( value && value.isColor ) {
  2981. this.copy( value );
  2982. } else if ( typeof value === 'number' ) {
  2983. this.setHex( value );
  2984. } else if ( typeof value === 'string' ) {
  2985. this.setStyle( value );
  2986. }
  2987. return this;
  2988. },
  2989. setScalar: function ( scalar ) {
  2990. this.r = scalar;
  2991. this.g = scalar;
  2992. this.b = scalar;
  2993. return this;
  2994. },
  2995. setHex: function ( hex ) {
  2996. hex = Math.floor( hex );
  2997. this.r = ( hex >> 16 & 255 ) / 255;
  2998. this.g = ( hex >> 8 & 255 ) / 255;
  2999. this.b = ( hex & 255 ) / 255;
  3000. return this;
  3001. },
  3002. setRGB: function ( r, g, b ) {
  3003. this.r = r;
  3004. this.g = g;
  3005. this.b = b;
  3006. return this;
  3007. },
  3008. setHSL: function () {
  3009. function hue2rgb( p, q, t ) {
  3010. if ( t < 0 ) t += 1;
  3011. if ( t > 1 ) t -= 1;
  3012. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3013. if ( t < 1 / 2 ) return q;
  3014. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3015. return p;
  3016. }
  3017. return function setHSL( h, s, l ) {
  3018. // h,s,l ranges are in 0.0 - 1.0
  3019. h = _Math.euclideanModulo( h, 1 );
  3020. s = _Math.clamp( s, 0, 1 );
  3021. l = _Math.clamp( l, 0, 1 );
  3022. if ( s === 0 ) {
  3023. this.r = this.g = this.b = l;
  3024. } else {
  3025. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3026. var q = ( 2 * l ) - p;
  3027. this.r = hue2rgb( q, p, h + 1 / 3 );
  3028. this.g = hue2rgb( q, p, h );
  3029. this.b = hue2rgb( q, p, h - 1 / 3 );
  3030. }
  3031. return this;
  3032. };
  3033. }(),
  3034. setStyle: function ( style ) {
  3035. function handleAlpha( string ) {
  3036. if ( string === undefined ) return;
  3037. if ( parseFloat( string ) < 1 ) {
  3038. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3039. }
  3040. }
  3041. var m;
  3042. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3043. // rgb / hsl
  3044. var color;
  3045. var name = m[ 1 ];
  3046. var components = m[ 2 ];
  3047. switch ( name ) {
  3048. case 'rgb':
  3049. case 'rgba':
  3050. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3051. // rgb(255,0,0) rgba(255,0,0,0.5)
  3052. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3053. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3054. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3055. handleAlpha( color[ 5 ] );
  3056. return this;
  3057. }
  3058. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3059. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3060. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3061. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3062. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3063. handleAlpha( color[ 5 ] );
  3064. return this;
  3065. }
  3066. break;
  3067. case 'hsl':
  3068. case 'hsla':
  3069. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3070. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3071. var h = parseFloat( color[ 1 ] ) / 360;
  3072. var s = parseInt( color[ 2 ], 10 ) / 100;
  3073. var l = parseInt( color[ 3 ], 10 ) / 100;
  3074. handleAlpha( color[ 5 ] );
  3075. return this.setHSL( h, s, l );
  3076. }
  3077. break;
  3078. }
  3079. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3080. // hex color
  3081. var hex = m[ 1 ];
  3082. var size = hex.length;
  3083. if ( size === 3 ) {
  3084. // #ff0
  3085. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3086. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3087. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3088. return this;
  3089. } else if ( size === 6 ) {
  3090. // #ff0000
  3091. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3092. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3093. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3094. return this;
  3095. }
  3096. }
  3097. if ( style && style.length > 0 ) {
  3098. // color keywords
  3099. var hex = ColorKeywords[ style ];
  3100. if ( hex !== undefined ) {
  3101. // red
  3102. this.setHex( hex );
  3103. } else {
  3104. // unknown color
  3105. console.warn( 'THREE.Color: Unknown color ' + style );
  3106. }
  3107. }
  3108. return this;
  3109. },
  3110. clone: function () {
  3111. return new this.constructor( this.r, this.g, this.b );
  3112. },
  3113. copy: function ( color ) {
  3114. this.r = color.r;
  3115. this.g = color.g;
  3116. this.b = color.b;
  3117. return this;
  3118. },
  3119. copyGammaToLinear: function ( color, gammaFactor ) {
  3120. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3121. this.r = Math.pow( color.r, gammaFactor );
  3122. this.g = Math.pow( color.g, gammaFactor );
  3123. this.b = Math.pow( color.b, gammaFactor );
  3124. return this;
  3125. },
  3126. copyLinearToGamma: function ( color, gammaFactor ) {
  3127. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3128. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3129. this.r = Math.pow( color.r, safeInverse );
  3130. this.g = Math.pow( color.g, safeInverse );
  3131. this.b = Math.pow( color.b, safeInverse );
  3132. return this;
  3133. },
  3134. convertGammaToLinear: function () {
  3135. var r = this.r, g = this.g, b = this.b;
  3136. this.r = r * r;
  3137. this.g = g * g;
  3138. this.b = b * b;
  3139. return this;
  3140. },
  3141. convertLinearToGamma: function () {
  3142. this.r = Math.sqrt( this.r );
  3143. this.g = Math.sqrt( this.g );
  3144. this.b = Math.sqrt( this.b );
  3145. return this;
  3146. },
  3147. getHex: function () {
  3148. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3149. },
  3150. getHexString: function () {
  3151. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3152. },
  3153. getHSL: function ( optionalTarget ) {
  3154. // h,s,l ranges are in 0.0 - 1.0
  3155. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3156. var r = this.r, g = this.g, b = this.b;
  3157. var max = Math.max( r, g, b );
  3158. var min = Math.min( r, g, b );
  3159. var hue, saturation;
  3160. var lightness = ( min + max ) / 2.0;
  3161. if ( min === max ) {
  3162. hue = 0;
  3163. saturation = 0;
  3164. } else {
  3165. var delta = max - min;
  3166. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3167. switch ( max ) {
  3168. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3169. case g: hue = ( b - r ) / delta + 2; break;
  3170. case b: hue = ( r - g ) / delta + 4; break;
  3171. }
  3172. hue /= 6;
  3173. }
  3174. hsl.h = hue;
  3175. hsl.s = saturation;
  3176. hsl.l = lightness;
  3177. return hsl;
  3178. },
  3179. getStyle: function () {
  3180. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3181. },
  3182. offsetHSL: function ( h, s, l ) {
  3183. var hsl = this.getHSL();
  3184. hsl.h += h; hsl.s += s; hsl.l += l;
  3185. this.setHSL( hsl.h, hsl.s, hsl.l );
  3186. return this;
  3187. },
  3188. add: function ( color ) {
  3189. this.r += color.r;
  3190. this.g += color.g;
  3191. this.b += color.b;
  3192. return this;
  3193. },
  3194. addColors: function ( color1, color2 ) {
  3195. this.r = color1.r + color2.r;
  3196. this.g = color1.g + color2.g;
  3197. this.b = color1.b + color2.b;
  3198. return this;
  3199. },
  3200. addScalar: function ( s ) {
  3201. this.r += s;
  3202. this.g += s;
  3203. this.b += s;
  3204. return this;
  3205. },
  3206. sub: function( color ) {
  3207. this.r = Math.max( 0, this.r - color.r );
  3208. this.g = Math.max( 0, this.g - color.g );
  3209. this.b = Math.max( 0, this.b - color.b );
  3210. return this;
  3211. },
  3212. multiply: function ( color ) {
  3213. this.r *= color.r;
  3214. this.g *= color.g;
  3215. this.b *= color.b;
  3216. return this;
  3217. },
  3218. multiplyScalar: function ( s ) {
  3219. this.r *= s;
  3220. this.g *= s;
  3221. this.b *= s;
  3222. return this;
  3223. },
  3224. lerp: function ( color, alpha ) {
  3225. this.r += ( color.r - this.r ) * alpha;
  3226. this.g += ( color.g - this.g ) * alpha;
  3227. this.b += ( color.b - this.b ) * alpha;
  3228. return this;
  3229. },
  3230. equals: function ( c ) {
  3231. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3232. },
  3233. fromArray: function ( array, offset ) {
  3234. if ( offset === undefined ) offset = 0;
  3235. this.r = array[ offset ];
  3236. this.g = array[ offset + 1 ];
  3237. this.b = array[ offset + 2 ];
  3238. return this;
  3239. },
  3240. toArray: function ( array, offset ) {
  3241. if ( array === undefined ) array = [];
  3242. if ( offset === undefined ) offset = 0;
  3243. array[ offset ] = this.r;
  3244. array[ offset + 1 ] = this.g;
  3245. array[ offset + 2 ] = this.b;
  3246. return array;
  3247. },
  3248. toJSON: function () {
  3249. return this.getHex();
  3250. }
  3251. } );
  3252. /**
  3253. * Uniforms library for shared webgl shaders
  3254. */
  3255. var UniformsLib = {
  3256. common: {
  3257. diffuse: { value: new Color( 0xeeeeee ) },
  3258. opacity: { value: 1.0 },
  3259. map: { value: null },
  3260. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3261. specularMap: { value: null },
  3262. alphaMap: { value: null },
  3263. envMap: { value: null },
  3264. flipEnvMap: { value: - 1 },
  3265. reflectivity: { value: 1.0 },
  3266. refractionRatio: { value: 0.98 }
  3267. },
  3268. aomap: {
  3269. aoMap: { value: null },
  3270. aoMapIntensity: { value: 1 }
  3271. },
  3272. lightmap: {
  3273. lightMap: { value: null },
  3274. lightMapIntensity: { value: 1 }
  3275. },
  3276. emissivemap: {
  3277. emissiveMap: { value: null }
  3278. },
  3279. bumpmap: {
  3280. bumpMap: { value: null },
  3281. bumpScale: { value: 1 }
  3282. },
  3283. normalmap: {
  3284. normalMap: { value: null },
  3285. normalScale: { value: new Vector2( 1, 1 ) }
  3286. },
  3287. displacementmap: {
  3288. displacementMap: { value: null },
  3289. displacementScale: { value: 1 },
  3290. displacementBias: { value: 0 }
  3291. },
  3292. roughnessmap: {
  3293. roughnessMap: { value: null }
  3294. },
  3295. metalnessmap: {
  3296. metalnessMap: { value: null }
  3297. },
  3298. gradientmap: {
  3299. gradientMap: { value: null }
  3300. },
  3301. fog: {
  3302. fogDensity: { value: 0.00025 },
  3303. fogNear: { value: 1 },
  3304. fogFar: { value: 2000 },
  3305. fogColor: { value: new Color( 0xffffff ) }
  3306. },
  3307. lights: {
  3308. ambientLightColor: { value: [] },
  3309. directionalLights: { value: [], properties: {
  3310. direction: {},
  3311. color: {},
  3312. shadow: {},
  3313. shadowBias: {},
  3314. shadowRadius: {},
  3315. shadowMapSize: {}
  3316. } },
  3317. directionalShadowMap: { value: [] },
  3318. directionalShadowMatrix: { value: [] },
  3319. spotLights: { value: [], properties: {
  3320. color: {},
  3321. position: {},
  3322. direction: {},
  3323. distance: {},
  3324. coneCos: {},
  3325. penumbraCos: {},
  3326. decay: {},
  3327. shadow: {},
  3328. shadowBias: {},
  3329. shadowRadius: {},
  3330. shadowMapSize: {}
  3331. } },
  3332. spotShadowMap: { value: [] },
  3333. spotShadowMatrix: { value: [] },
  3334. pointLights: { value: [], properties: {
  3335. color: {},
  3336. position: {},
  3337. decay: {},
  3338. distance: {},
  3339. shadow: {},
  3340. shadowBias: {},
  3341. shadowRadius: {},
  3342. shadowMapSize: {}
  3343. } },
  3344. pointShadowMap: { value: [] },
  3345. pointShadowMatrix: { value: [] },
  3346. hemisphereLights: { value: [], properties: {
  3347. direction: {},
  3348. skyColor: {},
  3349. groundColor: {}
  3350. } },
  3351. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3352. rectAreaLights: { value: [], properties: {
  3353. color: {},
  3354. position: {},
  3355. width: {},
  3356. height: {}
  3357. } }
  3358. },
  3359. points: {
  3360. diffuse: { value: new Color( 0xeeeeee ) },
  3361. opacity: { value: 1.0 },
  3362. size: { value: 1.0 },
  3363. scale: { value: 1.0 },
  3364. map: { value: null },
  3365. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3366. }
  3367. };
  3368. /**
  3369. * Uniform Utilities
  3370. */
  3371. var UniformsUtils = {
  3372. merge: function ( uniforms ) {
  3373. var merged = {};
  3374. for ( var u = 0; u < uniforms.length; u ++ ) {
  3375. var tmp = this.clone( uniforms[ u ] );
  3376. for ( var p in tmp ) {
  3377. merged[ p ] = tmp[ p ];
  3378. }
  3379. }
  3380. return merged;
  3381. },
  3382. clone: function ( uniforms_src ) {
  3383. var uniforms_dst = {};
  3384. for ( var u in uniforms_src ) {
  3385. uniforms_dst[ u ] = {};
  3386. for ( var p in uniforms_src[ u ] ) {
  3387. var parameter_src = uniforms_src[ u ][ p ];
  3388. if ( parameter_src && ( parameter_src.isColor ||
  3389. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3390. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3391. parameter_src.isTexture ) ) {
  3392. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3393. } else if ( Array.isArray( parameter_src ) ) {
  3394. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3395. } else {
  3396. uniforms_dst[ u ][ p ] = parameter_src;
  3397. }
  3398. }
  3399. }
  3400. return uniforms_dst;
  3401. }
  3402. };
  3403. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3404. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3405. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3406. 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";
  3407. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3408. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3409. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3410. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\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 LTC_Uv( const in vec3 N, const in vec3 V, 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\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}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\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";
  3411. 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 = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\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";
  3412. 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";
  3413. 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";
  3414. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3415. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3416. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3417. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3418. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3419. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3420. 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";
  3421. 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";
  3422. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  3423. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3424. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3425. 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";
  3426. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3427. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3428. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn 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\treturn 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\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn 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\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn 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\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3429. 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 = asin( flipNormal * reflectVec.y ) * RECIPROCAL_PI + 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";
  3430. 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";
  3431. 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";
  3432. 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";
  3433. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3434. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3435. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3436. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\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\n";
  3437. 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";
  3438. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3439. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3440. 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_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";
  3441. 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";
  3442. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3443. 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};\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_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3444. 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";
  3445. 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\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\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";
  3446. 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\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3447. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3448. 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";
  3449. 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";
  3450. 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";
  3451. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3452. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3453. 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";
  3454. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3455. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3456. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3457. 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";
  3458. 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";
  3459. 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";
  3460. 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";
  3461. 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";
  3462. 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 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\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";
  3463. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 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\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3464. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3465. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  3466. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3467. var dithering_pars_fragment = "#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n";
  3468. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3469. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3470. 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\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\tfloat shadow = 1.0;\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\tshadow = (\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\tshadow = (\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\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\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";
  3471. 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#endif\n";
  3472. 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#endif\n";
  3473. 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#endif\n\treturn shadow;\n}\n";
  3474. 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";
  3475. 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 boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\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";
  3476. 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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n";
  3477. 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";
  3478. 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";
  3479. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3480. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3481. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn 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\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3482. 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";
  3483. 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";
  3484. 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";
  3485. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3486. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3487. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3488. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  3489. 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";
  3490. 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";
  3491. 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";
  3492. 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#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3493. 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";
  3494. 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";
  3495. 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";
  3496. 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";
  3497. 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";
  3498. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_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\t#include <fog_vertex>\n}\n";
  3499. 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";
  3500. 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 <fog_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\t#include <fog_vertex>\n}\n";
  3501. 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 <dithering_pars_fragment>\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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3502. 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 <fog_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\t#include <fog_vertex>\n}\n";
  3503. 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 <dithering_pars_fragment>\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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3504. 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 <fog_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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_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\t#include <fog_vertex>\n}\n";
  3505. 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 <dithering_pars_fragment>\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 <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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3506. 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 <fog_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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_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\t#include <fog_vertex>\n}\n";
  3507. 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}\n";
  3508. 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 <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_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";
  3509. 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";
  3510. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_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\t#include <fog_vertex>\n}\n";
  3511. 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";
  3512. 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";
  3513. var ShaderChunk = {
  3514. alphamap_fragment: alphamap_fragment,
  3515. alphamap_pars_fragment: alphamap_pars_fragment,
  3516. alphatest_fragment: alphatest_fragment,
  3517. aomap_fragment: aomap_fragment,
  3518. aomap_pars_fragment: aomap_pars_fragment,
  3519. begin_vertex: begin_vertex,
  3520. beginnormal_vertex: beginnormal_vertex,
  3521. bsdfs: bsdfs,
  3522. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3523. clipping_planes_fragment: clipping_planes_fragment,
  3524. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3525. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3526. clipping_planes_vertex: clipping_planes_vertex,
  3527. color_fragment: color_fragment,
  3528. color_pars_fragment: color_pars_fragment,
  3529. color_pars_vertex: color_pars_vertex,
  3530. color_vertex: color_vertex,
  3531. common: common,
  3532. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3533. defaultnormal_vertex: defaultnormal_vertex,
  3534. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3535. displacementmap_vertex: displacementmap_vertex,
  3536. emissivemap_fragment: emissivemap_fragment,
  3537. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3538. encodings_fragment: encodings_fragment,
  3539. encodings_pars_fragment: encodings_pars_fragment,
  3540. envmap_fragment: envmap_fragment,
  3541. envmap_pars_fragment: envmap_pars_fragment,
  3542. envmap_pars_vertex: envmap_pars_vertex,
  3543. envmap_vertex: envmap_vertex,
  3544. fog_vertex: fog_vertex,
  3545. fog_pars_vertex: fog_pars_vertex,
  3546. fog_fragment: fog_fragment,
  3547. fog_pars_fragment: fog_pars_fragment,
  3548. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3549. lightmap_fragment: lightmap_fragment,
  3550. lightmap_pars_fragment: lightmap_pars_fragment,
  3551. lights_lambert_vertex: lights_lambert_vertex,
  3552. lights_pars: lights_pars,
  3553. lights_phong_fragment: lights_phong_fragment,
  3554. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3555. lights_physical_fragment: lights_physical_fragment,
  3556. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3557. lights_template: lights_template,
  3558. logdepthbuf_fragment: logdepthbuf_fragment,
  3559. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3560. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3561. logdepthbuf_vertex: logdepthbuf_vertex,
  3562. map_fragment: map_fragment,
  3563. map_pars_fragment: map_pars_fragment,
  3564. map_particle_fragment: map_particle_fragment,
  3565. map_particle_pars_fragment: map_particle_pars_fragment,
  3566. metalnessmap_fragment: metalnessmap_fragment,
  3567. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3568. morphnormal_vertex: morphnormal_vertex,
  3569. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3570. morphtarget_vertex: morphtarget_vertex,
  3571. normal_flip: normal_flip,
  3572. normal_fragment: normal_fragment,
  3573. normalmap_pars_fragment: normalmap_pars_fragment,
  3574. packing: packing,
  3575. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3576. project_vertex: project_vertex,
  3577. dithering_fragment: dithering_fragment,
  3578. dithering_pars_fragment: dithering_pars_fragment,
  3579. roughnessmap_fragment: roughnessmap_fragment,
  3580. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3581. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3582. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3583. shadowmap_vertex: shadowmap_vertex,
  3584. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3585. skinbase_vertex: skinbase_vertex,
  3586. skinning_pars_vertex: skinning_pars_vertex,
  3587. skinning_vertex: skinning_vertex,
  3588. skinnormal_vertex: skinnormal_vertex,
  3589. specularmap_fragment: specularmap_fragment,
  3590. specularmap_pars_fragment: specularmap_pars_fragment,
  3591. tonemapping_fragment: tonemapping_fragment,
  3592. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3593. uv_pars_fragment: uv_pars_fragment,
  3594. uv_pars_vertex: uv_pars_vertex,
  3595. uv_vertex: uv_vertex,
  3596. uv2_pars_fragment: uv2_pars_fragment,
  3597. uv2_pars_vertex: uv2_pars_vertex,
  3598. uv2_vertex: uv2_vertex,
  3599. worldpos_vertex: worldpos_vertex,
  3600. cube_frag: cube_frag,
  3601. cube_vert: cube_vert,
  3602. depth_frag: depth_frag,
  3603. depth_vert: depth_vert,
  3604. distanceRGBA_frag: distanceRGBA_frag,
  3605. distanceRGBA_vert: distanceRGBA_vert,
  3606. equirect_frag: equirect_frag,
  3607. equirect_vert: equirect_vert,
  3608. linedashed_frag: linedashed_frag,
  3609. linedashed_vert: linedashed_vert,
  3610. meshbasic_frag: meshbasic_frag,
  3611. meshbasic_vert: meshbasic_vert,
  3612. meshlambert_frag: meshlambert_frag,
  3613. meshlambert_vert: meshlambert_vert,
  3614. meshphong_frag: meshphong_frag,
  3615. meshphong_vert: meshphong_vert,
  3616. meshphysical_frag: meshphysical_frag,
  3617. meshphysical_vert: meshphysical_vert,
  3618. normal_frag: normal_frag,
  3619. normal_vert: normal_vert,
  3620. points_frag: points_frag,
  3621. points_vert: points_vert,
  3622. shadow_frag: shadow_frag,
  3623. shadow_vert: shadow_vert
  3624. };
  3625. /**
  3626. * @author alteredq / http://alteredqualia.com/
  3627. * @author mrdoob / http://mrdoob.com/
  3628. * @author mikael emtinger / http://gomo.se/
  3629. */
  3630. var ShaderLib = {
  3631. basic: {
  3632. uniforms: UniformsUtils.merge( [
  3633. UniformsLib.common,
  3634. UniformsLib.aomap,
  3635. UniformsLib.lightmap,
  3636. UniformsLib.fog
  3637. ] ),
  3638. vertexShader: ShaderChunk.meshbasic_vert,
  3639. fragmentShader: ShaderChunk.meshbasic_frag
  3640. },
  3641. lambert: {
  3642. uniforms: UniformsUtils.merge( [
  3643. UniformsLib.common,
  3644. UniformsLib.aomap,
  3645. UniformsLib.lightmap,
  3646. UniformsLib.emissivemap,
  3647. UniformsLib.fog,
  3648. UniformsLib.lights,
  3649. {
  3650. emissive: { value: new Color( 0x000000 ) }
  3651. }
  3652. ] ),
  3653. vertexShader: ShaderChunk.meshlambert_vert,
  3654. fragmentShader: ShaderChunk.meshlambert_frag
  3655. },
  3656. phong: {
  3657. uniforms: UniformsUtils.merge( [
  3658. UniformsLib.common,
  3659. UniformsLib.aomap,
  3660. UniformsLib.lightmap,
  3661. UniformsLib.emissivemap,
  3662. UniformsLib.bumpmap,
  3663. UniformsLib.normalmap,
  3664. UniformsLib.displacementmap,
  3665. UniformsLib.gradientmap,
  3666. UniformsLib.fog,
  3667. UniformsLib.lights,
  3668. {
  3669. emissive: { value: new Color( 0x000000 ) },
  3670. specular: { value: new Color( 0x111111 ) },
  3671. shininess: { value: 30 }
  3672. }
  3673. ] ),
  3674. vertexShader: ShaderChunk.meshphong_vert,
  3675. fragmentShader: ShaderChunk.meshphong_frag
  3676. },
  3677. standard: {
  3678. uniforms: UniformsUtils.merge( [
  3679. UniformsLib.common,
  3680. UniformsLib.aomap,
  3681. UniformsLib.lightmap,
  3682. UniformsLib.emissivemap,
  3683. UniformsLib.bumpmap,
  3684. UniformsLib.normalmap,
  3685. UniformsLib.displacementmap,
  3686. UniformsLib.roughnessmap,
  3687. UniformsLib.metalnessmap,
  3688. UniformsLib.fog,
  3689. UniformsLib.lights,
  3690. {
  3691. emissive: { value: new Color( 0x000000 ) },
  3692. roughness: { value: 0.5 },
  3693. metalness: { value: 0.5 },
  3694. envMapIntensity: { value: 1 } // temporary
  3695. }
  3696. ] ),
  3697. vertexShader: ShaderChunk.meshphysical_vert,
  3698. fragmentShader: ShaderChunk.meshphysical_frag
  3699. },
  3700. points: {
  3701. uniforms: UniformsUtils.merge( [
  3702. UniformsLib.points,
  3703. UniformsLib.fog
  3704. ] ),
  3705. vertexShader: ShaderChunk.points_vert,
  3706. fragmentShader: ShaderChunk.points_frag
  3707. },
  3708. dashed: {
  3709. uniforms: UniformsUtils.merge( [
  3710. UniformsLib.common,
  3711. UniformsLib.fog,
  3712. {
  3713. scale: { value: 1 },
  3714. dashSize: { value: 1 },
  3715. totalSize: { value: 2 }
  3716. }
  3717. ] ),
  3718. vertexShader: ShaderChunk.linedashed_vert,
  3719. fragmentShader: ShaderChunk.linedashed_frag
  3720. },
  3721. depth: {
  3722. uniforms: UniformsUtils.merge( [
  3723. UniformsLib.common,
  3724. UniformsLib.displacementmap
  3725. ] ),
  3726. vertexShader: ShaderChunk.depth_vert,
  3727. fragmentShader: ShaderChunk.depth_frag
  3728. },
  3729. normal: {
  3730. uniforms: UniformsUtils.merge( [
  3731. UniformsLib.common,
  3732. UniformsLib.bumpmap,
  3733. UniformsLib.normalmap,
  3734. UniformsLib.displacementmap,
  3735. {
  3736. opacity: { value: 1.0 }
  3737. }
  3738. ] ),
  3739. vertexShader: ShaderChunk.normal_vert,
  3740. fragmentShader: ShaderChunk.normal_frag
  3741. },
  3742. /* -------------------------------------------------------------------------
  3743. // Cube map shader
  3744. ------------------------------------------------------------------------- */
  3745. cube: {
  3746. uniforms: {
  3747. tCube: { value: null },
  3748. tFlip: { value: - 1 },
  3749. opacity: { value: 1.0 }
  3750. },
  3751. vertexShader: ShaderChunk.cube_vert,
  3752. fragmentShader: ShaderChunk.cube_frag
  3753. },
  3754. /* -------------------------------------------------------------------------
  3755. // Cube map shader
  3756. ------------------------------------------------------------------------- */
  3757. equirect: {
  3758. uniforms: {
  3759. tEquirect: { value: null },
  3760. tFlip: { value: - 1 }
  3761. },
  3762. vertexShader: ShaderChunk.equirect_vert,
  3763. fragmentShader: ShaderChunk.equirect_frag
  3764. },
  3765. distanceRGBA: {
  3766. uniforms: {
  3767. lightPos: { value: new Vector3() }
  3768. },
  3769. vertexShader: ShaderChunk.distanceRGBA_vert,
  3770. fragmentShader: ShaderChunk.distanceRGBA_frag
  3771. }
  3772. };
  3773. ShaderLib.physical = {
  3774. uniforms: UniformsUtils.merge( [
  3775. ShaderLib.standard.uniforms,
  3776. {
  3777. clearCoat: { value: 0 },
  3778. clearCoatRoughness: { value: 0 }
  3779. }
  3780. ] ),
  3781. vertexShader: ShaderChunk.meshphysical_vert,
  3782. fragmentShader: ShaderChunk.meshphysical_frag
  3783. };
  3784. /**
  3785. * @author bhouston / http://clara.io
  3786. */
  3787. function Box2( min, max ) {
  3788. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3789. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3790. }
  3791. Object.assign( Box2.prototype, {
  3792. set: function ( min, max ) {
  3793. this.min.copy( min );
  3794. this.max.copy( max );
  3795. return this;
  3796. },
  3797. setFromPoints: function ( points ) {
  3798. this.makeEmpty();
  3799. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3800. this.expandByPoint( points[ i ] );
  3801. }
  3802. return this;
  3803. },
  3804. setFromCenterAndSize: function () {
  3805. var v1 = new Vector2();
  3806. return function setFromCenterAndSize( center, size ) {
  3807. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3808. this.min.copy( center ).sub( halfSize );
  3809. this.max.copy( center ).add( halfSize );
  3810. return this;
  3811. };
  3812. }(),
  3813. clone: function () {
  3814. return new this.constructor().copy( this );
  3815. },
  3816. copy: function ( box ) {
  3817. this.min.copy( box.min );
  3818. this.max.copy( box.max );
  3819. return this;
  3820. },
  3821. makeEmpty: function () {
  3822. this.min.x = this.min.y = + Infinity;
  3823. this.max.x = this.max.y = - Infinity;
  3824. return this;
  3825. },
  3826. isEmpty: function () {
  3827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3828. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3829. },
  3830. getCenter: function ( optionalTarget ) {
  3831. var result = optionalTarget || new Vector2();
  3832. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3833. },
  3834. getSize: function ( optionalTarget ) {
  3835. var result = optionalTarget || new Vector2();
  3836. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3837. },
  3838. expandByPoint: function ( point ) {
  3839. this.min.min( point );
  3840. this.max.max( point );
  3841. return this;
  3842. },
  3843. expandByVector: function ( vector ) {
  3844. this.min.sub( vector );
  3845. this.max.add( vector );
  3846. return this;
  3847. },
  3848. expandByScalar: function ( scalar ) {
  3849. this.min.addScalar( - scalar );
  3850. this.max.addScalar( scalar );
  3851. return this;
  3852. },
  3853. containsPoint: function ( point ) {
  3854. return point.x < this.min.x || point.x > this.max.x ||
  3855. point.y < this.min.y || point.y > this.max.y ? false : true;
  3856. },
  3857. containsBox: function ( box ) {
  3858. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3859. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3860. },
  3861. getParameter: function ( point, optionalTarget ) {
  3862. // This can potentially have a divide by zero if the box
  3863. // has a size dimension of 0.
  3864. var result = optionalTarget || new Vector2();
  3865. return result.set(
  3866. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3867. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3868. );
  3869. },
  3870. intersectsBox: function ( box ) {
  3871. // using 4 splitting planes to rule out intersections
  3872. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3873. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3874. },
  3875. clampPoint: function ( point, optionalTarget ) {
  3876. var result = optionalTarget || new Vector2();
  3877. return result.copy( point ).clamp( this.min, this.max );
  3878. },
  3879. distanceToPoint: function () {
  3880. var v1 = new Vector2();
  3881. return function distanceToPoint( point ) {
  3882. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3883. return clampedPoint.sub( point ).length();
  3884. };
  3885. }(),
  3886. intersect: function ( box ) {
  3887. this.min.max( box.min );
  3888. this.max.min( box.max );
  3889. return this;
  3890. },
  3891. union: function ( box ) {
  3892. this.min.min( box.min );
  3893. this.max.max( box.max );
  3894. return this;
  3895. },
  3896. translate: function ( offset ) {
  3897. this.min.add( offset );
  3898. this.max.add( offset );
  3899. return this;
  3900. },
  3901. equals: function ( box ) {
  3902. return box.min.equals( this.min ) && box.max.equals( this.max );
  3903. }
  3904. } );
  3905. /**
  3906. * @author mikael emtinger / http://gomo.se/
  3907. * @author alteredq / http://alteredqualia.com/
  3908. */
  3909. function LensFlarePlugin( renderer, flares ) {
  3910. var gl = renderer.context;
  3911. var state = renderer.state;
  3912. var vertexBuffer, elementBuffer;
  3913. var shader, program, attributes, uniforms;
  3914. var tempTexture, occlusionTexture;
  3915. function init() {
  3916. var vertices = new Float32Array( [
  3917. - 1, - 1, 0, 0,
  3918. 1, - 1, 1, 0,
  3919. 1, 1, 1, 1,
  3920. - 1, 1, 0, 1
  3921. ] );
  3922. var faces = new Uint16Array( [
  3923. 0, 1, 2,
  3924. 0, 2, 3
  3925. ] );
  3926. // buffers
  3927. vertexBuffer = gl.createBuffer();
  3928. elementBuffer = gl.createBuffer();
  3929. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3930. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3931. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3932. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3933. // textures
  3934. tempTexture = gl.createTexture();
  3935. occlusionTexture = gl.createTexture();
  3936. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3937. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3938. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3939. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3940. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3941. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3942. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3943. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3944. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3945. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3946. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3947. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3948. shader = {
  3949. vertexShader: [
  3950. "uniform lowp int renderType;",
  3951. "uniform vec3 screenPosition;",
  3952. "uniform vec2 scale;",
  3953. "uniform float rotation;",
  3954. "uniform sampler2D occlusionMap;",
  3955. "attribute vec2 position;",
  3956. "attribute vec2 uv;",
  3957. "varying vec2 vUV;",
  3958. "varying float vVisibility;",
  3959. "void main() {",
  3960. "vUV = uv;",
  3961. "vec2 pos = position;",
  3962. "if ( renderType == 2 ) {",
  3963. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3964. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3965. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3966. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3967. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3968. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3969. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3970. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3971. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3972. "vVisibility = visibility.r / 9.0;",
  3973. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3974. "vVisibility *= visibility.b / 9.0;",
  3975. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3976. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3977. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3978. "}",
  3979. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3980. "}"
  3981. ].join( "\n" ),
  3982. fragmentShader: [
  3983. "uniform lowp int renderType;",
  3984. "uniform sampler2D map;",
  3985. "uniform float opacity;",
  3986. "uniform vec3 color;",
  3987. "varying vec2 vUV;",
  3988. "varying float vVisibility;",
  3989. "void main() {",
  3990. // pink square
  3991. "if ( renderType == 0 ) {",
  3992. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  3993. // restore
  3994. "} else if ( renderType == 1 ) {",
  3995. "gl_FragColor = texture2D( map, vUV );",
  3996. // flare
  3997. "} else {",
  3998. "vec4 texture = texture2D( map, vUV );",
  3999. "texture.a *= opacity * vVisibility;",
  4000. "gl_FragColor = texture;",
  4001. "gl_FragColor.rgb *= color;",
  4002. "}",
  4003. "}"
  4004. ].join( "\n" )
  4005. };
  4006. program = createProgram( shader );
  4007. attributes = {
  4008. vertex: gl.getAttribLocation ( program, "position" ),
  4009. uv: gl.getAttribLocation ( program, "uv" )
  4010. };
  4011. uniforms = {
  4012. renderType: gl.getUniformLocation( program, "renderType" ),
  4013. map: gl.getUniformLocation( program, "map" ),
  4014. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4015. opacity: gl.getUniformLocation( program, "opacity" ),
  4016. color: gl.getUniformLocation( program, "color" ),
  4017. scale: gl.getUniformLocation( program, "scale" ),
  4018. rotation: gl.getUniformLocation( program, "rotation" ),
  4019. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4020. };
  4021. }
  4022. /*
  4023. * Render lens flares
  4024. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4025. * reads these back and calculates occlusion.
  4026. */
  4027. this.render = function ( scene, camera, viewport ) {
  4028. if ( flares.length === 0 ) return;
  4029. var tempPosition = new Vector3();
  4030. var invAspect = viewport.w / viewport.z,
  4031. halfViewportWidth = viewport.z * 0.5,
  4032. halfViewportHeight = viewport.w * 0.5;
  4033. var size = 16 / viewport.w,
  4034. scale = new Vector2( size * invAspect, size );
  4035. var screenPosition = new Vector3( 1, 1, 0 ),
  4036. screenPositionPixels = new Vector2( 1, 1 );
  4037. var validArea = new Box2();
  4038. validArea.min.set( viewport.x, viewport.y );
  4039. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4040. if ( program === undefined ) {
  4041. init();
  4042. }
  4043. gl.useProgram( program );
  4044. state.initAttributes();
  4045. state.enableAttribute( attributes.vertex );
  4046. state.enableAttribute( attributes.uv );
  4047. state.disableUnusedAttributes();
  4048. // loop through all lens flares to update their occlusion and positions
  4049. // setup gl and common used attribs/uniforms
  4050. gl.uniform1i( uniforms.occlusionMap, 0 );
  4051. gl.uniform1i( uniforms.map, 1 );
  4052. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4053. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4054. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4055. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4056. state.disable( gl.CULL_FACE );
  4057. state.buffers.depth.setMask( false );
  4058. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4059. size = 16 / viewport.w;
  4060. scale.set( size * invAspect, size );
  4061. // calc object screen position
  4062. var flare = flares[ i ];
  4063. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4064. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4065. tempPosition.applyMatrix4( camera.projectionMatrix );
  4066. // setup arrays for gl programs
  4067. screenPosition.copy( tempPosition );
  4068. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4069. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4070. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4071. // screen cull
  4072. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4073. // save current RGB to temp texture
  4074. state.activeTexture( gl.TEXTURE0 );
  4075. state.bindTexture( gl.TEXTURE_2D, null );
  4076. state.activeTexture( gl.TEXTURE1 );
  4077. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4078. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4079. // render pink quad
  4080. gl.uniform1i( uniforms.renderType, 0 );
  4081. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4082. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4083. state.disable( gl.BLEND );
  4084. state.enable( gl.DEPTH_TEST );
  4085. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4086. // copy result to occlusionMap
  4087. state.activeTexture( gl.TEXTURE0 );
  4088. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4089. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4090. // restore graphics
  4091. gl.uniform1i( uniforms.renderType, 1 );
  4092. state.disable( gl.DEPTH_TEST );
  4093. state.activeTexture( gl.TEXTURE1 );
  4094. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4095. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4096. // update object positions
  4097. flare.positionScreen.copy( screenPosition );
  4098. if ( flare.customUpdateCallback ) {
  4099. flare.customUpdateCallback( flare );
  4100. } else {
  4101. flare.updateLensFlares();
  4102. }
  4103. // render flares
  4104. gl.uniform1i( uniforms.renderType, 2 );
  4105. state.enable( gl.BLEND );
  4106. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4107. var sprite = flare.lensFlares[ j ];
  4108. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4109. screenPosition.x = sprite.x;
  4110. screenPosition.y = sprite.y;
  4111. screenPosition.z = sprite.z;
  4112. size = sprite.size * sprite.scale / viewport.w;
  4113. scale.x = size * invAspect;
  4114. scale.y = size;
  4115. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4116. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4117. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4118. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4119. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4120. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4121. renderer.setTexture2D( sprite.texture, 1 );
  4122. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4123. }
  4124. }
  4125. }
  4126. }
  4127. // restore gl
  4128. state.enable( gl.CULL_FACE );
  4129. state.enable( gl.DEPTH_TEST );
  4130. state.buffers.depth.setMask( true );
  4131. renderer.resetGLState();
  4132. };
  4133. function createProgram( shader ) {
  4134. var program = gl.createProgram();
  4135. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4136. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4137. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4138. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4139. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4140. gl.compileShader( fragmentShader );
  4141. gl.compileShader( vertexShader );
  4142. gl.attachShader( program, fragmentShader );
  4143. gl.attachShader( program, vertexShader );
  4144. gl.linkProgram( program );
  4145. return program;
  4146. }
  4147. }
  4148. /**
  4149. * @author mikael emtinger / http://gomo.se/
  4150. * @author alteredq / http://alteredqualia.com/
  4151. */
  4152. function SpritePlugin( renderer, sprites ) {
  4153. var gl = renderer.context;
  4154. var state = renderer.state;
  4155. var vertexBuffer, elementBuffer;
  4156. var program, attributes, uniforms;
  4157. var texture;
  4158. // decompose matrixWorld
  4159. var spritePosition = new Vector3();
  4160. var spriteRotation = new Quaternion();
  4161. var spriteScale = new Vector3();
  4162. function init() {
  4163. var vertices = new Float32Array( [
  4164. - 0.5, - 0.5, 0, 0,
  4165. 0.5, - 0.5, 1, 0,
  4166. 0.5, 0.5, 1, 1,
  4167. - 0.5, 0.5, 0, 1
  4168. ] );
  4169. var faces = new Uint16Array( [
  4170. 0, 1, 2,
  4171. 0, 2, 3
  4172. ] );
  4173. vertexBuffer = gl.createBuffer();
  4174. elementBuffer = gl.createBuffer();
  4175. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4176. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4177. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4178. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4179. program = createProgram();
  4180. attributes = {
  4181. position: gl.getAttribLocation ( program, 'position' ),
  4182. uv: gl.getAttribLocation ( program, 'uv' )
  4183. };
  4184. uniforms = {
  4185. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4186. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4187. rotation: gl.getUniformLocation( program, 'rotation' ),
  4188. scale: gl.getUniformLocation( program, 'scale' ),
  4189. color: gl.getUniformLocation( program, 'color' ),
  4190. map: gl.getUniformLocation( program, 'map' ),
  4191. opacity: gl.getUniformLocation( program, 'opacity' ),
  4192. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4193. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4194. fogType: gl.getUniformLocation( program, 'fogType' ),
  4195. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4196. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4197. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4198. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4199. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4200. };
  4201. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4202. canvas.width = 8;
  4203. canvas.height = 8;
  4204. var context = canvas.getContext( '2d' );
  4205. context.fillStyle = 'white';
  4206. context.fillRect( 0, 0, 8, 8 );
  4207. texture = new Texture( canvas );
  4208. texture.needsUpdate = true;
  4209. }
  4210. this.render = function ( scene, camera ) {
  4211. if ( sprites.length === 0 ) return;
  4212. // setup gl
  4213. if ( program === undefined ) {
  4214. init();
  4215. }
  4216. gl.useProgram( program );
  4217. state.initAttributes();
  4218. state.enableAttribute( attributes.position );
  4219. state.enableAttribute( attributes.uv );
  4220. state.disableUnusedAttributes();
  4221. state.disable( gl.CULL_FACE );
  4222. state.enable( gl.BLEND );
  4223. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4224. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4225. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4226. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4227. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4228. state.activeTexture( gl.TEXTURE0 );
  4229. gl.uniform1i( uniforms.map, 0 );
  4230. var oldFogType = 0;
  4231. var sceneFogType = 0;
  4232. var fog = scene.fog;
  4233. if ( fog ) {
  4234. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4235. if ( fog.isFog ) {
  4236. gl.uniform1f( uniforms.fogNear, fog.near );
  4237. gl.uniform1f( uniforms.fogFar, fog.far );
  4238. gl.uniform1i( uniforms.fogType, 1 );
  4239. oldFogType = 1;
  4240. sceneFogType = 1;
  4241. } else if ( fog.isFogExp2 ) {
  4242. gl.uniform1f( uniforms.fogDensity, fog.density );
  4243. gl.uniform1i( uniforms.fogType, 2 );
  4244. oldFogType = 2;
  4245. sceneFogType = 2;
  4246. }
  4247. } else {
  4248. gl.uniform1i( uniforms.fogType, 0 );
  4249. oldFogType = 0;
  4250. sceneFogType = 0;
  4251. }
  4252. // update positions and sort
  4253. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4254. var sprite = sprites[ i ];
  4255. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4256. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4257. }
  4258. sprites.sort( painterSortStable );
  4259. // render all sprites
  4260. var scale = [];
  4261. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4262. var sprite = sprites[ i ];
  4263. var material = sprite.material;
  4264. if ( material.visible === false ) continue;
  4265. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  4266. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4267. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4268. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4269. scale[ 0 ] = spriteScale.x;
  4270. scale[ 1 ] = spriteScale.y;
  4271. var fogType = 0;
  4272. if ( scene.fog && material.fog ) {
  4273. fogType = sceneFogType;
  4274. }
  4275. if ( oldFogType !== fogType ) {
  4276. gl.uniform1i( uniforms.fogType, fogType );
  4277. oldFogType = fogType;
  4278. }
  4279. if ( material.map !== null ) {
  4280. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4281. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4282. } else {
  4283. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4284. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4285. }
  4286. gl.uniform1f( uniforms.opacity, material.opacity );
  4287. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4288. gl.uniform1f( uniforms.rotation, material.rotation );
  4289. gl.uniform2fv( uniforms.scale, scale );
  4290. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4291. state.buffers.depth.setTest( material.depthTest );
  4292. state.buffers.depth.setMask( material.depthWrite );
  4293. if ( material.map ) {
  4294. renderer.setTexture2D( material.map, 0 );
  4295. } else {
  4296. renderer.setTexture2D( texture, 0 );
  4297. }
  4298. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4299. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  4300. }
  4301. // restore gl
  4302. state.enable( gl.CULL_FACE );
  4303. renderer.resetGLState();
  4304. };
  4305. function createProgram() {
  4306. var program = gl.createProgram();
  4307. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4308. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4309. gl.shaderSource( vertexShader, [
  4310. 'precision ' + renderer.getPrecision() + ' float;',
  4311. '#define SHADER_NAME ' + 'SpriteMaterial',
  4312. 'uniform mat4 modelViewMatrix;',
  4313. 'uniform mat4 projectionMatrix;',
  4314. 'uniform float rotation;',
  4315. 'uniform vec2 scale;',
  4316. 'uniform vec2 uvOffset;',
  4317. 'uniform vec2 uvScale;',
  4318. 'attribute vec2 position;',
  4319. 'attribute vec2 uv;',
  4320. 'varying vec2 vUV;',
  4321. 'void main() {',
  4322. 'vUV = uvOffset + uv * uvScale;',
  4323. 'vec2 alignedPosition = position * scale;',
  4324. 'vec2 rotatedPosition;',
  4325. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4326. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4327. 'vec4 finalPosition;',
  4328. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4329. 'finalPosition.xy += rotatedPosition;',
  4330. 'finalPosition = projectionMatrix * finalPosition;',
  4331. 'gl_Position = finalPosition;',
  4332. '}'
  4333. ].join( '\n' ) );
  4334. gl.shaderSource( fragmentShader, [
  4335. 'precision ' + renderer.getPrecision() + ' float;',
  4336. '#define SHADER_NAME ' + 'SpriteMaterial',
  4337. 'uniform vec3 color;',
  4338. 'uniform sampler2D map;',
  4339. 'uniform float opacity;',
  4340. 'uniform int fogType;',
  4341. 'uniform vec3 fogColor;',
  4342. 'uniform float fogDensity;',
  4343. 'uniform float fogNear;',
  4344. 'uniform float fogFar;',
  4345. 'uniform float alphaTest;',
  4346. 'varying vec2 vUV;',
  4347. 'void main() {',
  4348. 'vec4 texture = texture2D( map, vUV );',
  4349. 'if ( texture.a < alphaTest ) discard;',
  4350. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4351. 'if ( fogType > 0 ) {',
  4352. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4353. 'float fogFactor = 0.0;',
  4354. 'if ( fogType == 1 ) {',
  4355. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4356. '} else {',
  4357. 'const float LOG2 = 1.442695;',
  4358. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4359. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4360. '}',
  4361. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4362. '}',
  4363. '}'
  4364. ].join( '\n' ) );
  4365. gl.compileShader( vertexShader );
  4366. gl.compileShader( fragmentShader );
  4367. gl.attachShader( program, vertexShader );
  4368. gl.attachShader( program, fragmentShader );
  4369. gl.linkProgram( program );
  4370. return program;
  4371. }
  4372. function painterSortStable( a, b ) {
  4373. if ( a.renderOrder !== b.renderOrder ) {
  4374. return a.renderOrder - b.renderOrder;
  4375. } else if ( a.z !== b.z ) {
  4376. return b.z - a.z;
  4377. } else {
  4378. return b.id - a.id;
  4379. }
  4380. }
  4381. }
  4382. /**
  4383. * @author mrdoob / http://mrdoob.com/
  4384. * @author alteredq / http://alteredqualia.com/
  4385. */
  4386. var materialId = 0;
  4387. function Material() {
  4388. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4389. this.uuid = _Math.generateUUID();
  4390. this.name = '';
  4391. this.type = 'Material';
  4392. this.fog = true;
  4393. this.lights = true;
  4394. this.blending = NormalBlending;
  4395. this.side = FrontSide;
  4396. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4397. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4398. this.opacity = 1;
  4399. this.transparent = false;
  4400. this.blendSrc = SrcAlphaFactor;
  4401. this.blendDst = OneMinusSrcAlphaFactor;
  4402. this.blendEquation = AddEquation;
  4403. this.blendSrcAlpha = null;
  4404. this.blendDstAlpha = null;
  4405. this.blendEquationAlpha = null;
  4406. this.depthFunc = LessEqualDepth;
  4407. this.depthTest = true;
  4408. this.depthWrite = true;
  4409. this.clippingPlanes = null;
  4410. this.clipIntersection = false;
  4411. this.clipShadows = false;
  4412. this.colorWrite = true;
  4413. this.precision = null; // override the renderer's default precision for this material
  4414. this.polygonOffset = false;
  4415. this.polygonOffsetFactor = 0;
  4416. this.polygonOffsetUnits = 0;
  4417. this.dithering = false;
  4418. this.alphaTest = 0;
  4419. this.premultipliedAlpha = false;
  4420. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4421. this.visible = true;
  4422. this.needsUpdate = true;
  4423. }
  4424. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4425. isMaterial: true,
  4426. onBeforeCompile: function () {},
  4427. setValues: function ( values ) {
  4428. if ( values === undefined ) return;
  4429. for ( var key in values ) {
  4430. var newValue = values[ key ];
  4431. if ( newValue === undefined ) {
  4432. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4433. continue;
  4434. }
  4435. var currentValue = this[ key ];
  4436. if ( currentValue === undefined ) {
  4437. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4438. continue;
  4439. }
  4440. if ( currentValue && currentValue.isColor ) {
  4441. currentValue.set( newValue );
  4442. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4443. currentValue.copy( newValue );
  4444. } else if ( key === 'overdraw' ) {
  4445. // ensure overdraw is backwards-compatible with legacy boolean type
  4446. this[ key ] = Number( newValue );
  4447. } else {
  4448. this[ key ] = newValue;
  4449. }
  4450. }
  4451. },
  4452. toJSON: function ( meta ) {
  4453. var isRoot = meta === undefined;
  4454. if ( isRoot ) {
  4455. meta = {
  4456. textures: {},
  4457. images: {}
  4458. };
  4459. }
  4460. var data = {
  4461. metadata: {
  4462. version: 4.5,
  4463. type: 'Material',
  4464. generator: 'Material.toJSON'
  4465. }
  4466. };
  4467. // standard Material serialization
  4468. data.uuid = this.uuid;
  4469. data.type = this.type;
  4470. if ( this.name !== '' ) data.name = this.name;
  4471. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4472. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4473. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4474. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4475. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4476. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4477. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4478. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4479. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4480. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4481. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4482. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4483. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4484. data.bumpScale = this.bumpScale;
  4485. }
  4486. if ( this.normalMap && this.normalMap.isTexture ) {
  4487. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4488. data.normalScale = this.normalScale.toArray();
  4489. }
  4490. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4491. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4492. data.displacementScale = this.displacementScale;
  4493. data.displacementBias = this.displacementBias;
  4494. }
  4495. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4496. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4497. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4498. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4499. if ( this.envMap && this.envMap.isTexture ) {
  4500. data.envMap = this.envMap.toJSON( meta ).uuid;
  4501. data.reflectivity = this.reflectivity; // Scale behind envMap
  4502. }
  4503. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4504. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4505. }
  4506. if ( this.size !== undefined ) data.size = this.size;
  4507. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4508. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4509. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4510. if ( this.side !== FrontSide ) data.side = this.side;
  4511. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4512. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4513. if ( this.transparent === true ) data.transparent = this.transparent;
  4514. data.depthFunc = this.depthFunc;
  4515. data.depthTest = this.depthTest;
  4516. data.depthWrite = this.depthWrite;
  4517. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4518. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4519. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4520. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4521. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4522. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4523. data.skinning = this.skinning;
  4524. data.morphTargets = this.morphTargets;
  4525. data.dithering = this.dithering;
  4526. // TODO: Copied from Object3D.toJSON
  4527. function extractFromCache( cache ) {
  4528. var values = [];
  4529. for ( var key in cache ) {
  4530. var data = cache[ key ];
  4531. delete data.metadata;
  4532. values.push( data );
  4533. }
  4534. return values;
  4535. }
  4536. if ( isRoot ) {
  4537. var textures = extractFromCache( meta.textures );
  4538. var images = extractFromCache( meta.images );
  4539. if ( textures.length > 0 ) data.textures = textures;
  4540. if ( images.length > 0 ) data.images = images;
  4541. }
  4542. return data;
  4543. },
  4544. clone: function () {
  4545. return new this.constructor().copy( this );
  4546. },
  4547. copy: function ( source ) {
  4548. this.name = source.name;
  4549. this.fog = source.fog;
  4550. this.lights = source.lights;
  4551. this.blending = source.blending;
  4552. this.side = source.side;
  4553. this.shading = source.shading;
  4554. this.vertexColors = source.vertexColors;
  4555. this.opacity = source.opacity;
  4556. this.transparent = source.transparent;
  4557. this.blendSrc = source.blendSrc;
  4558. this.blendDst = source.blendDst;
  4559. this.blendEquation = source.blendEquation;
  4560. this.blendSrcAlpha = source.blendSrcAlpha;
  4561. this.blendDstAlpha = source.blendDstAlpha;
  4562. this.blendEquationAlpha = source.blendEquationAlpha;
  4563. this.depthFunc = source.depthFunc;
  4564. this.depthTest = source.depthTest;
  4565. this.depthWrite = source.depthWrite;
  4566. this.colorWrite = source.colorWrite;
  4567. this.precision = source.precision;
  4568. this.polygonOffset = source.polygonOffset;
  4569. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4570. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4571. this.dithering = source.dithering;
  4572. this.alphaTest = source.alphaTest;
  4573. this.premultipliedAlpha = source.premultipliedAlpha;
  4574. this.overdraw = source.overdraw;
  4575. this.visible = source.visible;
  4576. this.clipShadows = source.clipShadows;
  4577. this.clipIntersection = source.clipIntersection;
  4578. var srcPlanes = source.clippingPlanes,
  4579. dstPlanes = null;
  4580. if ( srcPlanes !== null ) {
  4581. var n = srcPlanes.length;
  4582. dstPlanes = new Array( n );
  4583. for ( var i = 0; i !== n; ++ i )
  4584. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4585. }
  4586. this.clippingPlanes = dstPlanes;
  4587. return this;
  4588. },
  4589. dispose: function () {
  4590. this.dispatchEvent( { type: 'dispose' } );
  4591. }
  4592. } );
  4593. /**
  4594. * @author alteredq / http://alteredqualia.com/
  4595. *
  4596. * parameters = {
  4597. * defines: { "label" : "value" },
  4598. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4599. *
  4600. * fragmentShader: <string>,
  4601. * vertexShader: <string>,
  4602. *
  4603. * wireframe: <boolean>,
  4604. * wireframeLinewidth: <float>,
  4605. *
  4606. * lights: <bool>,
  4607. *
  4608. * skinning: <bool>,
  4609. * morphTargets: <bool>,
  4610. * morphNormals: <bool>
  4611. * }
  4612. */
  4613. function ShaderMaterial( parameters ) {
  4614. Material.call( this );
  4615. this.type = 'ShaderMaterial';
  4616. this.defines = {};
  4617. this.uniforms = {};
  4618. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4619. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4620. this.linewidth = 1;
  4621. this.wireframe = false;
  4622. this.wireframeLinewidth = 1;
  4623. this.fog = false; // set to use scene fog
  4624. this.lights = false; // set to use scene lights
  4625. this.clipping = false; // set to use user-defined clipping planes
  4626. this.skinning = false; // set to use skinning attribute streams
  4627. this.morphTargets = false; // set to use morph targets
  4628. this.morphNormals = false; // set to use morph normals
  4629. this.extensions = {
  4630. derivatives: false, // set to use derivatives
  4631. fragDepth: false, // set to use fragment depth values
  4632. drawBuffers: false, // set to use draw buffers
  4633. shaderTextureLOD: false // set to use shader texture LOD
  4634. };
  4635. // When rendered geometry doesn't include these attributes but the material does,
  4636. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4637. this.defaultAttributeValues = {
  4638. 'color': [ 1, 1, 1 ],
  4639. 'uv': [ 0, 0 ],
  4640. 'uv2': [ 0, 0 ]
  4641. };
  4642. this.index0AttributeName = undefined;
  4643. if ( parameters !== undefined ) {
  4644. if ( parameters.attributes !== undefined ) {
  4645. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4646. }
  4647. this.setValues( parameters );
  4648. }
  4649. }
  4650. ShaderMaterial.prototype = Object.create( Material.prototype );
  4651. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4652. ShaderMaterial.prototype.isShaderMaterial = true;
  4653. ShaderMaterial.prototype.copy = function ( source ) {
  4654. Material.prototype.copy.call( this, source );
  4655. this.fragmentShader = source.fragmentShader;
  4656. this.vertexShader = source.vertexShader;
  4657. this.uniforms = UniformsUtils.clone( source.uniforms );
  4658. this.defines = source.defines;
  4659. this.wireframe = source.wireframe;
  4660. this.wireframeLinewidth = source.wireframeLinewidth;
  4661. this.lights = source.lights;
  4662. this.clipping = source.clipping;
  4663. this.skinning = source.skinning;
  4664. this.morphTargets = source.morphTargets;
  4665. this.morphNormals = source.morphNormals;
  4666. this.extensions = source.extensions;
  4667. return this;
  4668. };
  4669. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4670. var data = Material.prototype.toJSON.call( this, meta );
  4671. data.uniforms = this.uniforms;
  4672. data.vertexShader = this.vertexShader;
  4673. data.fragmentShader = this.fragmentShader;
  4674. return data;
  4675. };
  4676. /**
  4677. * @author mrdoob / http://mrdoob.com/
  4678. * @author alteredq / http://alteredqualia.com/
  4679. * @author bhouston / https://clara.io
  4680. * @author WestLangley / http://github.com/WestLangley
  4681. *
  4682. * parameters = {
  4683. *
  4684. * opacity: <float>,
  4685. *
  4686. * map: new THREE.Texture( <Image> ),
  4687. *
  4688. * alphaMap: new THREE.Texture( <Image> ),
  4689. *
  4690. * displacementMap: new THREE.Texture( <Image> ),
  4691. * displacementScale: <float>,
  4692. * displacementBias: <float>,
  4693. *
  4694. * wireframe: <boolean>,
  4695. * wireframeLinewidth: <float>
  4696. * }
  4697. */
  4698. function MeshDepthMaterial( parameters ) {
  4699. Material.call( this );
  4700. this.type = 'MeshDepthMaterial';
  4701. this.depthPacking = BasicDepthPacking;
  4702. this.skinning = false;
  4703. this.morphTargets = false;
  4704. this.map = null;
  4705. this.alphaMap = null;
  4706. this.displacementMap = null;
  4707. this.displacementScale = 1;
  4708. this.displacementBias = 0;
  4709. this.wireframe = false;
  4710. this.wireframeLinewidth = 1;
  4711. this.fog = false;
  4712. this.lights = false;
  4713. this.setValues( parameters );
  4714. }
  4715. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4716. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4717. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4718. MeshDepthMaterial.prototype.copy = function ( source ) {
  4719. Material.prototype.copy.call( this, source );
  4720. this.depthPacking = source.depthPacking;
  4721. this.skinning = source.skinning;
  4722. this.morphTargets = source.morphTargets;
  4723. this.map = source.map;
  4724. this.alphaMap = source.alphaMap;
  4725. this.displacementMap = source.displacementMap;
  4726. this.displacementScale = source.displacementScale;
  4727. this.displacementBias = source.displacementBias;
  4728. this.wireframe = source.wireframe;
  4729. this.wireframeLinewidth = source.wireframeLinewidth;
  4730. return this;
  4731. };
  4732. /**
  4733. * @author bhouston / http://clara.io
  4734. * @author WestLangley / http://github.com/WestLangley
  4735. */
  4736. function Box3( min, max ) {
  4737. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4738. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4739. }
  4740. Object.assign( Box3.prototype, {
  4741. isBox3: true,
  4742. set: function ( min, max ) {
  4743. this.min.copy( min );
  4744. this.max.copy( max );
  4745. return this;
  4746. },
  4747. setFromArray: function ( array ) {
  4748. var minX = + Infinity;
  4749. var minY = + Infinity;
  4750. var minZ = + Infinity;
  4751. var maxX = - Infinity;
  4752. var maxY = - Infinity;
  4753. var maxZ = - Infinity;
  4754. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4755. var x = array[ i ];
  4756. var y = array[ i + 1 ];
  4757. var z = array[ i + 2 ];
  4758. if ( x < minX ) minX = x;
  4759. if ( y < minY ) minY = y;
  4760. if ( z < minZ ) minZ = z;
  4761. if ( x > maxX ) maxX = x;
  4762. if ( y > maxY ) maxY = y;
  4763. if ( z > maxZ ) maxZ = z;
  4764. }
  4765. this.min.set( minX, minY, minZ );
  4766. this.max.set( maxX, maxY, maxZ );
  4767. return this;
  4768. },
  4769. setFromBufferAttribute: function ( attribute ) {
  4770. var minX = + Infinity;
  4771. var minY = + Infinity;
  4772. var minZ = + Infinity;
  4773. var maxX = - Infinity;
  4774. var maxY = - Infinity;
  4775. var maxZ = - Infinity;
  4776. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4777. var x = attribute.getX( i );
  4778. var y = attribute.getY( i );
  4779. var z = attribute.getZ( i );
  4780. if ( x < minX ) minX = x;
  4781. if ( y < minY ) minY = y;
  4782. if ( z < minZ ) minZ = z;
  4783. if ( x > maxX ) maxX = x;
  4784. if ( y > maxY ) maxY = y;
  4785. if ( z > maxZ ) maxZ = z;
  4786. }
  4787. this.min.set( minX, minY, minZ );
  4788. this.max.set( maxX, maxY, maxZ );
  4789. return this;
  4790. },
  4791. setFromPoints: function ( points ) {
  4792. this.makeEmpty();
  4793. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4794. this.expandByPoint( points[ i ] );
  4795. }
  4796. return this;
  4797. },
  4798. setFromCenterAndSize: function () {
  4799. var v1 = new Vector3();
  4800. return function setFromCenterAndSize( center, size ) {
  4801. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4802. this.min.copy( center ).sub( halfSize );
  4803. this.max.copy( center ).add( halfSize );
  4804. return this;
  4805. };
  4806. }(),
  4807. setFromObject: function ( object ) {
  4808. this.makeEmpty();
  4809. return this.expandByObject( object );
  4810. },
  4811. clone: function () {
  4812. return new this.constructor().copy( this );
  4813. },
  4814. copy: function ( box ) {
  4815. this.min.copy( box.min );
  4816. this.max.copy( box.max );
  4817. return this;
  4818. },
  4819. makeEmpty: function () {
  4820. this.min.x = this.min.y = this.min.z = + Infinity;
  4821. this.max.x = this.max.y = this.max.z = - Infinity;
  4822. return this;
  4823. },
  4824. isEmpty: function () {
  4825. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4826. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4827. },
  4828. getCenter: function ( optionalTarget ) {
  4829. var result = optionalTarget || new Vector3();
  4830. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4831. },
  4832. getSize: function ( optionalTarget ) {
  4833. var result = optionalTarget || new Vector3();
  4834. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4835. },
  4836. expandByPoint: function ( point ) {
  4837. this.min.min( point );
  4838. this.max.max( point );
  4839. return this;
  4840. },
  4841. expandByVector: function ( vector ) {
  4842. this.min.sub( vector );
  4843. this.max.add( vector );
  4844. return this;
  4845. },
  4846. expandByScalar: function ( scalar ) {
  4847. this.min.addScalar( - scalar );
  4848. this.max.addScalar( scalar );
  4849. return this;
  4850. },
  4851. expandByObject: function () {
  4852. // Computes the world-axis-aligned bounding box of an object (including its children),
  4853. // accounting for both the object's, and children's, world transforms
  4854. var v1 = new Vector3();
  4855. return function expandByObject( object ) {
  4856. var scope = this;
  4857. object.updateMatrixWorld( true );
  4858. object.traverse( function ( node ) {
  4859. var i, l;
  4860. var geometry = node.geometry;
  4861. if ( geometry !== undefined ) {
  4862. if ( geometry.isGeometry ) {
  4863. var vertices = geometry.vertices;
  4864. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4865. v1.copy( vertices[ i ] );
  4866. v1.applyMatrix4( node.matrixWorld );
  4867. scope.expandByPoint( v1 );
  4868. }
  4869. } else if ( geometry.isBufferGeometry ) {
  4870. var attribute = geometry.attributes.position;
  4871. if ( attribute !== undefined ) {
  4872. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4873. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4874. scope.expandByPoint( v1 );
  4875. }
  4876. }
  4877. }
  4878. }
  4879. } );
  4880. return this;
  4881. };
  4882. }(),
  4883. containsPoint: function ( point ) {
  4884. return point.x < this.min.x || point.x > this.max.x ||
  4885. point.y < this.min.y || point.y > this.max.y ||
  4886. point.z < this.min.z || point.z > this.max.z ? false : true;
  4887. },
  4888. containsBox: function ( box ) {
  4889. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4890. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4891. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4892. },
  4893. getParameter: function ( point, optionalTarget ) {
  4894. // This can potentially have a divide by zero if the box
  4895. // has a size dimension of 0.
  4896. var result = optionalTarget || new Vector3();
  4897. return result.set(
  4898. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4899. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4900. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4901. );
  4902. },
  4903. intersectsBox: function ( box ) {
  4904. // using 6 splitting planes to rule out intersections.
  4905. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4906. box.max.y < this.min.y || box.min.y > this.max.y ||
  4907. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4908. },
  4909. intersectsSphere: ( function () {
  4910. var closestPoint = new Vector3();
  4911. return function intersectsSphere( sphere ) {
  4912. // Find the point on the AABB closest to the sphere center.
  4913. this.clampPoint( sphere.center, closestPoint );
  4914. // If that point is inside the sphere, the AABB and sphere intersect.
  4915. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4916. };
  4917. } )(),
  4918. intersectsPlane: function ( plane ) {
  4919. // We compute the minimum and maximum dot product values. If those values
  4920. // are on the same side (back or front) of the plane, then there is no intersection.
  4921. var min, max;
  4922. if ( plane.normal.x > 0 ) {
  4923. min = plane.normal.x * this.min.x;
  4924. max = plane.normal.x * this.max.x;
  4925. } else {
  4926. min = plane.normal.x * this.max.x;
  4927. max = plane.normal.x * this.min.x;
  4928. }
  4929. if ( plane.normal.y > 0 ) {
  4930. min += plane.normal.y * this.min.y;
  4931. max += plane.normal.y * this.max.y;
  4932. } else {
  4933. min += plane.normal.y * this.max.y;
  4934. max += plane.normal.y * this.min.y;
  4935. }
  4936. if ( plane.normal.z > 0 ) {
  4937. min += plane.normal.z * this.min.z;
  4938. max += plane.normal.z * this.max.z;
  4939. } else {
  4940. min += plane.normal.z * this.max.z;
  4941. max += plane.normal.z * this.min.z;
  4942. }
  4943. return ( min <= plane.constant && max >= plane.constant );
  4944. },
  4945. clampPoint: function ( point, optionalTarget ) {
  4946. var result = optionalTarget || new Vector3();
  4947. return result.copy( point ).clamp( this.min, this.max );
  4948. },
  4949. distanceToPoint: function () {
  4950. var v1 = new Vector3();
  4951. return function distanceToPoint( point ) {
  4952. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4953. return clampedPoint.sub( point ).length();
  4954. };
  4955. }(),
  4956. getBoundingSphere: function () {
  4957. var v1 = new Vector3();
  4958. return function getBoundingSphere( optionalTarget ) {
  4959. var result = optionalTarget || new Sphere();
  4960. this.getCenter( result.center );
  4961. result.radius = this.getSize( v1 ).length() * 0.5;
  4962. return result;
  4963. };
  4964. }(),
  4965. intersect: function ( box ) {
  4966. this.min.max( box.min );
  4967. this.max.min( box.max );
  4968. // 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.
  4969. if( this.isEmpty() ) this.makeEmpty();
  4970. return this;
  4971. },
  4972. union: function ( box ) {
  4973. this.min.min( box.min );
  4974. this.max.max( box.max );
  4975. return this;
  4976. },
  4977. applyMatrix4: function () {
  4978. var points = [
  4979. new Vector3(),
  4980. new Vector3(),
  4981. new Vector3(),
  4982. new Vector3(),
  4983. new Vector3(),
  4984. new Vector3(),
  4985. new Vector3(),
  4986. new Vector3()
  4987. ];
  4988. return function applyMatrix4( matrix ) {
  4989. // transform of empty box is an empty box.
  4990. if( this.isEmpty() ) return this;
  4991. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4992. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4993. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4994. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4995. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4996. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  4997. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  4998. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  4999. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5000. this.setFromPoints( points );
  5001. return this;
  5002. };
  5003. }(),
  5004. translate: function ( offset ) {
  5005. this.min.add( offset );
  5006. this.max.add( offset );
  5007. return this;
  5008. },
  5009. equals: function ( box ) {
  5010. return box.min.equals( this.min ) && box.max.equals( this.max );
  5011. }
  5012. } );
  5013. /**
  5014. * @author bhouston / http://clara.io
  5015. * @author mrdoob / http://mrdoob.com/
  5016. */
  5017. function Sphere( center, radius ) {
  5018. this.center = ( center !== undefined ) ? center : new Vector3();
  5019. this.radius = ( radius !== undefined ) ? radius : 0;
  5020. }
  5021. Object.assign( Sphere.prototype, {
  5022. set: function ( center, radius ) {
  5023. this.center.copy( center );
  5024. this.radius = radius;
  5025. return this;
  5026. },
  5027. setFromPoints: function () {
  5028. var box = new Box3();
  5029. return function setFromPoints( points, optionalCenter ) {
  5030. var center = this.center;
  5031. if ( optionalCenter !== undefined ) {
  5032. center.copy( optionalCenter );
  5033. } else {
  5034. box.setFromPoints( points ).getCenter( center );
  5035. }
  5036. var maxRadiusSq = 0;
  5037. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5038. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5039. }
  5040. this.radius = Math.sqrt( maxRadiusSq );
  5041. return this;
  5042. };
  5043. }(),
  5044. clone: function () {
  5045. return new this.constructor().copy( this );
  5046. },
  5047. copy: function ( sphere ) {
  5048. this.center.copy( sphere.center );
  5049. this.radius = sphere.radius;
  5050. return this;
  5051. },
  5052. empty: function () {
  5053. return ( this.radius <= 0 );
  5054. },
  5055. containsPoint: function ( point ) {
  5056. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5057. },
  5058. distanceToPoint: function ( point ) {
  5059. return ( point.distanceTo( this.center ) - this.radius );
  5060. },
  5061. intersectsSphere: function ( sphere ) {
  5062. var radiusSum = this.radius + sphere.radius;
  5063. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5064. },
  5065. intersectsBox: function ( box ) {
  5066. return box.intersectsSphere( this );
  5067. },
  5068. intersectsPlane: function ( plane ) {
  5069. // We use the following equation to compute the signed distance from
  5070. // the center of the sphere to the plane.
  5071. //
  5072. // distance = q * n - d
  5073. //
  5074. // If this distance is greater than the radius of the sphere,
  5075. // then there is no intersection.
  5076. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5077. },
  5078. clampPoint: function ( point, optionalTarget ) {
  5079. var deltaLengthSq = this.center.distanceToSquared( point );
  5080. var result = optionalTarget || new Vector3();
  5081. result.copy( point );
  5082. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5083. result.sub( this.center ).normalize();
  5084. result.multiplyScalar( this.radius ).add( this.center );
  5085. }
  5086. return result;
  5087. },
  5088. getBoundingBox: function ( optionalTarget ) {
  5089. var box = optionalTarget || new Box3();
  5090. box.set( this.center, this.center );
  5091. box.expandByScalar( this.radius );
  5092. return box;
  5093. },
  5094. applyMatrix4: function ( matrix ) {
  5095. this.center.applyMatrix4( matrix );
  5096. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5097. return this;
  5098. },
  5099. translate: function ( offset ) {
  5100. this.center.add( offset );
  5101. return this;
  5102. },
  5103. equals: function ( sphere ) {
  5104. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5105. }
  5106. } );
  5107. /**
  5108. * @author alteredq / http://alteredqualia.com/
  5109. * @author WestLangley / http://github.com/WestLangley
  5110. * @author bhouston / http://clara.io
  5111. * @author tschw
  5112. */
  5113. function Matrix3() {
  5114. this.elements = [
  5115. 1, 0, 0,
  5116. 0, 1, 0,
  5117. 0, 0, 1
  5118. ];
  5119. if ( arguments.length > 0 ) {
  5120. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5121. }
  5122. }
  5123. Object.assign( Matrix3.prototype, {
  5124. isMatrix3: true,
  5125. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5126. var te = this.elements;
  5127. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5128. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5129. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5130. return this;
  5131. },
  5132. identity: function () {
  5133. this.set(
  5134. 1, 0, 0,
  5135. 0, 1, 0,
  5136. 0, 0, 1
  5137. );
  5138. return this;
  5139. },
  5140. clone: function () {
  5141. return new this.constructor().fromArray( this.elements );
  5142. },
  5143. copy: function ( m ) {
  5144. var te = this.elements;
  5145. var me = m.elements;
  5146. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5147. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5148. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5149. return this;
  5150. },
  5151. setFromMatrix4: function ( m ) {
  5152. var me = m.elements;
  5153. this.set(
  5154. me[ 0 ], me[ 4 ], me[ 8 ],
  5155. me[ 1 ], me[ 5 ], me[ 9 ],
  5156. me[ 2 ], me[ 6 ], me[ 10 ]
  5157. );
  5158. return this;
  5159. },
  5160. applyToBufferAttribute: function () {
  5161. var v1 = new Vector3();
  5162. return function applyToBufferAttribute( attribute ) {
  5163. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5164. v1.x = attribute.getX( i );
  5165. v1.y = attribute.getY( i );
  5166. v1.z = attribute.getZ( i );
  5167. v1.applyMatrix3( this );
  5168. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5169. }
  5170. return attribute;
  5171. };
  5172. }(),
  5173. multiply: function ( m ) {
  5174. return this.multiplyMatrices( this, m );
  5175. },
  5176. premultiply: function ( m ) {
  5177. return this.multiplyMatrices( m, this );
  5178. },
  5179. multiplyMatrices: function ( a, b ) {
  5180. var ae = a.elements;
  5181. var be = b.elements;
  5182. var te = this.elements;
  5183. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5184. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5185. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5186. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5187. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5188. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5189. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5190. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5191. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5192. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5193. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5194. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5195. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5196. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5197. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5198. return this;
  5199. },
  5200. multiplyScalar: function ( s ) {
  5201. var te = this.elements;
  5202. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5203. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5204. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5205. return this;
  5206. },
  5207. determinant: function () {
  5208. var te = this.elements;
  5209. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5210. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5211. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5212. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5213. },
  5214. getInverse: function ( matrix, throwOnDegenerate ) {
  5215. if ( matrix && matrix.isMatrix4 ) {
  5216. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5217. }
  5218. var me = matrix.elements,
  5219. te = this.elements,
  5220. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5221. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5222. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5223. t11 = n33 * n22 - n32 * n23,
  5224. t12 = n32 * n13 - n33 * n12,
  5225. t13 = n23 * n12 - n22 * n13,
  5226. det = n11 * t11 + n21 * t12 + n31 * t13;
  5227. if ( det === 0 ) {
  5228. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5229. if ( throwOnDegenerate === true ) {
  5230. throw new Error( msg );
  5231. } else {
  5232. console.warn( msg );
  5233. }
  5234. return this.identity();
  5235. }
  5236. var detInv = 1 / det;
  5237. te[ 0 ] = t11 * detInv;
  5238. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5239. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5240. te[ 3 ] = t12 * detInv;
  5241. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5242. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5243. te[ 6 ] = t13 * detInv;
  5244. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5245. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5246. return this;
  5247. },
  5248. transpose: function () {
  5249. var tmp, m = this.elements;
  5250. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5251. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5252. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5253. return this;
  5254. },
  5255. getNormalMatrix: function ( matrix4 ) {
  5256. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5257. },
  5258. transposeIntoArray: function ( r ) {
  5259. var m = this.elements;
  5260. r[ 0 ] = m[ 0 ];
  5261. r[ 1 ] = m[ 3 ];
  5262. r[ 2 ] = m[ 6 ];
  5263. r[ 3 ] = m[ 1 ];
  5264. r[ 4 ] = m[ 4 ];
  5265. r[ 5 ] = m[ 7 ];
  5266. r[ 6 ] = m[ 2 ];
  5267. r[ 7 ] = m[ 5 ];
  5268. r[ 8 ] = m[ 8 ];
  5269. return this;
  5270. },
  5271. equals: function ( matrix ) {
  5272. var te = this.elements;
  5273. var me = matrix.elements;
  5274. for ( var i = 0; i < 9; i ++ ) {
  5275. if ( te[ i ] !== me[ i ] ) return false;
  5276. }
  5277. return true;
  5278. },
  5279. fromArray: function ( array, offset ) {
  5280. if ( offset === undefined ) offset = 0;
  5281. for ( var i = 0; i < 9; i ++ ) {
  5282. this.elements[ i ] = array[ i + offset ];
  5283. }
  5284. return this;
  5285. },
  5286. toArray: function ( array, offset ) {
  5287. if ( array === undefined ) array = [];
  5288. if ( offset === undefined ) offset = 0;
  5289. var te = this.elements;
  5290. array[ offset ] = te[ 0 ];
  5291. array[ offset + 1 ] = te[ 1 ];
  5292. array[ offset + 2 ] = te[ 2 ];
  5293. array[ offset + 3 ] = te[ 3 ];
  5294. array[ offset + 4 ] = te[ 4 ];
  5295. array[ offset + 5 ] = te[ 5 ];
  5296. array[ offset + 6 ] = te[ 6 ];
  5297. array[ offset + 7 ] = te[ 7 ];
  5298. array[ offset + 8 ] = te[ 8 ];
  5299. return array;
  5300. }
  5301. } );
  5302. /**
  5303. * @author bhouston / http://clara.io
  5304. */
  5305. function Plane( normal, constant ) {
  5306. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5307. this.constant = ( constant !== undefined ) ? constant : 0;
  5308. }
  5309. Object.assign( Plane.prototype, {
  5310. set: function ( normal, constant ) {
  5311. this.normal.copy( normal );
  5312. this.constant = constant;
  5313. return this;
  5314. },
  5315. setComponents: function ( x, y, z, w ) {
  5316. this.normal.set( x, y, z );
  5317. this.constant = w;
  5318. return this;
  5319. },
  5320. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5321. this.normal.copy( normal );
  5322. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5323. return this;
  5324. },
  5325. setFromCoplanarPoints: function () {
  5326. var v1 = new Vector3();
  5327. var v2 = new Vector3();
  5328. return function setFromCoplanarPoints( a, b, c ) {
  5329. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5330. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5331. this.setFromNormalAndCoplanarPoint( normal, a );
  5332. return this;
  5333. };
  5334. }(),
  5335. clone: function () {
  5336. return new this.constructor().copy( this );
  5337. },
  5338. copy: function ( plane ) {
  5339. this.normal.copy( plane.normal );
  5340. this.constant = plane.constant;
  5341. return this;
  5342. },
  5343. normalize: function () {
  5344. // Note: will lead to a divide by zero if the plane is invalid.
  5345. var inverseNormalLength = 1.0 / this.normal.length();
  5346. this.normal.multiplyScalar( inverseNormalLength );
  5347. this.constant *= inverseNormalLength;
  5348. return this;
  5349. },
  5350. negate: function () {
  5351. this.constant *= - 1;
  5352. this.normal.negate();
  5353. return this;
  5354. },
  5355. distanceToPoint: function ( point ) {
  5356. return this.normal.dot( point ) + this.constant;
  5357. },
  5358. distanceToSphere: function ( sphere ) {
  5359. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5360. },
  5361. projectPoint: function ( point, optionalTarget ) {
  5362. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5363. },
  5364. orthoPoint: function ( point, optionalTarget ) {
  5365. var perpendicularMagnitude = this.distanceToPoint( point );
  5366. var result = optionalTarget || new Vector3();
  5367. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5368. },
  5369. intersectLine: function () {
  5370. var v1 = new Vector3();
  5371. return function intersectLine( line, optionalTarget ) {
  5372. var result = optionalTarget || new Vector3();
  5373. var direction = line.delta( v1 );
  5374. var denominator = this.normal.dot( direction );
  5375. if ( denominator === 0 ) {
  5376. // line is coplanar, return origin
  5377. if ( this.distanceToPoint( line.start ) === 0 ) {
  5378. return result.copy( line.start );
  5379. }
  5380. // Unsure if this is the correct method to handle this case.
  5381. return undefined;
  5382. }
  5383. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5384. if ( t < 0 || t > 1 ) {
  5385. return undefined;
  5386. }
  5387. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5388. };
  5389. }(),
  5390. intersectsLine: function ( line ) {
  5391. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5392. var startSign = this.distanceToPoint( line.start );
  5393. var endSign = this.distanceToPoint( line.end );
  5394. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5395. },
  5396. intersectsBox: function ( box ) {
  5397. return box.intersectsPlane( this );
  5398. },
  5399. intersectsSphere: function ( sphere ) {
  5400. return sphere.intersectsPlane( this );
  5401. },
  5402. coplanarPoint: function ( optionalTarget ) {
  5403. var result = optionalTarget || new Vector3();
  5404. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5405. },
  5406. applyMatrix4: function () {
  5407. var v1 = new Vector3();
  5408. var m1 = new Matrix3();
  5409. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5410. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5411. // transform normal based on theory here:
  5412. // http://www.songho.ca/opengl/gl_normaltransform.html
  5413. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5414. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5415. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5416. this.constant = - referencePoint.dot( normal );
  5417. return this;
  5418. };
  5419. }(),
  5420. translate: function ( offset ) {
  5421. this.constant = this.constant - offset.dot( this.normal );
  5422. return this;
  5423. },
  5424. equals: function ( plane ) {
  5425. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5426. }
  5427. } );
  5428. /**
  5429. * @author mrdoob / http://mrdoob.com/
  5430. * @author alteredq / http://alteredqualia.com/
  5431. * @author bhouston / http://clara.io
  5432. */
  5433. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5434. this.planes = [
  5435. ( p0 !== undefined ) ? p0 : new Plane(),
  5436. ( p1 !== undefined ) ? p1 : new Plane(),
  5437. ( p2 !== undefined ) ? p2 : new Plane(),
  5438. ( p3 !== undefined ) ? p3 : new Plane(),
  5439. ( p4 !== undefined ) ? p4 : new Plane(),
  5440. ( p5 !== undefined ) ? p5 : new Plane()
  5441. ];
  5442. }
  5443. Object.assign( Frustum.prototype, {
  5444. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5445. var planes = this.planes;
  5446. planes[ 0 ].copy( p0 );
  5447. planes[ 1 ].copy( p1 );
  5448. planes[ 2 ].copy( p2 );
  5449. planes[ 3 ].copy( p3 );
  5450. planes[ 4 ].copy( p4 );
  5451. planes[ 5 ].copy( p5 );
  5452. return this;
  5453. },
  5454. clone: function () {
  5455. return new this.constructor().copy( this );
  5456. },
  5457. copy: function ( frustum ) {
  5458. var planes = this.planes;
  5459. for ( var i = 0; i < 6; i ++ ) {
  5460. planes[ i ].copy( frustum.planes[ i ] );
  5461. }
  5462. return this;
  5463. },
  5464. setFromMatrix: function ( m ) {
  5465. var planes = this.planes;
  5466. var me = m.elements;
  5467. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5468. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5469. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5470. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5471. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5472. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5473. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5474. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5475. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5476. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5477. return this;
  5478. },
  5479. intersectsObject: function () {
  5480. var sphere = new Sphere();
  5481. return function intersectsObject( object ) {
  5482. var geometry = object.geometry;
  5483. if ( geometry.boundingSphere === null )
  5484. geometry.computeBoundingSphere();
  5485. sphere.copy( geometry.boundingSphere )
  5486. .applyMatrix4( object.matrixWorld );
  5487. return this.intersectsSphere( sphere );
  5488. };
  5489. }(),
  5490. intersectsSprite: function () {
  5491. var sphere = new Sphere();
  5492. return function intersectsSprite( sprite ) {
  5493. sphere.center.set( 0, 0, 0 );
  5494. sphere.radius = 0.7071067811865476;
  5495. sphere.applyMatrix4( sprite.matrixWorld );
  5496. return this.intersectsSphere( sphere );
  5497. };
  5498. }(),
  5499. intersectsSphere: function ( sphere ) {
  5500. var planes = this.planes;
  5501. var center = sphere.center;
  5502. var negRadius = - sphere.radius;
  5503. for ( var i = 0; i < 6; i ++ ) {
  5504. var distance = planes[ i ].distanceToPoint( center );
  5505. if ( distance < negRadius ) {
  5506. return false;
  5507. }
  5508. }
  5509. return true;
  5510. },
  5511. intersectsBox: function () {
  5512. var p1 = new Vector3(),
  5513. p2 = new Vector3();
  5514. return function intersectsBox( box ) {
  5515. var planes = this.planes;
  5516. for ( var i = 0; i < 6; i ++ ) {
  5517. var plane = planes[ i ];
  5518. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5519. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5520. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5521. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5522. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5523. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5524. var d1 = plane.distanceToPoint( p1 );
  5525. var d2 = plane.distanceToPoint( p2 );
  5526. // if both outside plane, no intersection
  5527. if ( d1 < 0 && d2 < 0 ) {
  5528. return false;
  5529. }
  5530. }
  5531. return true;
  5532. };
  5533. }(),
  5534. containsPoint: function ( point ) {
  5535. var planes = this.planes;
  5536. for ( var i = 0; i < 6; i ++ ) {
  5537. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5538. return false;
  5539. }
  5540. }
  5541. return true;
  5542. }
  5543. } );
  5544. /**
  5545. * @author alteredq / http://alteredqualia.com/
  5546. * @author mrdoob / http://mrdoob.com/
  5547. */
  5548. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5549. var _gl = _renderer.context,
  5550. _state = _renderer.state,
  5551. _frustum = new Frustum(),
  5552. _projScreenMatrix = new Matrix4(),
  5553. _lightShadows = _lights.shadows,
  5554. _shadowMapSize = new Vector2(),
  5555. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5556. _lookTarget = new Vector3(),
  5557. _lightPositionWorld = new Vector3(),
  5558. _MorphingFlag = 1,
  5559. _SkinningFlag = 2,
  5560. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5561. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5562. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5563. _materialCache = {};
  5564. var cubeDirections = [
  5565. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5566. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5567. ];
  5568. var cubeUps = [
  5569. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5570. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5571. ];
  5572. var cube2DViewPorts = [
  5573. new Vector4(), new Vector4(), new Vector4(),
  5574. new Vector4(), new Vector4(), new Vector4()
  5575. ];
  5576. // init
  5577. var depthMaterialTemplate = new MeshDepthMaterial();
  5578. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5579. depthMaterialTemplate.clipping = true;
  5580. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5581. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  5582. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5583. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5584. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5585. var depthMaterial = depthMaterialTemplate.clone();
  5586. depthMaterial.morphTargets = useMorphing;
  5587. depthMaterial.skinning = useSkinning;
  5588. _depthMaterials[ i ] = depthMaterial;
  5589. var distanceMaterial = new ShaderMaterial( {
  5590. defines: {
  5591. 'USE_SHADOWMAP': ''
  5592. },
  5593. uniforms: distanceUniforms,
  5594. vertexShader: distanceShader.vertexShader,
  5595. fragmentShader: distanceShader.fragmentShader,
  5596. morphTargets: useMorphing,
  5597. skinning: useSkinning,
  5598. clipping: true
  5599. } );
  5600. _distanceMaterials[ i ] = distanceMaterial;
  5601. }
  5602. //
  5603. var scope = this;
  5604. this.enabled = false;
  5605. this.autoUpdate = true;
  5606. this.needsUpdate = false;
  5607. this.type = PCFShadowMap;
  5608. this.renderReverseSided = true;
  5609. this.renderSingleSided = true;
  5610. this.render = function ( scene, camera ) {
  5611. if ( scope.enabled === false ) return;
  5612. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5613. if ( _lightShadows.length === 0 ) return;
  5614. // Set GL state for depth map.
  5615. _state.disable( _gl.BLEND );
  5616. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5617. _state.buffers.depth.setTest( true );
  5618. _state.setScissorTest( false );
  5619. // render depth map
  5620. var faceCount;
  5621. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5622. var light = _lightShadows[ i ];
  5623. var shadow = light.shadow;
  5624. var isPointLight = light && light.isPointLight;
  5625. if ( shadow === undefined ) {
  5626. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5627. continue;
  5628. }
  5629. var shadowCamera = shadow.camera;
  5630. _shadowMapSize.copy( shadow.mapSize );
  5631. _shadowMapSize.min( _maxShadowMapSize );
  5632. if ( isPointLight ) {
  5633. var vpWidth = _shadowMapSize.x;
  5634. var vpHeight = _shadowMapSize.y;
  5635. // These viewports map a cube-map onto a 2D texture with the
  5636. // following orientation:
  5637. //
  5638. // xzXZ
  5639. // y Y
  5640. //
  5641. // X - Positive x direction
  5642. // x - Negative x direction
  5643. // Y - Positive y direction
  5644. // y - Negative y direction
  5645. // Z - Positive z direction
  5646. // z - Negative z direction
  5647. // positive X
  5648. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5649. // negative X
  5650. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5651. // positive Z
  5652. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5653. // negative Z
  5654. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5655. // positive Y
  5656. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5657. // negative Y
  5658. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5659. _shadowMapSize.x *= 4.0;
  5660. _shadowMapSize.y *= 2.0;
  5661. }
  5662. if ( shadow.map === null ) {
  5663. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5664. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5665. shadow.map.texture.name = light.name + ".shadowMap";
  5666. shadowCamera.updateProjectionMatrix();
  5667. }
  5668. if ( shadow.isSpotLightShadow ) {
  5669. shadow.update( light );
  5670. }
  5671. var shadowMap = shadow.map;
  5672. var shadowMatrix = shadow.matrix;
  5673. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5674. shadowCamera.position.copy( _lightPositionWorld );
  5675. if ( isPointLight ) {
  5676. faceCount = 6;
  5677. // for point lights we set the shadow matrix to be a translation-only matrix
  5678. // equal to inverse of the light's position
  5679. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5680. } else {
  5681. faceCount = 1;
  5682. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5683. shadowCamera.lookAt( _lookTarget );
  5684. shadowCamera.updateMatrixWorld();
  5685. // compute shadow matrix
  5686. shadowMatrix.set(
  5687. 0.5, 0.0, 0.0, 0.5,
  5688. 0.0, 0.5, 0.0, 0.5,
  5689. 0.0, 0.0, 0.5, 0.5,
  5690. 0.0, 0.0, 0.0, 1.0
  5691. );
  5692. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5693. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5694. }
  5695. _renderer.setRenderTarget( shadowMap );
  5696. _renderer.clear();
  5697. // render shadow map for each cube face (if omni-directional) or
  5698. // run a single pass if not
  5699. for ( var face = 0; face < faceCount; face ++ ) {
  5700. if ( isPointLight ) {
  5701. _lookTarget.copy( shadowCamera.position );
  5702. _lookTarget.add( cubeDirections[ face ] );
  5703. shadowCamera.up.copy( cubeUps[ face ] );
  5704. shadowCamera.lookAt( _lookTarget );
  5705. shadowCamera.updateMatrixWorld();
  5706. var vpDimensions = cube2DViewPorts[ face ];
  5707. _state.viewport( vpDimensions );
  5708. }
  5709. // update camera matrices and frustum
  5710. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5711. _frustum.setFromMatrix( _projScreenMatrix );
  5712. // set object matrices & frustum culling
  5713. renderObject( scene, camera, shadowCamera, isPointLight );
  5714. }
  5715. }
  5716. // Restore GL state.
  5717. var clearColor = _renderer.getClearColor();
  5718. var clearAlpha = _renderer.getClearAlpha();
  5719. _renderer.setClearColor( clearColor, clearAlpha );
  5720. scope.needsUpdate = false;
  5721. };
  5722. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5723. var geometry = object.geometry;
  5724. var result = null;
  5725. var materialVariants = _depthMaterials;
  5726. var customMaterial = object.customDepthMaterial;
  5727. if ( isPointLight ) {
  5728. materialVariants = _distanceMaterials;
  5729. customMaterial = object.customDistanceMaterial;
  5730. }
  5731. if ( ! customMaterial ) {
  5732. var useMorphing = false;
  5733. if ( material.morphTargets ) {
  5734. if ( geometry && geometry.isBufferGeometry ) {
  5735. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5736. } else if ( geometry && geometry.isGeometry ) {
  5737. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5738. }
  5739. }
  5740. if ( object.isSkinnedMesh && material.skinning === false ) {
  5741. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5742. }
  5743. var useSkinning = object.isSkinnedMesh && material.skinning;
  5744. var variantIndex = 0;
  5745. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5746. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5747. result = materialVariants[ variantIndex ];
  5748. } else {
  5749. result = customMaterial;
  5750. }
  5751. if ( _renderer.localClippingEnabled &&
  5752. material.clipShadows === true &&
  5753. material.clippingPlanes.length !== 0 ) {
  5754. // in this case we need a unique material instance reflecting the
  5755. // appropriate state
  5756. var keyA = result.uuid, keyB = material.uuid;
  5757. var materialsForVariant = _materialCache[ keyA ];
  5758. if ( materialsForVariant === undefined ) {
  5759. materialsForVariant = {};
  5760. _materialCache[ keyA ] = materialsForVariant;
  5761. }
  5762. var cachedMaterial = materialsForVariant[ keyB ];
  5763. if ( cachedMaterial === undefined ) {
  5764. cachedMaterial = result.clone();
  5765. materialsForVariant[ keyB ] = cachedMaterial;
  5766. }
  5767. result = cachedMaterial;
  5768. }
  5769. result.visible = material.visible;
  5770. result.wireframe = material.wireframe;
  5771. var side = material.side;
  5772. if ( scope.renderSingleSided && side == DoubleSide ) {
  5773. side = FrontSide;
  5774. }
  5775. if ( scope.renderReverseSided ) {
  5776. if ( side === FrontSide ) side = BackSide;
  5777. else if ( side === BackSide ) side = FrontSide;
  5778. }
  5779. result.side = side;
  5780. result.clipShadows = material.clipShadows;
  5781. result.clippingPlanes = material.clippingPlanes;
  5782. result.wireframeLinewidth = material.wireframeLinewidth;
  5783. result.linewidth = material.linewidth;
  5784. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5785. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5786. }
  5787. return result;
  5788. }
  5789. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5790. if ( object.visible === false ) return;
  5791. var visible = object.layers.test( camera.layers );
  5792. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5793. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5794. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5795. var geometry = _objects.update( object );
  5796. var material = object.material;
  5797. if ( Array.isArray( material ) ) {
  5798. var groups = geometry.groups;
  5799. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5800. var group = groups[ k ];
  5801. var groupMaterial = material[ group.materialIndex ];
  5802. if ( groupMaterial && groupMaterial.visible ) {
  5803. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5804. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5805. }
  5806. }
  5807. } else if ( material.visible ) {
  5808. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5809. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5810. }
  5811. }
  5812. }
  5813. var children = object.children;
  5814. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5815. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5816. }
  5817. }
  5818. }
  5819. /**
  5820. * @author mrdoob / http://mrdoob.com/
  5821. */
  5822. function WebGLAttributes( gl ) {
  5823. var buffers = {};
  5824. function createBuffer( attribute, bufferType ) {
  5825. var array = attribute.array;
  5826. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  5827. var buffer = gl.createBuffer();
  5828. gl.bindBuffer( bufferType, buffer );
  5829. gl.bufferData( bufferType, array, usage );
  5830. attribute.onUploadCallback();
  5831. var type = gl.FLOAT;
  5832. if ( array instanceof Float32Array ) {
  5833. type = gl.FLOAT;
  5834. } else if ( array instanceof Float64Array ) {
  5835. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  5836. } else if ( array instanceof Uint16Array ) {
  5837. type = gl.UNSIGNED_SHORT;
  5838. } else if ( array instanceof Int16Array ) {
  5839. type = gl.SHORT;
  5840. } else if ( array instanceof Uint32Array ) {
  5841. type = gl.UNSIGNED_INT;
  5842. } else if ( array instanceof Int32Array ) {
  5843. type = gl.INT;
  5844. } else if ( array instanceof Int8Array ) {
  5845. type = gl.BYTE;
  5846. } else if ( array instanceof Uint8Array ) {
  5847. type = gl.UNSIGNED_BYTE;
  5848. }
  5849. return {
  5850. buffer: buffer,
  5851. type: type,
  5852. bytesPerElement: array.BYTES_PER_ELEMENT,
  5853. version: attribute.version
  5854. };
  5855. }
  5856. function updateBuffer( buffer, attribute, bufferType ) {
  5857. var array = attribute.array;
  5858. var updateRange = attribute.updateRange;
  5859. gl.bindBuffer( bufferType, buffer );
  5860. if ( attribute.dynamic === false ) {
  5861. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  5862. } else if ( updateRange.count === - 1 ) {
  5863. // Not using update ranges
  5864. gl.bufferSubData( bufferType, 0, array );
  5865. } else if ( updateRange.count === 0 ) {
  5866. 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.' );
  5867. } else {
  5868. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  5869. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  5870. updateRange.count = -1; // reset range
  5871. }
  5872. }
  5873. //
  5874. function get( attribute ) {
  5875. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5876. return buffers[ attribute.uuid ];
  5877. }
  5878. function remove( attribute ) {
  5879. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5880. var data = buffers[ attribute.uuid ];
  5881. if ( data ) {
  5882. gl.deleteBuffer( data.buffer );
  5883. delete buffers[ attribute.uuid ];
  5884. }
  5885. }
  5886. function update( attribute, bufferType ) {
  5887. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5888. var data = buffers[ attribute.uuid ];
  5889. if ( data === undefined ) {
  5890. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  5891. } else if ( data.version < attribute.version ) {
  5892. updateBuffer( data.buffer, attribute, bufferType );
  5893. data.version = attribute.version;
  5894. }
  5895. }
  5896. return {
  5897. get: get,
  5898. remove: remove,
  5899. update: update
  5900. };
  5901. }
  5902. /**
  5903. * @author mrdoob / http://mrdoob.com/
  5904. * @author WestLangley / http://github.com/WestLangley
  5905. * @author bhouston / http://clara.io
  5906. */
  5907. function Euler( x, y, z, order ) {
  5908. this._x = x || 0;
  5909. this._y = y || 0;
  5910. this._z = z || 0;
  5911. this._order = order || Euler.DefaultOrder;
  5912. }
  5913. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  5914. Euler.DefaultOrder = 'XYZ';
  5915. Object.defineProperties( Euler.prototype, {
  5916. x: {
  5917. get: function () {
  5918. return this._x;
  5919. },
  5920. set: function ( value ) {
  5921. this._x = value;
  5922. this.onChangeCallback();
  5923. }
  5924. },
  5925. y: {
  5926. get: function () {
  5927. return this._y;
  5928. },
  5929. set: function ( value ) {
  5930. this._y = value;
  5931. this.onChangeCallback();
  5932. }
  5933. },
  5934. z: {
  5935. get: function () {
  5936. return this._z;
  5937. },
  5938. set: function ( value ) {
  5939. this._z = value;
  5940. this.onChangeCallback();
  5941. }
  5942. },
  5943. order: {
  5944. get: function () {
  5945. return this._order;
  5946. },
  5947. set: function ( value ) {
  5948. this._order = value;
  5949. this.onChangeCallback();
  5950. }
  5951. }
  5952. } );
  5953. Object.assign( Euler.prototype, {
  5954. isEuler: true,
  5955. set: function ( x, y, z, order ) {
  5956. this._x = x;
  5957. this._y = y;
  5958. this._z = z;
  5959. this._order = order || this._order;
  5960. this.onChangeCallback();
  5961. return this;
  5962. },
  5963. clone: function () {
  5964. return new this.constructor( this._x, this._y, this._z, this._order );
  5965. },
  5966. copy: function ( euler ) {
  5967. this._x = euler._x;
  5968. this._y = euler._y;
  5969. this._z = euler._z;
  5970. this._order = euler._order;
  5971. this.onChangeCallback();
  5972. return this;
  5973. },
  5974. setFromRotationMatrix: function ( m, order, update ) {
  5975. var clamp = _Math.clamp;
  5976. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5977. var te = m.elements;
  5978. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  5979. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  5980. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  5981. order = order || this._order;
  5982. if ( order === 'XYZ' ) {
  5983. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  5984. if ( Math.abs( m13 ) < 0.99999 ) {
  5985. this._x = Math.atan2( - m23, m33 );
  5986. this._z = Math.atan2( - m12, m11 );
  5987. } else {
  5988. this._x = Math.atan2( m32, m22 );
  5989. this._z = 0;
  5990. }
  5991. } else if ( order === 'YXZ' ) {
  5992. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  5993. if ( Math.abs( m23 ) < 0.99999 ) {
  5994. this._y = Math.atan2( m13, m33 );
  5995. this._z = Math.atan2( m21, m22 );
  5996. } else {
  5997. this._y = Math.atan2( - m31, m11 );
  5998. this._z = 0;
  5999. }
  6000. } else if ( order === 'ZXY' ) {
  6001. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6002. if ( Math.abs( m32 ) < 0.99999 ) {
  6003. this._y = Math.atan2( - m31, m33 );
  6004. this._z = Math.atan2( - m12, m22 );
  6005. } else {
  6006. this._y = 0;
  6007. this._z = Math.atan2( m21, m11 );
  6008. }
  6009. } else if ( order === 'ZYX' ) {
  6010. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6011. if ( Math.abs( m31 ) < 0.99999 ) {
  6012. this._x = Math.atan2( m32, m33 );
  6013. this._z = Math.atan2( m21, m11 );
  6014. } else {
  6015. this._x = 0;
  6016. this._z = Math.atan2( - m12, m22 );
  6017. }
  6018. } else if ( order === 'YZX' ) {
  6019. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6020. if ( Math.abs( m21 ) < 0.99999 ) {
  6021. this._x = Math.atan2( - m23, m22 );
  6022. this._y = Math.atan2( - m31, m11 );
  6023. } else {
  6024. this._x = 0;
  6025. this._y = Math.atan2( m13, m33 );
  6026. }
  6027. } else if ( order === 'XZY' ) {
  6028. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6029. if ( Math.abs( m12 ) < 0.99999 ) {
  6030. this._x = Math.atan2( m32, m22 );
  6031. this._y = Math.atan2( m13, m11 );
  6032. } else {
  6033. this._x = Math.atan2( - m23, m33 );
  6034. this._y = 0;
  6035. }
  6036. } else {
  6037. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6038. }
  6039. this._order = order;
  6040. if ( update !== false ) this.onChangeCallback();
  6041. return this;
  6042. },
  6043. setFromQuaternion: function () {
  6044. var matrix = new Matrix4();
  6045. return function setFromQuaternion( q, order, update ) {
  6046. matrix.makeRotationFromQuaternion( q );
  6047. return this.setFromRotationMatrix( matrix, order, update );
  6048. };
  6049. }(),
  6050. setFromVector3: function ( v, order ) {
  6051. return this.set( v.x, v.y, v.z, order || this._order );
  6052. },
  6053. reorder: function () {
  6054. // WARNING: this discards revolution information -bhouston
  6055. var q = new Quaternion();
  6056. return function reorder( newOrder ) {
  6057. q.setFromEuler( this );
  6058. return this.setFromQuaternion( q, newOrder );
  6059. };
  6060. }(),
  6061. equals: function ( euler ) {
  6062. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6063. },
  6064. fromArray: function ( array ) {
  6065. this._x = array[ 0 ];
  6066. this._y = array[ 1 ];
  6067. this._z = array[ 2 ];
  6068. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6069. this.onChangeCallback();
  6070. return this;
  6071. },
  6072. toArray: function ( array, offset ) {
  6073. if ( array === undefined ) array = [];
  6074. if ( offset === undefined ) offset = 0;
  6075. array[ offset ] = this._x;
  6076. array[ offset + 1 ] = this._y;
  6077. array[ offset + 2 ] = this._z;
  6078. array[ offset + 3 ] = this._order;
  6079. return array;
  6080. },
  6081. toVector3: function ( optionalResult ) {
  6082. if ( optionalResult ) {
  6083. return optionalResult.set( this._x, this._y, this._z );
  6084. } else {
  6085. return new Vector3( this._x, this._y, this._z );
  6086. }
  6087. },
  6088. onChange: function ( callback ) {
  6089. this.onChangeCallback = callback;
  6090. return this;
  6091. },
  6092. onChangeCallback: function () {}
  6093. } );
  6094. /**
  6095. * @author mrdoob / http://mrdoob.com/
  6096. */
  6097. function Layers() {
  6098. this.mask = 1 | 0;
  6099. }
  6100. Object.assign( Layers.prototype, {
  6101. set: function ( channel ) {
  6102. this.mask = 1 << channel | 0;
  6103. },
  6104. enable: function ( channel ) {
  6105. this.mask |= 1 << channel | 0;
  6106. },
  6107. toggle: function ( channel ) {
  6108. this.mask ^= 1 << channel | 0;
  6109. },
  6110. disable: function ( channel ) {
  6111. this.mask &= ~ ( 1 << channel | 0 );
  6112. },
  6113. test: function ( layers ) {
  6114. return ( this.mask & layers.mask ) !== 0;
  6115. }
  6116. } );
  6117. /**
  6118. * @author mrdoob / http://mrdoob.com/
  6119. * @author mikael emtinger / http://gomo.se/
  6120. * @author alteredq / http://alteredqualia.com/
  6121. * @author WestLangley / http://github.com/WestLangley
  6122. * @author elephantatwork / www.elephantatwork.ch
  6123. */
  6124. var object3DId = 0;
  6125. function Object3D() {
  6126. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6127. this.uuid = _Math.generateUUID();
  6128. this.name = '';
  6129. this.type = 'Object3D';
  6130. this.parent = null;
  6131. this.children = [];
  6132. this.up = Object3D.DefaultUp.clone();
  6133. var position = new Vector3();
  6134. var rotation = new Euler();
  6135. var quaternion = new Quaternion();
  6136. var scale = new Vector3( 1, 1, 1 );
  6137. function onRotationChange() {
  6138. quaternion.setFromEuler( rotation, false );
  6139. }
  6140. function onQuaternionChange() {
  6141. rotation.setFromQuaternion( quaternion, undefined, false );
  6142. }
  6143. rotation.onChange( onRotationChange );
  6144. quaternion.onChange( onQuaternionChange );
  6145. Object.defineProperties( this, {
  6146. position: {
  6147. enumerable: true,
  6148. value: position
  6149. },
  6150. rotation: {
  6151. enumerable: true,
  6152. value: rotation
  6153. },
  6154. quaternion: {
  6155. enumerable: true,
  6156. value: quaternion
  6157. },
  6158. scale: {
  6159. enumerable: true,
  6160. value: scale
  6161. },
  6162. modelViewMatrix: {
  6163. value: new Matrix4()
  6164. },
  6165. normalMatrix: {
  6166. value: new Matrix3()
  6167. }
  6168. } );
  6169. this.matrix = new Matrix4();
  6170. this.matrixWorld = new Matrix4();
  6171. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6172. this.matrixWorldNeedsUpdate = false;
  6173. this.layers = new Layers();
  6174. this.visible = true;
  6175. this.castShadow = false;
  6176. this.receiveShadow = false;
  6177. this.frustumCulled = true;
  6178. this.renderOrder = 0;
  6179. this.userData = {};
  6180. }
  6181. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6182. Object3D.DefaultMatrixAutoUpdate = true;
  6183. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6184. isObject3D: true,
  6185. onBeforeRender: function () {},
  6186. onAfterRender: function () {},
  6187. applyMatrix: function ( matrix ) {
  6188. this.matrix.multiplyMatrices( matrix, this.matrix );
  6189. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6190. },
  6191. applyQuaternion: function ( q ) {
  6192. this.quaternion.premultiply( q );
  6193. return this;
  6194. },
  6195. setRotationFromAxisAngle: function ( axis, angle ) {
  6196. // assumes axis is normalized
  6197. this.quaternion.setFromAxisAngle( axis, angle );
  6198. },
  6199. setRotationFromEuler: function ( euler ) {
  6200. this.quaternion.setFromEuler( euler, true );
  6201. },
  6202. setRotationFromMatrix: function ( m ) {
  6203. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6204. this.quaternion.setFromRotationMatrix( m );
  6205. },
  6206. setRotationFromQuaternion: function ( q ) {
  6207. // assumes q is normalized
  6208. this.quaternion.copy( q );
  6209. },
  6210. rotateOnAxis: function () {
  6211. // rotate object on axis in object space
  6212. // axis is assumed to be normalized
  6213. var q1 = new Quaternion();
  6214. return function rotateOnAxis( axis, angle ) {
  6215. q1.setFromAxisAngle( axis, angle );
  6216. this.quaternion.multiply( q1 );
  6217. return this;
  6218. };
  6219. }(),
  6220. rotateX: function () {
  6221. var v1 = new Vector3( 1, 0, 0 );
  6222. return function rotateX( angle ) {
  6223. return this.rotateOnAxis( v1, angle );
  6224. };
  6225. }(),
  6226. rotateY: function () {
  6227. var v1 = new Vector3( 0, 1, 0 );
  6228. return function rotateY( angle ) {
  6229. return this.rotateOnAxis( v1, angle );
  6230. };
  6231. }(),
  6232. rotateZ: function () {
  6233. var v1 = new Vector3( 0, 0, 1 );
  6234. return function rotateZ( angle ) {
  6235. return this.rotateOnAxis( v1, angle );
  6236. };
  6237. }(),
  6238. translateOnAxis: function () {
  6239. // translate object by distance along axis in object space
  6240. // axis is assumed to be normalized
  6241. var v1 = new Vector3();
  6242. return function translateOnAxis( axis, distance ) {
  6243. v1.copy( axis ).applyQuaternion( this.quaternion );
  6244. this.position.add( v1.multiplyScalar( distance ) );
  6245. return this;
  6246. };
  6247. }(),
  6248. translateX: function () {
  6249. var v1 = new Vector3( 1, 0, 0 );
  6250. return function translateX( distance ) {
  6251. return this.translateOnAxis( v1, distance );
  6252. };
  6253. }(),
  6254. translateY: function () {
  6255. var v1 = new Vector3( 0, 1, 0 );
  6256. return function translateY( distance ) {
  6257. return this.translateOnAxis( v1, distance );
  6258. };
  6259. }(),
  6260. translateZ: function () {
  6261. var v1 = new Vector3( 0, 0, 1 );
  6262. return function translateZ( distance ) {
  6263. return this.translateOnAxis( v1, distance );
  6264. };
  6265. }(),
  6266. localToWorld: function ( vector ) {
  6267. return vector.applyMatrix4( this.matrixWorld );
  6268. },
  6269. worldToLocal: function () {
  6270. var m1 = new Matrix4();
  6271. return function worldToLocal( vector ) {
  6272. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6273. };
  6274. }(),
  6275. lookAt: function () {
  6276. // This method does not support objects with rotated and/or translated parent(s)
  6277. var m1 = new Matrix4();
  6278. return function lookAt( vector ) {
  6279. if ( this.isCamera ) {
  6280. m1.lookAt( this.position, vector, this.up );
  6281. } else {
  6282. m1.lookAt( vector, this.position, this.up );
  6283. }
  6284. this.quaternion.setFromRotationMatrix( m1 );
  6285. };
  6286. }(),
  6287. add: function ( object ) {
  6288. if ( arguments.length > 1 ) {
  6289. for ( var i = 0; i < arguments.length; i ++ ) {
  6290. this.add( arguments[ i ] );
  6291. }
  6292. return this;
  6293. }
  6294. if ( object === this ) {
  6295. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6296. return this;
  6297. }
  6298. if ( ( object && object.isObject3D ) ) {
  6299. if ( object.parent !== null ) {
  6300. object.parent.remove( object );
  6301. }
  6302. object.parent = this;
  6303. object.dispatchEvent( { type: 'added' } );
  6304. this.children.push( object );
  6305. } else {
  6306. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6307. }
  6308. return this;
  6309. },
  6310. remove: function ( object ) {
  6311. if ( arguments.length > 1 ) {
  6312. for ( var i = 0; i < arguments.length; i ++ ) {
  6313. this.remove( arguments[ i ] );
  6314. }
  6315. return this;
  6316. }
  6317. var index = this.children.indexOf( object );
  6318. if ( index !== - 1 ) {
  6319. object.parent = null;
  6320. object.dispatchEvent( { type: 'removed' } );
  6321. this.children.splice( index, 1 );
  6322. }
  6323. return this;
  6324. },
  6325. getObjectById: function ( id ) {
  6326. return this.getObjectByProperty( 'id', id );
  6327. },
  6328. getObjectByName: function ( name ) {
  6329. return this.getObjectByProperty( 'name', name );
  6330. },
  6331. getObjectByProperty: function ( name, value ) {
  6332. if ( this[ name ] === value ) return this;
  6333. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6334. var child = this.children[ i ];
  6335. var object = child.getObjectByProperty( name, value );
  6336. if ( object !== undefined ) {
  6337. return object;
  6338. }
  6339. }
  6340. return undefined;
  6341. },
  6342. getWorldPosition: function ( optionalTarget ) {
  6343. var result = optionalTarget || new Vector3();
  6344. this.updateMatrixWorld( true );
  6345. return result.setFromMatrixPosition( this.matrixWorld );
  6346. },
  6347. getWorldQuaternion: function () {
  6348. var position = new Vector3();
  6349. var scale = new Vector3();
  6350. return function getWorldQuaternion( optionalTarget ) {
  6351. var result = optionalTarget || new Quaternion();
  6352. this.updateMatrixWorld( true );
  6353. this.matrixWorld.decompose( position, result, scale );
  6354. return result;
  6355. };
  6356. }(),
  6357. getWorldRotation: function () {
  6358. var quaternion = new Quaternion();
  6359. return function getWorldRotation( optionalTarget ) {
  6360. var result = optionalTarget || new Euler();
  6361. this.getWorldQuaternion( quaternion );
  6362. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6363. };
  6364. }(),
  6365. getWorldScale: function () {
  6366. var position = new Vector3();
  6367. var quaternion = new Quaternion();
  6368. return function getWorldScale( optionalTarget ) {
  6369. var result = optionalTarget || new Vector3();
  6370. this.updateMatrixWorld( true );
  6371. this.matrixWorld.decompose( position, quaternion, result );
  6372. return result;
  6373. };
  6374. }(),
  6375. getWorldDirection: function () {
  6376. var quaternion = new Quaternion();
  6377. return function getWorldDirection( optionalTarget ) {
  6378. var result = optionalTarget || new Vector3();
  6379. this.getWorldQuaternion( quaternion );
  6380. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6381. };
  6382. }(),
  6383. raycast: function () {},
  6384. traverse: function ( callback ) {
  6385. callback( this );
  6386. var children = this.children;
  6387. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6388. children[ i ].traverse( callback );
  6389. }
  6390. },
  6391. traverseVisible: function ( callback ) {
  6392. if ( this.visible === false ) return;
  6393. callback( this );
  6394. var children = this.children;
  6395. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6396. children[ i ].traverseVisible( callback );
  6397. }
  6398. },
  6399. traverseAncestors: function ( callback ) {
  6400. var parent = this.parent;
  6401. if ( parent !== null ) {
  6402. callback( parent );
  6403. parent.traverseAncestors( callback );
  6404. }
  6405. },
  6406. updateMatrix: function () {
  6407. this.matrix.compose( this.position, this.quaternion, this.scale );
  6408. this.matrixWorldNeedsUpdate = true;
  6409. },
  6410. updateMatrixWorld: function ( force ) {
  6411. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6412. if ( this.matrixWorldNeedsUpdate || force ) {
  6413. if ( this.parent === null ) {
  6414. this.matrixWorld.copy( this.matrix );
  6415. } else {
  6416. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6417. }
  6418. this.matrixWorldNeedsUpdate = false;
  6419. force = true;
  6420. }
  6421. // update children
  6422. var children = this.children;
  6423. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6424. children[ i ].updateMatrixWorld( force );
  6425. }
  6426. },
  6427. toJSON: function ( meta ) {
  6428. // meta is '' when called from JSON.stringify
  6429. var isRootObject = ( meta === undefined || meta === '' );
  6430. var output = {};
  6431. // meta is a hash used to collect geometries, materials.
  6432. // not providing it implies that this is the root object
  6433. // being serialized.
  6434. if ( isRootObject ) {
  6435. // initialize meta obj
  6436. meta = {
  6437. geometries: {},
  6438. materials: {},
  6439. textures: {},
  6440. images: {}
  6441. };
  6442. output.metadata = {
  6443. version: 4.5,
  6444. type: 'Object',
  6445. generator: 'Object3D.toJSON'
  6446. };
  6447. }
  6448. // standard Object3D serialization
  6449. var object = {};
  6450. object.uuid = this.uuid;
  6451. object.type = this.type;
  6452. if ( this.name !== '' ) object.name = this.name;
  6453. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6454. if ( this.castShadow === true ) object.castShadow = true;
  6455. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6456. if ( this.visible === false ) object.visible = false;
  6457. object.matrix = this.matrix.toArray();
  6458. //
  6459. function serialize( library, element ) {
  6460. if ( library[ element.uuid ] === undefined ) {
  6461. library[ element.uuid ] = element.toJSON( meta );
  6462. }
  6463. return element.uuid;
  6464. }
  6465. if ( this.geometry !== undefined ) {
  6466. object.geometry = serialize( meta.geometries, this.geometry );
  6467. }
  6468. if ( this.material !== undefined ) {
  6469. if ( Array.isArray( this.material ) ) {
  6470. var uuids = [];
  6471. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6472. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6473. }
  6474. object.material = uuids;
  6475. } else {
  6476. object.material = serialize( meta.materials, this.material );
  6477. }
  6478. }
  6479. //
  6480. if ( this.children.length > 0 ) {
  6481. object.children = [];
  6482. for ( var i = 0; i < this.children.length; i ++ ) {
  6483. object.children.push( this.children[ i ].toJSON( meta ).object );
  6484. }
  6485. }
  6486. if ( isRootObject ) {
  6487. var geometries = extractFromCache( meta.geometries );
  6488. var materials = extractFromCache( meta.materials );
  6489. var textures = extractFromCache( meta.textures );
  6490. var images = extractFromCache( meta.images );
  6491. if ( geometries.length > 0 ) output.geometries = geometries;
  6492. if ( materials.length > 0 ) output.materials = materials;
  6493. if ( textures.length > 0 ) output.textures = textures;
  6494. if ( images.length > 0 ) output.images = images;
  6495. }
  6496. output.object = object;
  6497. return output;
  6498. // extract data from the cache hash
  6499. // remove metadata on each item
  6500. // and return as array
  6501. function extractFromCache( cache ) {
  6502. var values = [];
  6503. for ( var key in cache ) {
  6504. var data = cache[ key ];
  6505. delete data.metadata;
  6506. values.push( data );
  6507. }
  6508. return values;
  6509. }
  6510. },
  6511. clone: function ( recursive ) {
  6512. return new this.constructor().copy( this, recursive );
  6513. },
  6514. copy: function ( source, recursive ) {
  6515. if ( recursive === undefined ) recursive = true;
  6516. this.name = source.name;
  6517. this.up.copy( source.up );
  6518. this.position.copy( source.position );
  6519. this.quaternion.copy( source.quaternion );
  6520. this.scale.copy( source.scale );
  6521. this.matrix.copy( source.matrix );
  6522. this.matrixWorld.copy( source.matrixWorld );
  6523. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6524. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6525. this.layers.mask = source.layers.mask;
  6526. this.visible = source.visible;
  6527. this.castShadow = source.castShadow;
  6528. this.receiveShadow = source.receiveShadow;
  6529. this.frustumCulled = source.frustumCulled;
  6530. this.renderOrder = source.renderOrder;
  6531. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6532. if ( recursive === true ) {
  6533. for ( var i = 0; i < source.children.length; i ++ ) {
  6534. var child = source.children[ i ];
  6535. this.add( child.clone() );
  6536. }
  6537. }
  6538. return this;
  6539. }
  6540. } );
  6541. /**
  6542. * @author mrdoob / http://mrdoob.com/
  6543. * @author mikael emtinger / http://gomo.se/
  6544. * @author WestLangley / http://github.com/WestLangley
  6545. */
  6546. function Camera() {
  6547. Object3D.call( this );
  6548. this.type = 'Camera';
  6549. this.matrixWorldInverse = new Matrix4();
  6550. this.projectionMatrix = new Matrix4();
  6551. }
  6552. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6553. constructor: Camera,
  6554. isCamera: true,
  6555. copy: function ( source, recursive ) {
  6556. Object3D.prototype.copy.call( this, source, recursive );
  6557. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6558. this.projectionMatrix.copy( source.projectionMatrix );
  6559. return this;
  6560. },
  6561. getWorldDirection: function () {
  6562. var quaternion = new Quaternion();
  6563. return function getWorldDirection( optionalTarget ) {
  6564. var result = optionalTarget || new Vector3();
  6565. this.getWorldQuaternion( quaternion );
  6566. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6567. };
  6568. }(),
  6569. updateMatrixWorld: function ( force ) {
  6570. Object3D.prototype.updateMatrixWorld.call( this, force );
  6571. this.matrixWorldInverse.getInverse( this.matrixWorld );
  6572. },
  6573. clone: function () {
  6574. return new this.constructor().copy( this );
  6575. }
  6576. } );
  6577. /**
  6578. * @author alteredq / http://alteredqualia.com/
  6579. * @author arose / http://github.com/arose
  6580. */
  6581. function OrthographicCamera( left, right, top, bottom, near, far ) {
  6582. Camera.call( this );
  6583. this.type = 'OrthographicCamera';
  6584. this.zoom = 1;
  6585. this.view = null;
  6586. this.left = left;
  6587. this.right = right;
  6588. this.top = top;
  6589. this.bottom = bottom;
  6590. this.near = ( near !== undefined ) ? near : 0.1;
  6591. this.far = ( far !== undefined ) ? far : 2000;
  6592. this.updateProjectionMatrix();
  6593. }
  6594. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6595. constructor: OrthographicCamera,
  6596. isOrthographicCamera: true,
  6597. copy: function ( source, recursive ) {
  6598. Camera.prototype.copy.call( this, source, recursive );
  6599. this.left = source.left;
  6600. this.right = source.right;
  6601. this.top = source.top;
  6602. this.bottom = source.bottom;
  6603. this.near = source.near;
  6604. this.far = source.far;
  6605. this.zoom = source.zoom;
  6606. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6607. return this;
  6608. },
  6609. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  6610. this.view = {
  6611. fullWidth: fullWidth,
  6612. fullHeight: fullHeight,
  6613. offsetX: x,
  6614. offsetY: y,
  6615. width: width,
  6616. height: height
  6617. };
  6618. this.updateProjectionMatrix();
  6619. },
  6620. clearViewOffset: function() {
  6621. this.view = null;
  6622. this.updateProjectionMatrix();
  6623. },
  6624. updateProjectionMatrix: function () {
  6625. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6626. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6627. var cx = ( this.right + this.left ) / 2;
  6628. var cy = ( this.top + this.bottom ) / 2;
  6629. var left = cx - dx;
  6630. var right = cx + dx;
  6631. var top = cy + dy;
  6632. var bottom = cy - dy;
  6633. if ( this.view !== null ) {
  6634. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  6635. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  6636. var scaleW = ( this.right - this.left ) / this.view.width;
  6637. var scaleH = ( this.top - this.bottom ) / this.view.height;
  6638. left += scaleW * ( this.view.offsetX / zoomW );
  6639. right = left + scaleW * ( this.view.width / zoomW );
  6640. top -= scaleH * ( this.view.offsetY / zoomH );
  6641. bottom = top - scaleH * ( this.view.height / zoomH );
  6642. }
  6643. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  6644. },
  6645. toJSON: function ( meta ) {
  6646. var data = Object3D.prototype.toJSON.call( this, meta );
  6647. data.object.zoom = this.zoom;
  6648. data.object.left = this.left;
  6649. data.object.right = this.right;
  6650. data.object.top = this.top;
  6651. data.object.bottom = this.bottom;
  6652. data.object.near = this.near;
  6653. data.object.far = this.far;
  6654. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6655. return data;
  6656. }
  6657. } );
  6658. /**
  6659. * @author mrdoob / http://mrdoob.com/
  6660. * @author greggman / http://games.greggman.com/
  6661. * @author zz85 / http://www.lab4games.net/zz85/blog
  6662. * @author tschw
  6663. */
  6664. function PerspectiveCamera( fov, aspect, near, far ) {
  6665. Camera.call( this );
  6666. this.type = 'PerspectiveCamera';
  6667. this.fov = fov !== undefined ? fov : 50;
  6668. this.zoom = 1;
  6669. this.near = near !== undefined ? near : 0.1;
  6670. this.far = far !== undefined ? far : 2000;
  6671. this.focus = 10;
  6672. this.aspect = aspect !== undefined ? aspect : 1;
  6673. this.view = null;
  6674. this.filmGauge = 35; // width of the film (default in millimeters)
  6675. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6676. this.updateProjectionMatrix();
  6677. }
  6678. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6679. constructor: PerspectiveCamera,
  6680. isPerspectiveCamera: true,
  6681. copy: function ( source, recursive ) {
  6682. Camera.prototype.copy.call( this, source, recursive );
  6683. this.fov = source.fov;
  6684. this.zoom = source.zoom;
  6685. this.near = source.near;
  6686. this.far = source.far;
  6687. this.focus = source.focus;
  6688. this.aspect = source.aspect;
  6689. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6690. this.filmGauge = source.filmGauge;
  6691. this.filmOffset = source.filmOffset;
  6692. return this;
  6693. },
  6694. /**
  6695. * Sets the FOV by focal length in respect to the current .filmGauge.
  6696. *
  6697. * The default film gauge is 35, so that the focal length can be specified for
  6698. * a 35mm (full frame) camera.
  6699. *
  6700. * Values for focal length and film gauge must have the same unit.
  6701. */
  6702. setFocalLength: function ( focalLength ) {
  6703. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  6704. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6705. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  6706. this.updateProjectionMatrix();
  6707. },
  6708. /**
  6709. * Calculates the focal length from the current .fov and .filmGauge.
  6710. */
  6711. getFocalLength: function () {
  6712. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  6713. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6714. },
  6715. getEffectiveFOV: function () {
  6716. return _Math.RAD2DEG * 2 * Math.atan(
  6717. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6718. },
  6719. getFilmWidth: function () {
  6720. // film not completely covered in portrait format (aspect < 1)
  6721. return this.filmGauge * Math.min( this.aspect, 1 );
  6722. },
  6723. getFilmHeight: function () {
  6724. // film not completely covered in landscape format (aspect > 1)
  6725. return this.filmGauge / Math.max( this.aspect, 1 );
  6726. },
  6727. /**
  6728. * Sets an offset in a larger frustum. This is useful for multi-window or
  6729. * multi-monitor/multi-machine setups.
  6730. *
  6731. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6732. * the monitors are in grid like this
  6733. *
  6734. * +---+---+---+
  6735. * | A | B | C |
  6736. * +---+---+---+
  6737. * | D | E | F |
  6738. * +---+---+---+
  6739. *
  6740. * then for each monitor you would call it like this
  6741. *
  6742. * var w = 1920;
  6743. * var h = 1080;
  6744. * var fullWidth = w * 3;
  6745. * var fullHeight = h * 2;
  6746. *
  6747. * --A--
  6748. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6749. * --B--
  6750. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6751. * --C--
  6752. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6753. * --D--
  6754. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6755. * --E--
  6756. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6757. * --F--
  6758. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6759. *
  6760. * Note there is no reason monitors have to be the same size or in a grid.
  6761. */
  6762. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  6763. this.aspect = fullWidth / fullHeight;
  6764. this.view = {
  6765. fullWidth: fullWidth,
  6766. fullHeight: fullHeight,
  6767. offsetX: x,
  6768. offsetY: y,
  6769. width: width,
  6770. height: height
  6771. };
  6772. this.updateProjectionMatrix();
  6773. },
  6774. clearViewOffset: function () {
  6775. this.view = null;
  6776. this.updateProjectionMatrix();
  6777. },
  6778. updateProjectionMatrix: function () {
  6779. var near = this.near,
  6780. top = near * Math.tan(
  6781. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  6782. height = 2 * top,
  6783. width = this.aspect * height,
  6784. left = - 0.5 * width,
  6785. view = this.view;
  6786. if ( view !== null ) {
  6787. var fullWidth = view.fullWidth,
  6788. fullHeight = view.fullHeight;
  6789. left += view.offsetX * width / fullWidth;
  6790. top -= view.offsetY * height / fullHeight;
  6791. width *= view.width / fullWidth;
  6792. height *= view.height / fullHeight;
  6793. }
  6794. var skew = this.filmOffset;
  6795. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6796. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6797. },
  6798. toJSON: function ( meta ) {
  6799. var data = Object3D.prototype.toJSON.call( this, meta );
  6800. data.object.fov = this.fov;
  6801. data.object.zoom = this.zoom;
  6802. data.object.near = this.near;
  6803. data.object.far = this.far;
  6804. data.object.focus = this.focus;
  6805. data.object.aspect = this.aspect;
  6806. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6807. data.object.filmGauge = this.filmGauge;
  6808. data.object.filmOffset = this.filmOffset;
  6809. return data;
  6810. }
  6811. } );
  6812. /**
  6813. * @author mrdoob / http://mrdoob.com/
  6814. * @author alteredq / http://alteredqualia.com/
  6815. */
  6816. function Face3( a, b, c, normal, color, materialIndex ) {
  6817. this.a = a;
  6818. this.b = b;
  6819. this.c = c;
  6820. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6821. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6822. this.color = ( color && color.isColor ) ? color : new Color();
  6823. this.vertexColors = Array.isArray( color ) ? color : [];
  6824. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6825. }
  6826. Object.assign( Face3.prototype, {
  6827. clone: function () {
  6828. return new this.constructor().copy( this );
  6829. },
  6830. copy: function ( source ) {
  6831. this.a = source.a;
  6832. this.b = source.b;
  6833. this.c = source.c;
  6834. this.normal.copy( source.normal );
  6835. this.color.copy( source.color );
  6836. this.materialIndex = source.materialIndex;
  6837. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6838. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6839. }
  6840. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6841. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6842. }
  6843. return this;
  6844. }
  6845. } );
  6846. /**
  6847. * @author mrdoob / http://mrdoob.com/
  6848. * @author kile / http://kile.stravaganza.org/
  6849. * @author alteredq / http://alteredqualia.com/
  6850. * @author mikael emtinger / http://gomo.se/
  6851. * @author zz85 / http://www.lab4games.net/zz85/blog
  6852. * @author bhouston / http://clara.io
  6853. */
  6854. var count = 0;
  6855. function GeometryIdCount() { return count++; }
  6856. function Geometry() {
  6857. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6858. this.uuid = _Math.generateUUID();
  6859. this.name = '';
  6860. this.type = 'Geometry';
  6861. this.vertices = [];
  6862. this.colors = [];
  6863. this.faces = [];
  6864. this.faceVertexUvs = [[]];
  6865. this.morphTargets = [];
  6866. this.morphNormals = [];
  6867. this.skinWeights = [];
  6868. this.skinIndices = [];
  6869. this.lineDistances = [];
  6870. this.boundingBox = null;
  6871. this.boundingSphere = null;
  6872. // update flags
  6873. this.elementsNeedUpdate = false;
  6874. this.verticesNeedUpdate = false;
  6875. this.uvsNeedUpdate = false;
  6876. this.normalsNeedUpdate = false;
  6877. this.colorsNeedUpdate = false;
  6878. this.lineDistancesNeedUpdate = false;
  6879. this.groupsNeedUpdate = false;
  6880. }
  6881. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  6882. isGeometry: true,
  6883. applyMatrix: function ( matrix ) {
  6884. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6885. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  6886. var vertex = this.vertices[ i ];
  6887. vertex.applyMatrix4( matrix );
  6888. }
  6889. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  6890. var face = this.faces[ i ];
  6891. face.normal.applyMatrix3( normalMatrix ).normalize();
  6892. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6893. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6894. }
  6895. }
  6896. if ( this.boundingBox !== null ) {
  6897. this.computeBoundingBox();
  6898. }
  6899. if ( this.boundingSphere !== null ) {
  6900. this.computeBoundingSphere();
  6901. }
  6902. this.verticesNeedUpdate = true;
  6903. this.normalsNeedUpdate = true;
  6904. return this;
  6905. },
  6906. rotateX: function () {
  6907. // rotate geometry around world x-axis
  6908. var m1 = new Matrix4();
  6909. return function rotateX( angle ) {
  6910. m1.makeRotationX( angle );
  6911. this.applyMatrix( m1 );
  6912. return this;
  6913. };
  6914. }(),
  6915. rotateY: function () {
  6916. // rotate geometry around world y-axis
  6917. var m1 = new Matrix4();
  6918. return function rotateY( angle ) {
  6919. m1.makeRotationY( angle );
  6920. this.applyMatrix( m1 );
  6921. return this;
  6922. };
  6923. }(),
  6924. rotateZ: function () {
  6925. // rotate geometry around world z-axis
  6926. var m1 = new Matrix4();
  6927. return function rotateZ( angle ) {
  6928. m1.makeRotationZ( angle );
  6929. this.applyMatrix( m1 );
  6930. return this;
  6931. };
  6932. }(),
  6933. translate: function () {
  6934. // translate geometry
  6935. var m1 = new Matrix4();
  6936. return function translate( x, y, z ) {
  6937. m1.makeTranslation( x, y, z );
  6938. this.applyMatrix( m1 );
  6939. return this;
  6940. };
  6941. }(),
  6942. scale: function () {
  6943. // scale geometry
  6944. var m1 = new Matrix4();
  6945. return function scale( x, y, z ) {
  6946. m1.makeScale( x, y, z );
  6947. this.applyMatrix( m1 );
  6948. return this;
  6949. };
  6950. }(),
  6951. lookAt: function () {
  6952. var obj = new Object3D();
  6953. return function lookAt( vector ) {
  6954. obj.lookAt( vector );
  6955. obj.updateMatrix();
  6956. this.applyMatrix( obj.matrix );
  6957. };
  6958. }(),
  6959. fromBufferGeometry: function ( geometry ) {
  6960. var scope = this;
  6961. var indices = geometry.index !== null ? geometry.index.array : undefined;
  6962. var attributes = geometry.attributes;
  6963. var positions = attributes.position.array;
  6964. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  6965. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  6966. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  6967. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  6968. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  6969. var tempNormals = [];
  6970. var tempUVs = [];
  6971. var tempUVs2 = [];
  6972. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  6973. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  6974. if ( normals !== undefined ) {
  6975. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  6976. }
  6977. if ( colors !== undefined ) {
  6978. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  6979. }
  6980. if ( uvs !== undefined ) {
  6981. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  6982. }
  6983. if ( uvs2 !== undefined ) {
  6984. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  6985. }
  6986. }
  6987. function addFace( a, b, c, materialIndex ) {
  6988. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  6989. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  6990. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  6991. scope.faces.push( face );
  6992. if ( uvs !== undefined ) {
  6993. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  6994. }
  6995. if ( uvs2 !== undefined ) {
  6996. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  6997. }
  6998. }
  6999. var groups = geometry.groups;
  7000. if ( groups.length > 0 ) {
  7001. for ( var i = 0; i < groups.length; i ++ ) {
  7002. var group = groups[ i ];
  7003. var start = group.start;
  7004. var count = group.count;
  7005. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7006. if ( indices !== undefined ) {
  7007. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7008. } else {
  7009. addFace( j, j + 1, j + 2, group.materialIndex );
  7010. }
  7011. }
  7012. }
  7013. } else {
  7014. if ( indices !== undefined ) {
  7015. for ( var i = 0; i < indices.length; i += 3 ) {
  7016. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7017. }
  7018. } else {
  7019. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7020. addFace( i, i + 1, i + 2 );
  7021. }
  7022. }
  7023. }
  7024. this.computeFaceNormals();
  7025. if ( geometry.boundingBox !== null ) {
  7026. this.boundingBox = geometry.boundingBox.clone();
  7027. }
  7028. if ( geometry.boundingSphere !== null ) {
  7029. this.boundingSphere = geometry.boundingSphere.clone();
  7030. }
  7031. return this;
  7032. },
  7033. center: function () {
  7034. this.computeBoundingBox();
  7035. var offset = this.boundingBox.getCenter().negate();
  7036. this.translate( offset.x, offset.y, offset.z );
  7037. return offset;
  7038. },
  7039. normalize: function () {
  7040. this.computeBoundingSphere();
  7041. var center = this.boundingSphere.center;
  7042. var radius = this.boundingSphere.radius;
  7043. var s = radius === 0 ? 1 : 1.0 / radius;
  7044. var matrix = new Matrix4();
  7045. matrix.set(
  7046. s, 0, 0, - s * center.x,
  7047. 0, s, 0, - s * center.y,
  7048. 0, 0, s, - s * center.z,
  7049. 0, 0, 0, 1
  7050. );
  7051. this.applyMatrix( matrix );
  7052. return this;
  7053. },
  7054. computeFaceNormals: function () {
  7055. var cb = new Vector3(), ab = new Vector3();
  7056. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7057. var face = this.faces[ f ];
  7058. var vA = this.vertices[ face.a ];
  7059. var vB = this.vertices[ face.b ];
  7060. var vC = this.vertices[ face.c ];
  7061. cb.subVectors( vC, vB );
  7062. ab.subVectors( vA, vB );
  7063. cb.cross( ab );
  7064. cb.normalize();
  7065. face.normal.copy( cb );
  7066. }
  7067. },
  7068. computeVertexNormals: function ( areaWeighted ) {
  7069. if ( areaWeighted === undefined ) areaWeighted = true;
  7070. var v, vl, f, fl, face, vertices;
  7071. vertices = new Array( this.vertices.length );
  7072. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7073. vertices[ v ] = new Vector3();
  7074. }
  7075. if ( areaWeighted ) {
  7076. // vertex normals weighted by triangle areas
  7077. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7078. var vA, vB, vC;
  7079. var cb = new Vector3(), ab = new Vector3();
  7080. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7081. face = this.faces[ f ];
  7082. vA = this.vertices[ face.a ];
  7083. vB = this.vertices[ face.b ];
  7084. vC = this.vertices[ face.c ];
  7085. cb.subVectors( vC, vB );
  7086. ab.subVectors( vA, vB );
  7087. cb.cross( ab );
  7088. vertices[ face.a ].add( cb );
  7089. vertices[ face.b ].add( cb );
  7090. vertices[ face.c ].add( cb );
  7091. }
  7092. } else {
  7093. this.computeFaceNormals();
  7094. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7095. face = this.faces[ f ];
  7096. vertices[ face.a ].add( face.normal );
  7097. vertices[ face.b ].add( face.normal );
  7098. vertices[ face.c ].add( face.normal );
  7099. }
  7100. }
  7101. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7102. vertices[ v ].normalize();
  7103. }
  7104. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7105. face = this.faces[ f ];
  7106. var vertexNormals = face.vertexNormals;
  7107. if ( vertexNormals.length === 3 ) {
  7108. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7109. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7110. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7111. } else {
  7112. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7113. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7114. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7115. }
  7116. }
  7117. if ( this.faces.length > 0 ) {
  7118. this.normalsNeedUpdate = true;
  7119. }
  7120. },
  7121. computeFlatVertexNormals: function () {
  7122. var f, fl, face;
  7123. this.computeFaceNormals();
  7124. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7125. face = this.faces[ f ];
  7126. var vertexNormals = face.vertexNormals;
  7127. if ( vertexNormals.length === 3 ) {
  7128. vertexNormals[ 0 ].copy( face.normal );
  7129. vertexNormals[ 1 ].copy( face.normal );
  7130. vertexNormals[ 2 ].copy( face.normal );
  7131. } else {
  7132. vertexNormals[ 0 ] = face.normal.clone();
  7133. vertexNormals[ 1 ] = face.normal.clone();
  7134. vertexNormals[ 2 ] = face.normal.clone();
  7135. }
  7136. }
  7137. if ( this.faces.length > 0 ) {
  7138. this.normalsNeedUpdate = true;
  7139. }
  7140. },
  7141. computeMorphNormals: function () {
  7142. var i, il, f, fl, face;
  7143. // save original normals
  7144. // - create temp variables on first access
  7145. // otherwise just copy (for faster repeated calls)
  7146. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7147. face = this.faces[ f ];
  7148. if ( ! face.__originalFaceNormal ) {
  7149. face.__originalFaceNormal = face.normal.clone();
  7150. } else {
  7151. face.__originalFaceNormal.copy( face.normal );
  7152. }
  7153. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7154. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7155. if ( ! face.__originalVertexNormals[ i ] ) {
  7156. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7157. } else {
  7158. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7159. }
  7160. }
  7161. }
  7162. // use temp geometry to compute face and vertex normals for each morph
  7163. var tmpGeo = new Geometry();
  7164. tmpGeo.faces = this.faces;
  7165. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7166. // create on first access
  7167. if ( ! this.morphNormals[ i ] ) {
  7168. this.morphNormals[ i ] = {};
  7169. this.morphNormals[ i ].faceNormals = [];
  7170. this.morphNormals[ i ].vertexNormals = [];
  7171. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7172. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7173. var faceNormal, vertexNormals;
  7174. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7175. faceNormal = new Vector3();
  7176. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7177. dstNormalsFace.push( faceNormal );
  7178. dstNormalsVertex.push( vertexNormals );
  7179. }
  7180. }
  7181. var morphNormals = this.morphNormals[ i ];
  7182. // set vertices to morph target
  7183. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7184. // compute morph normals
  7185. tmpGeo.computeFaceNormals();
  7186. tmpGeo.computeVertexNormals();
  7187. // store morph normals
  7188. var faceNormal, vertexNormals;
  7189. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7190. face = this.faces[ f ];
  7191. faceNormal = morphNormals.faceNormals[ f ];
  7192. vertexNormals = morphNormals.vertexNormals[ f ];
  7193. faceNormal.copy( face.normal );
  7194. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7195. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7196. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7197. }
  7198. }
  7199. // restore original normals
  7200. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7201. face = this.faces[ f ];
  7202. face.normal = face.__originalFaceNormal;
  7203. face.vertexNormals = face.__originalVertexNormals;
  7204. }
  7205. },
  7206. computeLineDistances: function () {
  7207. var d = 0;
  7208. var vertices = this.vertices;
  7209. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7210. if ( i > 0 ) {
  7211. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7212. }
  7213. this.lineDistances[ i ] = d;
  7214. }
  7215. },
  7216. computeBoundingBox: function () {
  7217. if ( this.boundingBox === null ) {
  7218. this.boundingBox = new Box3();
  7219. }
  7220. this.boundingBox.setFromPoints( this.vertices );
  7221. },
  7222. computeBoundingSphere: function () {
  7223. if ( this.boundingSphere === null ) {
  7224. this.boundingSphere = new Sphere();
  7225. }
  7226. this.boundingSphere.setFromPoints( this.vertices );
  7227. },
  7228. merge: function ( geometry, matrix, materialIndexOffset ) {
  7229. if ( ! ( geometry && geometry.isGeometry ) ) {
  7230. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7231. return;
  7232. }
  7233. var normalMatrix,
  7234. vertexOffset = this.vertices.length,
  7235. vertices1 = this.vertices,
  7236. vertices2 = geometry.vertices,
  7237. faces1 = this.faces,
  7238. faces2 = geometry.faces,
  7239. uvs1 = this.faceVertexUvs[ 0 ],
  7240. uvs2 = geometry.faceVertexUvs[ 0 ],
  7241. colors1 = this.colors,
  7242. colors2 = geometry.colors;
  7243. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7244. if ( matrix !== undefined ) {
  7245. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7246. }
  7247. // vertices
  7248. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7249. var vertex = vertices2[ i ];
  7250. var vertexCopy = vertex.clone();
  7251. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7252. vertices1.push( vertexCopy );
  7253. }
  7254. // colors
  7255. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7256. colors1.push( colors2[ i ].clone() );
  7257. }
  7258. // faces
  7259. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7260. var face = faces2[ i ], faceCopy, normal, color,
  7261. faceVertexNormals = face.vertexNormals,
  7262. faceVertexColors = face.vertexColors;
  7263. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7264. faceCopy.normal.copy( face.normal );
  7265. if ( normalMatrix !== undefined ) {
  7266. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7267. }
  7268. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7269. normal = faceVertexNormals[ j ].clone();
  7270. if ( normalMatrix !== undefined ) {
  7271. normal.applyMatrix3( normalMatrix ).normalize();
  7272. }
  7273. faceCopy.vertexNormals.push( normal );
  7274. }
  7275. faceCopy.color.copy( face.color );
  7276. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7277. color = faceVertexColors[ j ];
  7278. faceCopy.vertexColors.push( color.clone() );
  7279. }
  7280. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7281. faces1.push( faceCopy );
  7282. }
  7283. // uvs
  7284. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7285. var uv = uvs2[ i ], uvCopy = [];
  7286. if ( uv === undefined ) {
  7287. continue;
  7288. }
  7289. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7290. uvCopy.push( uv[ j ].clone() );
  7291. }
  7292. uvs1.push( uvCopy );
  7293. }
  7294. },
  7295. mergeMesh: function ( mesh ) {
  7296. if ( ! ( mesh && mesh.isMesh ) ) {
  7297. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7298. return;
  7299. }
  7300. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7301. this.merge( mesh.geometry, mesh.matrix );
  7302. },
  7303. /*
  7304. * Checks for duplicate vertices with hashmap.
  7305. * Duplicated vertices are removed
  7306. * and faces' vertices are updated.
  7307. */
  7308. mergeVertices: function () {
  7309. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7310. var unique = [], changes = [];
  7311. var v, key;
  7312. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7313. var precision = Math.pow( 10, precisionPoints );
  7314. var i, il, face;
  7315. var indices, j, jl;
  7316. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7317. v = this.vertices[ i ];
  7318. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7319. if ( verticesMap[ key ] === undefined ) {
  7320. verticesMap[ key ] = i;
  7321. unique.push( this.vertices[ i ] );
  7322. changes[ i ] = unique.length - 1;
  7323. } else {
  7324. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7325. changes[ i ] = changes[ verticesMap[ key ] ];
  7326. }
  7327. }
  7328. // if faces are completely degenerate after merging vertices, we
  7329. // have to remove them from the geometry.
  7330. var faceIndicesToRemove = [];
  7331. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7332. face = this.faces[ i ];
  7333. face.a = changes[ face.a ];
  7334. face.b = changes[ face.b ];
  7335. face.c = changes[ face.c ];
  7336. indices = [ face.a, face.b, face.c ];
  7337. // if any duplicate vertices are found in a Face3
  7338. // we have to remove the face as nothing can be saved
  7339. for ( var n = 0; n < 3; n ++ ) {
  7340. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7341. faceIndicesToRemove.push( i );
  7342. break;
  7343. }
  7344. }
  7345. }
  7346. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7347. var idx = faceIndicesToRemove[ i ];
  7348. this.faces.splice( idx, 1 );
  7349. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7350. this.faceVertexUvs[ j ].splice( idx, 1 );
  7351. }
  7352. }
  7353. // Use unique set of vertices
  7354. var diff = this.vertices.length - unique.length;
  7355. this.vertices = unique;
  7356. return diff;
  7357. },
  7358. sortFacesByMaterialIndex: function () {
  7359. var faces = this.faces;
  7360. var length = faces.length;
  7361. // tag faces
  7362. for ( var i = 0; i < length; i ++ ) {
  7363. faces[ i ]._id = i;
  7364. }
  7365. // sort faces
  7366. function materialIndexSort( a, b ) {
  7367. return a.materialIndex - b.materialIndex;
  7368. }
  7369. faces.sort( materialIndexSort );
  7370. // sort uvs
  7371. var uvs1 = this.faceVertexUvs[ 0 ];
  7372. var uvs2 = this.faceVertexUvs[ 1 ];
  7373. var newUvs1, newUvs2;
  7374. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7375. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7376. for ( var i = 0; i < length; i ++ ) {
  7377. var id = faces[ i ]._id;
  7378. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7379. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7380. }
  7381. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7382. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7383. },
  7384. toJSON: function () {
  7385. var data = {
  7386. metadata: {
  7387. version: 4.5,
  7388. type: 'Geometry',
  7389. generator: 'Geometry.toJSON'
  7390. }
  7391. };
  7392. // standard Geometry serialization
  7393. data.uuid = this.uuid;
  7394. data.type = this.type;
  7395. if ( this.name !== '' ) data.name = this.name;
  7396. if ( this.parameters !== undefined ) {
  7397. var parameters = this.parameters;
  7398. for ( var key in parameters ) {
  7399. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7400. }
  7401. return data;
  7402. }
  7403. var vertices = [];
  7404. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7405. var vertex = this.vertices[ i ];
  7406. vertices.push( vertex.x, vertex.y, vertex.z );
  7407. }
  7408. var faces = [];
  7409. var normals = [];
  7410. var normalsHash = {};
  7411. var colors = [];
  7412. var colorsHash = {};
  7413. var uvs = [];
  7414. var uvsHash = {};
  7415. for ( var i = 0; i < this.faces.length; i ++ ) {
  7416. var face = this.faces[ i ];
  7417. var hasMaterial = true;
  7418. var hasFaceUv = false; // deprecated
  7419. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7420. var hasFaceNormal = face.normal.length() > 0;
  7421. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7422. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7423. var hasFaceVertexColor = face.vertexColors.length > 0;
  7424. var faceType = 0;
  7425. faceType = setBit( faceType, 0, 0 ); // isQuad
  7426. faceType = setBit( faceType, 1, hasMaterial );
  7427. faceType = setBit( faceType, 2, hasFaceUv );
  7428. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7429. faceType = setBit( faceType, 4, hasFaceNormal );
  7430. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7431. faceType = setBit( faceType, 6, hasFaceColor );
  7432. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7433. faces.push( faceType );
  7434. faces.push( face.a, face.b, face.c );
  7435. faces.push( face.materialIndex );
  7436. if ( hasFaceVertexUv ) {
  7437. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7438. faces.push(
  7439. getUvIndex( faceVertexUvs[ 0 ] ),
  7440. getUvIndex( faceVertexUvs[ 1 ] ),
  7441. getUvIndex( faceVertexUvs[ 2 ] )
  7442. );
  7443. }
  7444. if ( hasFaceNormal ) {
  7445. faces.push( getNormalIndex( face.normal ) );
  7446. }
  7447. if ( hasFaceVertexNormal ) {
  7448. var vertexNormals = face.vertexNormals;
  7449. faces.push(
  7450. getNormalIndex( vertexNormals[ 0 ] ),
  7451. getNormalIndex( vertexNormals[ 1 ] ),
  7452. getNormalIndex( vertexNormals[ 2 ] )
  7453. );
  7454. }
  7455. if ( hasFaceColor ) {
  7456. faces.push( getColorIndex( face.color ) );
  7457. }
  7458. if ( hasFaceVertexColor ) {
  7459. var vertexColors = face.vertexColors;
  7460. faces.push(
  7461. getColorIndex( vertexColors[ 0 ] ),
  7462. getColorIndex( vertexColors[ 1 ] ),
  7463. getColorIndex( vertexColors[ 2 ] )
  7464. );
  7465. }
  7466. }
  7467. function setBit( value, position, enabled ) {
  7468. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7469. }
  7470. function getNormalIndex( normal ) {
  7471. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7472. if ( normalsHash[ hash ] !== undefined ) {
  7473. return normalsHash[ hash ];
  7474. }
  7475. normalsHash[ hash ] = normals.length / 3;
  7476. normals.push( normal.x, normal.y, normal.z );
  7477. return normalsHash[ hash ];
  7478. }
  7479. function getColorIndex( color ) {
  7480. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7481. if ( colorsHash[ hash ] !== undefined ) {
  7482. return colorsHash[ hash ];
  7483. }
  7484. colorsHash[ hash ] = colors.length;
  7485. colors.push( color.getHex() );
  7486. return colorsHash[ hash ];
  7487. }
  7488. function getUvIndex( uv ) {
  7489. var hash = uv.x.toString() + uv.y.toString();
  7490. if ( uvsHash[ hash ] !== undefined ) {
  7491. return uvsHash[ hash ];
  7492. }
  7493. uvsHash[ hash ] = uvs.length / 2;
  7494. uvs.push( uv.x, uv.y );
  7495. return uvsHash[ hash ];
  7496. }
  7497. data.data = {};
  7498. data.data.vertices = vertices;
  7499. data.data.normals = normals;
  7500. if ( colors.length > 0 ) data.data.colors = colors;
  7501. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7502. data.data.faces = faces;
  7503. return data;
  7504. },
  7505. clone: function () {
  7506. /*
  7507. // Handle primitives
  7508. var parameters = this.parameters;
  7509. if ( parameters !== undefined ) {
  7510. var values = [];
  7511. for ( var key in parameters ) {
  7512. values.push( parameters[ key ] );
  7513. }
  7514. var geometry = Object.create( this.constructor.prototype );
  7515. this.constructor.apply( geometry, values );
  7516. return geometry;
  7517. }
  7518. return new this.constructor().copy( this );
  7519. */
  7520. return new Geometry().copy( this );
  7521. },
  7522. copy: function ( source ) {
  7523. var i, il, j, jl, k, kl;
  7524. // reset
  7525. this.vertices = [];
  7526. this.colors = [];
  7527. this.faces = [];
  7528. this.faceVertexUvs = [[]];
  7529. this.morphTargets = [];
  7530. this.morphNormals = [];
  7531. this.skinWeights = [];
  7532. this.skinIndices = [];
  7533. this.lineDistances = [];
  7534. this.boundingBox = null;
  7535. this.boundingSphere = null;
  7536. // name
  7537. this.name = source.name;
  7538. // vertices
  7539. var vertices = source.vertices;
  7540. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  7541. this.vertices.push( vertices[ i ].clone() );
  7542. }
  7543. // colors
  7544. var colors = source.colors;
  7545. for ( i = 0, il = colors.length; i < il; i ++ ) {
  7546. this.colors.push( colors[ i ].clone() );
  7547. }
  7548. // faces
  7549. var faces = source.faces;
  7550. for ( i = 0, il = faces.length; i < il; i ++ ) {
  7551. this.faces.push( faces[ i ].clone() );
  7552. }
  7553. // face vertex uvs
  7554. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7555. var faceVertexUvs = source.faceVertexUvs[ i ];
  7556. if ( this.faceVertexUvs[ i ] === undefined ) {
  7557. this.faceVertexUvs[ i ] = [];
  7558. }
  7559. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7560. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7561. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  7562. var uv = uvs[ k ];
  7563. uvsCopy.push( uv.clone() );
  7564. }
  7565. this.faceVertexUvs[ i ].push( uvsCopy );
  7566. }
  7567. }
  7568. // morph targets
  7569. var morphTargets = source.morphTargets;
  7570. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  7571. var morphTarget = {};
  7572. morphTarget.name = morphTargets[ i ].name;
  7573. // vertices
  7574. if ( morphTargets[ i ].vertices !== undefined ) {
  7575. morphTarget.vertices = [];
  7576. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  7577. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  7578. }
  7579. }
  7580. // normals
  7581. if ( morphTargets[ i ].normals !== undefined ) {
  7582. morphTarget.normals = [];
  7583. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  7584. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  7585. }
  7586. }
  7587. this.morphTargets.push( morphTarget );
  7588. }
  7589. // morph normals
  7590. var morphNormals = source.morphNormals;
  7591. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  7592. var morphNormal = {};
  7593. // vertex normals
  7594. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  7595. morphNormal.vertexNormals = [];
  7596. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  7597. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  7598. var destVertexNormal = {};
  7599. destVertexNormal.a = srcVertexNormal.a.clone();
  7600. destVertexNormal.b = srcVertexNormal.b.clone();
  7601. destVertexNormal.c = srcVertexNormal.c.clone();
  7602. morphNormal.vertexNormals.push( destVertexNormal );
  7603. }
  7604. }
  7605. // face normals
  7606. if ( morphNormals[ i ].faceNormals !== undefined ) {
  7607. morphNormal.faceNormals = [];
  7608. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  7609. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  7610. }
  7611. }
  7612. this.morphNormals.push( morphNormal );
  7613. }
  7614. // skin weights
  7615. var skinWeights = source.skinWeights;
  7616. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  7617. this.skinWeights.push( skinWeights[ i ].clone() );
  7618. }
  7619. // skin indices
  7620. var skinIndices = source.skinIndices;
  7621. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  7622. this.skinIndices.push( skinIndices[ i ].clone() );
  7623. }
  7624. // line distances
  7625. var lineDistances = source.lineDistances;
  7626. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  7627. this.lineDistances.push( lineDistances[ i ] );
  7628. }
  7629. // bounding box
  7630. var boundingBox = source.boundingBox;
  7631. if ( boundingBox !== null ) {
  7632. this.boundingBox = boundingBox.clone();
  7633. }
  7634. // bounding sphere
  7635. var boundingSphere = source.boundingSphere;
  7636. if ( boundingSphere !== null ) {
  7637. this.boundingSphere = boundingSphere.clone();
  7638. }
  7639. // update flags
  7640. this.elementsNeedUpdate = source.elementsNeedUpdate;
  7641. this.verticesNeedUpdate = source.verticesNeedUpdate;
  7642. this.uvsNeedUpdate = source.uvsNeedUpdate;
  7643. this.normalsNeedUpdate = source.normalsNeedUpdate;
  7644. this.colorsNeedUpdate = source.colorsNeedUpdate;
  7645. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  7646. this.groupsNeedUpdate = source.groupsNeedUpdate;
  7647. return this;
  7648. },
  7649. dispose: function () {
  7650. this.dispatchEvent( { type: 'dispose' } );
  7651. }
  7652. } );
  7653. /**
  7654. * @author mrdoob / http://mrdoob.com/
  7655. */
  7656. function BufferAttribute( array, itemSize, normalized ) {
  7657. if ( Array.isArray( array ) ) {
  7658. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7659. }
  7660. this.uuid = _Math.generateUUID();
  7661. this.name = '';
  7662. this.array = array;
  7663. this.itemSize = itemSize;
  7664. this.count = array !== undefined ? array.length / itemSize : 0;
  7665. this.normalized = normalized === true;
  7666. this.dynamic = false;
  7667. this.updateRange = { offset: 0, count: - 1 };
  7668. this.onUploadCallback = function () {};
  7669. this.version = 0;
  7670. }
  7671. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7672. set: function ( value ) {
  7673. if ( value === true ) this.version ++;
  7674. }
  7675. } );
  7676. Object.assign( BufferAttribute.prototype, {
  7677. isBufferAttribute: true,
  7678. setArray: function ( array ) {
  7679. if ( Array.isArray( array ) ) {
  7680. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7681. }
  7682. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7683. this.array = array;
  7684. },
  7685. setDynamic: function ( value ) {
  7686. this.dynamic = value;
  7687. return this;
  7688. },
  7689. copy: function ( source ) {
  7690. this.array = new source.array.constructor( source.array );
  7691. this.itemSize = source.itemSize;
  7692. this.count = source.count;
  7693. this.normalized = source.normalized;
  7694. this.dynamic = source.dynamic;
  7695. return this;
  7696. },
  7697. copyAt: function ( index1, attribute, index2 ) {
  7698. index1 *= this.itemSize;
  7699. index2 *= attribute.itemSize;
  7700. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7701. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7702. }
  7703. return this;
  7704. },
  7705. copyArray: function ( array ) {
  7706. this.array.set( array );
  7707. return this;
  7708. },
  7709. copyColorsArray: function ( colors ) {
  7710. var array = this.array, offset = 0;
  7711. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7712. var color = colors[ i ];
  7713. if ( color === undefined ) {
  7714. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7715. color = new Color();
  7716. }
  7717. array[ offset ++ ] = color.r;
  7718. array[ offset ++ ] = color.g;
  7719. array[ offset ++ ] = color.b;
  7720. }
  7721. return this;
  7722. },
  7723. copyIndicesArray: function ( indices ) {
  7724. var array = this.array, offset = 0;
  7725. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7726. var index = indices[ i ];
  7727. array[ offset ++ ] = index.a;
  7728. array[ offset ++ ] = index.b;
  7729. array[ offset ++ ] = index.c;
  7730. }
  7731. return this;
  7732. },
  7733. copyVector2sArray: function ( vectors ) {
  7734. var array = this.array, offset = 0;
  7735. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7736. var vector = vectors[ i ];
  7737. if ( vector === undefined ) {
  7738. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7739. vector = new Vector2();
  7740. }
  7741. array[ offset ++ ] = vector.x;
  7742. array[ offset ++ ] = vector.y;
  7743. }
  7744. return this;
  7745. },
  7746. copyVector3sArray: function ( vectors ) {
  7747. var array = this.array, offset = 0;
  7748. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7749. var vector = vectors[ i ];
  7750. if ( vector === undefined ) {
  7751. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7752. vector = new Vector3();
  7753. }
  7754. array[ offset ++ ] = vector.x;
  7755. array[ offset ++ ] = vector.y;
  7756. array[ offset ++ ] = vector.z;
  7757. }
  7758. return this;
  7759. },
  7760. copyVector4sArray: function ( vectors ) {
  7761. var array = this.array, offset = 0;
  7762. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7763. var vector = vectors[ i ];
  7764. if ( vector === undefined ) {
  7765. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7766. vector = new Vector4();
  7767. }
  7768. array[ offset ++ ] = vector.x;
  7769. array[ offset ++ ] = vector.y;
  7770. array[ offset ++ ] = vector.z;
  7771. array[ offset ++ ] = vector.w;
  7772. }
  7773. return this;
  7774. },
  7775. set: function ( value, offset ) {
  7776. if ( offset === undefined ) offset = 0;
  7777. this.array.set( value, offset );
  7778. return this;
  7779. },
  7780. getX: function ( index ) {
  7781. return this.array[ index * this.itemSize ];
  7782. },
  7783. setX: function ( index, x ) {
  7784. this.array[ index * this.itemSize ] = x;
  7785. return this;
  7786. },
  7787. getY: function ( index ) {
  7788. return this.array[ index * this.itemSize + 1 ];
  7789. },
  7790. setY: function ( index, y ) {
  7791. this.array[ index * this.itemSize + 1 ] = y;
  7792. return this;
  7793. },
  7794. getZ: function ( index ) {
  7795. return this.array[ index * this.itemSize + 2 ];
  7796. },
  7797. setZ: function ( index, z ) {
  7798. this.array[ index * this.itemSize + 2 ] = z;
  7799. return this;
  7800. },
  7801. getW: function ( index ) {
  7802. return this.array[ index * this.itemSize + 3 ];
  7803. },
  7804. setW: function ( index, w ) {
  7805. this.array[ index * this.itemSize + 3 ] = w;
  7806. return this;
  7807. },
  7808. setXY: function ( index, x, y ) {
  7809. index *= this.itemSize;
  7810. this.array[ index + 0 ] = x;
  7811. this.array[ index + 1 ] = y;
  7812. return this;
  7813. },
  7814. setXYZ: function ( index, x, y, z ) {
  7815. index *= this.itemSize;
  7816. this.array[ index + 0 ] = x;
  7817. this.array[ index + 1 ] = y;
  7818. this.array[ index + 2 ] = z;
  7819. return this;
  7820. },
  7821. setXYZW: function ( index, x, y, z, w ) {
  7822. index *= this.itemSize;
  7823. this.array[ index + 0 ] = x;
  7824. this.array[ index + 1 ] = y;
  7825. this.array[ index + 2 ] = z;
  7826. this.array[ index + 3 ] = w;
  7827. return this;
  7828. },
  7829. onUpload: function ( callback ) {
  7830. this.onUploadCallback = callback;
  7831. return this;
  7832. },
  7833. clone: function () {
  7834. return new this.constructor( this.array, this.itemSize ).copy( this );
  7835. }
  7836. } );
  7837. //
  7838. function Int8BufferAttribute( array, itemSize ) {
  7839. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7840. }
  7841. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7842. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7843. function Uint8BufferAttribute( array, itemSize ) {
  7844. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7845. }
  7846. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7847. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7848. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7849. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7850. }
  7851. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7852. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7853. function Int16BufferAttribute( array, itemSize ) {
  7854. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7855. }
  7856. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7857. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7858. function Uint16BufferAttribute( array, itemSize ) {
  7859. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7860. }
  7861. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7862. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7863. function Int32BufferAttribute( array, itemSize ) {
  7864. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7865. }
  7866. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7867. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7868. function Uint32BufferAttribute( array, itemSize ) {
  7869. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7870. }
  7871. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7872. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7873. function Float32BufferAttribute( array, itemSize ) {
  7874. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7875. }
  7876. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7877. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7878. function Float64BufferAttribute( array, itemSize ) {
  7879. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7880. }
  7881. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7882. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7883. /**
  7884. * @author mrdoob / http://mrdoob.com/
  7885. */
  7886. function DirectGeometry() {
  7887. this.indices = [];
  7888. this.vertices = [];
  7889. this.normals = [];
  7890. this.colors = [];
  7891. this.uvs = [];
  7892. this.uvs2 = [];
  7893. this.groups = [];
  7894. this.morphTargets = {};
  7895. this.skinWeights = [];
  7896. this.skinIndices = [];
  7897. // this.lineDistances = [];
  7898. this.boundingBox = null;
  7899. this.boundingSphere = null;
  7900. // update flags
  7901. this.verticesNeedUpdate = false;
  7902. this.normalsNeedUpdate = false;
  7903. this.colorsNeedUpdate = false;
  7904. this.uvsNeedUpdate = false;
  7905. this.groupsNeedUpdate = false;
  7906. }
  7907. Object.assign( DirectGeometry.prototype, {
  7908. computeGroups: function ( geometry ) {
  7909. var group;
  7910. var groups = [];
  7911. var materialIndex = undefined;
  7912. var faces = geometry.faces;
  7913. for ( var i = 0; i < faces.length; i ++ ) {
  7914. var face = faces[ i ];
  7915. // materials
  7916. if ( face.materialIndex !== materialIndex ) {
  7917. materialIndex = face.materialIndex;
  7918. if ( group !== undefined ) {
  7919. group.count = ( i * 3 ) - group.start;
  7920. groups.push( group );
  7921. }
  7922. group = {
  7923. start: i * 3,
  7924. materialIndex: materialIndex
  7925. };
  7926. }
  7927. }
  7928. if ( group !== undefined ) {
  7929. group.count = ( i * 3 ) - group.start;
  7930. groups.push( group );
  7931. }
  7932. this.groups = groups;
  7933. },
  7934. fromGeometry: function ( geometry ) {
  7935. var faces = geometry.faces;
  7936. var vertices = geometry.vertices;
  7937. var faceVertexUvs = geometry.faceVertexUvs;
  7938. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7939. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7940. // morphs
  7941. var morphTargets = geometry.morphTargets;
  7942. var morphTargetsLength = morphTargets.length;
  7943. var morphTargetsPosition;
  7944. if ( morphTargetsLength > 0 ) {
  7945. morphTargetsPosition = [];
  7946. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7947. morphTargetsPosition[ i ] = [];
  7948. }
  7949. this.morphTargets.position = morphTargetsPosition;
  7950. }
  7951. var morphNormals = geometry.morphNormals;
  7952. var morphNormalsLength = morphNormals.length;
  7953. var morphTargetsNormal;
  7954. if ( morphNormalsLength > 0 ) {
  7955. morphTargetsNormal = [];
  7956. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7957. morphTargetsNormal[ i ] = [];
  7958. }
  7959. this.morphTargets.normal = morphTargetsNormal;
  7960. }
  7961. // skins
  7962. var skinIndices = geometry.skinIndices;
  7963. var skinWeights = geometry.skinWeights;
  7964. var hasSkinIndices = skinIndices.length === vertices.length;
  7965. var hasSkinWeights = skinWeights.length === vertices.length;
  7966. //
  7967. for ( var i = 0; i < faces.length; i ++ ) {
  7968. var face = faces[ i ];
  7969. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7970. var vertexNormals = face.vertexNormals;
  7971. if ( vertexNormals.length === 3 ) {
  7972. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7973. } else {
  7974. var normal = face.normal;
  7975. this.normals.push( normal, normal, normal );
  7976. }
  7977. var vertexColors = face.vertexColors;
  7978. if ( vertexColors.length === 3 ) {
  7979. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7980. } else {
  7981. var color = face.color;
  7982. this.colors.push( color, color, color );
  7983. }
  7984. if ( hasFaceVertexUv === true ) {
  7985. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7986. if ( vertexUvs !== undefined ) {
  7987. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7988. } else {
  7989. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7990. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7991. }
  7992. }
  7993. if ( hasFaceVertexUv2 === true ) {
  7994. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7995. if ( vertexUvs !== undefined ) {
  7996. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7997. } else {
  7998. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7999. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  8000. }
  8001. }
  8002. // morphs
  8003. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  8004. var morphTarget = morphTargets[ j ].vertices;
  8005. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  8006. }
  8007. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  8008. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  8009. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  8010. }
  8011. // skins
  8012. if ( hasSkinIndices ) {
  8013. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  8014. }
  8015. if ( hasSkinWeights ) {
  8016. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  8017. }
  8018. }
  8019. this.computeGroups( geometry );
  8020. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8021. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8022. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8023. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8024. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8025. return this;
  8026. }
  8027. } );
  8028. function arrayMax( array ) {
  8029. if ( array.length === 0 ) return - Infinity;
  8030. var max = array[ 0 ];
  8031. for ( var i = 1, l = array.length; i < l; ++ i ) {
  8032. if ( array[ i ] > max ) max = array[ i ];
  8033. }
  8034. return max;
  8035. }
  8036. /**
  8037. * @author alteredq / http://alteredqualia.com/
  8038. * @author mrdoob / http://mrdoob.com/
  8039. */
  8040. function BufferGeometry() {
  8041. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8042. this.uuid = _Math.generateUUID();
  8043. this.name = '';
  8044. this.type = 'BufferGeometry';
  8045. this.index = null;
  8046. this.attributes = {};
  8047. this.morphAttributes = {};
  8048. this.groups = [];
  8049. this.boundingBox = null;
  8050. this.boundingSphere = null;
  8051. this.drawRange = { start: 0, count: Infinity };
  8052. }
  8053. BufferGeometry.MaxIndex = 65535;
  8054. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8055. isBufferGeometry: true,
  8056. getIndex: function () {
  8057. return this.index;
  8058. },
  8059. setIndex: function ( index ) {
  8060. if ( Array.isArray( index ) ) {
  8061. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8062. } else {
  8063. this.index = index;
  8064. }
  8065. },
  8066. addAttribute: function ( name, attribute ) {
  8067. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  8068. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8069. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8070. return;
  8071. }
  8072. if ( name === 'index' ) {
  8073. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8074. this.setIndex( attribute );
  8075. return;
  8076. }
  8077. this.attributes[ name ] = attribute;
  8078. return this;
  8079. },
  8080. getAttribute: function ( name ) {
  8081. return this.attributes[ name ];
  8082. },
  8083. removeAttribute: function ( name ) {
  8084. delete this.attributes[ name ];
  8085. return this;
  8086. },
  8087. addGroup: function ( start, count, materialIndex ) {
  8088. this.groups.push( {
  8089. start: start,
  8090. count: count,
  8091. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8092. } );
  8093. },
  8094. clearGroups: function () {
  8095. this.groups = [];
  8096. },
  8097. setDrawRange: function ( start, count ) {
  8098. this.drawRange.start = start;
  8099. this.drawRange.count = count;
  8100. },
  8101. applyMatrix: function ( matrix ) {
  8102. var position = this.attributes.position;
  8103. if ( position !== undefined ) {
  8104. matrix.applyToBufferAttribute( position );
  8105. position.needsUpdate = true;
  8106. }
  8107. var normal = this.attributes.normal;
  8108. if ( normal !== undefined ) {
  8109. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8110. normalMatrix.applyToBufferAttribute( normal );
  8111. normal.needsUpdate = true;
  8112. }
  8113. if ( this.boundingBox !== null ) {
  8114. this.computeBoundingBox();
  8115. }
  8116. if ( this.boundingSphere !== null ) {
  8117. this.computeBoundingSphere();
  8118. }
  8119. return this;
  8120. },
  8121. rotateX: function () {
  8122. // rotate geometry around world x-axis
  8123. var m1 = new Matrix4();
  8124. return function rotateX( angle ) {
  8125. m1.makeRotationX( angle );
  8126. this.applyMatrix( m1 );
  8127. return this;
  8128. };
  8129. }(),
  8130. rotateY: function () {
  8131. // rotate geometry around world y-axis
  8132. var m1 = new Matrix4();
  8133. return function rotateY( angle ) {
  8134. m1.makeRotationY( angle );
  8135. this.applyMatrix( m1 );
  8136. return this;
  8137. };
  8138. }(),
  8139. rotateZ: function () {
  8140. // rotate geometry around world z-axis
  8141. var m1 = new Matrix4();
  8142. return function rotateZ( angle ) {
  8143. m1.makeRotationZ( angle );
  8144. this.applyMatrix( m1 );
  8145. return this;
  8146. };
  8147. }(),
  8148. translate: function () {
  8149. // translate geometry
  8150. var m1 = new Matrix4();
  8151. return function translate( x, y, z ) {
  8152. m1.makeTranslation( x, y, z );
  8153. this.applyMatrix( m1 );
  8154. return this;
  8155. };
  8156. }(),
  8157. scale: function () {
  8158. // scale geometry
  8159. var m1 = new Matrix4();
  8160. return function scale( x, y, z ) {
  8161. m1.makeScale( x, y, z );
  8162. this.applyMatrix( m1 );
  8163. return this;
  8164. };
  8165. }(),
  8166. lookAt: function () {
  8167. var obj = new Object3D();
  8168. return function lookAt( vector ) {
  8169. obj.lookAt( vector );
  8170. obj.updateMatrix();
  8171. this.applyMatrix( obj.matrix );
  8172. };
  8173. }(),
  8174. center: function () {
  8175. this.computeBoundingBox();
  8176. var offset = this.boundingBox.getCenter().negate();
  8177. this.translate( offset.x, offset.y, offset.z );
  8178. return offset;
  8179. },
  8180. setFromObject: function ( object ) {
  8181. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8182. var geometry = object.geometry;
  8183. if ( object.isPoints || object.isLine ) {
  8184. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8185. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8186. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8187. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8188. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8189. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8190. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8191. }
  8192. if ( geometry.boundingSphere !== null ) {
  8193. this.boundingSphere = geometry.boundingSphere.clone();
  8194. }
  8195. if ( geometry.boundingBox !== null ) {
  8196. this.boundingBox = geometry.boundingBox.clone();
  8197. }
  8198. } else if ( object.isMesh ) {
  8199. if ( geometry && geometry.isGeometry ) {
  8200. this.fromGeometry( geometry );
  8201. }
  8202. }
  8203. return this;
  8204. },
  8205. updateFromObject: function ( object ) {
  8206. var geometry = object.geometry;
  8207. if ( object.isMesh ) {
  8208. var direct = geometry.__directGeometry;
  8209. if ( geometry.elementsNeedUpdate === true ) {
  8210. direct = undefined;
  8211. geometry.elementsNeedUpdate = false;
  8212. }
  8213. if ( direct === undefined ) {
  8214. return this.fromGeometry( geometry );
  8215. }
  8216. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8217. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8218. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8219. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8220. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8221. geometry.verticesNeedUpdate = false;
  8222. geometry.normalsNeedUpdate = false;
  8223. geometry.colorsNeedUpdate = false;
  8224. geometry.uvsNeedUpdate = false;
  8225. geometry.groupsNeedUpdate = false;
  8226. geometry = direct;
  8227. }
  8228. var attribute;
  8229. if ( geometry.verticesNeedUpdate === true ) {
  8230. attribute = this.attributes.position;
  8231. if ( attribute !== undefined ) {
  8232. attribute.copyVector3sArray( geometry.vertices );
  8233. attribute.needsUpdate = true;
  8234. }
  8235. geometry.verticesNeedUpdate = false;
  8236. }
  8237. if ( geometry.normalsNeedUpdate === true ) {
  8238. attribute = this.attributes.normal;
  8239. if ( attribute !== undefined ) {
  8240. attribute.copyVector3sArray( geometry.normals );
  8241. attribute.needsUpdate = true;
  8242. }
  8243. geometry.normalsNeedUpdate = false;
  8244. }
  8245. if ( geometry.colorsNeedUpdate === true ) {
  8246. attribute = this.attributes.color;
  8247. if ( attribute !== undefined ) {
  8248. attribute.copyColorsArray( geometry.colors );
  8249. attribute.needsUpdate = true;
  8250. }
  8251. geometry.colorsNeedUpdate = false;
  8252. }
  8253. if ( geometry.uvsNeedUpdate ) {
  8254. attribute = this.attributes.uv;
  8255. if ( attribute !== undefined ) {
  8256. attribute.copyVector2sArray( geometry.uvs );
  8257. attribute.needsUpdate = true;
  8258. }
  8259. geometry.uvsNeedUpdate = false;
  8260. }
  8261. if ( geometry.lineDistancesNeedUpdate ) {
  8262. attribute = this.attributes.lineDistance;
  8263. if ( attribute !== undefined ) {
  8264. attribute.copyArray( geometry.lineDistances );
  8265. attribute.needsUpdate = true;
  8266. }
  8267. geometry.lineDistancesNeedUpdate = false;
  8268. }
  8269. if ( geometry.groupsNeedUpdate ) {
  8270. geometry.computeGroups( object.geometry );
  8271. this.groups = geometry.groups;
  8272. geometry.groupsNeedUpdate = false;
  8273. }
  8274. return this;
  8275. },
  8276. fromGeometry: function ( geometry ) {
  8277. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8278. return this.fromDirectGeometry( geometry.__directGeometry );
  8279. },
  8280. fromDirectGeometry: function ( geometry ) {
  8281. var positions = new Float32Array( geometry.vertices.length * 3 );
  8282. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8283. if ( geometry.normals.length > 0 ) {
  8284. var normals = new Float32Array( geometry.normals.length * 3 );
  8285. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8286. }
  8287. if ( geometry.colors.length > 0 ) {
  8288. var colors = new Float32Array( geometry.colors.length * 3 );
  8289. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8290. }
  8291. if ( geometry.uvs.length > 0 ) {
  8292. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8293. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8294. }
  8295. if ( geometry.uvs2.length > 0 ) {
  8296. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8297. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8298. }
  8299. if ( geometry.indices.length > 0 ) {
  8300. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8301. var indices = new TypeArray( geometry.indices.length * 3 );
  8302. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8303. }
  8304. // groups
  8305. this.groups = geometry.groups;
  8306. // morphs
  8307. for ( var name in geometry.morphTargets ) {
  8308. var array = [];
  8309. var morphTargets = geometry.morphTargets[ name ];
  8310. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8311. var morphTarget = morphTargets[ i ];
  8312. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8313. array.push( attribute.copyVector3sArray( morphTarget ) );
  8314. }
  8315. this.morphAttributes[ name ] = array;
  8316. }
  8317. // skinning
  8318. if ( geometry.skinIndices.length > 0 ) {
  8319. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8320. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8321. }
  8322. if ( geometry.skinWeights.length > 0 ) {
  8323. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8324. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8325. }
  8326. //
  8327. if ( geometry.boundingSphere !== null ) {
  8328. this.boundingSphere = geometry.boundingSphere.clone();
  8329. }
  8330. if ( geometry.boundingBox !== null ) {
  8331. this.boundingBox = geometry.boundingBox.clone();
  8332. }
  8333. return this;
  8334. },
  8335. computeBoundingBox: function () {
  8336. if ( this.boundingBox === null ) {
  8337. this.boundingBox = new Box3();
  8338. }
  8339. var position = this.attributes.position;
  8340. if ( position !== undefined ) {
  8341. this.boundingBox.setFromBufferAttribute( position );
  8342. } else {
  8343. this.boundingBox.makeEmpty();
  8344. }
  8345. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8346. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8347. }
  8348. },
  8349. computeBoundingSphere: function () {
  8350. var box = new Box3();
  8351. var vector = new Vector3();
  8352. return function computeBoundingSphere() {
  8353. if ( this.boundingSphere === null ) {
  8354. this.boundingSphere = new Sphere();
  8355. }
  8356. var position = this.attributes.position;
  8357. if ( position ) {
  8358. var center = this.boundingSphere.center;
  8359. box.setFromBufferAttribute( position );
  8360. box.getCenter( center );
  8361. // hoping to find a boundingSphere with a radius smaller than the
  8362. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8363. var maxRadiusSq = 0;
  8364. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8365. vector.x = position.getX( i );
  8366. vector.y = position.getY( i );
  8367. vector.z = position.getZ( i );
  8368. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8369. }
  8370. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8371. if ( isNaN( this.boundingSphere.radius ) ) {
  8372. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8373. }
  8374. }
  8375. };
  8376. }(),
  8377. computeFaceNormals: function () {
  8378. // backwards compatibility
  8379. },
  8380. computeVertexNormals: function () {
  8381. var index = this.index;
  8382. var attributes = this.attributes;
  8383. var groups = this.groups;
  8384. if ( attributes.position ) {
  8385. var positions = attributes.position.array;
  8386. if ( attributes.normal === undefined ) {
  8387. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8388. } else {
  8389. // reset existing normals to zero
  8390. var array = attributes.normal.array;
  8391. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8392. array[ i ] = 0;
  8393. }
  8394. }
  8395. var normals = attributes.normal.array;
  8396. var vA, vB, vC;
  8397. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8398. var cb = new Vector3(), ab = new Vector3();
  8399. // indexed elements
  8400. if ( index ) {
  8401. var indices = index.array;
  8402. if ( groups.length === 0 ) {
  8403. this.addGroup( 0, indices.length );
  8404. }
  8405. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8406. var group = groups[ j ];
  8407. var start = group.start;
  8408. var count = group.count;
  8409. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8410. vA = indices[ i + 0 ] * 3;
  8411. vB = indices[ i + 1 ] * 3;
  8412. vC = indices[ i + 2 ] * 3;
  8413. pA.fromArray( positions, vA );
  8414. pB.fromArray( positions, vB );
  8415. pC.fromArray( positions, vC );
  8416. cb.subVectors( pC, pB );
  8417. ab.subVectors( pA, pB );
  8418. cb.cross( ab );
  8419. normals[ vA ] += cb.x;
  8420. normals[ vA + 1 ] += cb.y;
  8421. normals[ vA + 2 ] += cb.z;
  8422. normals[ vB ] += cb.x;
  8423. normals[ vB + 1 ] += cb.y;
  8424. normals[ vB + 2 ] += cb.z;
  8425. normals[ vC ] += cb.x;
  8426. normals[ vC + 1 ] += cb.y;
  8427. normals[ vC + 2 ] += cb.z;
  8428. }
  8429. }
  8430. } else {
  8431. // non-indexed elements (unconnected triangle soup)
  8432. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8433. pA.fromArray( positions, i );
  8434. pB.fromArray( positions, i + 3 );
  8435. pC.fromArray( positions, i + 6 );
  8436. cb.subVectors( pC, pB );
  8437. ab.subVectors( pA, pB );
  8438. cb.cross( ab );
  8439. normals[ i ] = cb.x;
  8440. normals[ i + 1 ] = cb.y;
  8441. normals[ i + 2 ] = cb.z;
  8442. normals[ i + 3 ] = cb.x;
  8443. normals[ i + 4 ] = cb.y;
  8444. normals[ i + 5 ] = cb.z;
  8445. normals[ i + 6 ] = cb.x;
  8446. normals[ i + 7 ] = cb.y;
  8447. normals[ i + 8 ] = cb.z;
  8448. }
  8449. }
  8450. this.normalizeNormals();
  8451. attributes.normal.needsUpdate = true;
  8452. }
  8453. },
  8454. merge: function ( geometry, offset ) {
  8455. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  8456. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8457. return;
  8458. }
  8459. if ( offset === undefined ) offset = 0;
  8460. var attributes = this.attributes;
  8461. for ( var key in attributes ) {
  8462. if ( geometry.attributes[ key ] === undefined ) continue;
  8463. var attribute1 = attributes[ key ];
  8464. var attributeArray1 = attribute1.array;
  8465. var attribute2 = geometry.attributes[ key ];
  8466. var attributeArray2 = attribute2.array;
  8467. var attributeSize = attribute2.itemSize;
  8468. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8469. attributeArray1[ j ] = attributeArray2[ i ];
  8470. }
  8471. }
  8472. return this;
  8473. },
  8474. normalizeNormals: function () {
  8475. var normals = this.attributes.normal;
  8476. var x, y, z, n;
  8477. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8478. x = normals.getX( i );
  8479. y = normals.getY( i );
  8480. z = normals.getZ( i );
  8481. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8482. normals.setXYZ( i, x * n, y * n, z * n );
  8483. }
  8484. },
  8485. toNonIndexed: function () {
  8486. if ( this.index === null ) {
  8487. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8488. return this;
  8489. }
  8490. var geometry2 = new BufferGeometry();
  8491. var indices = this.index.array;
  8492. var attributes = this.attributes;
  8493. for ( var name in attributes ) {
  8494. var attribute = attributes[ name ];
  8495. var array = attribute.array;
  8496. var itemSize = attribute.itemSize;
  8497. var array2 = new array.constructor( indices.length * itemSize );
  8498. var index = 0, index2 = 0;
  8499. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8500. index = indices[ i ] * itemSize;
  8501. for ( var j = 0; j < itemSize; j ++ ) {
  8502. array2[ index2 ++ ] = array[ index ++ ];
  8503. }
  8504. }
  8505. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8506. }
  8507. return geometry2;
  8508. },
  8509. toJSON: function () {
  8510. var data = {
  8511. metadata: {
  8512. version: 4.5,
  8513. type: 'BufferGeometry',
  8514. generator: 'BufferGeometry.toJSON'
  8515. }
  8516. };
  8517. // standard BufferGeometry serialization
  8518. data.uuid = this.uuid;
  8519. data.type = this.type;
  8520. if ( this.name !== '' ) data.name = this.name;
  8521. if ( this.parameters !== undefined ) {
  8522. var parameters = this.parameters;
  8523. for ( var key in parameters ) {
  8524. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8525. }
  8526. return data;
  8527. }
  8528. data.data = { attributes: {} };
  8529. var index = this.index;
  8530. if ( index !== null ) {
  8531. var array = Array.prototype.slice.call( index.array );
  8532. data.data.index = {
  8533. type: index.array.constructor.name,
  8534. array: array
  8535. };
  8536. }
  8537. var attributes = this.attributes;
  8538. for ( var key in attributes ) {
  8539. var attribute = attributes[ key ];
  8540. var array = Array.prototype.slice.call( attribute.array );
  8541. data.data.attributes[ key ] = {
  8542. itemSize: attribute.itemSize,
  8543. type: attribute.array.constructor.name,
  8544. array: array,
  8545. normalized: attribute.normalized
  8546. };
  8547. }
  8548. var groups = this.groups;
  8549. if ( groups.length > 0 ) {
  8550. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8551. }
  8552. var boundingSphere = this.boundingSphere;
  8553. if ( boundingSphere !== null ) {
  8554. data.data.boundingSphere = {
  8555. center: boundingSphere.center.toArray(),
  8556. radius: boundingSphere.radius
  8557. };
  8558. }
  8559. return data;
  8560. },
  8561. clone: function () {
  8562. /*
  8563. // Handle primitives
  8564. var parameters = this.parameters;
  8565. if ( parameters !== undefined ) {
  8566. var values = [];
  8567. for ( var key in parameters ) {
  8568. values.push( parameters[ key ] );
  8569. }
  8570. var geometry = Object.create( this.constructor.prototype );
  8571. this.constructor.apply( geometry, values );
  8572. return geometry;
  8573. }
  8574. return new this.constructor().copy( this );
  8575. */
  8576. return new BufferGeometry().copy( this );
  8577. },
  8578. copy: function ( source ) {
  8579. var name, i, l;
  8580. // reset
  8581. this.index = null;
  8582. this.attributes = {};
  8583. this.morphAttributes = {};
  8584. this.groups = [];
  8585. this.boundingBox = null;
  8586. this.boundingSphere = null;
  8587. // name
  8588. this.name = source.name;
  8589. // index
  8590. var index = source.index;
  8591. if ( index !== null ) {
  8592. this.setIndex( index.clone() );
  8593. }
  8594. // attributes
  8595. var attributes = source.attributes;
  8596. for ( name in attributes ) {
  8597. var attribute = attributes[ name ];
  8598. this.addAttribute( name, attribute.clone() );
  8599. }
  8600. // morph attributes
  8601. var morphAttributes = source.morphAttributes;
  8602. for ( name in morphAttributes ) {
  8603. var array = [];
  8604. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8605. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8606. array.push( morphAttribute[ i ].clone() );
  8607. }
  8608. this.morphAttributes[ name ] = array;
  8609. }
  8610. // groups
  8611. var groups = source.groups;
  8612. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8613. var group = groups[ i ];
  8614. this.addGroup( group.start, group.count, group.materialIndex );
  8615. }
  8616. // bounding box
  8617. var boundingBox = source.boundingBox;
  8618. if ( boundingBox !== null ) {
  8619. this.boundingBox = boundingBox.clone();
  8620. }
  8621. // bounding sphere
  8622. var boundingSphere = source.boundingSphere;
  8623. if ( boundingSphere !== null ) {
  8624. this.boundingSphere = boundingSphere.clone();
  8625. }
  8626. // draw range
  8627. this.drawRange.start = source.drawRange.start;
  8628. this.drawRange.count = source.drawRange.count;
  8629. return this;
  8630. },
  8631. dispose: function () {
  8632. this.dispatchEvent( { type: 'dispose' } );
  8633. }
  8634. } );
  8635. /**
  8636. * @author mrdoob / http://mrdoob.com/
  8637. * @author Mugen87 / https://github.com/Mugen87
  8638. */
  8639. // BoxGeometry
  8640. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8641. Geometry.call( this );
  8642. this.type = 'BoxGeometry';
  8643. this.parameters = {
  8644. width: width,
  8645. height: height,
  8646. depth: depth,
  8647. widthSegments: widthSegments,
  8648. heightSegments: heightSegments,
  8649. depthSegments: depthSegments
  8650. };
  8651. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  8652. this.mergeVertices();
  8653. }
  8654. BoxGeometry.prototype = Object.create( Geometry.prototype );
  8655. BoxGeometry.prototype.constructor = BoxGeometry;
  8656. // BoxBufferGeometry
  8657. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8658. BufferGeometry.call( this );
  8659. this.type = 'BoxBufferGeometry';
  8660. this.parameters = {
  8661. width: width,
  8662. height: height,
  8663. depth: depth,
  8664. widthSegments: widthSegments,
  8665. heightSegments: heightSegments,
  8666. depthSegments: depthSegments
  8667. };
  8668. var scope = this;
  8669. // segments
  8670. widthSegments = Math.floor( widthSegments ) || 1;
  8671. heightSegments = Math.floor( heightSegments ) || 1;
  8672. depthSegments = Math.floor( depthSegments ) || 1;
  8673. // buffers
  8674. var indices = [];
  8675. var vertices = [];
  8676. var normals = [];
  8677. var uvs = [];
  8678. // helper variables
  8679. var numberOfVertices = 0;
  8680. var groupStart = 0;
  8681. // build each side of the box geometry
  8682. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8683. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8684. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8685. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8686. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8687. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8688. // build geometry
  8689. this.setIndex( indices );
  8690. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8691. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8692. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8693. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8694. var segmentWidth = width / gridX;
  8695. var segmentHeight = height / gridY;
  8696. var widthHalf = width / 2;
  8697. var heightHalf = height / 2;
  8698. var depthHalf = depth / 2;
  8699. var gridX1 = gridX + 1;
  8700. var gridY1 = gridY + 1;
  8701. var vertexCounter = 0;
  8702. var groupCount = 0;
  8703. var ix, iy;
  8704. var vector = new Vector3();
  8705. // generate vertices, normals and uvs
  8706. for ( iy = 0; iy < gridY1; iy ++ ) {
  8707. var y = iy * segmentHeight - heightHalf;
  8708. for ( ix = 0; ix < gridX1; ix ++ ) {
  8709. var x = ix * segmentWidth - widthHalf;
  8710. // set values to correct vector component
  8711. vector[ u ] = x * udir;
  8712. vector[ v ] = y * vdir;
  8713. vector[ w ] = depthHalf;
  8714. // now apply vector to vertex buffer
  8715. vertices.push( vector.x, vector.y, vector.z );
  8716. // set values to correct vector component
  8717. vector[ u ] = 0;
  8718. vector[ v ] = 0;
  8719. vector[ w ] = depth > 0 ? 1 : - 1;
  8720. // now apply vector to normal buffer
  8721. normals.push( vector.x, vector.y, vector.z );
  8722. // uvs
  8723. uvs.push( ix / gridX );
  8724. uvs.push( 1 - ( iy / gridY ) );
  8725. // counters
  8726. vertexCounter += 1;
  8727. }
  8728. }
  8729. // indices
  8730. // 1. you need three indices to draw a single face
  8731. // 2. a single segment consists of two faces
  8732. // 3. so we need to generate six (2*3) indices per segment
  8733. for ( iy = 0; iy < gridY; iy ++ ) {
  8734. for ( ix = 0; ix < gridX; ix ++ ) {
  8735. var a = numberOfVertices + ix + gridX1 * iy;
  8736. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8737. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8738. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8739. // faces
  8740. indices.push( a, b, d );
  8741. indices.push( b, c, d );
  8742. // increase counter
  8743. groupCount += 6;
  8744. }
  8745. }
  8746. // add a group to the geometry. this will ensure multi material support
  8747. scope.addGroup( groupStart, groupCount, materialIndex );
  8748. // calculate new start value for groups
  8749. groupStart += groupCount;
  8750. // update total number of vertices
  8751. numberOfVertices += vertexCounter;
  8752. }
  8753. }
  8754. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8755. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8756. /**
  8757. * @author mrdoob / http://mrdoob.com/
  8758. * @author Mugen87 / https://github.com/Mugen87
  8759. */
  8760. // PlaneGeometry
  8761. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  8762. Geometry.call( this );
  8763. this.type = 'PlaneGeometry';
  8764. this.parameters = {
  8765. width: width,
  8766. height: height,
  8767. widthSegments: widthSegments,
  8768. heightSegments: heightSegments
  8769. };
  8770. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  8771. this.mergeVertices();
  8772. }
  8773. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  8774. PlaneGeometry.prototype.constructor = PlaneGeometry;
  8775. // PlaneBufferGeometry
  8776. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  8777. BufferGeometry.call( this );
  8778. this.type = 'PlaneBufferGeometry';
  8779. this.parameters = {
  8780. width: width,
  8781. height: height,
  8782. widthSegments: widthSegments,
  8783. heightSegments: heightSegments
  8784. };
  8785. var width_half = width / 2;
  8786. var height_half = height / 2;
  8787. var gridX = Math.floor( widthSegments ) || 1;
  8788. var gridY = Math.floor( heightSegments ) || 1;
  8789. var gridX1 = gridX + 1;
  8790. var gridY1 = gridY + 1;
  8791. var segment_width = width / gridX;
  8792. var segment_height = height / gridY;
  8793. var ix, iy;
  8794. // buffers
  8795. var indices = [];
  8796. var vertices = [];
  8797. var normals = [];
  8798. var uvs = [];
  8799. // generate vertices, normals and uvs
  8800. for ( iy = 0; iy < gridY1; iy ++ ) {
  8801. var y = iy * segment_height - height_half;
  8802. for ( ix = 0; ix < gridX1; ix ++ ) {
  8803. var x = ix * segment_width - width_half;
  8804. vertices.push( x, - y, 0 );
  8805. normals.push( 0, 0, 1 );
  8806. uvs.push( ix / gridX );
  8807. uvs.push( 1 - ( iy / gridY ) );
  8808. }
  8809. }
  8810. // indices
  8811. for ( iy = 0; iy < gridY; iy ++ ) {
  8812. for ( ix = 0; ix < gridX; ix ++ ) {
  8813. var a = ix + gridX1 * iy;
  8814. var b = ix + gridX1 * ( iy + 1 );
  8815. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8816. var d = ( ix + 1 ) + gridX1 * iy;
  8817. // faces
  8818. indices.push( a, b, d );
  8819. indices.push( b, c, d );
  8820. }
  8821. }
  8822. // build geometry
  8823. this.setIndex( indices );
  8824. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8825. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8826. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8827. }
  8828. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8829. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  8830. /**
  8831. * @author mrdoob / http://mrdoob.com/
  8832. * @author alteredq / http://alteredqualia.com/
  8833. *
  8834. * parameters = {
  8835. * color: <hex>,
  8836. * opacity: <float>,
  8837. * map: new THREE.Texture( <Image> ),
  8838. *
  8839. * lightMap: new THREE.Texture( <Image> ),
  8840. * lightMapIntensity: <float>
  8841. *
  8842. * aoMap: new THREE.Texture( <Image> ),
  8843. * aoMapIntensity: <float>
  8844. *
  8845. * specularMap: new THREE.Texture( <Image> ),
  8846. *
  8847. * alphaMap: new THREE.Texture( <Image> ),
  8848. *
  8849. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8850. * combine: THREE.Multiply,
  8851. * reflectivity: <float>,
  8852. * refractionRatio: <float>,
  8853. *
  8854. * shading: THREE.SmoothShading,
  8855. * depthTest: <bool>,
  8856. * depthWrite: <bool>,
  8857. *
  8858. * wireframe: <boolean>,
  8859. * wireframeLinewidth: <float>,
  8860. *
  8861. * skinning: <bool>,
  8862. * morphTargets: <bool>
  8863. * }
  8864. */
  8865. function MeshBasicMaterial( parameters ) {
  8866. Material.call( this );
  8867. this.type = 'MeshBasicMaterial';
  8868. this.color = new Color( 0xffffff ); // emissive
  8869. this.map = null;
  8870. this.lightMap = null;
  8871. this.lightMapIntensity = 1.0;
  8872. this.aoMap = null;
  8873. this.aoMapIntensity = 1.0;
  8874. this.specularMap = null;
  8875. this.alphaMap = null;
  8876. this.envMap = null;
  8877. this.combine = MultiplyOperation;
  8878. this.reflectivity = 1;
  8879. this.refractionRatio = 0.98;
  8880. this.wireframe = false;
  8881. this.wireframeLinewidth = 1;
  8882. this.wireframeLinecap = 'round';
  8883. this.wireframeLinejoin = 'round';
  8884. this.skinning = false;
  8885. this.morphTargets = false;
  8886. this.lights = false;
  8887. this.setValues( parameters );
  8888. }
  8889. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  8890. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  8891. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  8892. MeshBasicMaterial.prototype.copy = function ( source ) {
  8893. Material.prototype.copy.call( this, source );
  8894. this.color.copy( source.color );
  8895. this.map = source.map;
  8896. this.lightMap = source.lightMap;
  8897. this.lightMapIntensity = source.lightMapIntensity;
  8898. this.aoMap = source.aoMap;
  8899. this.aoMapIntensity = source.aoMapIntensity;
  8900. this.specularMap = source.specularMap;
  8901. this.alphaMap = source.alphaMap;
  8902. this.envMap = source.envMap;
  8903. this.combine = source.combine;
  8904. this.reflectivity = source.reflectivity;
  8905. this.refractionRatio = source.refractionRatio;
  8906. this.wireframe = source.wireframe;
  8907. this.wireframeLinewidth = source.wireframeLinewidth;
  8908. this.wireframeLinecap = source.wireframeLinecap;
  8909. this.wireframeLinejoin = source.wireframeLinejoin;
  8910. this.skinning = source.skinning;
  8911. this.morphTargets = source.morphTargets;
  8912. return this;
  8913. };
  8914. /**
  8915. * @author bhouston / http://clara.io
  8916. */
  8917. function Ray( origin, direction ) {
  8918. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  8919. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  8920. }
  8921. Object.assign( Ray.prototype, {
  8922. set: function ( origin, direction ) {
  8923. this.origin.copy( origin );
  8924. this.direction.copy( direction );
  8925. return this;
  8926. },
  8927. clone: function () {
  8928. return new this.constructor().copy( this );
  8929. },
  8930. copy: function ( ray ) {
  8931. this.origin.copy( ray.origin );
  8932. this.direction.copy( ray.direction );
  8933. return this;
  8934. },
  8935. at: function ( t, optionalTarget ) {
  8936. var result = optionalTarget || new Vector3();
  8937. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  8938. },
  8939. lookAt: function ( v ) {
  8940. this.direction.copy( v ).sub( this.origin ).normalize();
  8941. return this;
  8942. },
  8943. recast: function () {
  8944. var v1 = new Vector3();
  8945. return function recast( t ) {
  8946. this.origin.copy( this.at( t, v1 ) );
  8947. return this;
  8948. };
  8949. }(),
  8950. closestPointToPoint: function ( point, optionalTarget ) {
  8951. var result = optionalTarget || new Vector3();
  8952. result.subVectors( point, this.origin );
  8953. var directionDistance = result.dot( this.direction );
  8954. if ( directionDistance < 0 ) {
  8955. return result.copy( this.origin );
  8956. }
  8957. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  8958. },
  8959. distanceToPoint: function ( point ) {
  8960. return Math.sqrt( this.distanceSqToPoint( point ) );
  8961. },
  8962. distanceSqToPoint: function () {
  8963. var v1 = new Vector3();
  8964. return function distanceSqToPoint( point ) {
  8965. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  8966. // point behind the ray
  8967. if ( directionDistance < 0 ) {
  8968. return this.origin.distanceToSquared( point );
  8969. }
  8970. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  8971. return v1.distanceToSquared( point );
  8972. };
  8973. }(),
  8974. distanceSqToSegment: function () {
  8975. var segCenter = new Vector3();
  8976. var segDir = new Vector3();
  8977. var diff = new Vector3();
  8978. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8979. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8980. // It returns the min distance between the ray and the segment
  8981. // defined by v0 and v1
  8982. // It can also set two optional targets :
  8983. // - The closest point on the ray
  8984. // - The closest point on the segment
  8985. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8986. segDir.copy( v1 ).sub( v0 ).normalize();
  8987. diff.copy( this.origin ).sub( segCenter );
  8988. var segExtent = v0.distanceTo( v1 ) * 0.5;
  8989. var a01 = - this.direction.dot( segDir );
  8990. var b0 = diff.dot( this.direction );
  8991. var b1 = - diff.dot( segDir );
  8992. var c = diff.lengthSq();
  8993. var det = Math.abs( 1 - a01 * a01 );
  8994. var s0, s1, sqrDist, extDet;
  8995. if ( det > 0 ) {
  8996. // The ray and segment are not parallel.
  8997. s0 = a01 * b1 - b0;
  8998. s1 = a01 * b0 - b1;
  8999. extDet = segExtent * det;
  9000. if ( s0 >= 0 ) {
  9001. if ( s1 >= - extDet ) {
  9002. if ( s1 <= extDet ) {
  9003. // region 0
  9004. // Minimum at interior points of ray and segment.
  9005. var invDet = 1 / det;
  9006. s0 *= invDet;
  9007. s1 *= invDet;
  9008. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9009. } else {
  9010. // region 1
  9011. s1 = segExtent;
  9012. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9013. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9014. }
  9015. } else {
  9016. // region 5
  9017. s1 = - segExtent;
  9018. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9019. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9020. }
  9021. } else {
  9022. if ( s1 <= - extDet ) {
  9023. // region 4
  9024. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9025. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9026. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9027. } else if ( s1 <= extDet ) {
  9028. // region 3
  9029. s0 = 0;
  9030. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9031. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9032. } else {
  9033. // region 2
  9034. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9035. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9036. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9037. }
  9038. }
  9039. } else {
  9040. // Ray and segment are parallel.
  9041. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9042. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9043. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9044. }
  9045. if ( optionalPointOnRay ) {
  9046. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9047. }
  9048. if ( optionalPointOnSegment ) {
  9049. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  9050. }
  9051. return sqrDist;
  9052. };
  9053. }(),
  9054. intersectSphere: function () {
  9055. var v1 = new Vector3();
  9056. return function intersectSphere( sphere, optionalTarget ) {
  9057. v1.subVectors( sphere.center, this.origin );
  9058. var tca = v1.dot( this.direction );
  9059. var d2 = v1.dot( v1 ) - tca * tca;
  9060. var radius2 = sphere.radius * sphere.radius;
  9061. if ( d2 > radius2 ) return null;
  9062. var thc = Math.sqrt( radius2 - d2 );
  9063. // t0 = first intersect point - entrance on front of sphere
  9064. var t0 = tca - thc;
  9065. // t1 = second intersect point - exit point on back of sphere
  9066. var t1 = tca + thc;
  9067. // test to see if both t0 and t1 are behind the ray - if so, return null
  9068. if ( t0 < 0 && t1 < 0 ) return null;
  9069. // test to see if t0 is behind the ray:
  9070. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9071. // in order to always return an intersect point that is in front of the ray.
  9072. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  9073. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9074. return this.at( t0, optionalTarget );
  9075. };
  9076. }(),
  9077. intersectsSphere: function ( sphere ) {
  9078. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  9079. },
  9080. distanceToPlane: function ( plane ) {
  9081. var denominator = plane.normal.dot( this.direction );
  9082. if ( denominator === 0 ) {
  9083. // line is coplanar, return origin
  9084. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9085. return 0;
  9086. }
  9087. // Null is preferable to undefined since undefined means.... it is undefined
  9088. return null;
  9089. }
  9090. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9091. // Return if the ray never intersects the plane
  9092. return t >= 0 ? t : null;
  9093. },
  9094. intersectPlane: function ( plane, optionalTarget ) {
  9095. var t = this.distanceToPlane( plane );
  9096. if ( t === null ) {
  9097. return null;
  9098. }
  9099. return this.at( t, optionalTarget );
  9100. },
  9101. intersectsPlane: function ( plane ) {
  9102. // check if the ray lies on the plane first
  9103. var distToPoint = plane.distanceToPoint( this.origin );
  9104. if ( distToPoint === 0 ) {
  9105. return true;
  9106. }
  9107. var denominator = plane.normal.dot( this.direction );
  9108. if ( denominator * distToPoint < 0 ) {
  9109. return true;
  9110. }
  9111. // ray origin is behind the plane (and is pointing behind it)
  9112. return false;
  9113. },
  9114. intersectBox: function ( box, optionalTarget ) {
  9115. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9116. var invdirx = 1 / this.direction.x,
  9117. invdiry = 1 / this.direction.y,
  9118. invdirz = 1 / this.direction.z;
  9119. var origin = this.origin;
  9120. if ( invdirx >= 0 ) {
  9121. tmin = ( box.min.x - origin.x ) * invdirx;
  9122. tmax = ( box.max.x - origin.x ) * invdirx;
  9123. } else {
  9124. tmin = ( box.max.x - origin.x ) * invdirx;
  9125. tmax = ( box.min.x - origin.x ) * invdirx;
  9126. }
  9127. if ( invdiry >= 0 ) {
  9128. tymin = ( box.min.y - origin.y ) * invdiry;
  9129. tymax = ( box.max.y - origin.y ) * invdiry;
  9130. } else {
  9131. tymin = ( box.max.y - origin.y ) * invdiry;
  9132. tymax = ( box.min.y - origin.y ) * invdiry;
  9133. }
  9134. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  9135. // These lines also handle the case where tmin or tmax is NaN
  9136. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9137. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  9138. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  9139. if ( invdirz >= 0 ) {
  9140. tzmin = ( box.min.z - origin.z ) * invdirz;
  9141. tzmax = ( box.max.z - origin.z ) * invdirz;
  9142. } else {
  9143. tzmin = ( box.max.z - origin.z ) * invdirz;
  9144. tzmax = ( box.min.z - origin.z ) * invdirz;
  9145. }
  9146. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  9147. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  9148. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  9149. //return point closest to the ray (positive side)
  9150. if ( tmax < 0 ) return null;
  9151. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  9152. },
  9153. intersectsBox: ( function () {
  9154. var v = new Vector3();
  9155. return function intersectsBox( box ) {
  9156. return this.intersectBox( box, v ) !== null;
  9157. };
  9158. } )(),
  9159. intersectTriangle: function () {
  9160. // Compute the offset origin, edges, and normal.
  9161. var diff = new Vector3();
  9162. var edge1 = new Vector3();
  9163. var edge2 = new Vector3();
  9164. var normal = new Vector3();
  9165. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  9166. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9167. edge1.subVectors( b, a );
  9168. edge2.subVectors( c, a );
  9169. normal.crossVectors( edge1, edge2 );
  9170. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9171. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9172. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9173. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9174. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9175. var DdN = this.direction.dot( normal );
  9176. var sign;
  9177. if ( DdN > 0 ) {
  9178. if ( backfaceCulling ) return null;
  9179. sign = 1;
  9180. } else if ( DdN < 0 ) {
  9181. sign = - 1;
  9182. DdN = - DdN;
  9183. } else {
  9184. return null;
  9185. }
  9186. diff.subVectors( this.origin, a );
  9187. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  9188. // b1 < 0, no intersection
  9189. if ( DdQxE2 < 0 ) {
  9190. return null;
  9191. }
  9192. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  9193. // b2 < 0, no intersection
  9194. if ( DdE1xQ < 0 ) {
  9195. return null;
  9196. }
  9197. // b1+b2 > 1, no intersection
  9198. if ( DdQxE2 + DdE1xQ > DdN ) {
  9199. return null;
  9200. }
  9201. // Line intersects triangle, check if ray does.
  9202. var QdN = - sign * diff.dot( normal );
  9203. // t < 0, no intersection
  9204. if ( QdN < 0 ) {
  9205. return null;
  9206. }
  9207. // Ray intersects triangle.
  9208. return this.at( QdN / DdN, optionalTarget );
  9209. };
  9210. }(),
  9211. applyMatrix4: function ( matrix4 ) {
  9212. this.origin.applyMatrix4( matrix4 );
  9213. this.direction.transformDirection( matrix4 );
  9214. return this;
  9215. },
  9216. equals: function ( ray ) {
  9217. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  9218. }
  9219. } );
  9220. /**
  9221. * @author bhouston / http://clara.io
  9222. */
  9223. function Line3( start, end ) {
  9224. this.start = ( start !== undefined ) ? start : new Vector3();
  9225. this.end = ( end !== undefined ) ? end : new Vector3();
  9226. }
  9227. Object.assign( Line3.prototype, {
  9228. set: function ( start, end ) {
  9229. this.start.copy( start );
  9230. this.end.copy( end );
  9231. return this;
  9232. },
  9233. clone: function () {
  9234. return new this.constructor().copy( this );
  9235. },
  9236. copy: function ( line ) {
  9237. this.start.copy( line.start );
  9238. this.end.copy( line.end );
  9239. return this;
  9240. },
  9241. getCenter: function ( optionalTarget ) {
  9242. var result = optionalTarget || new Vector3();
  9243. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  9244. },
  9245. delta: function ( optionalTarget ) {
  9246. var result = optionalTarget || new Vector3();
  9247. return result.subVectors( this.end, this.start );
  9248. },
  9249. distanceSq: function () {
  9250. return this.start.distanceToSquared( this.end );
  9251. },
  9252. distance: function () {
  9253. return this.start.distanceTo( this.end );
  9254. },
  9255. at: function ( t, optionalTarget ) {
  9256. var result = optionalTarget || new Vector3();
  9257. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9258. },
  9259. closestPointToPointParameter: function () {
  9260. var startP = new Vector3();
  9261. var startEnd = new Vector3();
  9262. return function closestPointToPointParameter( point, clampToLine ) {
  9263. startP.subVectors( point, this.start );
  9264. startEnd.subVectors( this.end, this.start );
  9265. var startEnd2 = startEnd.dot( startEnd );
  9266. var startEnd_startP = startEnd.dot( startP );
  9267. var t = startEnd_startP / startEnd2;
  9268. if ( clampToLine ) {
  9269. t = _Math.clamp( t, 0, 1 );
  9270. }
  9271. return t;
  9272. };
  9273. }(),
  9274. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  9275. var t = this.closestPointToPointParameter( point, clampToLine );
  9276. var result = optionalTarget || new Vector3();
  9277. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9278. },
  9279. applyMatrix4: function ( matrix ) {
  9280. this.start.applyMatrix4( matrix );
  9281. this.end.applyMatrix4( matrix );
  9282. return this;
  9283. },
  9284. equals: function ( line ) {
  9285. return line.start.equals( this.start ) && line.end.equals( this.end );
  9286. }
  9287. } );
  9288. /**
  9289. * @author bhouston / http://clara.io
  9290. * @author mrdoob / http://mrdoob.com/
  9291. */
  9292. function Triangle( a, b, c ) {
  9293. this.a = ( a !== undefined ) ? a : new Vector3();
  9294. this.b = ( b !== undefined ) ? b : new Vector3();
  9295. this.c = ( c !== undefined ) ? c : new Vector3();
  9296. }
  9297. Object.assign( Triangle, {
  9298. normal: function () {
  9299. var v0 = new Vector3();
  9300. return function normal( a, b, c, optionalTarget ) {
  9301. var result = optionalTarget || new Vector3();
  9302. result.subVectors( c, b );
  9303. v0.subVectors( a, b );
  9304. result.cross( v0 );
  9305. var resultLengthSq = result.lengthSq();
  9306. if ( resultLengthSq > 0 ) {
  9307. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  9308. }
  9309. return result.set( 0, 0, 0 );
  9310. };
  9311. }(),
  9312. // static/instance method to calculate barycentric coordinates
  9313. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9314. barycoordFromPoint: function () {
  9315. var v0 = new Vector3();
  9316. var v1 = new Vector3();
  9317. var v2 = new Vector3();
  9318. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  9319. v0.subVectors( c, a );
  9320. v1.subVectors( b, a );
  9321. v2.subVectors( point, a );
  9322. var dot00 = v0.dot( v0 );
  9323. var dot01 = v0.dot( v1 );
  9324. var dot02 = v0.dot( v2 );
  9325. var dot11 = v1.dot( v1 );
  9326. var dot12 = v1.dot( v2 );
  9327. var denom = ( dot00 * dot11 - dot01 * dot01 );
  9328. var result = optionalTarget || new Vector3();
  9329. // collinear or singular triangle
  9330. if ( denom === 0 ) {
  9331. // arbitrary location outside of triangle?
  9332. // not sure if this is the best idea, maybe should be returning undefined
  9333. return result.set( - 2, - 1, - 1 );
  9334. }
  9335. var invDenom = 1 / denom;
  9336. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9337. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9338. // barycentric coordinates must always sum to 1
  9339. return result.set( 1 - u - v, v, u );
  9340. };
  9341. }(),
  9342. containsPoint: function () {
  9343. var v1 = new Vector3();
  9344. return function containsPoint( point, a, b, c ) {
  9345. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  9346. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  9347. };
  9348. }()
  9349. } );
  9350. Object.assign( Triangle.prototype, {
  9351. set: function ( a, b, c ) {
  9352. this.a.copy( a );
  9353. this.b.copy( b );
  9354. this.c.copy( c );
  9355. return this;
  9356. },
  9357. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  9358. this.a.copy( points[ i0 ] );
  9359. this.b.copy( points[ i1 ] );
  9360. this.c.copy( points[ i2 ] );
  9361. return this;
  9362. },
  9363. clone: function () {
  9364. return new this.constructor().copy( this );
  9365. },
  9366. copy: function ( triangle ) {
  9367. this.a.copy( triangle.a );
  9368. this.b.copy( triangle.b );
  9369. this.c.copy( triangle.c );
  9370. return this;
  9371. },
  9372. area: function () {
  9373. var v0 = new Vector3();
  9374. var v1 = new Vector3();
  9375. return function area() {
  9376. v0.subVectors( this.c, this.b );
  9377. v1.subVectors( this.a, this.b );
  9378. return v0.cross( v1 ).length() * 0.5;
  9379. };
  9380. }(),
  9381. midpoint: function ( optionalTarget ) {
  9382. var result = optionalTarget || new Vector3();
  9383. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9384. },
  9385. normal: function ( optionalTarget ) {
  9386. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  9387. },
  9388. plane: function ( optionalTarget ) {
  9389. var result = optionalTarget || new Plane();
  9390. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  9391. },
  9392. barycoordFromPoint: function ( point, optionalTarget ) {
  9393. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  9394. },
  9395. containsPoint: function ( point ) {
  9396. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9397. },
  9398. closestPointToPoint: function () {
  9399. var plane = new Plane();
  9400. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  9401. var projectedPoint = new Vector3();
  9402. var closestPoint = new Vector3();
  9403. return function closestPointToPoint( point, optionalTarget ) {
  9404. var result = optionalTarget || new Vector3();
  9405. var minDistance = Infinity;
  9406. // project the point onto the plane of the triangle
  9407. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  9408. plane.projectPoint( point, projectedPoint );
  9409. // check if the projection lies within the triangle
  9410. if( this.containsPoint( projectedPoint ) === true ) {
  9411. // if so, this is the closest point
  9412. result.copy( projectedPoint );
  9413. } else {
  9414. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  9415. edgeList[ 0 ].set( this.a, this.b );
  9416. edgeList[ 1 ].set( this.b, this.c );
  9417. edgeList[ 2 ].set( this.c, this.a );
  9418. for( var i = 0; i < edgeList.length; i ++ ) {
  9419. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  9420. var distance = projectedPoint.distanceToSquared( closestPoint );
  9421. if( distance < minDistance ) {
  9422. minDistance = distance;
  9423. result.copy( closestPoint );
  9424. }
  9425. }
  9426. }
  9427. return result;
  9428. };
  9429. }(),
  9430. equals: function ( triangle ) {
  9431. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9432. }
  9433. } );
  9434. /**
  9435. * @author mrdoob / http://mrdoob.com/
  9436. * @author alteredq / http://alteredqualia.com/
  9437. * @author mikael emtinger / http://gomo.se/
  9438. * @author jonobr1 / http://jonobr1.com/
  9439. */
  9440. function Mesh( geometry, material ) {
  9441. Object3D.call( this );
  9442. this.type = 'Mesh';
  9443. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  9444. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9445. this.drawMode = TrianglesDrawMode;
  9446. this.updateMorphTargets();
  9447. }
  9448. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9449. constructor: Mesh,
  9450. isMesh: true,
  9451. setDrawMode: function ( value ) {
  9452. this.drawMode = value;
  9453. },
  9454. copy: function ( source ) {
  9455. Object3D.prototype.copy.call( this, source );
  9456. this.drawMode = source.drawMode;
  9457. return this;
  9458. },
  9459. updateMorphTargets: function () {
  9460. var geometry = this.geometry;
  9461. var m, ml, name;
  9462. if ( geometry.isBufferGeometry ) {
  9463. var morphAttributes = geometry.morphAttributes;
  9464. var keys = Object.keys( morphAttributes );
  9465. if ( keys.length > 0 ) {
  9466. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  9467. if ( morphAttribute !== undefined ) {
  9468. this.morphTargetInfluences = [];
  9469. this.morphTargetDictionary = {};
  9470. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9471. name = morphAttribute[ m ].name || String( m );
  9472. this.morphTargetInfluences.push( 0 );
  9473. this.morphTargetDictionary[ name ] = m;
  9474. }
  9475. }
  9476. }
  9477. } else {
  9478. var morphTargets = geometry.morphTargets;
  9479. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  9480. this.morphTargetInfluences = [];
  9481. this.morphTargetDictionary = {};
  9482. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  9483. name = morphTargets[ m ].name || String( m );
  9484. this.morphTargetInfluences.push( 0 );
  9485. this.morphTargetDictionary[ name ] = m;
  9486. }
  9487. }
  9488. }
  9489. },
  9490. raycast: ( function () {
  9491. var inverseMatrix = new Matrix4();
  9492. var ray = new Ray();
  9493. var sphere = new Sphere();
  9494. var vA = new Vector3();
  9495. var vB = new Vector3();
  9496. var vC = new Vector3();
  9497. var tempA = new Vector3();
  9498. var tempB = new Vector3();
  9499. var tempC = new Vector3();
  9500. var uvA = new Vector2();
  9501. var uvB = new Vector2();
  9502. var uvC = new Vector2();
  9503. var barycoord = new Vector3();
  9504. var intersectionPoint = new Vector3();
  9505. var intersectionPointWorld = new Vector3();
  9506. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  9507. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  9508. uv1.multiplyScalar( barycoord.x );
  9509. uv2.multiplyScalar( barycoord.y );
  9510. uv3.multiplyScalar( barycoord.z );
  9511. uv1.add( uv2 ).add( uv3 );
  9512. return uv1.clone();
  9513. }
  9514. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  9515. var intersect;
  9516. var material = object.material;
  9517. if ( material.side === BackSide ) {
  9518. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  9519. } else {
  9520. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  9521. }
  9522. if ( intersect === null ) return null;
  9523. intersectionPointWorld.copy( point );
  9524. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  9525. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  9526. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  9527. return {
  9528. distance: distance,
  9529. point: intersectionPointWorld.clone(),
  9530. object: object
  9531. };
  9532. }
  9533. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  9534. vA.fromBufferAttribute( position, a );
  9535. vB.fromBufferAttribute( position, b );
  9536. vC.fromBufferAttribute( position, c );
  9537. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  9538. if ( intersection ) {
  9539. if ( uv ) {
  9540. uvA.fromBufferAttribute( uv, a );
  9541. uvB.fromBufferAttribute( uv, b );
  9542. uvC.fromBufferAttribute( uv, c );
  9543. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  9544. }
  9545. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  9546. intersection.faceIndex = a;
  9547. }
  9548. return intersection;
  9549. }
  9550. return function raycast( raycaster, intersects ) {
  9551. var geometry = this.geometry;
  9552. var material = this.material;
  9553. var matrixWorld = this.matrixWorld;
  9554. if ( material === undefined ) return;
  9555. // Checking boundingSphere distance to ray
  9556. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9557. sphere.copy( geometry.boundingSphere );
  9558. sphere.applyMatrix4( matrixWorld );
  9559. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9560. //
  9561. inverseMatrix.getInverse( matrixWorld );
  9562. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9563. // Check boundingBox before continuing
  9564. if ( geometry.boundingBox !== null ) {
  9565. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  9566. }
  9567. var intersection;
  9568. if ( geometry.isBufferGeometry ) {
  9569. var a, b, c;
  9570. var index = geometry.index;
  9571. var position = geometry.attributes.position;
  9572. var uv = geometry.attributes.uv;
  9573. var i, l;
  9574. if ( index !== null ) {
  9575. // indexed buffer geometry
  9576. for ( i = 0, l = index.count; i < l; i += 3 ) {
  9577. a = index.getX( i );
  9578. b = index.getX( i + 1 );
  9579. c = index.getX( i + 2 );
  9580. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9581. if ( intersection ) {
  9582. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  9583. intersects.push( intersection );
  9584. }
  9585. }
  9586. } else {
  9587. // non-indexed buffer geometry
  9588. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9589. a = i;
  9590. b = i + 1;
  9591. c = i + 2;
  9592. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9593. if ( intersection ) {
  9594. intersection.index = a; // triangle number in positions buffer semantics
  9595. intersects.push( intersection );
  9596. }
  9597. }
  9598. }
  9599. } else if ( geometry.isGeometry ) {
  9600. var fvA, fvB, fvC;
  9601. var isMultiMaterial = Array.isArray( material );
  9602. var vertices = geometry.vertices;
  9603. var faces = geometry.faces;
  9604. var uvs;
  9605. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9606. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9607. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9608. var face = faces[ f ];
  9609. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9610. if ( faceMaterial === undefined ) continue;
  9611. fvA = vertices[ face.a ];
  9612. fvB = vertices[ face.b ];
  9613. fvC = vertices[ face.c ];
  9614. if ( faceMaterial.morphTargets === true ) {
  9615. var morphTargets = geometry.morphTargets;
  9616. var morphInfluences = this.morphTargetInfluences;
  9617. vA.set( 0, 0, 0 );
  9618. vB.set( 0, 0, 0 );
  9619. vC.set( 0, 0, 0 );
  9620. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9621. var influence = morphInfluences[ t ];
  9622. if ( influence === 0 ) continue;
  9623. var targets = morphTargets[ t ].vertices;
  9624. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9625. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9626. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9627. }
  9628. vA.add( fvA );
  9629. vB.add( fvB );
  9630. vC.add( fvC );
  9631. fvA = vA;
  9632. fvB = vB;
  9633. fvC = vC;
  9634. }
  9635. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9636. if ( intersection ) {
  9637. if ( uvs && uvs[ f ] ) {
  9638. var uvs_f = uvs[ f ];
  9639. uvA.copy( uvs_f[ 0 ] );
  9640. uvB.copy( uvs_f[ 1 ] );
  9641. uvC.copy( uvs_f[ 2 ] );
  9642. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9643. }
  9644. intersection.face = face;
  9645. intersection.faceIndex = f;
  9646. intersects.push( intersection );
  9647. }
  9648. }
  9649. }
  9650. };
  9651. }() ),
  9652. clone: function () {
  9653. return new this.constructor( this.geometry, this.material ).copy( this );
  9654. }
  9655. } );
  9656. /**
  9657. * @author mrdoob / http://mrdoob.com/
  9658. */
  9659. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  9660. var clearColor = new Color( 0x000000 );
  9661. var clearAlpha = 0;
  9662. var planeCamera, planeMesh;
  9663. var boxCamera, boxMesh;
  9664. function render( scene, camera, forceClear ) {
  9665. var background = scene.background;
  9666. if ( background === null ) {
  9667. setClear( clearColor, clearAlpha );
  9668. } else if ( background && background.isColor ) {
  9669. setClear( background, 1 );
  9670. forceClear = true;
  9671. }
  9672. if ( renderer.autoClear || forceClear ) {
  9673. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9674. }
  9675. if ( background && background.isCubeTexture ) {
  9676. if ( boxCamera === undefined ) {
  9677. boxCamera = new PerspectiveCamera();
  9678. boxMesh = new Mesh(
  9679. new BoxBufferGeometry( 5, 5, 5 ),
  9680. new ShaderMaterial( {
  9681. uniforms: ShaderLib.cube.uniforms,
  9682. vertexShader: ShaderLib.cube.vertexShader,
  9683. fragmentShader: ShaderLib.cube.fragmentShader,
  9684. side: BackSide,
  9685. depthTest: false,
  9686. depthWrite: false,
  9687. fog: false
  9688. } )
  9689. );
  9690. }
  9691. boxCamera.projectionMatrix.copy( camera.projectionMatrix );
  9692. boxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  9693. boxCamera.matrixWorldInverse.getInverse( boxCamera.matrixWorld );
  9694. boxMesh.material.uniforms[ "tCube" ].value = background;
  9695. boxMesh.modelViewMatrix.multiplyMatrices( boxCamera.matrixWorldInverse, boxMesh.matrixWorld );
  9696. objects.update( boxMesh );
  9697. renderer.renderBufferDirect( boxCamera, null, boxMesh.geometry, boxMesh.material, boxMesh, null );
  9698. } else if ( background && background.isTexture ) {
  9699. if ( planeCamera === undefined ) {
  9700. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9701. planeMesh = new Mesh(
  9702. new PlaneBufferGeometry( 2, 2 ),
  9703. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  9704. );
  9705. }
  9706. planeMesh.material.map = background;
  9707. objects.update( planeMesh );
  9708. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  9709. }
  9710. }
  9711. function setClear( color, alpha ) {
  9712. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9713. }
  9714. return {
  9715. getClearColor: function () {
  9716. return clearColor;
  9717. },
  9718. setClearColor: function ( color, alpha ) {
  9719. clearColor.set( color );
  9720. clearAlpha = alpha !== undefined ? alpha : 1;
  9721. setClear( clearColor, clearAlpha );
  9722. },
  9723. getClearAlpha: function () {
  9724. return clearAlpha;
  9725. },
  9726. setClearAlpha: function ( alpha ) {
  9727. clearAlpha = alpha;
  9728. setClear( clearColor, clearAlpha );
  9729. },
  9730. render: render
  9731. };
  9732. }
  9733. /**
  9734. * @author mrdoob / http://mrdoob.com/
  9735. */
  9736. function painterSortStable( a, b ) {
  9737. if ( a.renderOrder !== b.renderOrder ) {
  9738. return a.renderOrder - b.renderOrder;
  9739. } else if ( a.program && b.program && a.program !== b.program ) {
  9740. return a.program.id - b.program.id;
  9741. } else if ( a.material.id !== b.material.id ) {
  9742. return a.material.id - b.material.id;
  9743. } else if ( a.z !== b.z ) {
  9744. return a.z - b.z;
  9745. } else {
  9746. return a.id - b.id;
  9747. }
  9748. }
  9749. function reversePainterSortStable( a, b ) {
  9750. if ( a.renderOrder !== b.renderOrder ) {
  9751. return a.renderOrder - b.renderOrder;
  9752. } if ( a.z !== b.z ) {
  9753. return b.z - a.z;
  9754. } else {
  9755. return a.id - b.id;
  9756. }
  9757. }
  9758. function WebGLRenderList() {
  9759. var opaque = [];
  9760. var opaqueLastIndex = - 1;
  9761. var transparent = [];
  9762. var transparentLastIndex = - 1;
  9763. function init() {
  9764. opaqueLastIndex = - 1;
  9765. transparentLastIndex = - 1;
  9766. }
  9767. function push( object, geometry, material, z, group ) {
  9768. var array, index;
  9769. // allocate the next position in the appropriate array
  9770. if ( material.transparent ) {
  9771. array = transparent;
  9772. index = ++ transparentLastIndex;
  9773. } else {
  9774. array = opaque;
  9775. index = ++ opaqueLastIndex;
  9776. }
  9777. // recycle existing render item or grow the array
  9778. var renderItem = array[ index ];
  9779. if ( renderItem ) {
  9780. renderItem.id = object.id;
  9781. renderItem.object = object;
  9782. renderItem.geometry = geometry;
  9783. renderItem.material = material;
  9784. renderItem.program = material.program;
  9785. renderItem.renderOrder = object.renderOrder;
  9786. renderItem.z = z;
  9787. renderItem.group = group;
  9788. } else {
  9789. renderItem = {
  9790. id: object.id,
  9791. object: object,
  9792. geometry: geometry,
  9793. material: material,
  9794. program: material.program,
  9795. renderOrder: object.renderOrder,
  9796. z: z,
  9797. group: group
  9798. };
  9799. // assert( index === array.length );
  9800. array.push( renderItem );
  9801. }
  9802. }
  9803. function finish() {
  9804. opaque.length = opaqueLastIndex + 1;
  9805. transparent.length = transparentLastIndex + 1;
  9806. }
  9807. function sort() {
  9808. opaque.sort( painterSortStable );
  9809. transparent.sort( reversePainterSortStable );
  9810. }
  9811. return {
  9812. opaque: opaque,
  9813. transparent: transparent,
  9814. init: init,
  9815. push: push,
  9816. finish: finish,
  9817. sort: sort
  9818. };
  9819. }
  9820. function WebGLRenderLists() {
  9821. var lists = {};
  9822. function get( scene, camera ) {
  9823. var hash = scene.id + ',' + camera.id;
  9824. var list = lists[ hash ];
  9825. if ( list === undefined ) {
  9826. // console.log( 'THREE.WebGLRenderLists:', hash );
  9827. list = new WebGLRenderList();
  9828. lists[ hash ] = list;
  9829. }
  9830. return list;
  9831. }
  9832. function dispose() {
  9833. lists = {};
  9834. }
  9835. return {
  9836. get: get,
  9837. dispose: dispose
  9838. };
  9839. }
  9840. /**
  9841. * @author mrdoob / http://mrdoob.com/
  9842. */
  9843. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9844. var mode;
  9845. function setMode( value ) {
  9846. mode = value;
  9847. }
  9848. var type, bytesPerElement;
  9849. function setIndex( value ) {
  9850. type = value.type;
  9851. bytesPerElement = value.bytesPerElement;
  9852. }
  9853. function render( start, count ) {
  9854. gl.drawElements( mode, count, type, start * bytesPerElement );
  9855. infoRender.calls ++;
  9856. infoRender.vertices += count;
  9857. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9858. }
  9859. function renderInstances( geometry, start, count ) {
  9860. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9861. if ( extension === null ) {
  9862. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9863. return;
  9864. }
  9865. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  9866. infoRender.calls ++;
  9867. infoRender.vertices += count * geometry.maxInstancedCount;
  9868. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9869. }
  9870. //
  9871. this.setMode = setMode;
  9872. this.setIndex = setIndex;
  9873. this.render = render;
  9874. this.renderInstances = renderInstances;
  9875. }
  9876. /**
  9877. * @author mrdoob / http://mrdoob.com/
  9878. */
  9879. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9880. var mode;
  9881. function setMode( value ) {
  9882. mode = value;
  9883. }
  9884. function render( start, count ) {
  9885. gl.drawArrays( mode, start, count );
  9886. infoRender.calls ++;
  9887. infoRender.vertices += count;
  9888. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9889. }
  9890. function renderInstances( geometry, start, count ) {
  9891. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9892. if ( extension === null ) {
  9893. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9894. return;
  9895. }
  9896. var position = geometry.attributes.position;
  9897. if ( position.isInterleavedBufferAttribute ) {
  9898. count = position.data.count;
  9899. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9900. } else {
  9901. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  9902. }
  9903. infoRender.calls ++;
  9904. infoRender.vertices += count * geometry.maxInstancedCount;
  9905. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9906. }
  9907. //
  9908. this.setMode = setMode;
  9909. this.render = render;
  9910. this.renderInstances = renderInstances;
  9911. }
  9912. /**
  9913. * @author mrdoob / http://mrdoob.com/
  9914. */
  9915. function WebGLGeometries( gl, attributes, infoMemory ) {
  9916. var geometries = {};
  9917. var wireframeAttributes = {};
  9918. function onGeometryDispose( event ) {
  9919. var geometry = event.target;
  9920. var buffergeometry = geometries[ geometry.id ];
  9921. if ( buffergeometry.index !== null ) {
  9922. attributes.remove( buffergeometry.index );
  9923. }
  9924. for ( var name in buffergeometry.attributes ) {
  9925. attributes.remove( buffergeometry.attributes[ name ] );
  9926. }
  9927. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9928. delete geometries[ geometry.id ];
  9929. // TODO Remove duplicate code
  9930. var attribute = wireframeAttributes[ geometry.id ];
  9931. if ( attribute ) {
  9932. attributes.remove( attribute );
  9933. delete wireframeAttributes[ geometry.id ];
  9934. }
  9935. attribute = wireframeAttributes[ buffergeometry.id ];
  9936. if ( attribute ) {
  9937. attributes.remove( attribute );
  9938. delete wireframeAttributes[ buffergeometry.id ];
  9939. }
  9940. //
  9941. infoMemory.geometries --;
  9942. }
  9943. function get( object, geometry ) {
  9944. var buffergeometry = geometries[ geometry.id ];
  9945. if ( buffergeometry ) return buffergeometry;
  9946. geometry.addEventListener( 'dispose', onGeometryDispose );
  9947. if ( geometry.isBufferGeometry ) {
  9948. buffergeometry = geometry;
  9949. } else if ( geometry.isGeometry ) {
  9950. if ( geometry._bufferGeometry === undefined ) {
  9951. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9952. }
  9953. buffergeometry = geometry._bufferGeometry;
  9954. }
  9955. geometries[ geometry.id ] = buffergeometry;
  9956. infoMemory.geometries ++;
  9957. return buffergeometry;
  9958. }
  9959. function update( geometry ) {
  9960. var index = geometry.index;
  9961. var geometryAttributes = geometry.attributes;
  9962. if ( index !== null ) {
  9963. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9964. }
  9965. for ( var name in geometryAttributes ) {
  9966. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9967. }
  9968. // morph targets
  9969. var morphAttributes = geometry.morphAttributes;
  9970. for ( var name in morphAttributes ) {
  9971. var array = morphAttributes[ name ];
  9972. for ( var i = 0, l = array.length; i < l; i ++ ) {
  9973. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9974. }
  9975. }
  9976. }
  9977. function getWireframeAttribute( geometry ) {
  9978. var attribute = wireframeAttributes[ geometry.id ];
  9979. if ( attribute ) return attribute;
  9980. var indices = [];
  9981. var geometryIndex = geometry.index;
  9982. var geometryAttributes = geometry.attributes;
  9983. // console.time( 'wireframe' );
  9984. if ( geometryIndex !== null ) {
  9985. var array = geometryIndex.array;
  9986. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9987. var a = array[ i + 0 ];
  9988. var b = array[ i + 1 ];
  9989. var c = array[ i + 2 ];
  9990. indices.push( a, b, b, c, c, a );
  9991. }
  9992. } else {
  9993. var array = geometryAttributes.position.array;
  9994. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9995. var a = i + 0;
  9996. var b = i + 1;
  9997. var c = i + 2;
  9998. indices.push( a, b, b, c, c, a );
  9999. }
  10000. }
  10001. // console.timeEnd( 'wireframe' );
  10002. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10003. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10004. wireframeAttributes[ geometry.id ] = attribute;
  10005. return attribute;
  10006. }
  10007. return {
  10008. get: get,
  10009. update: update,
  10010. getWireframeAttribute: getWireframeAttribute
  10011. };
  10012. }
  10013. /**
  10014. * @author mrdoob / http://mrdoob.com/
  10015. */
  10016. function WebGLLights() {
  10017. var lights = {};
  10018. return {
  10019. get: function ( light ) {
  10020. if ( lights[ light.id ] !== undefined ) {
  10021. return lights[ light.id ];
  10022. }
  10023. var uniforms;
  10024. switch ( light.type ) {
  10025. case 'DirectionalLight':
  10026. uniforms = {
  10027. direction: new Vector3(),
  10028. color: new Color(),
  10029. shadow: false,
  10030. shadowBias: 0,
  10031. shadowRadius: 1,
  10032. shadowMapSize: new Vector2()
  10033. };
  10034. break;
  10035. case 'SpotLight':
  10036. uniforms = {
  10037. position: new Vector3(),
  10038. direction: new Vector3(),
  10039. color: new Color(),
  10040. distance: 0,
  10041. coneCos: 0,
  10042. penumbraCos: 0,
  10043. decay: 0,
  10044. shadow: false,
  10045. shadowBias: 0,
  10046. shadowRadius: 1,
  10047. shadowMapSize: new Vector2()
  10048. };
  10049. break;
  10050. case 'PointLight':
  10051. uniforms = {
  10052. position: new Vector3(),
  10053. color: new Color(),
  10054. distance: 0,
  10055. decay: 0,
  10056. shadow: false,
  10057. shadowBias: 0,
  10058. shadowRadius: 1,
  10059. shadowMapSize: new Vector2()
  10060. };
  10061. break;
  10062. case 'HemisphereLight':
  10063. uniforms = {
  10064. direction: new Vector3(),
  10065. skyColor: new Color(),
  10066. groundColor: new Color()
  10067. };
  10068. break;
  10069. case 'RectAreaLight':
  10070. uniforms = {
  10071. color: new Color(),
  10072. position: new Vector3(),
  10073. halfWidth: new Vector3(),
  10074. halfHeight: new Vector3()
  10075. // TODO (abelnation): set RectAreaLight shadow uniforms
  10076. };
  10077. break;
  10078. }
  10079. lights[ light.id ] = uniforms;
  10080. return uniforms;
  10081. }
  10082. };
  10083. }
  10084. /**
  10085. * @author mrdoob / http://mrdoob.com/
  10086. */
  10087. function WebGLObjects( gl, geometries, infoRender ) {
  10088. var updateList = {};
  10089. function update( object ) {
  10090. var frame = infoRender.frame;
  10091. var geometry = object.geometry;
  10092. var buffergeometry = geometries.get( object, geometry );
  10093. // Update once per frame
  10094. if ( updateList[ buffergeometry.id ] !== frame ) {
  10095. if ( geometry.isGeometry ) {
  10096. buffergeometry.updateFromObject( object );
  10097. }
  10098. geometries.update( buffergeometry );
  10099. updateList[ buffergeometry.id ] = frame;
  10100. }
  10101. return buffergeometry;
  10102. }
  10103. function clear() {
  10104. updateList = {};
  10105. }
  10106. return {
  10107. update: update,
  10108. clear: clear
  10109. };
  10110. }
  10111. /**
  10112. * @author mrdoob / http://mrdoob.com/
  10113. */
  10114. function addLineNumbers( string ) {
  10115. var lines = string.split( '\n' );
  10116. for ( var i = 0; i < lines.length; i ++ ) {
  10117. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10118. }
  10119. return lines.join( '\n' );
  10120. }
  10121. function WebGLShader( gl, type, string ) {
  10122. var shader = gl.createShader( type );
  10123. gl.shaderSource( shader, string );
  10124. gl.compileShader( shader );
  10125. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10126. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10127. }
  10128. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10129. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10130. }
  10131. // --enable-privileged-webgl-extension
  10132. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10133. return shader;
  10134. }
  10135. /**
  10136. * @author mrdoob / http://mrdoob.com/
  10137. */
  10138. var programIdCount = 0;
  10139. function getEncodingComponents( encoding ) {
  10140. switch ( encoding ) {
  10141. case LinearEncoding:
  10142. return [ 'Linear','( value )' ];
  10143. case sRGBEncoding:
  10144. return [ 'sRGB','( value )' ];
  10145. case RGBEEncoding:
  10146. return [ 'RGBE','( value )' ];
  10147. case RGBM7Encoding:
  10148. return [ 'RGBM','( value, 7.0 )' ];
  10149. case RGBM16Encoding:
  10150. return [ 'RGBM','( value, 16.0 )' ];
  10151. case RGBDEncoding:
  10152. return [ 'RGBD','( value, 256.0 )' ];
  10153. case GammaEncoding:
  10154. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10155. default:
  10156. throw new Error( 'unsupported encoding: ' + encoding );
  10157. }
  10158. }
  10159. function getTexelDecodingFunction( functionName, encoding ) {
  10160. var components = getEncodingComponents( encoding );
  10161. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10162. }
  10163. function getTexelEncodingFunction( functionName, encoding ) {
  10164. var components = getEncodingComponents( encoding );
  10165. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10166. }
  10167. function getToneMappingFunction( functionName, toneMapping ) {
  10168. var toneMappingName;
  10169. switch ( toneMapping ) {
  10170. case LinearToneMapping:
  10171. toneMappingName = "Linear";
  10172. break;
  10173. case ReinhardToneMapping:
  10174. toneMappingName = "Reinhard";
  10175. break;
  10176. case Uncharted2ToneMapping:
  10177. toneMappingName = "Uncharted2";
  10178. break;
  10179. case CineonToneMapping:
  10180. toneMappingName = "OptimizedCineon";
  10181. break;
  10182. default:
  10183. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10184. }
  10185. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10186. }
  10187. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10188. extensions = extensions || {};
  10189. var chunks = [
  10190. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10191. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10192. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10193. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10194. ];
  10195. return chunks.filter( filterEmptyLine ).join( '\n' );
  10196. }
  10197. function generateDefines( defines ) {
  10198. var chunks = [];
  10199. for ( var name in defines ) {
  10200. var value = defines[ name ];
  10201. if ( value === false ) continue;
  10202. chunks.push( '#define ' + name + ' ' + value );
  10203. }
  10204. return chunks.join( '\n' );
  10205. }
  10206. function fetchAttributeLocations( gl, program, identifiers ) {
  10207. var attributes = {};
  10208. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10209. for ( var i = 0; i < n; i ++ ) {
  10210. var info = gl.getActiveAttrib( program, i );
  10211. var name = info.name;
  10212. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10213. attributes[ name ] = gl.getAttribLocation( program, name );
  10214. }
  10215. return attributes;
  10216. }
  10217. function filterEmptyLine( string ) {
  10218. return string !== '';
  10219. }
  10220. function replaceLightNums( string, parameters ) {
  10221. return string
  10222. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10223. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10224. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10225. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10226. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10227. }
  10228. function parseIncludes( string ) {
  10229. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10230. function replace( match, include ) {
  10231. var replace = ShaderChunk[ include ];
  10232. if ( replace === undefined ) {
  10233. throw new Error( 'Can not resolve #include <' + include + '>' );
  10234. }
  10235. return parseIncludes( replace );
  10236. }
  10237. return string.replace( pattern, replace );
  10238. }
  10239. function unrollLoops( string ) {
  10240. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10241. function replace( match, start, end, snippet ) {
  10242. var unroll = '';
  10243. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10244. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10245. }
  10246. return unroll;
  10247. }
  10248. return string.replace( pattern, replace );
  10249. }
  10250. function WebGLProgram( renderer, code, material, shader, parameters ) {
  10251. var gl = renderer.context;
  10252. var extensions = material.extensions;
  10253. var defines = material.defines;
  10254. var vertexShader = shader.vertexShader;
  10255. var fragmentShader = shader.fragmentShader;
  10256. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10257. if ( parameters.shadowMapType === PCFShadowMap ) {
  10258. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10259. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10260. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10261. }
  10262. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10263. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10264. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10265. if ( parameters.envMap ) {
  10266. switch ( material.envMap.mapping ) {
  10267. case CubeReflectionMapping:
  10268. case CubeRefractionMapping:
  10269. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10270. break;
  10271. case CubeUVReflectionMapping:
  10272. case CubeUVRefractionMapping:
  10273. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10274. break;
  10275. case EquirectangularReflectionMapping:
  10276. case EquirectangularRefractionMapping:
  10277. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10278. break;
  10279. case SphericalReflectionMapping:
  10280. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10281. break;
  10282. }
  10283. switch ( material.envMap.mapping ) {
  10284. case CubeRefractionMapping:
  10285. case EquirectangularRefractionMapping:
  10286. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10287. break;
  10288. }
  10289. switch ( material.combine ) {
  10290. case MultiplyOperation:
  10291. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10292. break;
  10293. case MixOperation:
  10294. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10295. break;
  10296. case AddOperation:
  10297. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10298. break;
  10299. }
  10300. }
  10301. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10302. // console.log( 'building new program ' );
  10303. //
  10304. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  10305. var customDefines = generateDefines( defines );
  10306. //
  10307. var program = gl.createProgram();
  10308. var prefixVertex, prefixFragment;
  10309. if ( material.isRawShaderMaterial ) {
  10310. prefixVertex = [
  10311. customDefines,
  10312. '\n'
  10313. ].filter( filterEmptyLine ).join( '\n' );
  10314. prefixFragment = [
  10315. customExtensions,
  10316. customDefines,
  10317. '\n'
  10318. ].filter( filterEmptyLine ).join( '\n' );
  10319. } else {
  10320. prefixVertex = [
  10321. 'precision ' + parameters.precision + ' float;',
  10322. 'precision ' + parameters.precision + ' int;',
  10323. '#define SHADER_NAME ' + shader.name,
  10324. customDefines,
  10325. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10326. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10327. '#define MAX_BONES ' + parameters.maxBones,
  10328. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10329. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10330. parameters.map ? '#define USE_MAP' : '',
  10331. parameters.envMap ? '#define USE_ENVMAP' : '',
  10332. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10333. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10334. parameters.aoMap ? '#define USE_AOMAP' : '',
  10335. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10336. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10337. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10338. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10339. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10340. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10341. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10342. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10343. parameters.vertexColors ? '#define USE_COLOR' : '',
  10344. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10345. parameters.skinning ? '#define USE_SKINNING' : '',
  10346. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10347. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10348. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10349. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10350. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10351. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10352. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10353. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10354. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10355. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10356. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10357. 'uniform mat4 modelMatrix;',
  10358. 'uniform mat4 modelViewMatrix;',
  10359. 'uniform mat4 projectionMatrix;',
  10360. 'uniform mat4 viewMatrix;',
  10361. 'uniform mat3 normalMatrix;',
  10362. 'uniform vec3 cameraPosition;',
  10363. 'attribute vec3 position;',
  10364. 'attribute vec3 normal;',
  10365. 'attribute vec2 uv;',
  10366. '#ifdef USE_COLOR',
  10367. ' attribute vec3 color;',
  10368. '#endif',
  10369. '#ifdef USE_MORPHTARGETS',
  10370. ' attribute vec3 morphTarget0;',
  10371. ' attribute vec3 morphTarget1;',
  10372. ' attribute vec3 morphTarget2;',
  10373. ' attribute vec3 morphTarget3;',
  10374. ' #ifdef USE_MORPHNORMALS',
  10375. ' attribute vec3 morphNormal0;',
  10376. ' attribute vec3 morphNormal1;',
  10377. ' attribute vec3 morphNormal2;',
  10378. ' attribute vec3 morphNormal3;',
  10379. ' #else',
  10380. ' attribute vec3 morphTarget4;',
  10381. ' attribute vec3 morphTarget5;',
  10382. ' attribute vec3 morphTarget6;',
  10383. ' attribute vec3 morphTarget7;',
  10384. ' #endif',
  10385. '#endif',
  10386. '#ifdef USE_SKINNING',
  10387. ' attribute vec4 skinIndex;',
  10388. ' attribute vec4 skinWeight;',
  10389. '#endif',
  10390. '\n'
  10391. ].filter( filterEmptyLine ).join( '\n' );
  10392. prefixFragment = [
  10393. customExtensions,
  10394. 'precision ' + parameters.precision + ' float;',
  10395. 'precision ' + parameters.precision + ' int;',
  10396. '#define SHADER_NAME ' + shader.name,
  10397. customDefines,
  10398. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10399. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10400. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10401. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10402. parameters.map ? '#define USE_MAP' : '',
  10403. parameters.envMap ? '#define USE_ENVMAP' : '',
  10404. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10405. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10406. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10407. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10408. parameters.aoMap ? '#define USE_AOMAP' : '',
  10409. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10410. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10411. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10412. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10413. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10414. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10415. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10416. parameters.vertexColors ? '#define USE_COLOR' : '',
  10417. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10418. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10419. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10420. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10421. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10422. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10423. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10424. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10425. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10426. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10427. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10428. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10429. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10430. 'uniform mat4 viewMatrix;',
  10431. 'uniform vec3 cameraPosition;',
  10432. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10433. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10434. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10435. parameters.dithering ? '#define DITHERING' : '',
  10436. ( 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
  10437. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10438. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10439. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10440. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10441. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10442. '\n'
  10443. ].filter( filterEmptyLine ).join( '\n' );
  10444. }
  10445. vertexShader = parseIncludes( vertexShader );
  10446. vertexShader = replaceLightNums( vertexShader, parameters );
  10447. fragmentShader = parseIncludes( fragmentShader );
  10448. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10449. if ( ! material.isShaderMaterial ) {
  10450. vertexShader = unrollLoops( vertexShader );
  10451. fragmentShader = unrollLoops( fragmentShader );
  10452. }
  10453. var vertexGlsl = prefixVertex + vertexShader;
  10454. var fragmentGlsl = prefixFragment + fragmentShader;
  10455. // console.log( '*VERTEX*', vertexGlsl );
  10456. // console.log( '*FRAGMENT*', fragmentGlsl );
  10457. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10458. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10459. gl.attachShader( program, glVertexShader );
  10460. gl.attachShader( program, glFragmentShader );
  10461. // Force a particular attribute to index 0.
  10462. if ( material.index0AttributeName !== undefined ) {
  10463. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10464. } else if ( parameters.morphTargets === true ) {
  10465. // programs with morphTargets displace position out of attribute 0
  10466. gl.bindAttribLocation( program, 0, 'position' );
  10467. }
  10468. gl.linkProgram( program );
  10469. var programLog = gl.getProgramInfoLog( program );
  10470. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10471. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10472. var runnable = true;
  10473. var haveDiagnostics = true;
  10474. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10475. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10476. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10477. runnable = false;
  10478. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10479. } else if ( programLog !== '' ) {
  10480. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10481. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10482. haveDiagnostics = false;
  10483. }
  10484. if ( haveDiagnostics ) {
  10485. this.diagnostics = {
  10486. runnable: runnable,
  10487. material: material,
  10488. programLog: programLog,
  10489. vertexShader: {
  10490. log: vertexLog,
  10491. prefix: prefixVertex
  10492. },
  10493. fragmentShader: {
  10494. log: fragmentLog,
  10495. prefix: prefixFragment
  10496. }
  10497. };
  10498. }
  10499. // clean up
  10500. gl.deleteShader( glVertexShader );
  10501. gl.deleteShader( glFragmentShader );
  10502. // set up caching for uniform locations
  10503. var cachedUniforms;
  10504. this.getUniforms = function() {
  10505. if ( cachedUniforms === undefined ) {
  10506. cachedUniforms =
  10507. new WebGLUniforms( gl, program, renderer );
  10508. }
  10509. return cachedUniforms;
  10510. };
  10511. // set up caching for attribute locations
  10512. var cachedAttributes;
  10513. this.getAttributes = function() {
  10514. if ( cachedAttributes === undefined ) {
  10515. cachedAttributes = fetchAttributeLocations( gl, program );
  10516. }
  10517. return cachedAttributes;
  10518. };
  10519. // free resource
  10520. this.destroy = function() {
  10521. gl.deleteProgram( program );
  10522. this.program = undefined;
  10523. };
  10524. // DEPRECATED
  10525. Object.defineProperties( this, {
  10526. uniforms: {
  10527. get: function() {
  10528. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10529. return this.getUniforms();
  10530. }
  10531. },
  10532. attributes: {
  10533. get: function() {
  10534. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10535. return this.getAttributes();
  10536. }
  10537. }
  10538. } );
  10539. //
  10540. this.id = programIdCount ++;
  10541. this.code = code;
  10542. this.usedTimes = 1;
  10543. this.program = program;
  10544. this.vertexShader = glVertexShader;
  10545. this.fragmentShader = glFragmentShader;
  10546. return this;
  10547. }
  10548. /**
  10549. * @author mrdoob / http://mrdoob.com/
  10550. */
  10551. function WebGLPrograms( renderer, capabilities ) {
  10552. var programs = [];
  10553. var shaderIDs = {
  10554. MeshDepthMaterial: 'depth',
  10555. MeshNormalMaterial: 'normal',
  10556. MeshBasicMaterial: 'basic',
  10557. MeshLambertMaterial: 'lambert',
  10558. MeshPhongMaterial: 'phong',
  10559. MeshToonMaterial: 'phong',
  10560. MeshStandardMaterial: 'physical',
  10561. MeshPhysicalMaterial: 'physical',
  10562. LineBasicMaterial: 'basic',
  10563. LineDashedMaterial: 'dashed',
  10564. PointsMaterial: 'points'
  10565. };
  10566. var parameterNames = [
  10567. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10568. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10569. "roughnessMap", "metalnessMap", "gradientMap",
  10570. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10571. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10572. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10573. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10574. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10575. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10576. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10577. ];
  10578. function allocateBones( object ) {
  10579. var skeleton = object.skeleton;
  10580. var bones = skeleton.bones;
  10581. if ( capabilities.floatVertexTextures ) {
  10582. return 1024;
  10583. } else {
  10584. // default for when object is not specified
  10585. // ( for example when prebuilding shader to be used with multiple objects )
  10586. //
  10587. // - leave some extra space for other uniforms
  10588. // - limit here is ANGLE's 254 max uniform vectors
  10589. // (up to 54 should be safe)
  10590. var nVertexUniforms = capabilities.maxVertexUniforms;
  10591. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10592. var maxBones = Math.min( nVertexMatrices, bones.length );
  10593. if ( maxBones < bones.length ) {
  10594. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10595. return 0;
  10596. }
  10597. return maxBones;
  10598. }
  10599. }
  10600. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10601. var encoding;
  10602. if ( ! map ) {
  10603. encoding = LinearEncoding;
  10604. } else if ( map.isTexture ) {
  10605. encoding = map.encoding;
  10606. } else if ( map.isWebGLRenderTarget ) {
  10607. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10608. encoding = map.texture.encoding;
  10609. }
  10610. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10611. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10612. encoding = GammaEncoding;
  10613. }
  10614. return encoding;
  10615. }
  10616. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10617. var shaderID = shaderIDs[ material.type ];
  10618. // heuristics to create shader parameters according to lights in the scene
  10619. // (not to blow over maxLights budget)
  10620. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10621. var precision = renderer.getPrecision();
  10622. if ( material.precision !== null ) {
  10623. precision = capabilities.getMaxPrecision( material.precision );
  10624. if ( precision !== material.precision ) {
  10625. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10626. }
  10627. }
  10628. var currentRenderTarget = renderer.getRenderTarget();
  10629. var parameters = {
  10630. shaderID: shaderID,
  10631. precision: precision,
  10632. supportsVertexTextures: capabilities.vertexTextures,
  10633. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10634. map: !! material.map,
  10635. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10636. envMap: !! material.envMap,
  10637. envMapMode: material.envMap && material.envMap.mapping,
  10638. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10639. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10640. lightMap: !! material.lightMap,
  10641. aoMap: !! material.aoMap,
  10642. emissiveMap: !! material.emissiveMap,
  10643. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10644. bumpMap: !! material.bumpMap,
  10645. normalMap: !! material.normalMap,
  10646. displacementMap: !! material.displacementMap,
  10647. roughnessMap: !! material.roughnessMap,
  10648. metalnessMap: !! material.metalnessMap,
  10649. specularMap: !! material.specularMap,
  10650. alphaMap: !! material.alphaMap,
  10651. gradientMap: !! material.gradientMap,
  10652. combine: material.combine,
  10653. vertexColors: material.vertexColors,
  10654. fog: !! fog,
  10655. useFog: material.fog,
  10656. fogExp: ( fog && fog.isFogExp2 ),
  10657. flatShading: material.shading === FlatShading,
  10658. sizeAttenuation: material.sizeAttenuation,
  10659. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10660. skinning: material.skinning && maxBones > 0,
  10661. maxBones: maxBones,
  10662. useVertexTexture: capabilities.floatVertexTextures,
  10663. morphTargets: material.morphTargets,
  10664. morphNormals: material.morphNormals,
  10665. maxMorphTargets: renderer.maxMorphTargets,
  10666. maxMorphNormals: renderer.maxMorphNormals,
  10667. numDirLights: lights.directional.length,
  10668. numPointLights: lights.point.length,
  10669. numSpotLights: lights.spot.length,
  10670. numRectAreaLights: lights.rectArea.length,
  10671. numHemiLights: lights.hemi.length,
  10672. numClippingPlanes: nClipPlanes,
  10673. numClipIntersection: nClipIntersection,
  10674. dithering: material.dithering,
  10675. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10676. shadowMapType: renderer.shadowMap.type,
  10677. toneMapping: renderer.toneMapping,
  10678. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10679. premultipliedAlpha: material.premultipliedAlpha,
  10680. alphaTest: material.alphaTest,
  10681. doubleSided: material.side === DoubleSide,
  10682. flipSided: material.side === BackSide,
  10683. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10684. };
  10685. return parameters;
  10686. };
  10687. this.getProgramCode = function ( material, parameters ) {
  10688. var array = [];
  10689. if ( parameters.shaderID ) {
  10690. array.push( parameters.shaderID );
  10691. } else {
  10692. array.push( material.fragmentShader );
  10693. array.push( material.vertexShader );
  10694. }
  10695. if ( material.defines !== undefined ) {
  10696. for ( var name in material.defines ) {
  10697. array.push( name );
  10698. array.push( material.defines[ name ] );
  10699. }
  10700. }
  10701. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10702. array.push( parameters[ parameterNames[ i ] ] );
  10703. }
  10704. array.push( material.onBeforeCompile.toString() );
  10705. array.push( renderer.gammaOutput );
  10706. return array.join();
  10707. };
  10708. this.acquireProgram = function ( material, shader, parameters, code ) {
  10709. var program;
  10710. // Check if code has been already compiled
  10711. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10712. var programInfo = programs[ p ];
  10713. if ( programInfo.code === code ) {
  10714. program = programInfo;
  10715. ++ program.usedTimes;
  10716. break;
  10717. }
  10718. }
  10719. if ( program === undefined ) {
  10720. program = new WebGLProgram( renderer, code, material, shader, parameters );
  10721. programs.push( program );
  10722. }
  10723. return program;
  10724. };
  10725. this.releaseProgram = function ( program ) {
  10726. if ( -- program.usedTimes === 0 ) {
  10727. // Remove from unordered set
  10728. var i = programs.indexOf( program );
  10729. programs[ i ] = programs[ programs.length - 1 ];
  10730. programs.pop();
  10731. // Free WebGL resources
  10732. program.destroy();
  10733. }
  10734. };
  10735. // Exposed for resource monitoring & error feedback via renderer.info:
  10736. this.programs = programs;
  10737. }
  10738. /**
  10739. * @author mrdoob / http://mrdoob.com/
  10740. */
  10741. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) {
  10742. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10743. //
  10744. function clampToMaxSize( image, maxSize ) {
  10745. if ( image.width > maxSize || image.height > maxSize ) {
  10746. // Warning: Scaling through the canvas will only work with images that use
  10747. // premultiplied alpha.
  10748. var scale = maxSize / Math.max( image.width, image.height );
  10749. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10750. canvas.width = Math.floor( image.width * scale );
  10751. canvas.height = Math.floor( image.height * scale );
  10752. var context = canvas.getContext( '2d' );
  10753. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10754. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10755. return canvas;
  10756. }
  10757. return image;
  10758. }
  10759. function isPowerOfTwo( image ) {
  10760. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10761. }
  10762. function makePowerOfTwo( image ) {
  10763. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10764. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10765. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10766. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10767. var context = canvas.getContext( '2d' );
  10768. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10769. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10770. return canvas;
  10771. }
  10772. return image;
  10773. }
  10774. function textureNeedsPowerOfTwo( texture ) {
  10775. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10776. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10777. }
  10778. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  10779. return texture.generateMipmaps && isPowerOfTwo &&
  10780. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  10781. }
  10782. // Fallback filters for non-power-of-2 textures
  10783. function filterFallback( f ) {
  10784. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10785. return _gl.NEAREST;
  10786. }
  10787. return _gl.LINEAR;
  10788. }
  10789. //
  10790. function onTextureDispose( event ) {
  10791. var texture = event.target;
  10792. texture.removeEventListener( 'dispose', onTextureDispose );
  10793. deallocateTexture( texture );
  10794. infoMemory.textures --;
  10795. }
  10796. function onRenderTargetDispose( event ) {
  10797. var renderTarget = event.target;
  10798. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10799. deallocateRenderTarget( renderTarget );
  10800. infoMemory.textures --;
  10801. }
  10802. //
  10803. function deallocateTexture( texture ) {
  10804. var textureProperties = properties.get( texture );
  10805. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10806. // cube texture
  10807. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10808. } else {
  10809. // 2D texture
  10810. if ( textureProperties.__webglInit === undefined ) return;
  10811. _gl.deleteTexture( textureProperties.__webglTexture );
  10812. }
  10813. // remove all webgl properties
  10814. properties.remove( texture );
  10815. }
  10816. function deallocateRenderTarget( renderTarget ) {
  10817. var renderTargetProperties = properties.get( renderTarget );
  10818. var textureProperties = properties.get( renderTarget.texture );
  10819. if ( ! renderTarget ) return;
  10820. if ( textureProperties.__webglTexture !== undefined ) {
  10821. _gl.deleteTexture( textureProperties.__webglTexture );
  10822. }
  10823. if ( renderTarget.depthTexture ) {
  10824. renderTarget.depthTexture.dispose();
  10825. }
  10826. if ( renderTarget.isWebGLRenderTargetCube ) {
  10827. for ( var i = 0; i < 6; i ++ ) {
  10828. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10829. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10830. }
  10831. } else {
  10832. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10833. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10834. }
  10835. properties.remove( renderTarget.texture );
  10836. properties.remove( renderTarget );
  10837. }
  10838. //
  10839. function setTexture2D( texture, slot ) {
  10840. var textureProperties = properties.get( texture );
  10841. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10842. var image = texture.image;
  10843. if ( image === undefined ) {
  10844. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10845. } else if ( image.complete === false ) {
  10846. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10847. } else {
  10848. uploadTexture( textureProperties, texture, slot );
  10849. return;
  10850. }
  10851. }
  10852. state.activeTexture( _gl.TEXTURE0 + slot );
  10853. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10854. }
  10855. function setTextureCube( texture, slot ) {
  10856. var textureProperties = properties.get( texture );
  10857. if ( texture.image.length === 6 ) {
  10858. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10859. if ( ! textureProperties.__image__webglTextureCube ) {
  10860. texture.addEventListener( 'dispose', onTextureDispose );
  10861. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10862. infoMemory.textures ++;
  10863. }
  10864. state.activeTexture( _gl.TEXTURE0 + slot );
  10865. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10866. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10867. var isCompressed = ( texture && texture.isCompressedTexture );
  10868. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  10869. var cubeImage = [];
  10870. for ( var i = 0; i < 6; i ++ ) {
  10871. if ( ! isCompressed && ! isDataTexture ) {
  10872. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10873. } else {
  10874. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10875. }
  10876. }
  10877. var image = cubeImage[ 0 ],
  10878. isPowerOfTwoImage = isPowerOfTwo( image ),
  10879. glFormat = paramThreeToGL( texture.format ),
  10880. glType = paramThreeToGL( texture.type );
  10881. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10882. for ( var i = 0; i < 6; i ++ ) {
  10883. if ( ! isCompressed ) {
  10884. if ( isDataTexture ) {
  10885. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10886. } else {
  10887. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10888. }
  10889. } else {
  10890. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10891. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10892. mipmap = mipmaps[ j ];
  10893. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10894. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10895. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10896. } else {
  10897. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10898. }
  10899. } else {
  10900. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10901. }
  10902. }
  10903. }
  10904. }
  10905. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  10906. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10907. }
  10908. textureProperties.__version = texture.version;
  10909. if ( texture.onUpdate ) texture.onUpdate( texture );
  10910. } else {
  10911. state.activeTexture( _gl.TEXTURE0 + slot );
  10912. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10913. }
  10914. }
  10915. }
  10916. function setTextureCubeDynamic( texture, slot ) {
  10917. state.activeTexture( _gl.TEXTURE0 + slot );
  10918. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10919. }
  10920. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10921. var extension;
  10922. if ( isPowerOfTwoImage ) {
  10923. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10924. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10925. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10926. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10927. } else {
  10928. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10929. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10930. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10931. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10932. }
  10933. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10934. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10935. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10936. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10937. }
  10938. }
  10939. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10940. if ( extension ) {
  10941. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10942. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10943. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10944. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10945. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10946. }
  10947. }
  10948. }
  10949. function uploadTexture( textureProperties, texture, slot ) {
  10950. if ( textureProperties.__webglInit === undefined ) {
  10951. textureProperties.__webglInit = true;
  10952. texture.addEventListener( 'dispose', onTextureDispose );
  10953. textureProperties.__webglTexture = _gl.createTexture();
  10954. infoMemory.textures ++;
  10955. }
  10956. state.activeTexture( _gl.TEXTURE0 + slot );
  10957. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10958. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10959. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10960. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10961. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10962. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10963. image = makePowerOfTwo( image );
  10964. }
  10965. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10966. glFormat = paramThreeToGL( texture.format ),
  10967. glType = paramThreeToGL( texture.type );
  10968. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10969. var mipmap, mipmaps = texture.mipmaps;
  10970. if ( texture.isDepthTexture ) {
  10971. // populate depth texture with dummy data
  10972. var internalFormat = _gl.DEPTH_COMPONENT;
  10973. if ( texture.type === FloatType ) {
  10974. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10975. internalFormat = _gl.DEPTH_COMPONENT32F;
  10976. } else if ( _isWebGL2 ) {
  10977. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10978. internalFormat = _gl.DEPTH_COMPONENT16;
  10979. }
  10980. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10981. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10982. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10983. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10984. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10985. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10986. texture.type = UnsignedShortType;
  10987. glType = paramThreeToGL( texture.type );
  10988. }
  10989. }
  10990. // Depth stencil textures need the DEPTH_STENCIL internal format
  10991. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10992. if ( texture.format === DepthStencilFormat ) {
  10993. internalFormat = _gl.DEPTH_STENCIL;
  10994. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10995. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10996. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10997. if ( texture.type !== UnsignedInt248Type ) {
  10998. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10999. texture.type = UnsignedInt248Type;
  11000. glType = paramThreeToGL( texture.type );
  11001. }
  11002. }
  11003. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  11004. } else if ( texture.isDataTexture ) {
  11005. // use manually created mipmaps if available
  11006. // if there are no manual mipmaps
  11007. // set 0 level mipmap and then use GL to generate other mipmap levels
  11008. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11009. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11010. mipmap = mipmaps[ i ];
  11011. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11012. }
  11013. texture.generateMipmaps = false;
  11014. } else {
  11015. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  11016. }
  11017. } else if ( texture.isCompressedTexture ) {
  11018. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11019. mipmap = mipmaps[ i ];
  11020. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11021. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11022. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11023. } else {
  11024. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  11025. }
  11026. } else {
  11027. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11028. }
  11029. }
  11030. } else {
  11031. // regular Texture (image, video, canvas)
  11032. // use manually created mipmaps if available
  11033. // if there are no manual mipmaps
  11034. // set 0 level mipmap and then use GL to generate other mipmap levels
  11035. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11036. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11037. mipmap = mipmaps[ i ];
  11038. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  11039. }
  11040. texture.generateMipmaps = false;
  11041. } else {
  11042. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  11043. }
  11044. }
  11045. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11046. textureProperties.__version = texture.version;
  11047. if ( texture.onUpdate ) texture.onUpdate( texture );
  11048. }
  11049. // Render targets
  11050. // Setup storage for target texture and bind it to correct framebuffer
  11051. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  11052. var glFormat = paramThreeToGL( renderTarget.texture.format );
  11053. var glType = paramThreeToGL( renderTarget.texture.type );
  11054. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  11055. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11056. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  11057. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11058. }
  11059. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  11060. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  11061. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  11062. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  11063. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  11064. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11065. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  11066. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  11067. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11068. } else {
  11069. // FIXME: We don't support !depth !stencil
  11070. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  11071. }
  11072. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  11073. }
  11074. // Setup resources for a Depth Texture for a FBO (needs an extension)
  11075. function setupDepthTexture( framebuffer, renderTarget ) {
  11076. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  11077. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  11078. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11079. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  11080. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  11081. }
  11082. // upload an empty depth texture with framebuffer size
  11083. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  11084. renderTarget.depthTexture.image.width !== renderTarget.width ||
  11085. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  11086. renderTarget.depthTexture.image.width = renderTarget.width;
  11087. renderTarget.depthTexture.image.height = renderTarget.height;
  11088. renderTarget.depthTexture.needsUpdate = true;
  11089. }
  11090. setTexture2D( renderTarget.depthTexture, 0 );
  11091. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  11092. if ( renderTarget.depthTexture.format === DepthFormat ) {
  11093. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11094. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  11095. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11096. } else {
  11097. throw new Error('Unknown depthTexture format')
  11098. }
  11099. }
  11100. // Setup GL resources for a non-texture depth buffer
  11101. function setupDepthRenderbuffer( renderTarget ) {
  11102. var renderTargetProperties = properties.get( renderTarget );
  11103. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11104. if ( renderTarget.depthTexture ) {
  11105. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  11106. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  11107. } else {
  11108. if ( isCube ) {
  11109. renderTargetProperties.__webglDepthbuffer = [];
  11110. for ( var i = 0; i < 6; i ++ ) {
  11111. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11112. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11113. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11114. }
  11115. } else {
  11116. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11117. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11118. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11119. }
  11120. }
  11121. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11122. }
  11123. // Set up GL resources for the render target
  11124. function setupRenderTarget( renderTarget ) {
  11125. var renderTargetProperties = properties.get( renderTarget );
  11126. var textureProperties = properties.get( renderTarget.texture );
  11127. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11128. textureProperties.__webglTexture = _gl.createTexture();
  11129. infoMemory.textures ++;
  11130. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11131. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11132. // Setup framebuffer
  11133. if ( isCube ) {
  11134. renderTargetProperties.__webglFramebuffer = [];
  11135. for ( var i = 0; i < 6; i ++ ) {
  11136. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11137. }
  11138. } else {
  11139. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11140. }
  11141. // Setup color buffer
  11142. if ( isCube ) {
  11143. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11144. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11145. for ( var i = 0; i < 6; i ++ ) {
  11146. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11147. }
  11148. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11149. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11150. } else {
  11151. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11152. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11153. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11154. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11155. state.bindTexture( _gl.TEXTURE_2D, null );
  11156. }
  11157. // Setup depth and stencil buffers
  11158. if ( renderTarget.depthBuffer ) {
  11159. setupDepthRenderbuffer( renderTarget );
  11160. }
  11161. }
  11162. function updateRenderTargetMipmap( renderTarget ) {
  11163. var texture = renderTarget.texture;
  11164. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11165. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  11166. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11167. var webglTexture = properties.get( texture ).__webglTexture;
  11168. state.bindTexture( target, webglTexture );
  11169. _gl.generateMipmap( target );
  11170. state.bindTexture( target, null );
  11171. }
  11172. }
  11173. this.setTexture2D = setTexture2D;
  11174. this.setTextureCube = setTextureCube;
  11175. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11176. this.setupRenderTarget = setupRenderTarget;
  11177. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11178. }
  11179. /**
  11180. * @author fordacious / fordacious.github.io
  11181. */
  11182. function WebGLProperties() {
  11183. var properties = {};
  11184. function get( object ) {
  11185. var uuid = object.uuid;
  11186. var map = properties[ uuid ];
  11187. if ( map === undefined ) {
  11188. map = {};
  11189. properties[ uuid ] = map;
  11190. }
  11191. return map;
  11192. }
  11193. function remove( object ) {
  11194. delete properties[ object.uuid ];
  11195. }
  11196. function clear() {
  11197. properties = {};
  11198. }
  11199. return {
  11200. get: get,
  11201. remove: remove,
  11202. clear: clear
  11203. };
  11204. }
  11205. /**
  11206. * @author mrdoob / http://mrdoob.com/
  11207. */
  11208. function WebGLState( gl, extensions, paramThreeToGL ) {
  11209. function ColorBuffer() {
  11210. var locked = false;
  11211. var color = new Vector4();
  11212. var currentColorMask = null;
  11213. var currentColorClear = new Vector4();
  11214. return {
  11215. setMask: function ( colorMask ) {
  11216. if ( currentColorMask !== colorMask && ! locked ) {
  11217. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11218. currentColorMask = colorMask;
  11219. }
  11220. },
  11221. setLocked: function ( lock ) {
  11222. locked = lock;
  11223. },
  11224. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11225. if ( premultipliedAlpha === true ) {
  11226. r *= a; g *= a; b *= a;
  11227. }
  11228. color.set( r, g, b, a );
  11229. if ( currentColorClear.equals( color ) === false ) {
  11230. gl.clearColor( r, g, b, a );
  11231. currentColorClear.copy( color );
  11232. }
  11233. },
  11234. reset: function () {
  11235. locked = false;
  11236. currentColorMask = null;
  11237. currentColorClear.set( 0, 0, 0, 1 );
  11238. }
  11239. };
  11240. }
  11241. function DepthBuffer() {
  11242. var locked = false;
  11243. var currentDepthMask = null;
  11244. var currentDepthFunc = null;
  11245. var currentDepthClear = null;
  11246. return {
  11247. setTest: function ( depthTest ) {
  11248. if ( depthTest ) {
  11249. enable( gl.DEPTH_TEST );
  11250. } else {
  11251. disable( gl.DEPTH_TEST );
  11252. }
  11253. },
  11254. setMask: function ( depthMask ) {
  11255. if ( currentDepthMask !== depthMask && ! locked ) {
  11256. gl.depthMask( depthMask );
  11257. currentDepthMask = depthMask;
  11258. }
  11259. },
  11260. setFunc: function ( depthFunc ) {
  11261. if ( currentDepthFunc !== depthFunc ) {
  11262. if ( depthFunc ) {
  11263. switch ( depthFunc ) {
  11264. case NeverDepth:
  11265. gl.depthFunc( gl.NEVER );
  11266. break;
  11267. case AlwaysDepth:
  11268. gl.depthFunc( gl.ALWAYS );
  11269. break;
  11270. case LessDepth:
  11271. gl.depthFunc( gl.LESS );
  11272. break;
  11273. case LessEqualDepth:
  11274. gl.depthFunc( gl.LEQUAL );
  11275. break;
  11276. case EqualDepth:
  11277. gl.depthFunc( gl.EQUAL );
  11278. break;
  11279. case GreaterEqualDepth:
  11280. gl.depthFunc( gl.GEQUAL );
  11281. break;
  11282. case GreaterDepth:
  11283. gl.depthFunc( gl.GREATER );
  11284. break;
  11285. case NotEqualDepth:
  11286. gl.depthFunc( gl.NOTEQUAL );
  11287. break;
  11288. default:
  11289. gl.depthFunc( gl.LEQUAL );
  11290. }
  11291. } else {
  11292. gl.depthFunc( gl.LEQUAL );
  11293. }
  11294. currentDepthFunc = depthFunc;
  11295. }
  11296. },
  11297. setLocked: function ( lock ) {
  11298. locked = lock;
  11299. },
  11300. setClear: function ( depth ) {
  11301. if ( currentDepthClear !== depth ) {
  11302. gl.clearDepth( depth );
  11303. currentDepthClear = depth;
  11304. }
  11305. },
  11306. reset: function () {
  11307. locked = false;
  11308. currentDepthMask = null;
  11309. currentDepthFunc = null;
  11310. currentDepthClear = null;
  11311. }
  11312. };
  11313. }
  11314. function StencilBuffer() {
  11315. var locked = false;
  11316. var currentStencilMask = null;
  11317. var currentStencilFunc = null;
  11318. var currentStencilRef = null;
  11319. var currentStencilFuncMask = null;
  11320. var currentStencilFail = null;
  11321. var currentStencilZFail = null;
  11322. var currentStencilZPass = null;
  11323. var currentStencilClear = null;
  11324. return {
  11325. setTest: function ( stencilTest ) {
  11326. if ( stencilTest ) {
  11327. enable( gl.STENCIL_TEST );
  11328. } else {
  11329. disable( gl.STENCIL_TEST );
  11330. }
  11331. },
  11332. setMask: function ( stencilMask ) {
  11333. if ( currentStencilMask !== stencilMask && ! locked ) {
  11334. gl.stencilMask( stencilMask );
  11335. currentStencilMask = stencilMask;
  11336. }
  11337. },
  11338. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11339. if ( currentStencilFunc !== stencilFunc ||
  11340. currentStencilRef !== stencilRef ||
  11341. currentStencilFuncMask !== stencilMask ) {
  11342. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11343. currentStencilFunc = stencilFunc;
  11344. currentStencilRef = stencilRef;
  11345. currentStencilFuncMask = stencilMask;
  11346. }
  11347. },
  11348. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11349. if ( currentStencilFail !== stencilFail ||
  11350. currentStencilZFail !== stencilZFail ||
  11351. currentStencilZPass !== stencilZPass ) {
  11352. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11353. currentStencilFail = stencilFail;
  11354. currentStencilZFail = stencilZFail;
  11355. currentStencilZPass = stencilZPass;
  11356. }
  11357. },
  11358. setLocked: function ( lock ) {
  11359. locked = lock;
  11360. },
  11361. setClear: function ( stencil ) {
  11362. if ( currentStencilClear !== stencil ) {
  11363. gl.clearStencil( stencil );
  11364. currentStencilClear = stencil;
  11365. }
  11366. },
  11367. reset: function () {
  11368. locked = false;
  11369. currentStencilMask = null;
  11370. currentStencilFunc = null;
  11371. currentStencilRef = null;
  11372. currentStencilFuncMask = null;
  11373. currentStencilFail = null;
  11374. currentStencilZFail = null;
  11375. currentStencilZPass = null;
  11376. currentStencilClear = null;
  11377. }
  11378. };
  11379. }
  11380. //
  11381. var colorBuffer = new ColorBuffer();
  11382. var depthBuffer = new DepthBuffer();
  11383. var stencilBuffer = new StencilBuffer();
  11384. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11385. var newAttributes = new Uint8Array( maxVertexAttributes );
  11386. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11387. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11388. var capabilities = {};
  11389. var compressedTextureFormats = null;
  11390. var currentBlending = null;
  11391. var currentBlendEquation = null;
  11392. var currentBlendSrc = null;
  11393. var currentBlendDst = null;
  11394. var currentBlendEquationAlpha = null;
  11395. var currentBlendSrcAlpha = null;
  11396. var currentBlendDstAlpha = null;
  11397. var currentPremultipledAlpha = false;
  11398. var currentFlipSided = null;
  11399. var currentCullFace = null;
  11400. var currentLineWidth = null;
  11401. var currentPolygonOffsetFactor = null;
  11402. var currentPolygonOffsetUnits = null;
  11403. var currentScissorTest = null;
  11404. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11405. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11406. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11407. var currentTextureSlot = null;
  11408. var currentBoundTextures = {};
  11409. var currentScissor = new Vector4();
  11410. var currentViewport = new Vector4();
  11411. function createTexture( type, target, count ) {
  11412. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11413. var texture = gl.createTexture();
  11414. gl.bindTexture( type, texture );
  11415. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11416. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11417. for ( var i = 0; i < count; i ++ ) {
  11418. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11419. }
  11420. return texture;
  11421. }
  11422. var emptyTextures = {};
  11423. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11424. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11425. //
  11426. function init() {
  11427. colorBuffer.setClear( 0, 0, 0, 1 );
  11428. depthBuffer.setClear( 1 );
  11429. stencilBuffer.setClear( 0 );
  11430. enable( gl.DEPTH_TEST );
  11431. depthBuffer.setFunc( LessEqualDepth );
  11432. setFlipSided( false );
  11433. setCullFace( CullFaceBack );
  11434. enable( gl.CULL_FACE );
  11435. enable( gl.BLEND );
  11436. setBlending( NormalBlending );
  11437. }
  11438. function initAttributes() {
  11439. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11440. newAttributes[ i ] = 0;
  11441. }
  11442. }
  11443. function enableAttribute( attribute ) {
  11444. newAttributes[ attribute ] = 1;
  11445. if ( enabledAttributes[ attribute ] === 0 ) {
  11446. gl.enableVertexAttribArray( attribute );
  11447. enabledAttributes[ attribute ] = 1;
  11448. }
  11449. if ( attributeDivisors[ attribute ] !== 0 ) {
  11450. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11451. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11452. attributeDivisors[ attribute ] = 0;
  11453. }
  11454. }
  11455. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11456. newAttributes[ attribute ] = 1;
  11457. if ( enabledAttributes[ attribute ] === 0 ) {
  11458. gl.enableVertexAttribArray( attribute );
  11459. enabledAttributes[ attribute ] = 1;
  11460. }
  11461. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11462. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11463. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11464. attributeDivisors[ attribute ] = meshPerAttribute;
  11465. }
  11466. }
  11467. function disableUnusedAttributes() {
  11468. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11469. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11470. gl.disableVertexAttribArray( i );
  11471. enabledAttributes[ i ] = 0;
  11472. }
  11473. }
  11474. }
  11475. function enable( id ) {
  11476. if ( capabilities[ id ] !== true ) {
  11477. gl.enable( id );
  11478. capabilities[ id ] = true;
  11479. }
  11480. }
  11481. function disable( id ) {
  11482. if ( capabilities[ id ] !== false ) {
  11483. gl.disable( id );
  11484. capabilities[ id ] = false;
  11485. }
  11486. }
  11487. function getCompressedTextureFormats() {
  11488. if ( compressedTextureFormats === null ) {
  11489. compressedTextureFormats = [];
  11490. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11491. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11492. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11493. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11494. for ( var i = 0; i < formats.length; i ++ ) {
  11495. compressedTextureFormats.push( formats[ i ] );
  11496. }
  11497. }
  11498. }
  11499. return compressedTextureFormats;
  11500. }
  11501. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11502. if ( blending !== NoBlending ) {
  11503. enable( gl.BLEND );
  11504. } else {
  11505. disable( gl.BLEND );
  11506. }
  11507. if ( ( blending !== CustomBlending ) && ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) ) {
  11508. if ( blending === AdditiveBlending ) {
  11509. if ( premultipliedAlpha ) {
  11510. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11511. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11512. } else {
  11513. gl.blendEquation( gl.FUNC_ADD );
  11514. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11515. }
  11516. } else if ( blending === SubtractiveBlending ) {
  11517. if ( premultipliedAlpha ) {
  11518. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11519. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11520. } else {
  11521. gl.blendEquation( gl.FUNC_ADD );
  11522. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11523. }
  11524. } else if ( blending === MultiplyBlending ) {
  11525. if ( premultipliedAlpha ) {
  11526. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11527. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11528. } else {
  11529. gl.blendEquation( gl.FUNC_ADD );
  11530. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11531. }
  11532. } else {
  11533. if ( premultipliedAlpha ) {
  11534. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11535. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11536. } else {
  11537. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11538. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11539. }
  11540. }
  11541. currentBlending = blending;
  11542. currentPremultipledAlpha = premultipliedAlpha;
  11543. }
  11544. if ( blending === CustomBlending ) {
  11545. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11546. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11547. blendDstAlpha = blendDstAlpha || blendDst;
  11548. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11549. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11550. currentBlendEquation = blendEquation;
  11551. currentBlendEquationAlpha = blendEquationAlpha;
  11552. }
  11553. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11554. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11555. currentBlendSrc = blendSrc;
  11556. currentBlendDst = blendDst;
  11557. currentBlendSrcAlpha = blendSrcAlpha;
  11558. currentBlendDstAlpha = blendDstAlpha;
  11559. }
  11560. } else {
  11561. currentBlendEquation = null;
  11562. currentBlendSrc = null;
  11563. currentBlendDst = null;
  11564. currentBlendEquationAlpha = null;
  11565. currentBlendSrcAlpha = null;
  11566. currentBlendDstAlpha = null;
  11567. }
  11568. }
  11569. function setMaterial( material ) {
  11570. material.side === DoubleSide
  11571. ? disable( gl.CULL_FACE )
  11572. : enable( gl.CULL_FACE );
  11573. setFlipSided( material.side === BackSide );
  11574. material.transparent === true
  11575. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11576. : setBlending( NoBlending );
  11577. depthBuffer.setFunc( material.depthFunc );
  11578. depthBuffer.setTest( material.depthTest );
  11579. depthBuffer.setMask( material.depthWrite );
  11580. colorBuffer.setMask( material.colorWrite );
  11581. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11582. }
  11583. //
  11584. function setFlipSided( flipSided ) {
  11585. if ( currentFlipSided !== flipSided ) {
  11586. if ( flipSided ) {
  11587. gl.frontFace( gl.CW );
  11588. } else {
  11589. gl.frontFace( gl.CCW );
  11590. }
  11591. currentFlipSided = flipSided;
  11592. }
  11593. }
  11594. function setCullFace( cullFace ) {
  11595. if ( cullFace !== CullFaceNone ) {
  11596. enable( gl.CULL_FACE );
  11597. if ( cullFace !== currentCullFace ) {
  11598. if ( cullFace === CullFaceBack ) {
  11599. gl.cullFace( gl.BACK );
  11600. } else if ( cullFace === CullFaceFront ) {
  11601. gl.cullFace( gl.FRONT );
  11602. } else {
  11603. gl.cullFace( gl.FRONT_AND_BACK );
  11604. }
  11605. }
  11606. } else {
  11607. disable( gl.CULL_FACE );
  11608. }
  11609. currentCullFace = cullFace;
  11610. }
  11611. function setLineWidth( width ) {
  11612. if ( width !== currentLineWidth ) {
  11613. if ( lineWidthAvailable ) gl.lineWidth( width );
  11614. currentLineWidth = width;
  11615. }
  11616. }
  11617. function setPolygonOffset( polygonOffset, factor, units ) {
  11618. if ( polygonOffset ) {
  11619. enable( gl.POLYGON_OFFSET_FILL );
  11620. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11621. gl.polygonOffset( factor, units );
  11622. currentPolygonOffsetFactor = factor;
  11623. currentPolygonOffsetUnits = units;
  11624. }
  11625. } else {
  11626. disable( gl.POLYGON_OFFSET_FILL );
  11627. }
  11628. }
  11629. function getScissorTest() {
  11630. return currentScissorTest;
  11631. }
  11632. function setScissorTest( scissorTest ) {
  11633. currentScissorTest = scissorTest;
  11634. if ( scissorTest ) {
  11635. enable( gl.SCISSOR_TEST );
  11636. } else {
  11637. disable( gl.SCISSOR_TEST );
  11638. }
  11639. }
  11640. // texture
  11641. function activeTexture( webglSlot ) {
  11642. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11643. if ( currentTextureSlot !== webglSlot ) {
  11644. gl.activeTexture( webglSlot );
  11645. currentTextureSlot = webglSlot;
  11646. }
  11647. }
  11648. function bindTexture( webglType, webglTexture ) {
  11649. if ( currentTextureSlot === null ) {
  11650. activeTexture();
  11651. }
  11652. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11653. if ( boundTexture === undefined ) {
  11654. boundTexture = { type: undefined, texture: undefined };
  11655. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11656. }
  11657. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11658. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11659. boundTexture.type = webglType;
  11660. boundTexture.texture = webglTexture;
  11661. }
  11662. }
  11663. function compressedTexImage2D() {
  11664. try {
  11665. gl.compressedTexImage2D.apply( gl, arguments );
  11666. } catch ( error ) {
  11667. console.error( 'THREE.WebGLState:', error );
  11668. }
  11669. }
  11670. function texImage2D() {
  11671. try {
  11672. gl.texImage2D.apply( gl, arguments );
  11673. } catch ( error ) {
  11674. console.error( 'THREE.WebGLState:', error );
  11675. }
  11676. }
  11677. //
  11678. function scissor( scissor ) {
  11679. if ( currentScissor.equals( scissor ) === false ) {
  11680. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11681. currentScissor.copy( scissor );
  11682. }
  11683. }
  11684. function viewport( viewport ) {
  11685. if ( currentViewport.equals( viewport ) === false ) {
  11686. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11687. currentViewport.copy( viewport );
  11688. }
  11689. }
  11690. //
  11691. function reset() {
  11692. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11693. if ( enabledAttributes[ i ] === 1 ) {
  11694. gl.disableVertexAttribArray( i );
  11695. enabledAttributes[ i ] = 0;
  11696. }
  11697. }
  11698. capabilities = {};
  11699. compressedTextureFormats = null;
  11700. currentTextureSlot = null;
  11701. currentBoundTextures = {};
  11702. currentBlending = null;
  11703. currentFlipSided = null;
  11704. currentCullFace = null;
  11705. colorBuffer.reset();
  11706. depthBuffer.reset();
  11707. stencilBuffer.reset();
  11708. }
  11709. return {
  11710. buffers: {
  11711. color: colorBuffer,
  11712. depth: depthBuffer,
  11713. stencil: stencilBuffer
  11714. },
  11715. init: init,
  11716. initAttributes: initAttributes,
  11717. enableAttribute: enableAttribute,
  11718. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11719. disableUnusedAttributes: disableUnusedAttributes,
  11720. enable: enable,
  11721. disable: disable,
  11722. getCompressedTextureFormats: getCompressedTextureFormats,
  11723. setBlending: setBlending,
  11724. setMaterial: setMaterial,
  11725. setFlipSided: setFlipSided,
  11726. setCullFace: setCullFace,
  11727. setLineWidth: setLineWidth,
  11728. setPolygonOffset: setPolygonOffset,
  11729. getScissorTest: getScissorTest,
  11730. setScissorTest: setScissorTest,
  11731. activeTexture: activeTexture,
  11732. bindTexture: bindTexture,
  11733. compressedTexImage2D: compressedTexImage2D,
  11734. texImage2D: texImage2D,
  11735. scissor: scissor,
  11736. viewport: viewport,
  11737. reset: reset
  11738. };
  11739. }
  11740. /**
  11741. * @author mrdoob / http://mrdoob.com/
  11742. */
  11743. function WebGLCapabilities( gl, extensions, parameters ) {
  11744. var maxAnisotropy;
  11745. function getMaxAnisotropy() {
  11746. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11747. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11748. if ( extension !== null ) {
  11749. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11750. } else {
  11751. maxAnisotropy = 0;
  11752. }
  11753. return maxAnisotropy;
  11754. }
  11755. function getMaxPrecision( precision ) {
  11756. if ( precision === 'highp' ) {
  11757. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11758. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11759. return 'highp';
  11760. }
  11761. precision = 'mediump';
  11762. }
  11763. if ( precision === 'mediump' ) {
  11764. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11765. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11766. return 'mediump';
  11767. }
  11768. }
  11769. return 'lowp';
  11770. }
  11771. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11772. var maxPrecision = getMaxPrecision( precision );
  11773. if ( maxPrecision !== precision ) {
  11774. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11775. precision = maxPrecision;
  11776. }
  11777. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11778. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11779. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11780. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11781. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11782. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11783. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11784. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11785. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11786. var vertexTextures = maxVertexTextures > 0;
  11787. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11788. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11789. return {
  11790. getMaxAnisotropy: getMaxAnisotropy,
  11791. getMaxPrecision: getMaxPrecision,
  11792. precision: precision,
  11793. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11794. maxTextures: maxTextures,
  11795. maxVertexTextures: maxVertexTextures,
  11796. maxTextureSize: maxTextureSize,
  11797. maxCubemapSize: maxCubemapSize,
  11798. maxAttributes: maxAttributes,
  11799. maxVertexUniforms: maxVertexUniforms,
  11800. maxVaryings: maxVaryings,
  11801. maxFragmentUniforms: maxFragmentUniforms,
  11802. vertexTextures: vertexTextures,
  11803. floatFragmentTextures: floatFragmentTextures,
  11804. floatVertexTextures: floatVertexTextures
  11805. };
  11806. }
  11807. /**
  11808. * @author mrdoob / http://mrdoob.com/
  11809. */
  11810. function ArrayCamera( array ) {
  11811. PerspectiveCamera.call( this );
  11812. this.cameras = array || [];
  11813. }
  11814. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  11815. constructor: ArrayCamera,
  11816. isArrayCamera: true
  11817. } );
  11818. /**
  11819. * @author mrdoob / http://mrdoob.com/
  11820. */
  11821. function WebVRManager( renderer ) {
  11822. var scope = this;
  11823. var device = null;
  11824. var frameData = null;
  11825. if ( 'VRFrameData' in window ) {
  11826. frameData = new window.VRFrameData();
  11827. }
  11828. var matrixWorldInverse = new Matrix4();
  11829. var standingMatrix = new Matrix4();
  11830. var standingMatrixInverse = new Matrix4();
  11831. var cameraL = new PerspectiveCamera();
  11832. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  11833. cameraL.layers.enable( 1 );
  11834. var cameraR = new PerspectiveCamera();
  11835. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  11836. cameraR.layers.enable( 2 );
  11837. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  11838. cameraVR.layers.enable( 1 );
  11839. cameraVR.layers.enable( 2 );
  11840. //
  11841. var currentSize, currentPixelRatio;
  11842. function onVRDisplayPresentChange() {
  11843. if ( device.isPresenting ) {
  11844. var eyeParameters = device.getEyeParameters( 'left' );
  11845. var renderWidth = eyeParameters.renderWidth;
  11846. var renderHeight = eyeParameters.renderHeight;
  11847. currentPixelRatio = renderer.getPixelRatio();
  11848. currentSize = renderer.getSize();
  11849. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  11850. } else if ( scope.enabled ) {
  11851. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  11852. }
  11853. }
  11854. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  11855. //
  11856. this.enabled = false;
  11857. this.standing = false;
  11858. this.getDevice = function () {
  11859. return device;
  11860. };
  11861. this.setDevice = function ( value ) {
  11862. if ( value !== undefined ) device = value;
  11863. };
  11864. this.getCamera = function ( camera ) {
  11865. if ( device === null ) return camera;
  11866. device.depthNear = camera.near;
  11867. device.depthFar = camera.far;
  11868. device.getFrameData( frameData );
  11869. //
  11870. var pose = frameData.pose;
  11871. if ( pose.position !== null ) {
  11872. camera.position.fromArray( pose.position );
  11873. } else {
  11874. camera.position.set( 0, 0, 0 );
  11875. }
  11876. if ( pose.orientation !== null ) {
  11877. camera.quaternion.fromArray( pose.orientation );
  11878. }
  11879. camera.updateMatrixWorld();
  11880. var stageParameters = device.stageParameters;
  11881. if ( this.standing && stageParameters ) {
  11882. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  11883. standingMatrixInverse.getInverse( standingMatrix );
  11884. camera.matrixWorld.multiply( standingMatrix );
  11885. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  11886. }
  11887. if ( device.isPresenting === false ) return camera;
  11888. //
  11889. cameraVR.matrixWorld.copy( camera.matrixWorld );
  11890. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  11891. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  11892. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  11893. if ( this.standing && stageParameters ) {
  11894. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  11895. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  11896. }
  11897. var parent = camera.parent;
  11898. if ( parent !== null ) {
  11899. matrixWorldInverse.getInverse( parent.matrixWorld );
  11900. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  11901. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  11902. }
  11903. // envMap and Mirror needs camera.matrixWorld
  11904. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  11905. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  11906. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  11907. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  11908. // HACK @mrdoob
  11909. // https://github.com/w3c/webvr/issues/203
  11910. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  11911. //
  11912. var layers = device.getLayers();
  11913. if ( layers.length ) {
  11914. var layer = layers[ 0 ];
  11915. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  11916. cameraL.bounds.fromArray( layer.leftBounds );
  11917. }
  11918. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  11919. cameraR.bounds.fromArray( layer.rightBounds );
  11920. }
  11921. }
  11922. return cameraVR;
  11923. };
  11924. this.getStandingMatrix = function () {
  11925. return standingMatrix;
  11926. };
  11927. this.submitFrame = function () {
  11928. if ( device && device.isPresenting ) device.submitFrame();
  11929. };
  11930. }
  11931. /**
  11932. * @author mrdoob / http://mrdoob.com/
  11933. */
  11934. function WebGLExtensions( gl ) {
  11935. var extensions = {};
  11936. return {
  11937. get: function ( name ) {
  11938. if ( extensions[ name ] !== undefined ) {
  11939. return extensions[ name ];
  11940. }
  11941. var extension;
  11942. switch ( name ) {
  11943. case 'WEBGL_depth_texture':
  11944. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11945. break;
  11946. case 'EXT_texture_filter_anisotropic':
  11947. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11948. break;
  11949. case 'WEBGL_compressed_texture_s3tc':
  11950. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11951. break;
  11952. case 'WEBGL_compressed_texture_pvrtc':
  11953. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11954. break;
  11955. case 'WEBGL_compressed_texture_etc1':
  11956. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11957. break;
  11958. default:
  11959. extension = gl.getExtension( name );
  11960. }
  11961. if ( extension === null ) {
  11962. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11963. }
  11964. extensions[ name ] = extension;
  11965. return extension;
  11966. }
  11967. };
  11968. }
  11969. /**
  11970. * @author tschw
  11971. */
  11972. function WebGLClipping() {
  11973. var scope = this,
  11974. globalState = null,
  11975. numGlobalPlanes = 0,
  11976. localClippingEnabled = false,
  11977. renderingShadows = false,
  11978. plane = new Plane(),
  11979. viewNormalMatrix = new Matrix3(),
  11980. uniform = { value: null, needsUpdate: false };
  11981. this.uniform = uniform;
  11982. this.numPlanes = 0;
  11983. this.numIntersection = 0;
  11984. this.init = function( planes, enableLocalClipping, camera ) {
  11985. var enabled =
  11986. planes.length !== 0 ||
  11987. enableLocalClipping ||
  11988. // enable state of previous frame - the clipping code has to
  11989. // run another frame in order to reset the state:
  11990. numGlobalPlanes !== 0 ||
  11991. localClippingEnabled;
  11992. localClippingEnabled = enableLocalClipping;
  11993. globalState = projectPlanes( planes, camera, 0 );
  11994. numGlobalPlanes = planes.length;
  11995. return enabled;
  11996. };
  11997. this.beginShadows = function() {
  11998. renderingShadows = true;
  11999. projectPlanes( null );
  12000. };
  12001. this.endShadows = function() {
  12002. renderingShadows = false;
  12003. resetGlobalState();
  12004. };
  12005. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12006. if ( ! localClippingEnabled ||
  12007. planes === null || planes.length === 0 ||
  12008. renderingShadows && ! clipShadows ) {
  12009. // there's no local clipping
  12010. if ( renderingShadows ) {
  12011. // there's no global clipping
  12012. projectPlanes( null );
  12013. } else {
  12014. resetGlobalState();
  12015. }
  12016. } else {
  12017. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12018. lGlobal = nGlobal * 4,
  12019. dstArray = cache.clippingState || null;
  12020. uniform.value = dstArray; // ensure unique state
  12021. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12022. for ( var i = 0; i !== lGlobal; ++ i ) {
  12023. dstArray[ i ] = globalState[ i ];
  12024. }
  12025. cache.clippingState = dstArray;
  12026. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12027. this.numPlanes += nGlobal;
  12028. }
  12029. };
  12030. function resetGlobalState() {
  12031. if ( uniform.value !== globalState ) {
  12032. uniform.value = globalState;
  12033. uniform.needsUpdate = numGlobalPlanes > 0;
  12034. }
  12035. scope.numPlanes = numGlobalPlanes;
  12036. scope.numIntersection = 0;
  12037. }
  12038. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12039. var nPlanes = planes !== null ? planes.length : 0,
  12040. dstArray = null;
  12041. if ( nPlanes !== 0 ) {
  12042. dstArray = uniform.value;
  12043. if ( skipTransform !== true || dstArray === null ) {
  12044. var flatSize = dstOffset + nPlanes * 4,
  12045. viewMatrix = camera.matrixWorldInverse;
  12046. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12047. if ( dstArray === null || dstArray.length < flatSize ) {
  12048. dstArray = new Float32Array( flatSize );
  12049. }
  12050. for ( var i = 0, i4 = dstOffset;
  12051. i !== nPlanes; ++ i, i4 += 4 ) {
  12052. plane.copy( planes[ i ] ).
  12053. applyMatrix4( viewMatrix, viewNormalMatrix );
  12054. plane.normal.toArray( dstArray, i4 );
  12055. dstArray[ i4 + 3 ] = plane.constant;
  12056. }
  12057. }
  12058. uniform.value = dstArray;
  12059. uniform.needsUpdate = true;
  12060. }
  12061. scope.numPlanes = nPlanes;
  12062. return dstArray;
  12063. }
  12064. }
  12065. // import { Sphere } from '../math/Sphere';
  12066. /**
  12067. * @author supereggbert / http://www.paulbrunt.co.uk/
  12068. * @author mrdoob / http://mrdoob.com/
  12069. * @author alteredq / http://alteredqualia.com/
  12070. * @author szimek / https://github.com/szimek/
  12071. * @author tschw
  12072. */
  12073. function WebGLRenderer( parameters ) {
  12074. console.log( 'THREE.WebGLRenderer', REVISION );
  12075. parameters = parameters || {};
  12076. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  12077. _context = parameters.context !== undefined ? parameters.context : null,
  12078. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12079. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12080. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12081. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12082. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12083. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  12084. var lights = [];
  12085. var currentRenderList = null;
  12086. var morphInfluences = new Float32Array( 8 );
  12087. var sprites = [];
  12088. var lensFlares = [];
  12089. // public properties
  12090. this.domElement = _canvas;
  12091. this.context = null;
  12092. // clearing
  12093. this.autoClear = true;
  12094. this.autoClearColor = true;
  12095. this.autoClearDepth = true;
  12096. this.autoClearStencil = true;
  12097. // scene graph
  12098. this.sortObjects = true;
  12099. // user-defined clipping
  12100. this.clippingPlanes = [];
  12101. this.localClippingEnabled = false;
  12102. // physically based shading
  12103. this.gammaFactor = 2.0; // for backwards compatibility
  12104. this.gammaInput = false;
  12105. this.gammaOutput = false;
  12106. // physical lights
  12107. this.physicallyCorrectLights = false;
  12108. // tone mapping
  12109. this.toneMapping = LinearToneMapping;
  12110. this.toneMappingExposure = 1.0;
  12111. this.toneMappingWhitePoint = 1.0;
  12112. // morphs
  12113. this.maxMorphTargets = 8;
  12114. this.maxMorphNormals = 4;
  12115. // internal properties
  12116. var _this = this,
  12117. // internal state cache
  12118. _currentProgram = null,
  12119. _currentRenderTarget = null,
  12120. _currentFramebuffer = null,
  12121. _currentMaterialId = - 1,
  12122. _currentGeometryProgram = '',
  12123. _currentCamera = null,
  12124. _currentArrayCamera = null,
  12125. _currentScissor = new Vector4(),
  12126. _currentScissorTest = null,
  12127. _currentViewport = new Vector4(),
  12128. //
  12129. _usedTextureUnits = 0,
  12130. //
  12131. _width = _canvas.width,
  12132. _height = _canvas.height,
  12133. _pixelRatio = 1,
  12134. _scissor = new Vector4( 0, 0, _width, _height ),
  12135. _scissorTest = false,
  12136. _viewport = new Vector4( 0, 0, _width, _height ),
  12137. // frustum
  12138. _frustum = new Frustum(),
  12139. // clipping
  12140. _clipping = new WebGLClipping(),
  12141. _clippingEnabled = false,
  12142. _localClippingEnabled = false,
  12143. // camera matrices cache
  12144. _projScreenMatrix = new Matrix4(),
  12145. _vector3 = new Vector3(),
  12146. _matrix4 = new Matrix4(),
  12147. _matrix42 = new Matrix4(),
  12148. // light arrays cache
  12149. _lights = {
  12150. hash: '',
  12151. ambient: [ 0, 0, 0 ],
  12152. directional: [],
  12153. directionalShadowMap: [],
  12154. directionalShadowMatrix: [],
  12155. spot: [],
  12156. spotShadowMap: [],
  12157. spotShadowMatrix: [],
  12158. rectArea: [],
  12159. point: [],
  12160. pointShadowMap: [],
  12161. pointShadowMatrix: [],
  12162. hemi: [],
  12163. shadows: []
  12164. },
  12165. // info
  12166. _infoMemory = {
  12167. geometries: 0,
  12168. textures: 0
  12169. },
  12170. _infoRender = {
  12171. frame: 0,
  12172. calls: 0,
  12173. vertices: 0,
  12174. faces: 0,
  12175. points: 0
  12176. };
  12177. this.info = {
  12178. render: _infoRender,
  12179. memory: _infoMemory,
  12180. programs: null
  12181. };
  12182. // initialize
  12183. var _gl;
  12184. try {
  12185. var contextAttributes = {
  12186. alpha: _alpha,
  12187. depth: _depth,
  12188. stencil: _stencil,
  12189. antialias: _antialias,
  12190. premultipliedAlpha: _premultipliedAlpha,
  12191. preserveDrawingBuffer: _preserveDrawingBuffer
  12192. };
  12193. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  12194. if ( _gl === null ) {
  12195. if ( _canvas.getContext( 'webgl' ) !== null ) {
  12196. throw 'Error creating WebGL context with your selected attributes.';
  12197. } else {
  12198. throw 'Error creating WebGL context.';
  12199. }
  12200. }
  12201. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  12202. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12203. _gl.getShaderPrecisionFormat = function () {
  12204. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  12205. };
  12206. }
  12207. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12208. } catch ( error ) {
  12209. console.error( 'THREE.WebGLRenderer: ' + error );
  12210. }
  12211. var extensions = new WebGLExtensions( _gl );
  12212. extensions.get( 'WEBGL_depth_texture' );
  12213. extensions.get( 'OES_texture_float' );
  12214. extensions.get( 'OES_texture_float_linear' );
  12215. extensions.get( 'OES_texture_half_float' );
  12216. extensions.get( 'OES_texture_half_float_linear' );
  12217. extensions.get( 'OES_standard_derivatives' );
  12218. extensions.get( 'ANGLE_instanced_arrays' );
  12219. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12220. BufferGeometry.MaxIndex = 4294967296;
  12221. }
  12222. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  12223. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  12224. var properties = new WebGLProperties();
  12225. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory );
  12226. var attributes = new WebGLAttributes( _gl );
  12227. var geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  12228. var objects = new WebGLObjects( _gl, geometries, _infoRender );
  12229. var programCache = new WebGLPrograms( this, capabilities );
  12230. var lightCache = new WebGLLights();
  12231. var renderLists = new WebGLRenderLists();
  12232. var background = new WebGLBackground( this, state, objects, _premultipliedAlpha );
  12233. var vr = new WebVRManager( this );
  12234. this.info.programs = programCache.programs;
  12235. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12236. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12237. //
  12238. function getTargetPixelRatio() {
  12239. return _currentRenderTarget === null ? _pixelRatio : 1;
  12240. }
  12241. function setDefaultGLState() {
  12242. state.init();
  12243. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12244. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12245. }
  12246. function resetGLState() {
  12247. _currentProgram = null;
  12248. _currentCamera = null;
  12249. _currentGeometryProgram = '';
  12250. _currentMaterialId = - 1;
  12251. state.reset();
  12252. }
  12253. setDefaultGLState();
  12254. this.context = _gl;
  12255. this.capabilities = capabilities;
  12256. this.extensions = extensions;
  12257. this.properties = properties;
  12258. this.renderLists = renderLists;
  12259. this.state = state;
  12260. this.vr = vr;
  12261. // shadow map
  12262. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  12263. this.shadowMap = shadowMap;
  12264. // Plugins
  12265. var spritePlugin = new SpritePlugin( this, sprites );
  12266. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  12267. // API
  12268. this.getContext = function () {
  12269. return _gl;
  12270. };
  12271. this.getContextAttributes = function () {
  12272. return _gl.getContextAttributes();
  12273. };
  12274. this.forceContextLoss = function () {
  12275. var extension = extensions.get( 'WEBGL_lose_context' );
  12276. if ( extension ) extension.loseContext();
  12277. };
  12278. this.getMaxAnisotropy = function () {
  12279. return capabilities.getMaxAnisotropy();
  12280. };
  12281. this.getPrecision = function () {
  12282. return capabilities.precision;
  12283. };
  12284. this.getPixelRatio = function () {
  12285. return _pixelRatio;
  12286. };
  12287. this.setPixelRatio = function ( value ) {
  12288. if ( value === undefined ) return;
  12289. _pixelRatio = value;
  12290. this.setSize( _width, _height, false );
  12291. };
  12292. this.getSize = function () {
  12293. return {
  12294. width: _width,
  12295. height: _height
  12296. };
  12297. };
  12298. this.setSize = function ( width, height, updateStyle ) {
  12299. var device = vr.getDevice();
  12300. if ( device && device.isPresenting ) {
  12301. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  12302. return;
  12303. }
  12304. _width = width;
  12305. _height = height;
  12306. _canvas.width = width * _pixelRatio;
  12307. _canvas.height = height * _pixelRatio;
  12308. if ( updateStyle !== false ) {
  12309. _canvas.style.width = width + 'px';
  12310. _canvas.style.height = height + 'px';
  12311. }
  12312. this.setViewport( 0, 0, width, height );
  12313. };
  12314. this.getDrawingBufferSize = function () {
  12315. return {
  12316. width: _width * _pixelRatio,
  12317. height: _height * _pixelRatio
  12318. };
  12319. };
  12320. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  12321. _width = width;
  12322. _height = height;
  12323. _pixelRatio = pixelRatio;
  12324. _canvas.width = width * pixelRatio;
  12325. _canvas.height = height * pixelRatio;
  12326. this.setViewport( 0, 0, width, height );
  12327. };
  12328. this.setViewport = function ( x, y, width, height ) {
  12329. _viewport.set( x, _height - y - height, width, height );
  12330. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12331. };
  12332. this.setScissor = function ( x, y, width, height ) {
  12333. _scissor.set( x, _height - y - height, width, height );
  12334. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12335. };
  12336. this.setScissorTest = function ( boolean ) {
  12337. state.setScissorTest( _scissorTest = boolean );
  12338. };
  12339. // Clearing
  12340. this.getClearColor = background.getClearColor;
  12341. this.setClearColor = background.setClearColor;
  12342. this.getClearAlpha = background.getClearAlpha;
  12343. this.setClearAlpha = background.setClearAlpha;
  12344. this.clear = function ( color, depth, stencil ) {
  12345. var bits = 0;
  12346. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12347. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12348. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12349. _gl.clear( bits );
  12350. };
  12351. this.clearColor = function () {
  12352. this.clear( true, false, false );
  12353. };
  12354. this.clearDepth = function () {
  12355. this.clear( false, true, false );
  12356. };
  12357. this.clearStencil = function () {
  12358. this.clear( false, false, true );
  12359. };
  12360. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12361. this.setRenderTarget( renderTarget );
  12362. this.clear( color, depth, stencil );
  12363. };
  12364. // Reset
  12365. this.resetGLState = resetGLState;
  12366. this.dispose = function () {
  12367. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12368. renderLists.dispose();
  12369. };
  12370. // Events
  12371. function onContextLost( event ) {
  12372. event.preventDefault();
  12373. resetGLState();
  12374. setDefaultGLState();
  12375. properties.clear();
  12376. objects.clear();
  12377. }
  12378. function onMaterialDispose( event ) {
  12379. var material = event.target;
  12380. material.removeEventListener( 'dispose', onMaterialDispose );
  12381. deallocateMaterial( material );
  12382. }
  12383. // Buffer deallocation
  12384. function deallocateMaterial( material ) {
  12385. releaseMaterialProgramReference( material );
  12386. properties.remove( material );
  12387. }
  12388. function releaseMaterialProgramReference( material ) {
  12389. var programInfo = properties.get( material ).program;
  12390. material.program = undefined;
  12391. if ( programInfo !== undefined ) {
  12392. programCache.releaseProgram( programInfo );
  12393. }
  12394. }
  12395. // Buffer rendering
  12396. function renderObjectImmediate( object, program, material ) {
  12397. object.render( function ( object ) {
  12398. _this.renderBufferImmediate( object, program, material );
  12399. } );
  12400. }
  12401. this.renderBufferImmediate = function ( object, program, material ) {
  12402. state.initAttributes();
  12403. var buffers = properties.get( object );
  12404. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12405. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12406. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12407. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12408. var programAttributes = program.getAttributes();
  12409. if ( object.hasPositions ) {
  12410. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12411. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12412. state.enableAttribute( programAttributes.position );
  12413. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12414. }
  12415. if ( object.hasNormals ) {
  12416. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12417. if ( ! material.isMeshPhongMaterial &&
  12418. ! material.isMeshStandardMaterial &&
  12419. ! material.isMeshNormalMaterial &&
  12420. material.shading === FlatShading ) {
  12421. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12422. var array = object.normalArray;
  12423. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12424. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12425. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12426. array[ i + 0 ] = nx;
  12427. array[ i + 1 ] = ny;
  12428. array[ i + 2 ] = nz;
  12429. array[ i + 3 ] = nx;
  12430. array[ i + 4 ] = ny;
  12431. array[ i + 5 ] = nz;
  12432. array[ i + 6 ] = nx;
  12433. array[ i + 7 ] = ny;
  12434. array[ i + 8 ] = nz;
  12435. }
  12436. }
  12437. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12438. state.enableAttribute( programAttributes.normal );
  12439. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12440. }
  12441. if ( object.hasUvs && material.map ) {
  12442. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12443. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12444. state.enableAttribute( programAttributes.uv );
  12445. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12446. }
  12447. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12448. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12449. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12450. state.enableAttribute( programAttributes.color );
  12451. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12452. }
  12453. state.disableUnusedAttributes();
  12454. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12455. object.count = 0;
  12456. };
  12457. function absNumericalSort( a, b ) {
  12458. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12459. }
  12460. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12461. state.setMaterial( material );
  12462. var program = setProgram( camera, fog, material, object );
  12463. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12464. var updateBuffers = false;
  12465. if ( geometryProgram !== _currentGeometryProgram ) {
  12466. _currentGeometryProgram = geometryProgram;
  12467. updateBuffers = true;
  12468. }
  12469. // morph targets
  12470. var morphTargetInfluences = object.morphTargetInfluences;
  12471. if ( morphTargetInfluences !== undefined ) {
  12472. // TODO Remove allocations
  12473. var activeInfluences = [];
  12474. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12475. var influence = morphTargetInfluences[ i ];
  12476. activeInfluences.push( [ influence, i ] );
  12477. }
  12478. activeInfluences.sort( absNumericalSort );
  12479. if ( activeInfluences.length > 8 ) {
  12480. activeInfluences.length = 8;
  12481. }
  12482. var morphAttributes = geometry.morphAttributes;
  12483. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12484. var influence = activeInfluences[ i ];
  12485. morphInfluences[ i ] = influence[ 0 ];
  12486. if ( influence[ 0 ] !== 0 ) {
  12487. var index = influence[ 1 ];
  12488. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12489. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12490. } else {
  12491. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12492. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12493. }
  12494. }
  12495. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12496. morphInfluences[ i ] = 0.0;
  12497. }
  12498. program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences );
  12499. updateBuffers = true;
  12500. }
  12501. //
  12502. var index = geometry.index;
  12503. var position = geometry.attributes.position;
  12504. var rangeFactor = 1;
  12505. if ( material.wireframe === true ) {
  12506. index = geometries.getWireframeAttribute( geometry );
  12507. rangeFactor = 2;
  12508. }
  12509. var attribute;
  12510. var renderer = bufferRenderer;
  12511. if ( index !== null ) {
  12512. attribute = attributes.get( index );
  12513. renderer = indexedBufferRenderer;
  12514. renderer.setIndex( attribute );
  12515. }
  12516. if ( updateBuffers ) {
  12517. setupVertexAttributes( material, program, geometry );
  12518. if ( index !== null ) {
  12519. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  12520. }
  12521. }
  12522. //
  12523. var dataCount = 0;
  12524. if ( index !== null ) {
  12525. dataCount = index.count;
  12526. } else if ( position !== undefined ) {
  12527. dataCount = position.count;
  12528. }
  12529. var rangeStart = geometry.drawRange.start * rangeFactor;
  12530. var rangeCount = geometry.drawRange.count * rangeFactor;
  12531. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12532. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12533. var drawStart = Math.max( rangeStart, groupStart );
  12534. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12535. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12536. if ( drawCount === 0 ) return;
  12537. //
  12538. if ( object.isMesh ) {
  12539. if ( material.wireframe === true ) {
  12540. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12541. renderer.setMode( _gl.LINES );
  12542. } else {
  12543. switch ( object.drawMode ) {
  12544. case TrianglesDrawMode:
  12545. renderer.setMode( _gl.TRIANGLES );
  12546. break;
  12547. case TriangleStripDrawMode:
  12548. renderer.setMode( _gl.TRIANGLE_STRIP );
  12549. break;
  12550. case TriangleFanDrawMode:
  12551. renderer.setMode( _gl.TRIANGLE_FAN );
  12552. break;
  12553. }
  12554. }
  12555. } else if ( object.isLine ) {
  12556. var lineWidth = material.linewidth;
  12557. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12558. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12559. if ( object.isLineSegments ) {
  12560. renderer.setMode( _gl.LINES );
  12561. } else if ( object.isLineLoop ) {
  12562. renderer.setMode( _gl.LINE_LOOP );
  12563. } else {
  12564. renderer.setMode( _gl.LINE_STRIP );
  12565. }
  12566. } else if ( object.isPoints ) {
  12567. renderer.setMode( _gl.POINTS );
  12568. }
  12569. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12570. if ( geometry.maxInstancedCount > 0 ) {
  12571. renderer.renderInstances( geometry, drawStart, drawCount );
  12572. }
  12573. } else {
  12574. renderer.render( drawStart, drawCount );
  12575. }
  12576. };
  12577. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12578. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12579. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12580. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12581. return;
  12582. }
  12583. }
  12584. if ( startIndex === undefined ) startIndex = 0;
  12585. state.initAttributes();
  12586. var geometryAttributes = geometry.attributes;
  12587. var programAttributes = program.getAttributes();
  12588. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12589. for ( var name in programAttributes ) {
  12590. var programAttribute = programAttributes[ name ];
  12591. if ( programAttribute >= 0 ) {
  12592. var geometryAttribute = geometryAttributes[ name ];
  12593. if ( geometryAttribute !== undefined ) {
  12594. var normalized = geometryAttribute.normalized;
  12595. var size = geometryAttribute.itemSize;
  12596. var attribute = attributes.get( geometryAttribute );
  12597. var buffer = attribute.buffer;
  12598. var type = attribute.type;
  12599. var bytesPerElement = attribute.bytesPerElement;
  12600. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12601. var data = geometryAttribute.data;
  12602. var stride = data.stride;
  12603. var offset = geometryAttribute.offset;
  12604. if ( data && data.isInstancedInterleavedBuffer ) {
  12605. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12606. if ( geometry.maxInstancedCount === undefined ) {
  12607. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12608. }
  12609. } else {
  12610. state.enableAttribute( programAttribute );
  12611. }
  12612. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12613. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12614. } else {
  12615. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12616. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12617. if ( geometry.maxInstancedCount === undefined ) {
  12618. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12619. }
  12620. } else {
  12621. state.enableAttribute( programAttribute );
  12622. }
  12623. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12624. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12625. }
  12626. } else if ( materialDefaultAttributeValues !== undefined ) {
  12627. var value = materialDefaultAttributeValues[ name ];
  12628. if ( value !== undefined ) {
  12629. switch ( value.length ) {
  12630. case 2:
  12631. _gl.vertexAttrib2fv( programAttribute, value );
  12632. break;
  12633. case 3:
  12634. _gl.vertexAttrib3fv( programAttribute, value );
  12635. break;
  12636. case 4:
  12637. _gl.vertexAttrib4fv( programAttribute, value );
  12638. break;
  12639. default:
  12640. _gl.vertexAttrib1fv( programAttribute, value );
  12641. }
  12642. }
  12643. }
  12644. }
  12645. }
  12646. state.disableUnusedAttributes();
  12647. }
  12648. // Compile
  12649. this.compile = function ( scene, camera ) {
  12650. lights = [];
  12651. scene.traverse( function ( object ) {
  12652. if ( object.isLight ) {
  12653. lights.push( object );
  12654. }
  12655. } );
  12656. setupLights( lights, camera );
  12657. scene.traverse( function ( object ) {
  12658. if ( object.material ) {
  12659. if ( Array.isArray( object.material ) ) {
  12660. for ( var i = 0; i < object.material.length; i ++ ) {
  12661. initMaterial( object.material[ i ], scene.fog, object );
  12662. }
  12663. } else {
  12664. initMaterial( object.material, scene.fog, object );
  12665. }
  12666. }
  12667. } );
  12668. };
  12669. // Rendering
  12670. this.animate = function ( callback ) {
  12671. function onFrame() {
  12672. callback();
  12673. ( vr.getDevice() || window ).requestAnimationFrame( onFrame );
  12674. }
  12675. ( vr.getDevice() || window ).requestAnimationFrame( onFrame );
  12676. };
  12677. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12678. if ( ! ( camera && camera.isCamera ) ) {
  12679. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12680. return;
  12681. }
  12682. // reset caching for this frame
  12683. _currentGeometryProgram = '';
  12684. _currentMaterialId = - 1;
  12685. _currentCamera = null;
  12686. // update scene graph
  12687. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12688. // update camera matrices and frustum
  12689. if ( camera.parent === null ) camera.updateMatrixWorld();
  12690. if ( vr.enabled ) {
  12691. camera = vr.getCamera( camera );
  12692. }
  12693. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12694. _frustum.setFromMatrix( _projScreenMatrix );
  12695. lights.length = 0;
  12696. sprites.length = 0;
  12697. lensFlares.length = 0;
  12698. _localClippingEnabled = this.localClippingEnabled;
  12699. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12700. currentRenderList = renderLists.get( scene, camera );
  12701. currentRenderList.init();
  12702. projectObject( scene, camera, _this.sortObjects );
  12703. currentRenderList.finish();
  12704. if ( _this.sortObjects === true ) {
  12705. currentRenderList.sort();
  12706. }
  12707. //
  12708. if ( _clippingEnabled ) _clipping.beginShadows();
  12709. setupShadows( lights );
  12710. shadowMap.render( scene, camera );
  12711. setupLights( lights, camera );
  12712. if ( _clippingEnabled ) _clipping.endShadows();
  12713. //
  12714. _infoRender.frame ++;
  12715. _infoRender.calls = 0;
  12716. _infoRender.vertices = 0;
  12717. _infoRender.faces = 0;
  12718. _infoRender.points = 0;
  12719. if ( renderTarget === undefined ) {
  12720. renderTarget = null;
  12721. }
  12722. this.setRenderTarget( renderTarget );
  12723. //
  12724. background.render( scene, camera, forceClear );
  12725. // render scene
  12726. var opaqueObjects = currentRenderList.opaque;
  12727. var transparentObjects = currentRenderList.transparent;
  12728. if ( scene.overrideMaterial ) {
  12729. var overrideMaterial = scene.overrideMaterial;
  12730. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12731. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12732. } else {
  12733. // opaque pass (front-to-back order)
  12734. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  12735. // transparent pass (back-to-front order)
  12736. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  12737. }
  12738. // custom render plugins (post pass)
  12739. spritePlugin.render( scene, camera );
  12740. lensFlarePlugin.render( scene, camera, _currentViewport );
  12741. // Generate mipmap if we're using any kind of mipmap filtering
  12742. if ( renderTarget ) {
  12743. textures.updateRenderTargetMipmap( renderTarget );
  12744. }
  12745. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12746. state.buffers.depth.setTest( true );
  12747. state.buffers.depth.setMask( true );
  12748. state.buffers.color.setMask( true );
  12749. if ( camera.isArrayCamera ) {
  12750. _this.setScissorTest( false );
  12751. }
  12752. if ( vr.enabled ) {
  12753. vr.submitFrame();
  12754. }
  12755. // _gl.finish();
  12756. };
  12757. /*
  12758. // TODO Duplicated code (Frustum)
  12759. var _sphere = new Sphere();
  12760. function isObjectViewable( object ) {
  12761. var geometry = object.geometry;
  12762. if ( geometry.boundingSphere === null )
  12763. geometry.computeBoundingSphere();
  12764. _sphere.copy( geometry.boundingSphere ).
  12765. applyMatrix4( object.matrixWorld );
  12766. return isSphereViewable( _sphere );
  12767. }
  12768. function isSpriteViewable( sprite ) {
  12769. _sphere.center.set( 0, 0, 0 );
  12770. _sphere.radius = 0.7071067811865476;
  12771. _sphere.applyMatrix4( sprite.matrixWorld );
  12772. return isSphereViewable( _sphere );
  12773. }
  12774. function isSphereViewable( sphere ) {
  12775. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12776. var numPlanes = _clipping.numPlanes;
  12777. if ( numPlanes === 0 ) return true;
  12778. var planes = _this.clippingPlanes,
  12779. center = sphere.center,
  12780. negRad = - sphere.radius,
  12781. i = 0;
  12782. do {
  12783. // out when deeper than radius in the negative halfspace
  12784. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12785. } while ( ++ i !== numPlanes );
  12786. return true;
  12787. }
  12788. */
  12789. function projectObject( object, camera, sortObjects ) {
  12790. if ( ! object.visible ) return;
  12791. var visible = object.layers.test( camera.layers );
  12792. if ( visible ) {
  12793. if ( object.isLight ) {
  12794. lights.push( object );
  12795. } else if ( object.isSprite ) {
  12796. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  12797. sprites.push( object );
  12798. }
  12799. } else if ( object.isLensFlare ) {
  12800. lensFlares.push( object );
  12801. } else if ( object.isImmediateRenderObject ) {
  12802. if ( sortObjects ) {
  12803. _vector3.setFromMatrixPosition( object.matrixWorld )
  12804. .applyMatrix4( _projScreenMatrix );
  12805. }
  12806. currentRenderList.push( object, null, object.material, _vector3.z, null );
  12807. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12808. if ( object.isSkinnedMesh ) {
  12809. object.skeleton.update();
  12810. }
  12811. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  12812. if ( sortObjects ) {
  12813. _vector3.setFromMatrixPosition( object.matrixWorld )
  12814. .applyMatrix4( _projScreenMatrix );
  12815. }
  12816. var geometry = objects.update( object );
  12817. var material = object.material;
  12818. if ( Array.isArray( material ) ) {
  12819. var groups = geometry.groups;
  12820. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12821. var group = groups[ i ];
  12822. var groupMaterial = material[ group.materialIndex ];
  12823. if ( groupMaterial && groupMaterial.visible ) {
  12824. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  12825. }
  12826. }
  12827. } else if ( material.visible ) {
  12828. currentRenderList.push( object, geometry, material, _vector3.z, null );
  12829. }
  12830. }
  12831. }
  12832. }
  12833. var children = object.children;
  12834. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12835. projectObject( children[ i ], camera, sortObjects );
  12836. }
  12837. }
  12838. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12839. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12840. var renderItem = renderList[ i ];
  12841. var object = renderItem.object;
  12842. var geometry = renderItem.geometry;
  12843. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12844. var group = renderItem.group;
  12845. if ( camera.isArrayCamera ) {
  12846. _currentArrayCamera = camera;
  12847. var cameras = camera.cameras;
  12848. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  12849. var camera2 = cameras[ j ];
  12850. if ( object.layers.test( camera2.layers ) ) {
  12851. var bounds = camera2.bounds;
  12852. var x = bounds.x * _width;
  12853. var y = bounds.y * _height;
  12854. var width = bounds.z * _width;
  12855. var height = bounds.w * _height;
  12856. _this.setViewport( x, y, width, height );
  12857. _this.setScissor( x, y, width, height );
  12858. _this.setScissorTest( true );
  12859. renderObject( object, scene, camera2, geometry, material, group );
  12860. }
  12861. }
  12862. } else {
  12863. _currentArrayCamera = null;
  12864. renderObject( object, scene, camera, geometry, material, group );
  12865. }
  12866. }
  12867. }
  12868. function renderObject( object, scene, camera, geometry, material, group ) {
  12869. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12870. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12871. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12872. if ( object.isImmediateRenderObject ) {
  12873. state.setMaterial( material );
  12874. var program = setProgram( camera, scene.fog, material, object );
  12875. _currentGeometryProgram = '';
  12876. renderObjectImmediate( object, program, material );
  12877. } else {
  12878. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12879. }
  12880. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12881. }
  12882. function initMaterial( material, fog, object ) {
  12883. var materialProperties = properties.get( material );
  12884. var parameters = programCache.getParameters(
  12885. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12886. var code = programCache.getProgramCode( material, parameters );
  12887. var program = materialProperties.program;
  12888. var programChange = true;
  12889. if ( program === undefined ) {
  12890. // new material
  12891. material.addEventListener( 'dispose', onMaterialDispose );
  12892. } else if ( program.code !== code ) {
  12893. // changed glsl or parameters
  12894. releaseMaterialProgramReference( material );
  12895. } else if ( parameters.shaderID !== undefined ) {
  12896. // same glsl and uniform list
  12897. return;
  12898. } else {
  12899. // only rebuild uniform list
  12900. programChange = false;
  12901. }
  12902. if ( programChange ) {
  12903. if ( parameters.shaderID ) {
  12904. var shader = ShaderLib[ parameters.shaderID ];
  12905. materialProperties.shader = {
  12906. name: material.type,
  12907. uniforms: UniformsUtils.clone( shader.uniforms ),
  12908. vertexShader: shader.vertexShader,
  12909. fragmentShader: shader.fragmentShader
  12910. };
  12911. } else {
  12912. materialProperties.shader = {
  12913. name: material.type,
  12914. uniforms: material.uniforms,
  12915. vertexShader: material.vertexShader,
  12916. fragmentShader: material.fragmentShader
  12917. };
  12918. }
  12919. material.onBeforeCompile( materialProperties.shader );
  12920. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  12921. materialProperties.program = program;
  12922. material.program = program;
  12923. }
  12924. var programAttributes = program.getAttributes();
  12925. if ( material.morphTargets ) {
  12926. material.numSupportedMorphTargets = 0;
  12927. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12928. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  12929. material.numSupportedMorphTargets ++;
  12930. }
  12931. }
  12932. }
  12933. if ( material.morphNormals ) {
  12934. material.numSupportedMorphNormals = 0;
  12935. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12936. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  12937. material.numSupportedMorphNormals ++;
  12938. }
  12939. }
  12940. }
  12941. var uniforms = materialProperties.shader.uniforms;
  12942. if ( ! material.isShaderMaterial &&
  12943. ! material.isRawShaderMaterial ||
  12944. material.clipping === true ) {
  12945. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12946. materialProperties.numIntersection = _clipping.numIntersection;
  12947. uniforms.clippingPlanes = _clipping.uniform;
  12948. }
  12949. materialProperties.fog = fog;
  12950. // store the light setup it was created for
  12951. materialProperties.lightsHash = _lights.hash;
  12952. if ( material.lights ) {
  12953. // wire up the material to this renderer's lighting state
  12954. uniforms.ambientLightColor.value = _lights.ambient;
  12955. uniforms.directionalLights.value = _lights.directional;
  12956. uniforms.spotLights.value = _lights.spot;
  12957. uniforms.rectAreaLights.value = _lights.rectArea;
  12958. uniforms.pointLights.value = _lights.point;
  12959. uniforms.hemisphereLights.value = _lights.hemi;
  12960. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12961. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12962. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12963. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12964. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12965. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12966. // TODO (abelnation): add area lights shadow info to uniforms
  12967. }
  12968. var progUniforms = materialProperties.program.getUniforms(),
  12969. uniformsList =
  12970. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12971. materialProperties.uniformsList = uniformsList;
  12972. }
  12973. function setProgram( camera, fog, material, object ) {
  12974. _usedTextureUnits = 0;
  12975. var materialProperties = properties.get( material );
  12976. if ( _clippingEnabled ) {
  12977. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12978. var useCache =
  12979. camera === _currentCamera &&
  12980. material.id === _currentMaterialId;
  12981. // we might want to call this function with some ClippingGroup
  12982. // object instead of the material, once it becomes feasible
  12983. // (#8465, #8379)
  12984. _clipping.setState(
  12985. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12986. camera, materialProperties, useCache );
  12987. }
  12988. }
  12989. if ( material.needsUpdate === false ) {
  12990. if ( materialProperties.program === undefined ) {
  12991. material.needsUpdate = true;
  12992. } else if ( material.fog && materialProperties.fog !== fog ) {
  12993. material.needsUpdate = true;
  12994. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12995. material.needsUpdate = true;
  12996. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12997. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12998. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12999. material.needsUpdate = true;
  13000. }
  13001. }
  13002. if ( material.needsUpdate ) {
  13003. initMaterial( material, fog, object );
  13004. material.needsUpdate = false;
  13005. }
  13006. var refreshProgram = false;
  13007. var refreshMaterial = false;
  13008. var refreshLights = false;
  13009. var program = materialProperties.program,
  13010. p_uniforms = program.getUniforms(),
  13011. m_uniforms = materialProperties.shader.uniforms;
  13012. if ( program.id !== _currentProgram ) {
  13013. _gl.useProgram( program.program );
  13014. _currentProgram = program.id;
  13015. refreshProgram = true;
  13016. refreshMaterial = true;
  13017. refreshLights = true;
  13018. }
  13019. if ( material.id !== _currentMaterialId ) {
  13020. _currentMaterialId = material.id;
  13021. refreshMaterial = true;
  13022. }
  13023. if ( refreshProgram || camera !== _currentCamera ) {
  13024. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  13025. if ( capabilities.logarithmicDepthBuffer ) {
  13026. p_uniforms.setValue( _gl, 'logDepthBufFC',
  13027. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13028. }
  13029. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  13030. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  13031. _currentCamera = ( _currentArrayCamera || camera );
  13032. // lighting uniforms depend on the camera so enforce an update
  13033. // now, in case this material supports lights - or later, when
  13034. // the next material that does gets activated:
  13035. refreshMaterial = true; // set to true on material change
  13036. refreshLights = true; // remains set until update done
  13037. }
  13038. // load material specific uniforms
  13039. // (shader material also gets them for the sake of genericity)
  13040. if ( material.isShaderMaterial ||
  13041. material.isMeshPhongMaterial ||
  13042. material.isMeshStandardMaterial ||
  13043. material.envMap ) {
  13044. var uCamPos = p_uniforms.map.cameraPosition;
  13045. if ( uCamPos !== undefined ) {
  13046. uCamPos.setValue( _gl,
  13047. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  13048. }
  13049. }
  13050. if ( material.isMeshPhongMaterial ||
  13051. material.isMeshLambertMaterial ||
  13052. material.isMeshBasicMaterial ||
  13053. material.isMeshStandardMaterial ||
  13054. material.isShaderMaterial ||
  13055. material.skinning ) {
  13056. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  13057. }
  13058. }
  13059. // skinning uniforms must be set even if material didn't change
  13060. // auto-setting of texture unit for bone texture must go before other textures
  13061. // not sure why, but otherwise weird things happen
  13062. if ( material.skinning ) {
  13063. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  13064. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  13065. var skeleton = object.skeleton;
  13066. if ( skeleton ) {
  13067. var bones = skeleton.bones;
  13068. if ( capabilities.floatVertexTextures ) {
  13069. if ( skeleton.boneTexture === undefined ) {
  13070. // layout (1 matrix = 4 pixels)
  13071. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13072. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13073. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13074. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13075. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13076. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  13077. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13078. size = Math.max( size, 4 );
  13079. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  13080. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  13081. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  13082. skeleton.boneMatrices = boneMatrices;
  13083. skeleton.boneTexture = boneTexture;
  13084. skeleton.boneTextureSize = size;
  13085. }
  13086. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  13087. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  13088. } else {
  13089. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  13090. }
  13091. }
  13092. }
  13093. if ( refreshMaterial ) {
  13094. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  13095. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  13096. if ( material.lights ) {
  13097. // the current material requires lighting info
  13098. // note: all lighting uniforms are always set correctly
  13099. // they simply reference the renderer's state for their
  13100. // values
  13101. //
  13102. // use the current material's .needsUpdate flags to set
  13103. // the GL state when required
  13104. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  13105. }
  13106. // refresh uniforms common to several materials
  13107. if ( fog && material.fog ) {
  13108. refreshUniformsFog( m_uniforms, fog );
  13109. }
  13110. if ( material.isMeshBasicMaterial ||
  13111. material.isMeshLambertMaterial ||
  13112. material.isMeshPhongMaterial ||
  13113. material.isMeshStandardMaterial ||
  13114. material.isMeshNormalMaterial ||
  13115. material.isMeshDepthMaterial ) {
  13116. refreshUniformsCommon( m_uniforms, material );
  13117. }
  13118. // refresh single material specific uniforms
  13119. if ( material.isLineBasicMaterial ) {
  13120. refreshUniformsLine( m_uniforms, material );
  13121. } else if ( material.isLineDashedMaterial ) {
  13122. refreshUniformsLine( m_uniforms, material );
  13123. refreshUniformsDash( m_uniforms, material );
  13124. } else if ( material.isPointsMaterial ) {
  13125. refreshUniformsPoints( m_uniforms, material );
  13126. } else if ( material.isMeshLambertMaterial ) {
  13127. refreshUniformsLambert( m_uniforms, material );
  13128. } else if ( material.isMeshToonMaterial ) {
  13129. refreshUniformsToon( m_uniforms, material );
  13130. } else if ( material.isMeshPhongMaterial ) {
  13131. refreshUniformsPhong( m_uniforms, material );
  13132. } else if ( material.isMeshPhysicalMaterial ) {
  13133. refreshUniformsPhysical( m_uniforms, material );
  13134. } else if ( material.isMeshStandardMaterial ) {
  13135. refreshUniformsStandard( m_uniforms, material );
  13136. } else if ( material.isMeshDepthMaterial ) {
  13137. if ( material.displacementMap ) {
  13138. m_uniforms.displacementMap.value = material.displacementMap;
  13139. m_uniforms.displacementScale.value = material.displacementScale;
  13140. m_uniforms.displacementBias.value = material.displacementBias;
  13141. }
  13142. } else if ( material.isMeshNormalMaterial ) {
  13143. refreshUniformsNormal( m_uniforms, material );
  13144. }
  13145. // RectAreaLight Texture
  13146. // TODO (mrdoob): Find a nicer implementation
  13147. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  13148. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  13149. WebGLUniforms.upload(
  13150. _gl, materialProperties.uniformsList, m_uniforms, _this );
  13151. }
  13152. // common matrices
  13153. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  13154. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  13155. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  13156. return program;
  13157. }
  13158. // Uniforms (refresh uniforms objects)
  13159. function refreshUniformsCommon( uniforms, material ) {
  13160. uniforms.opacity.value = material.opacity;
  13161. uniforms.diffuse.value = material.color;
  13162. if ( material.emissive ) {
  13163. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13164. }
  13165. uniforms.map.value = material.map;
  13166. uniforms.specularMap.value = material.specularMap;
  13167. uniforms.alphaMap.value = material.alphaMap;
  13168. if ( material.lightMap ) {
  13169. uniforms.lightMap.value = material.lightMap;
  13170. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13171. }
  13172. if ( material.aoMap ) {
  13173. uniforms.aoMap.value = material.aoMap;
  13174. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13175. }
  13176. // uv repeat and offset setting priorities
  13177. // 1. color map
  13178. // 2. specular map
  13179. // 3. normal map
  13180. // 4. bump map
  13181. // 5. alpha map
  13182. // 6. emissive map
  13183. var uvScaleMap;
  13184. if ( material.map ) {
  13185. uvScaleMap = material.map;
  13186. } else if ( material.specularMap ) {
  13187. uvScaleMap = material.specularMap;
  13188. } else if ( material.displacementMap ) {
  13189. uvScaleMap = material.displacementMap;
  13190. } else if ( material.normalMap ) {
  13191. uvScaleMap = material.normalMap;
  13192. } else if ( material.bumpMap ) {
  13193. uvScaleMap = material.bumpMap;
  13194. } else if ( material.roughnessMap ) {
  13195. uvScaleMap = material.roughnessMap;
  13196. } else if ( material.metalnessMap ) {
  13197. uvScaleMap = material.metalnessMap;
  13198. } else if ( material.alphaMap ) {
  13199. uvScaleMap = material.alphaMap;
  13200. } else if ( material.emissiveMap ) {
  13201. uvScaleMap = material.emissiveMap;
  13202. }
  13203. if ( uvScaleMap !== undefined ) {
  13204. // backwards compatibility
  13205. if ( uvScaleMap.isWebGLRenderTarget ) {
  13206. uvScaleMap = uvScaleMap.texture;
  13207. }
  13208. var offset = uvScaleMap.offset;
  13209. var repeat = uvScaleMap.repeat;
  13210. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13211. }
  13212. uniforms.envMap.value = material.envMap;
  13213. // don't flip CubeTexture envMaps, flip everything else:
  13214. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13215. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13216. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13217. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13218. uniforms.reflectivity.value = material.reflectivity;
  13219. uniforms.refractionRatio.value = material.refractionRatio;
  13220. }
  13221. function refreshUniformsLine( uniforms, material ) {
  13222. uniforms.diffuse.value = material.color;
  13223. uniforms.opacity.value = material.opacity;
  13224. }
  13225. function refreshUniformsDash( uniforms, material ) {
  13226. uniforms.dashSize.value = material.dashSize;
  13227. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13228. uniforms.scale.value = material.scale;
  13229. }
  13230. function refreshUniformsPoints( uniforms, material ) {
  13231. uniforms.diffuse.value = material.color;
  13232. uniforms.opacity.value = material.opacity;
  13233. uniforms.size.value = material.size * _pixelRatio;
  13234. uniforms.scale.value = _height * 0.5;
  13235. uniforms.map.value = material.map;
  13236. if ( material.map !== null ) {
  13237. var offset = material.map.offset;
  13238. var repeat = material.map.repeat;
  13239. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13240. }
  13241. }
  13242. function refreshUniformsFog( uniforms, fog ) {
  13243. uniforms.fogColor.value = fog.color;
  13244. if ( fog.isFog ) {
  13245. uniforms.fogNear.value = fog.near;
  13246. uniforms.fogFar.value = fog.far;
  13247. } else if ( fog.isFogExp2 ) {
  13248. uniforms.fogDensity.value = fog.density;
  13249. }
  13250. }
  13251. function refreshUniformsLambert( uniforms, material ) {
  13252. if ( material.emissiveMap ) {
  13253. uniforms.emissiveMap.value = material.emissiveMap;
  13254. }
  13255. }
  13256. function refreshUniformsPhong( uniforms, material ) {
  13257. uniforms.specular.value = material.specular;
  13258. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13259. if ( material.emissiveMap ) {
  13260. uniforms.emissiveMap.value = material.emissiveMap;
  13261. }
  13262. if ( material.bumpMap ) {
  13263. uniforms.bumpMap.value = material.bumpMap;
  13264. uniforms.bumpScale.value = material.bumpScale;
  13265. }
  13266. if ( material.normalMap ) {
  13267. uniforms.normalMap.value = material.normalMap;
  13268. uniforms.normalScale.value.copy( material.normalScale );
  13269. }
  13270. if ( material.displacementMap ) {
  13271. uniforms.displacementMap.value = material.displacementMap;
  13272. uniforms.displacementScale.value = material.displacementScale;
  13273. uniforms.displacementBias.value = material.displacementBias;
  13274. }
  13275. }
  13276. function refreshUniformsToon( uniforms, material ) {
  13277. refreshUniformsPhong( uniforms, material );
  13278. if ( material.gradientMap ) {
  13279. uniforms.gradientMap.value = material.gradientMap;
  13280. }
  13281. }
  13282. function refreshUniformsStandard( uniforms, material ) {
  13283. uniforms.roughness.value = material.roughness;
  13284. uniforms.metalness.value = material.metalness;
  13285. if ( material.roughnessMap ) {
  13286. uniforms.roughnessMap.value = material.roughnessMap;
  13287. }
  13288. if ( material.metalnessMap ) {
  13289. uniforms.metalnessMap.value = material.metalnessMap;
  13290. }
  13291. if ( material.emissiveMap ) {
  13292. uniforms.emissiveMap.value = material.emissiveMap;
  13293. }
  13294. if ( material.bumpMap ) {
  13295. uniforms.bumpMap.value = material.bumpMap;
  13296. uniforms.bumpScale.value = material.bumpScale;
  13297. }
  13298. if ( material.normalMap ) {
  13299. uniforms.normalMap.value = material.normalMap;
  13300. uniforms.normalScale.value.copy( material.normalScale );
  13301. }
  13302. if ( material.displacementMap ) {
  13303. uniforms.displacementMap.value = material.displacementMap;
  13304. uniforms.displacementScale.value = material.displacementScale;
  13305. uniforms.displacementBias.value = material.displacementBias;
  13306. }
  13307. if ( material.envMap ) {
  13308. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13309. uniforms.envMapIntensity.value = material.envMapIntensity;
  13310. }
  13311. }
  13312. function refreshUniformsPhysical( uniforms, material ) {
  13313. uniforms.clearCoat.value = material.clearCoat;
  13314. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13315. refreshUniformsStandard( uniforms, material );
  13316. }
  13317. function refreshUniformsNormal( uniforms, material ) {
  13318. if ( material.bumpMap ) {
  13319. uniforms.bumpMap.value = material.bumpMap;
  13320. uniforms.bumpScale.value = material.bumpScale;
  13321. }
  13322. if ( material.normalMap ) {
  13323. uniforms.normalMap.value = material.normalMap;
  13324. uniforms.normalScale.value.copy( material.normalScale );
  13325. }
  13326. if ( material.displacementMap ) {
  13327. uniforms.displacementMap.value = material.displacementMap;
  13328. uniforms.displacementScale.value = material.displacementScale;
  13329. uniforms.displacementBias.value = material.displacementBias;
  13330. }
  13331. }
  13332. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13333. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13334. uniforms.ambientLightColor.needsUpdate = value;
  13335. uniforms.directionalLights.needsUpdate = value;
  13336. uniforms.pointLights.needsUpdate = value;
  13337. uniforms.spotLights.needsUpdate = value;
  13338. uniforms.rectAreaLights.needsUpdate = value;
  13339. uniforms.hemisphereLights.needsUpdate = value;
  13340. }
  13341. // Lighting
  13342. function setupShadows( lights ) {
  13343. var lightShadowsLength = 0;
  13344. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  13345. var light = lights[ i ];
  13346. if ( light.castShadow ) {
  13347. _lights.shadows[ lightShadowsLength ] = light;
  13348. lightShadowsLength ++;
  13349. }
  13350. }
  13351. _lights.shadows.length = lightShadowsLength;
  13352. }
  13353. function setupLights( lights, camera ) {
  13354. var l, ll, light, shadow,
  13355. r = 0, g = 0, b = 0,
  13356. color,
  13357. intensity,
  13358. distance,
  13359. shadowMap,
  13360. viewMatrix = camera.matrixWorldInverse,
  13361. directionalLength = 0,
  13362. pointLength = 0,
  13363. spotLength = 0,
  13364. rectAreaLength = 0,
  13365. hemiLength = 0;
  13366. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13367. light = lights[ l ];
  13368. color = light.color;
  13369. intensity = light.intensity;
  13370. distance = light.distance;
  13371. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13372. if ( light.isAmbientLight ) {
  13373. r += color.r * intensity;
  13374. g += color.g * intensity;
  13375. b += color.b * intensity;
  13376. } else if ( light.isDirectionalLight ) {
  13377. var uniforms = lightCache.get( light );
  13378. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13379. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13380. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13381. uniforms.direction.sub( _vector3 );
  13382. uniforms.direction.transformDirection( viewMatrix );
  13383. uniforms.shadow = light.castShadow;
  13384. if ( light.castShadow ) {
  13385. shadow = light.shadow;
  13386. uniforms.shadowBias = shadow.bias;
  13387. uniforms.shadowRadius = shadow.radius;
  13388. uniforms.shadowMapSize = shadow.mapSize;
  13389. }
  13390. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  13391. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13392. _lights.directional[ directionalLength ] = uniforms;
  13393. directionalLength ++;
  13394. } else if ( light.isSpotLight ) {
  13395. var uniforms = lightCache.get( light );
  13396. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13397. uniforms.position.applyMatrix4( viewMatrix );
  13398. uniforms.color.copy( color ).multiplyScalar( intensity );
  13399. uniforms.distance = distance;
  13400. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13401. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13402. uniforms.direction.sub( _vector3 );
  13403. uniforms.direction.transformDirection( viewMatrix );
  13404. uniforms.coneCos = Math.cos( light.angle );
  13405. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13406. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13407. uniforms.shadow = light.castShadow;
  13408. if ( light.castShadow ) {
  13409. shadow = light.shadow;
  13410. uniforms.shadowBias = shadow.bias;
  13411. uniforms.shadowRadius = shadow.radius;
  13412. uniforms.shadowMapSize = shadow.mapSize;
  13413. }
  13414. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13415. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13416. _lights.spot[ spotLength ] = uniforms;
  13417. spotLength ++;
  13418. } else if ( light.isRectAreaLight ) {
  13419. var uniforms = lightCache.get( light );
  13420. // (a) intensity controls irradiance of entire light
  13421. uniforms.color
  13422. .copy( color )
  13423. .multiplyScalar( intensity / ( light.width * light.height ) );
  13424. // (b) intensity controls the radiance per light area
  13425. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13426. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13427. uniforms.position.applyMatrix4( viewMatrix );
  13428. // extract local rotation of light to derive width/height half vectors
  13429. _matrix42.identity();
  13430. _matrix4.copy( light.matrixWorld );
  13431. _matrix4.premultiply( viewMatrix );
  13432. _matrix42.extractRotation( _matrix4 );
  13433. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13434. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13435. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13436. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13437. // TODO (abelnation): RectAreaLight distance?
  13438. // uniforms.distance = distance;
  13439. _lights.rectArea[ rectAreaLength ] = uniforms;
  13440. rectAreaLength ++;
  13441. } else if ( light.isPointLight ) {
  13442. var uniforms = lightCache.get( light );
  13443. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13444. uniforms.position.applyMatrix4( viewMatrix );
  13445. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13446. uniforms.distance = light.distance;
  13447. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13448. uniforms.shadow = light.castShadow;
  13449. if ( light.castShadow ) {
  13450. shadow = light.shadow;
  13451. uniforms.shadowBias = shadow.bias;
  13452. uniforms.shadowRadius = shadow.radius;
  13453. uniforms.shadowMapSize = shadow.mapSize;
  13454. }
  13455. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13456. _lights.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13457. _lights.point[ pointLength ] = uniforms;
  13458. pointLength ++;
  13459. } else if ( light.isHemisphereLight ) {
  13460. var uniforms = lightCache.get( light );
  13461. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13462. uniforms.direction.transformDirection( viewMatrix );
  13463. uniforms.direction.normalize();
  13464. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13465. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13466. _lights.hemi[ hemiLength ] = uniforms;
  13467. hemiLength ++;
  13468. }
  13469. }
  13470. _lights.ambient[ 0 ] = r;
  13471. _lights.ambient[ 1 ] = g;
  13472. _lights.ambient[ 2 ] = b;
  13473. _lights.directional.length = directionalLength;
  13474. _lights.spot.length = spotLength;
  13475. _lights.rectArea.length = rectAreaLength;
  13476. _lights.point.length = pointLength;
  13477. _lights.hemi.length = hemiLength;
  13478. // TODO (sam-g-steel) why aren't we using join
  13479. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13480. }
  13481. // GL state setting
  13482. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13483. state.setCullFace( cullFace );
  13484. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13485. };
  13486. // Textures
  13487. function allocTextureUnit() {
  13488. var textureUnit = _usedTextureUnits;
  13489. if ( textureUnit >= capabilities.maxTextures ) {
  13490. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13491. }
  13492. _usedTextureUnits += 1;
  13493. return textureUnit;
  13494. }
  13495. this.allocTextureUnit = allocTextureUnit;
  13496. // this.setTexture2D = setTexture2D;
  13497. this.setTexture2D = ( function () {
  13498. var warned = false;
  13499. // backwards compatibility: peel texture.texture
  13500. return function setTexture2D( texture, slot ) {
  13501. if ( texture && texture.isWebGLRenderTarget ) {
  13502. if ( ! warned ) {
  13503. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13504. warned = true;
  13505. }
  13506. texture = texture.texture;
  13507. }
  13508. textures.setTexture2D( texture, slot );
  13509. };
  13510. }() );
  13511. this.setTexture = ( function () {
  13512. var warned = false;
  13513. return function setTexture( texture, slot ) {
  13514. if ( ! warned ) {
  13515. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13516. warned = true;
  13517. }
  13518. textures.setTexture2D( texture, slot );
  13519. };
  13520. }() );
  13521. this.setTextureCube = ( function () {
  13522. var warned = false;
  13523. return function setTextureCube( texture, slot ) {
  13524. // backwards compatibility: peel texture.texture
  13525. if ( texture && texture.isWebGLRenderTargetCube ) {
  13526. if ( ! warned ) {
  13527. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13528. warned = true;
  13529. }
  13530. texture = texture.texture;
  13531. }
  13532. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13533. // TODO: unify these code paths
  13534. if ( ( texture && texture.isCubeTexture ) ||
  13535. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13536. // CompressedTexture can have Array in image :/
  13537. // this function alone should take care of cube textures
  13538. textures.setTextureCube( texture, slot );
  13539. } else {
  13540. // assumed: texture property of THREE.WebGLRenderTargetCube
  13541. textures.setTextureCubeDynamic( texture, slot );
  13542. }
  13543. };
  13544. }() );
  13545. this.getRenderTarget = function () {
  13546. return _currentRenderTarget;
  13547. };
  13548. this.setRenderTarget = function ( renderTarget ) {
  13549. _currentRenderTarget = renderTarget;
  13550. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13551. textures.setupRenderTarget( renderTarget );
  13552. }
  13553. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13554. var framebuffer;
  13555. if ( renderTarget ) {
  13556. var renderTargetProperties = properties.get( renderTarget );
  13557. if ( isCube ) {
  13558. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13559. } else {
  13560. framebuffer = renderTargetProperties.__webglFramebuffer;
  13561. }
  13562. _currentScissor.copy( renderTarget.scissor );
  13563. _currentScissorTest = renderTarget.scissorTest;
  13564. _currentViewport.copy( renderTarget.viewport );
  13565. } else {
  13566. framebuffer = null;
  13567. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13568. _currentScissorTest = _scissorTest;
  13569. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13570. }
  13571. if ( _currentFramebuffer !== framebuffer ) {
  13572. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13573. _currentFramebuffer = framebuffer;
  13574. }
  13575. state.scissor( _currentScissor );
  13576. state.setScissorTest( _currentScissorTest );
  13577. state.viewport( _currentViewport );
  13578. if ( isCube ) {
  13579. var textureProperties = properties.get( renderTarget.texture );
  13580. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13581. }
  13582. };
  13583. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13584. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  13585. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13586. return;
  13587. }
  13588. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13589. if ( framebuffer ) {
  13590. var restore = false;
  13591. if ( framebuffer !== _currentFramebuffer ) {
  13592. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13593. restore = true;
  13594. }
  13595. try {
  13596. var texture = renderTarget.texture;
  13597. var textureFormat = texture.format;
  13598. var textureType = texture.type;
  13599. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13600. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13601. return;
  13602. }
  13603. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13604. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13605. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13606. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13607. return;
  13608. }
  13609. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13610. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13611. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13612. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13613. }
  13614. } else {
  13615. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13616. }
  13617. } finally {
  13618. if ( restore ) {
  13619. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13620. }
  13621. }
  13622. }
  13623. };
  13624. // Map three.js constants to WebGL constants
  13625. function paramThreeToGL( p ) {
  13626. var extension;
  13627. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13628. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13629. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13630. if ( p === NearestFilter ) return _gl.NEAREST;
  13631. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13632. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13633. if ( p === LinearFilter ) return _gl.LINEAR;
  13634. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13635. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13636. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13637. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13638. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13639. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13640. if ( p === ByteType ) return _gl.BYTE;
  13641. if ( p === ShortType ) return _gl.SHORT;
  13642. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13643. if ( p === IntType ) return _gl.INT;
  13644. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13645. if ( p === FloatType ) return _gl.FLOAT;
  13646. if ( p === HalfFloatType ) {
  13647. extension = extensions.get( 'OES_texture_half_float' );
  13648. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13649. }
  13650. if ( p === AlphaFormat ) return _gl.ALPHA;
  13651. if ( p === RGBFormat ) return _gl.RGB;
  13652. if ( p === RGBAFormat ) return _gl.RGBA;
  13653. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13654. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13655. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13656. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13657. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13658. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13659. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13660. if ( p === ZeroFactor ) return _gl.ZERO;
  13661. if ( p === OneFactor ) return _gl.ONE;
  13662. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13663. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13664. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13665. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13666. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13667. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13668. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13669. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13670. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13671. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13672. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13673. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13674. if ( extension !== null ) {
  13675. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13676. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13677. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13678. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13679. }
  13680. }
  13681. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13682. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13683. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13684. if ( extension !== null ) {
  13685. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13686. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13687. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13688. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13689. }
  13690. }
  13691. if ( p === RGB_ETC1_Format ) {
  13692. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13693. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13694. }
  13695. if ( p === MinEquation || p === MaxEquation ) {
  13696. extension = extensions.get( 'EXT_blend_minmax' );
  13697. if ( extension !== null ) {
  13698. if ( p === MinEquation ) return extension.MIN_EXT;
  13699. if ( p === MaxEquation ) return extension.MAX_EXT;
  13700. }
  13701. }
  13702. if ( p === UnsignedInt248Type ) {
  13703. extension = extensions.get( 'WEBGL_depth_texture' );
  13704. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13705. }
  13706. return 0;
  13707. }
  13708. }
  13709. /**
  13710. * @author mrdoob / http://mrdoob.com/
  13711. * @author alteredq / http://alteredqualia.com/
  13712. */
  13713. function FogExp2 ( color, density ) {
  13714. this.name = '';
  13715. this.color = new Color( color );
  13716. this.density = ( density !== undefined ) ? density : 0.00025;
  13717. }
  13718. FogExp2.prototype.isFogExp2 = true;
  13719. FogExp2.prototype.clone = function () {
  13720. return new FogExp2( this.color.getHex(), this.density );
  13721. };
  13722. FogExp2.prototype.toJSON = function ( meta ) {
  13723. return {
  13724. type: 'FogExp2',
  13725. color: this.color.getHex(),
  13726. density: this.density
  13727. };
  13728. };
  13729. /**
  13730. * @author mrdoob / http://mrdoob.com/
  13731. * @author alteredq / http://alteredqualia.com/
  13732. */
  13733. function Fog ( color, near, far ) {
  13734. this.name = '';
  13735. this.color = new Color( color );
  13736. this.near = ( near !== undefined ) ? near : 1;
  13737. this.far = ( far !== undefined ) ? far : 1000;
  13738. }
  13739. Fog.prototype.isFog = true;
  13740. Fog.prototype.clone = function () {
  13741. return new Fog( this.color.getHex(), this.near, this.far );
  13742. };
  13743. Fog.prototype.toJSON = function ( meta ) {
  13744. return {
  13745. type: 'Fog',
  13746. color: this.color.getHex(),
  13747. near: this.near,
  13748. far: this.far
  13749. };
  13750. };
  13751. /**
  13752. * @author mrdoob / http://mrdoob.com/
  13753. */
  13754. function Scene () {
  13755. Object3D.call( this );
  13756. this.type = 'Scene';
  13757. this.background = null;
  13758. this.fog = null;
  13759. this.overrideMaterial = null;
  13760. this.autoUpdate = true; // checked by the renderer
  13761. }
  13762. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13763. constructor: Scene,
  13764. copy: function ( source, recursive ) {
  13765. Object3D.prototype.copy.call( this, source, recursive );
  13766. if ( source.background !== null ) this.background = source.background.clone();
  13767. if ( source.fog !== null ) this.fog = source.fog.clone();
  13768. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13769. this.autoUpdate = source.autoUpdate;
  13770. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13771. return this;
  13772. },
  13773. toJSON: function ( meta ) {
  13774. var data = Object3D.prototype.toJSON.call( this, meta );
  13775. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13776. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13777. return data;
  13778. }
  13779. } );
  13780. /**
  13781. * @author mikael emtinger / http://gomo.se/
  13782. * @author alteredq / http://alteredqualia.com/
  13783. */
  13784. function LensFlare( texture, size, distance, blending, color ) {
  13785. Object3D.call( this );
  13786. this.lensFlares = [];
  13787. this.positionScreen = new Vector3();
  13788. this.customUpdateCallback = undefined;
  13789. if ( texture !== undefined ) {
  13790. this.add( texture, size, distance, blending, color );
  13791. }
  13792. }
  13793. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13794. constructor: LensFlare,
  13795. isLensFlare: true,
  13796. copy: function ( source ) {
  13797. Object3D.prototype.copy.call( this, source );
  13798. this.positionScreen.copy( source.positionScreen );
  13799. this.customUpdateCallback = source.customUpdateCallback;
  13800. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13801. this.lensFlares.push( source.lensFlares[ i ] );
  13802. }
  13803. return this;
  13804. },
  13805. add: function ( texture, size, distance, blending, color, opacity ) {
  13806. if ( size === undefined ) size = - 1;
  13807. if ( distance === undefined ) distance = 0;
  13808. if ( opacity === undefined ) opacity = 1;
  13809. if ( color === undefined ) color = new Color( 0xffffff );
  13810. if ( blending === undefined ) blending = NormalBlending;
  13811. distance = Math.min( distance, Math.max( 0, distance ) );
  13812. this.lensFlares.push( {
  13813. texture: texture, // THREE.Texture
  13814. size: size, // size in pixels (-1 = use texture.width)
  13815. distance: distance, // distance (0-1) from light source (0=at light source)
  13816. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13817. scale: 1, // scale
  13818. rotation: 0, // rotation
  13819. opacity: opacity, // opacity
  13820. color: color, // color
  13821. blending: blending // blending
  13822. } );
  13823. },
  13824. /*
  13825. * Update lens flares update positions on all flares based on the screen position
  13826. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13827. */
  13828. updateLensFlares: function () {
  13829. var f, fl = this.lensFlares.length;
  13830. var flare;
  13831. var vecX = - this.positionScreen.x * 2;
  13832. var vecY = - this.positionScreen.y * 2;
  13833. for ( f = 0; f < fl; f ++ ) {
  13834. flare = this.lensFlares[ f ];
  13835. flare.x = this.positionScreen.x + vecX * flare.distance;
  13836. flare.y = this.positionScreen.y + vecY * flare.distance;
  13837. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13838. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13839. }
  13840. }
  13841. } );
  13842. /**
  13843. * @author alteredq / http://alteredqualia.com/
  13844. *
  13845. * parameters = {
  13846. * color: <hex>,
  13847. * opacity: <float>,
  13848. * map: new THREE.Texture( <Image> ),
  13849. *
  13850. * uvOffset: new THREE.Vector2(),
  13851. * uvScale: new THREE.Vector2()
  13852. * }
  13853. */
  13854. function SpriteMaterial( parameters ) {
  13855. Material.call( this );
  13856. this.type = 'SpriteMaterial';
  13857. this.color = new Color( 0xffffff );
  13858. this.map = null;
  13859. this.rotation = 0;
  13860. this.fog = false;
  13861. this.lights = false;
  13862. this.setValues( parameters );
  13863. }
  13864. SpriteMaterial.prototype = Object.create( Material.prototype );
  13865. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13866. SpriteMaterial.prototype.isSpriteMaterial = true;
  13867. SpriteMaterial.prototype.copy = function ( source ) {
  13868. Material.prototype.copy.call( this, source );
  13869. this.color.copy( source.color );
  13870. this.map = source.map;
  13871. this.rotation = source.rotation;
  13872. return this;
  13873. };
  13874. /**
  13875. * @author mikael emtinger / http://gomo.se/
  13876. * @author alteredq / http://alteredqualia.com/
  13877. */
  13878. function Sprite( material ) {
  13879. Object3D.call( this );
  13880. this.type = 'Sprite';
  13881. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13882. }
  13883. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13884. constructor: Sprite,
  13885. isSprite: true,
  13886. raycast: ( function () {
  13887. var intersectPoint = new Vector3();
  13888. var worldPosition = new Vector3();
  13889. var worldScale = new Vector3();
  13890. return function raycast( raycaster, intersects ) {
  13891. worldPosition.setFromMatrixPosition( this.matrixWorld );
  13892. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  13893. worldScale.setFromMatrixScale( this.matrixWorld );
  13894. var guessSizeSq = worldScale.x * worldScale.y / 4;
  13895. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  13896. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13897. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13898. intersects.push( {
  13899. distance: distance,
  13900. point: intersectPoint.clone(),
  13901. face: null,
  13902. object: this
  13903. } );
  13904. };
  13905. }() ),
  13906. clone: function () {
  13907. return new this.constructor( this.material ).copy( this );
  13908. }
  13909. } );
  13910. /**
  13911. * @author mikael emtinger / http://gomo.se/
  13912. * @author alteredq / http://alteredqualia.com/
  13913. * @author mrdoob / http://mrdoob.com/
  13914. */
  13915. function LOD() {
  13916. Object3D.call( this );
  13917. this.type = 'LOD';
  13918. Object.defineProperties( this, {
  13919. levels: {
  13920. enumerable: true,
  13921. value: []
  13922. }
  13923. } );
  13924. }
  13925. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13926. constructor: LOD,
  13927. copy: function ( source ) {
  13928. Object3D.prototype.copy.call( this, source, false );
  13929. var levels = source.levels;
  13930. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13931. var level = levels[ i ];
  13932. this.addLevel( level.object.clone(), level.distance );
  13933. }
  13934. return this;
  13935. },
  13936. addLevel: function ( object, distance ) {
  13937. if ( distance === undefined ) distance = 0;
  13938. distance = Math.abs( distance );
  13939. var levels = this.levels;
  13940. for ( var l = 0; l < levels.length; l ++ ) {
  13941. if ( distance < levels[ l ].distance ) {
  13942. break;
  13943. }
  13944. }
  13945. levels.splice( l, 0, { distance: distance, object: object } );
  13946. this.add( object );
  13947. },
  13948. getObjectForDistance: function ( distance ) {
  13949. var levels = this.levels;
  13950. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13951. if ( distance < levels[ i ].distance ) {
  13952. break;
  13953. }
  13954. }
  13955. return levels[ i - 1 ].object;
  13956. },
  13957. raycast: ( function () {
  13958. var matrixPosition = new Vector3();
  13959. return function raycast( raycaster, intersects ) {
  13960. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13961. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13962. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13963. };
  13964. }() ),
  13965. update: function () {
  13966. var v1 = new Vector3();
  13967. var v2 = new Vector3();
  13968. return function update( camera ) {
  13969. var levels = this.levels;
  13970. if ( levels.length > 1 ) {
  13971. v1.setFromMatrixPosition( camera.matrixWorld );
  13972. v2.setFromMatrixPosition( this.matrixWorld );
  13973. var distance = v1.distanceTo( v2 );
  13974. levels[ 0 ].object.visible = true;
  13975. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13976. if ( distance >= levels[ i ].distance ) {
  13977. levels[ i - 1 ].object.visible = false;
  13978. levels[ i ].object.visible = true;
  13979. } else {
  13980. break;
  13981. }
  13982. }
  13983. for ( ; i < l; i ++ ) {
  13984. levels[ i ].object.visible = false;
  13985. }
  13986. }
  13987. };
  13988. }(),
  13989. toJSON: function ( meta ) {
  13990. var data = Object3D.prototype.toJSON.call( this, meta );
  13991. data.object.levels = [];
  13992. var levels = this.levels;
  13993. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13994. var level = levels[ i ];
  13995. data.object.levels.push( {
  13996. object: level.object.uuid,
  13997. distance: level.distance
  13998. } );
  13999. }
  14000. return data;
  14001. }
  14002. } );
  14003. /**
  14004. * @author mikael emtinger / http://gomo.se/
  14005. * @author alteredq / http://alteredqualia.com/
  14006. * @author michael guerrero / http://realitymeltdown.com
  14007. * @author ikerr / http://verold.com
  14008. */
  14009. function Skeleton( bones, boneInverses ) {
  14010. // copy the bone array
  14011. bones = bones || [];
  14012. this.bones = bones.slice( 0 );
  14013. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  14014. // use the supplied bone inverses or calculate the inverses
  14015. if ( boneInverses === undefined ) {
  14016. this.calculateInverses();
  14017. } else {
  14018. if ( this.bones.length === boneInverses.length ) {
  14019. this.boneInverses = boneInverses.slice( 0 );
  14020. } else {
  14021. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  14022. this.boneInverses = [];
  14023. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14024. this.boneInverses.push( new Matrix4() );
  14025. }
  14026. }
  14027. }
  14028. }
  14029. Object.assign( Skeleton.prototype, {
  14030. calculateInverses: function () {
  14031. this.boneInverses = [];
  14032. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14033. var inverse = new Matrix4();
  14034. if ( this.bones[ i ] ) {
  14035. inverse.getInverse( this.bones[ i ].matrixWorld );
  14036. }
  14037. this.boneInverses.push( inverse );
  14038. }
  14039. },
  14040. pose: function () {
  14041. var bone, i, il;
  14042. // recover the bind-time world matrices
  14043. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14044. bone = this.bones[ i ];
  14045. if ( bone ) {
  14046. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  14047. }
  14048. }
  14049. // compute the local matrices, positions, rotations and scales
  14050. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14051. bone = this.bones[ i ];
  14052. if ( bone ) {
  14053. if ( bone.parent && bone.parent.isBone ) {
  14054. bone.matrix.getInverse( bone.parent.matrixWorld );
  14055. bone.matrix.multiply( bone.matrixWorld );
  14056. } else {
  14057. bone.matrix.copy( bone.matrixWorld );
  14058. }
  14059. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14060. }
  14061. }
  14062. },
  14063. update: ( function () {
  14064. var offsetMatrix = new Matrix4();
  14065. var identityMatrix = new Matrix4();
  14066. return function update() {
  14067. var bones = this.bones;
  14068. var boneInverses = this.boneInverses;
  14069. var boneMatrices = this.boneMatrices;
  14070. var boneTexture = this.boneTexture;
  14071. // flatten bone matrices to array
  14072. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  14073. // compute the offset between the current and the original transform
  14074. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  14075. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14076. offsetMatrix.toArray( boneMatrices, i * 16 );
  14077. }
  14078. if ( boneTexture !== undefined ) {
  14079. boneTexture.needsUpdate = true;
  14080. }
  14081. };
  14082. } )(),
  14083. clone: function () {
  14084. return new Skeleton( this.bones, this.boneInverses );
  14085. }
  14086. } );
  14087. /**
  14088. * @author mikael emtinger / http://gomo.se/
  14089. * @author alteredq / http://alteredqualia.com/
  14090. * @author ikerr / http://verold.com
  14091. */
  14092. function Bone() {
  14093. Object3D.call( this );
  14094. this.type = 'Bone';
  14095. }
  14096. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14097. constructor: Bone,
  14098. isBone: true
  14099. } );
  14100. /**
  14101. * @author mikael emtinger / http://gomo.se/
  14102. * @author alteredq / http://alteredqualia.com/
  14103. * @author ikerr / http://verold.com
  14104. */
  14105. function SkinnedMesh( geometry, material ) {
  14106. Mesh.call( this, geometry, material );
  14107. this.type = 'SkinnedMesh';
  14108. this.bindMode = 'attached';
  14109. this.bindMatrix = new Matrix4();
  14110. this.bindMatrixInverse = new Matrix4();
  14111. var bones = this.initBones();
  14112. var skeleton = new Skeleton( bones );
  14113. this.bind( skeleton, this.matrixWorld );
  14114. this.normalizeSkinWeights();
  14115. }
  14116. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  14117. constructor: SkinnedMesh,
  14118. isSkinnedMesh: true,
  14119. initBones: function () {
  14120. var bones = [], bone, gbone;
  14121. var i, il;
  14122. if ( this.geometry && this.geometry.bones !== undefined ) {
  14123. // first, create array of 'Bone' objects from geometry data
  14124. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14125. gbone = this.geometry.bones[ i ];
  14126. // create new 'Bone' object
  14127. bone = new Bone();
  14128. bones.push( bone );
  14129. // apply values
  14130. bone.name = gbone.name;
  14131. bone.position.fromArray( gbone.pos );
  14132. bone.quaternion.fromArray( gbone.rotq );
  14133. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  14134. }
  14135. // second, create bone hierarchy
  14136. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14137. gbone = this.geometry.bones[ i ];
  14138. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  14139. // subsequent bones in the hierarchy
  14140. bones[ gbone.parent ].add( bones[ i ] );
  14141. } else {
  14142. // topmost bone, immediate child of the skinned mesh
  14143. this.add( bones[ i ] );
  14144. }
  14145. }
  14146. }
  14147. // now the bones are part of the scene graph and children of the skinned mesh.
  14148. // let's update the corresponding matrices
  14149. this.updateMatrixWorld( true );
  14150. return bones;
  14151. },
  14152. bind: function ( skeleton, bindMatrix ) {
  14153. this.skeleton = skeleton;
  14154. if ( bindMatrix === undefined ) {
  14155. this.updateMatrixWorld( true );
  14156. this.skeleton.calculateInverses();
  14157. bindMatrix = this.matrixWorld;
  14158. }
  14159. this.bindMatrix.copy( bindMatrix );
  14160. this.bindMatrixInverse.getInverse( bindMatrix );
  14161. },
  14162. pose: function () {
  14163. this.skeleton.pose();
  14164. },
  14165. normalizeSkinWeights: function () {
  14166. var scale, i;
  14167. if ( this.geometry && this.geometry.isGeometry ) {
  14168. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  14169. var sw = this.geometry.skinWeights[ i ];
  14170. scale = 1.0 / sw.lengthManhattan();
  14171. if ( scale !== Infinity ) {
  14172. sw.multiplyScalar( scale );
  14173. } else {
  14174. sw.set( 1, 0, 0, 0 ); // do something reasonable
  14175. }
  14176. }
  14177. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  14178. var vec = new Vector4();
  14179. var skinWeight = this.geometry.attributes.skinWeight;
  14180. for ( i = 0; i < skinWeight.count; i ++ ) {
  14181. vec.x = skinWeight.getX( i );
  14182. vec.y = skinWeight.getY( i );
  14183. vec.z = skinWeight.getZ( i );
  14184. vec.w = skinWeight.getW( i );
  14185. scale = 1.0 / vec.lengthManhattan();
  14186. if ( scale !== Infinity ) {
  14187. vec.multiplyScalar( scale );
  14188. } else {
  14189. vec.set( 1, 0, 0, 0 ); // do something reasonable
  14190. }
  14191. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  14192. }
  14193. }
  14194. },
  14195. updateMatrixWorld: function ( force ) {
  14196. Mesh.prototype.updateMatrixWorld.call( this, force );
  14197. if ( this.bindMode === 'attached' ) {
  14198. this.bindMatrixInverse.getInverse( this.matrixWorld );
  14199. } else if ( this.bindMode === 'detached' ) {
  14200. this.bindMatrixInverse.getInverse( this.bindMatrix );
  14201. } else {
  14202. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14203. }
  14204. },
  14205. clone: function () {
  14206. return new this.constructor( this.geometry, this.material ).copy( this );
  14207. }
  14208. } );
  14209. /**
  14210. * @author mrdoob / http://mrdoob.com/
  14211. * @author alteredq / http://alteredqualia.com/
  14212. *
  14213. * parameters = {
  14214. * color: <hex>,
  14215. * opacity: <float>,
  14216. *
  14217. * linewidth: <float>,
  14218. * linecap: "round",
  14219. * linejoin: "round"
  14220. * }
  14221. */
  14222. function LineBasicMaterial( parameters ) {
  14223. Material.call( this );
  14224. this.type = 'LineBasicMaterial';
  14225. this.color = new Color( 0xffffff );
  14226. this.linewidth = 1;
  14227. this.linecap = 'round';
  14228. this.linejoin = 'round';
  14229. this.lights = false;
  14230. this.setValues( parameters );
  14231. }
  14232. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14233. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14234. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14235. LineBasicMaterial.prototype.copy = function ( source ) {
  14236. Material.prototype.copy.call( this, source );
  14237. this.color.copy( source.color );
  14238. this.linewidth = source.linewidth;
  14239. this.linecap = source.linecap;
  14240. this.linejoin = source.linejoin;
  14241. return this;
  14242. };
  14243. /**
  14244. * @author mrdoob / http://mrdoob.com/
  14245. */
  14246. function Line( geometry, material, mode ) {
  14247. if ( mode === 1 ) {
  14248. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14249. return new LineSegments( geometry, material );
  14250. }
  14251. Object3D.call( this );
  14252. this.type = 'Line';
  14253. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14254. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14255. }
  14256. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14257. constructor: Line,
  14258. isLine: true,
  14259. raycast: ( function () {
  14260. var inverseMatrix = new Matrix4();
  14261. var ray = new Ray();
  14262. var sphere = new Sphere();
  14263. return function raycast( raycaster, intersects ) {
  14264. var precision = raycaster.linePrecision;
  14265. var precisionSq = precision * precision;
  14266. var geometry = this.geometry;
  14267. var matrixWorld = this.matrixWorld;
  14268. // Checking boundingSphere distance to ray
  14269. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14270. sphere.copy( geometry.boundingSphere );
  14271. sphere.applyMatrix4( matrixWorld );
  14272. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14273. //
  14274. inverseMatrix.getInverse( matrixWorld );
  14275. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14276. var vStart = new Vector3();
  14277. var vEnd = new Vector3();
  14278. var interSegment = new Vector3();
  14279. var interRay = new Vector3();
  14280. var step = (this && this.isLineSegments) ? 2 : 1;
  14281. if ( geometry.isBufferGeometry ) {
  14282. var index = geometry.index;
  14283. var attributes = geometry.attributes;
  14284. var positions = attributes.position.array;
  14285. if ( index !== null ) {
  14286. var indices = index.array;
  14287. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14288. var a = indices[ i ];
  14289. var b = indices[ i + 1 ];
  14290. vStart.fromArray( positions, a * 3 );
  14291. vEnd.fromArray( positions, b * 3 );
  14292. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14293. if ( distSq > precisionSq ) continue;
  14294. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14295. var distance = raycaster.ray.origin.distanceTo( interRay );
  14296. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14297. intersects.push( {
  14298. distance: distance,
  14299. // What do we want? intersection point on the ray or on the segment??
  14300. // point: raycaster.ray.at( distance ),
  14301. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14302. index: i,
  14303. face: null,
  14304. faceIndex: null,
  14305. object: this
  14306. } );
  14307. }
  14308. } else {
  14309. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14310. vStart.fromArray( positions, 3 * i );
  14311. vEnd.fromArray( positions, 3 * i + 3 );
  14312. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14313. if ( distSq > precisionSq ) continue;
  14314. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14315. var distance = raycaster.ray.origin.distanceTo( interRay );
  14316. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14317. intersects.push( {
  14318. distance: distance,
  14319. // What do we want? intersection point on the ray or on the segment??
  14320. // point: raycaster.ray.at( distance ),
  14321. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14322. index: i,
  14323. face: null,
  14324. faceIndex: null,
  14325. object: this
  14326. } );
  14327. }
  14328. }
  14329. } else if ( geometry.isGeometry ) {
  14330. var vertices = geometry.vertices;
  14331. var nbVertices = vertices.length;
  14332. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14333. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14334. if ( distSq > precisionSq ) continue;
  14335. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14336. var distance = raycaster.ray.origin.distanceTo( interRay );
  14337. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14338. intersects.push( {
  14339. distance: distance,
  14340. // What do we want? intersection point on the ray or on the segment??
  14341. // point: raycaster.ray.at( distance ),
  14342. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14343. index: i,
  14344. face: null,
  14345. faceIndex: null,
  14346. object: this
  14347. } );
  14348. }
  14349. }
  14350. };
  14351. }() ),
  14352. clone: function () {
  14353. return new this.constructor( this.geometry, this.material ).copy( this );
  14354. }
  14355. } );
  14356. /**
  14357. * @author mrdoob / http://mrdoob.com/
  14358. */
  14359. function LineSegments( geometry, material ) {
  14360. Line.call( this, geometry, material );
  14361. this.type = 'LineSegments';
  14362. }
  14363. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14364. constructor: LineSegments,
  14365. isLineSegments: true
  14366. } );
  14367. /**
  14368. * @author mgreter / http://github.com/mgreter
  14369. */
  14370. function LineLoop( geometry, material ) {
  14371. Line.call( this, geometry, material );
  14372. this.type = 'LineLoop';
  14373. }
  14374. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14375. constructor: LineLoop,
  14376. isLineLoop: true,
  14377. } );
  14378. /**
  14379. * @author mrdoob / http://mrdoob.com/
  14380. * @author alteredq / http://alteredqualia.com/
  14381. *
  14382. * parameters = {
  14383. * color: <hex>,
  14384. * opacity: <float>,
  14385. * map: new THREE.Texture( <Image> ),
  14386. *
  14387. * size: <float>,
  14388. * sizeAttenuation: <bool>
  14389. * }
  14390. */
  14391. function PointsMaterial( parameters ) {
  14392. Material.call( this );
  14393. this.type = 'PointsMaterial';
  14394. this.color = new Color( 0xffffff );
  14395. this.map = null;
  14396. this.size = 1;
  14397. this.sizeAttenuation = true;
  14398. this.lights = false;
  14399. this.setValues( parameters );
  14400. }
  14401. PointsMaterial.prototype = Object.create( Material.prototype );
  14402. PointsMaterial.prototype.constructor = PointsMaterial;
  14403. PointsMaterial.prototype.isPointsMaterial = true;
  14404. PointsMaterial.prototype.copy = function ( source ) {
  14405. Material.prototype.copy.call( this, source );
  14406. this.color.copy( source.color );
  14407. this.map = source.map;
  14408. this.size = source.size;
  14409. this.sizeAttenuation = source.sizeAttenuation;
  14410. return this;
  14411. };
  14412. /**
  14413. * @author alteredq / http://alteredqualia.com/
  14414. */
  14415. function Points( geometry, material ) {
  14416. Object3D.call( this );
  14417. this.type = 'Points';
  14418. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14419. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14420. }
  14421. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14422. constructor: Points,
  14423. isPoints: true,
  14424. raycast: ( function () {
  14425. var inverseMatrix = new Matrix4();
  14426. var ray = new Ray();
  14427. var sphere = new Sphere();
  14428. return function raycast( raycaster, intersects ) {
  14429. var object = this;
  14430. var geometry = this.geometry;
  14431. var matrixWorld = this.matrixWorld;
  14432. var threshold = raycaster.params.Points.threshold;
  14433. // Checking boundingSphere distance to ray
  14434. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14435. sphere.copy( geometry.boundingSphere );
  14436. sphere.applyMatrix4( matrixWorld );
  14437. sphere.radius += threshold;
  14438. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14439. //
  14440. inverseMatrix.getInverse( matrixWorld );
  14441. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14442. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14443. var localThresholdSq = localThreshold * localThreshold;
  14444. var position = new Vector3();
  14445. function testPoint( point, index ) {
  14446. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14447. if ( rayPointDistanceSq < localThresholdSq ) {
  14448. var intersectPoint = ray.closestPointToPoint( point );
  14449. intersectPoint.applyMatrix4( matrixWorld );
  14450. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14451. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14452. intersects.push( {
  14453. distance: distance,
  14454. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14455. point: intersectPoint.clone(),
  14456. index: index,
  14457. face: null,
  14458. object: object
  14459. } );
  14460. }
  14461. }
  14462. if ( geometry.isBufferGeometry ) {
  14463. var index = geometry.index;
  14464. var attributes = geometry.attributes;
  14465. var positions = attributes.position.array;
  14466. if ( index !== null ) {
  14467. var indices = index.array;
  14468. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14469. var a = indices[ i ];
  14470. position.fromArray( positions, a * 3 );
  14471. testPoint( position, a );
  14472. }
  14473. } else {
  14474. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14475. position.fromArray( positions, i * 3 );
  14476. testPoint( position, i );
  14477. }
  14478. }
  14479. } else {
  14480. var vertices = geometry.vertices;
  14481. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14482. testPoint( vertices[ i ], i );
  14483. }
  14484. }
  14485. };
  14486. }() ),
  14487. clone: function () {
  14488. return new this.constructor( this.geometry, this.material ).copy( this );
  14489. }
  14490. } );
  14491. /**
  14492. * @author mrdoob / http://mrdoob.com/
  14493. */
  14494. function Group() {
  14495. Object3D.call( this );
  14496. this.type = 'Group';
  14497. }
  14498. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14499. constructor: Group
  14500. } );
  14501. /**
  14502. * @author mrdoob / http://mrdoob.com/
  14503. */
  14504. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14505. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14506. this.generateMipmaps = false;
  14507. var scope = this;
  14508. function update() {
  14509. requestAnimationFrame( update );
  14510. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14511. scope.needsUpdate = true;
  14512. }
  14513. }
  14514. update();
  14515. }
  14516. VideoTexture.prototype = Object.create( Texture.prototype );
  14517. VideoTexture.prototype.constructor = VideoTexture;
  14518. /**
  14519. * @author alteredq / http://alteredqualia.com/
  14520. */
  14521. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14522. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14523. this.image = { width: width, height: height };
  14524. this.mipmaps = mipmaps;
  14525. // no flipping for cube textures
  14526. // (also flipping doesn't work for compressed textures )
  14527. this.flipY = false;
  14528. // can't generate mipmaps for compressed textures
  14529. // mips must be embedded in DDS files
  14530. this.generateMipmaps = false;
  14531. }
  14532. CompressedTexture.prototype = Object.create( Texture.prototype );
  14533. CompressedTexture.prototype.constructor = CompressedTexture;
  14534. CompressedTexture.prototype.isCompressedTexture = true;
  14535. /**
  14536. * @author mrdoob / http://mrdoob.com/
  14537. */
  14538. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14539. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14540. this.needsUpdate = true;
  14541. }
  14542. CanvasTexture.prototype = Object.create( Texture.prototype );
  14543. CanvasTexture.prototype.constructor = CanvasTexture;
  14544. /**
  14545. * @author Matt DesLauriers / @mattdesl
  14546. * @author atix / arthursilber.de
  14547. */
  14548. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14549. format = format !== undefined ? format : DepthFormat;
  14550. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14551. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14552. }
  14553. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14554. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14555. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14556. this.image = { width: width, height: height };
  14557. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14558. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14559. this.flipY = false;
  14560. this.generateMipmaps = false;
  14561. }
  14562. DepthTexture.prototype = Object.create( Texture.prototype );
  14563. DepthTexture.prototype.constructor = DepthTexture;
  14564. DepthTexture.prototype.isDepthTexture = true;
  14565. /**
  14566. * @author mrdoob / http://mrdoob.com/
  14567. * @author Mugen87 / https://github.com/Mugen87
  14568. */
  14569. function WireframeGeometry( geometry ) {
  14570. BufferGeometry.call( this );
  14571. this.type = 'WireframeGeometry';
  14572. // buffer
  14573. var vertices = [];
  14574. // helper variables
  14575. var i, j, l, o, ol;
  14576. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14577. var key, keys = [ 'a', 'b', 'c' ];
  14578. var vertex;
  14579. // different logic for Geometry and BufferGeometry
  14580. if ( geometry && geometry.isGeometry ) {
  14581. // create a data structure that contains all edges without duplicates
  14582. var faces = geometry.faces;
  14583. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14584. var face = faces[ i ];
  14585. for ( j = 0; j < 3; j ++ ) {
  14586. edge1 = face[ keys[ j ] ];
  14587. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14588. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14589. edge[ 1 ] = Math.max( edge1, edge2 );
  14590. key = edge[ 0 ] + ',' + edge[ 1 ];
  14591. if ( edges[ key ] === undefined ) {
  14592. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14593. }
  14594. }
  14595. }
  14596. // generate vertices
  14597. for ( key in edges ) {
  14598. e = edges[ key ];
  14599. vertex = geometry.vertices[ e.index1 ];
  14600. vertices.push( vertex.x, vertex.y, vertex.z );
  14601. vertex = geometry.vertices[ e.index2 ];
  14602. vertices.push( vertex.x, vertex.y, vertex.z );
  14603. }
  14604. } else if ( geometry && geometry.isBufferGeometry ) {
  14605. var position, indices, groups;
  14606. var group, start, count;
  14607. var index1, index2;
  14608. vertex = new Vector3();
  14609. if ( geometry.index !== null ) {
  14610. // indexed BufferGeometry
  14611. position = geometry.attributes.position;
  14612. indices = geometry.index;
  14613. groups = geometry.groups;
  14614. if ( groups.length === 0 ) {
  14615. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14616. }
  14617. // create a data structure that contains all eges without duplicates
  14618. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14619. group = groups[ o ];
  14620. start = group.start;
  14621. count = group.count;
  14622. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14623. for ( j = 0; j < 3; j ++ ) {
  14624. edge1 = indices.getX( i + j );
  14625. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14626. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14627. edge[ 1 ] = Math.max( edge1, edge2 );
  14628. key = edge[ 0 ] + ',' + edge[ 1 ];
  14629. if ( edges[ key ] === undefined ) {
  14630. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14631. }
  14632. }
  14633. }
  14634. }
  14635. // generate vertices
  14636. for ( key in edges ) {
  14637. e = edges[ key ];
  14638. vertex.fromBufferAttribute( position, e.index1 );
  14639. vertices.push( vertex.x, vertex.y, vertex.z );
  14640. vertex.fromBufferAttribute( position, e.index2 );
  14641. vertices.push( vertex.x, vertex.y, vertex.z );
  14642. }
  14643. } else {
  14644. // non-indexed BufferGeometry
  14645. position = geometry.attributes.position;
  14646. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14647. for ( j = 0; j < 3; j ++ ) {
  14648. // three edges per triangle, an edge is represented as (index1, index2)
  14649. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14650. index1 = 3 * i + j;
  14651. vertex.fromBufferAttribute( position, index1 );
  14652. vertices.push( vertex.x, vertex.y, vertex.z );
  14653. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14654. vertex.fromBufferAttribute( position, index2 );
  14655. vertices.push( vertex.x, vertex.y, vertex.z );
  14656. }
  14657. }
  14658. }
  14659. }
  14660. // build geometry
  14661. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14662. }
  14663. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14664. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14665. /**
  14666. * @author zz85 / https://github.com/zz85
  14667. * @author Mugen87 / https://github.com/Mugen87
  14668. *
  14669. * Parametric Surfaces Geometry
  14670. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14671. */
  14672. // ParametricGeometry
  14673. function ParametricGeometry( func, slices, stacks ) {
  14674. Geometry.call( this );
  14675. this.type = 'ParametricGeometry';
  14676. this.parameters = {
  14677. func: func,
  14678. slices: slices,
  14679. stacks: stacks
  14680. };
  14681. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14682. this.mergeVertices();
  14683. }
  14684. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14685. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14686. // ParametricBufferGeometry
  14687. function ParametricBufferGeometry( func, slices, stacks ) {
  14688. BufferGeometry.call( this );
  14689. this.type = 'ParametricBufferGeometry';
  14690. this.parameters = {
  14691. func: func,
  14692. slices: slices,
  14693. stacks: stacks
  14694. };
  14695. // buffers
  14696. var indices = [];
  14697. var vertices = [];
  14698. var normals = [];
  14699. var uvs = [];
  14700. var EPS = 0.00001;
  14701. var normal = new Vector3();
  14702. var p0 = new Vector3(), p1 = new Vector3();
  14703. var pu = new Vector3(), pv = new Vector3();
  14704. var i, j;
  14705. // generate vertices, normals and uvs
  14706. var sliceCount = slices + 1;
  14707. for ( i = 0; i <= stacks; i ++ ) {
  14708. var v = i / stacks;
  14709. for ( j = 0; j <= slices; j ++ ) {
  14710. var u = j / slices;
  14711. // vertex
  14712. p0 = func( u, v, p0 );
  14713. vertices.push( p0.x, p0.y, p0.z );
  14714. // normal
  14715. // approximate tangent vectors via finite differences
  14716. if ( u - EPS >= 0 ) {
  14717. p1 = func( u - EPS, v, p1 );
  14718. pu.subVectors( p0, p1 );
  14719. } else {
  14720. p1 = func( u + EPS, v, p1 );
  14721. pu.subVectors( p1, p0 );
  14722. }
  14723. if ( v - EPS >= 0 ) {
  14724. p1 = func( u, v - EPS, p1 );
  14725. pv.subVectors( p0, p1 );
  14726. } else {
  14727. p1 = func( u, v + EPS, p1 );
  14728. pv.subVectors( p1, p0 );
  14729. }
  14730. // cross product of tangent vectors returns surface normal
  14731. normal.crossVectors( pu, pv ).normalize();
  14732. normals.push( normal.x, normal.y, normal.z );
  14733. // uv
  14734. uvs.push( u, v );
  14735. }
  14736. }
  14737. // generate indices
  14738. for ( i = 0; i < stacks; i ++ ) {
  14739. for ( j = 0; j < slices; j ++ ) {
  14740. var a = i * sliceCount + j;
  14741. var b = i * sliceCount + j + 1;
  14742. var c = ( i + 1 ) * sliceCount + j + 1;
  14743. var d = ( i + 1 ) * sliceCount + j;
  14744. // faces one and two
  14745. indices.push( a, b, d );
  14746. indices.push( b, c, d );
  14747. }
  14748. }
  14749. // build geometry
  14750. this.setIndex( indices );
  14751. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14752. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14753. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14754. }
  14755. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14756. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14757. /**
  14758. * @author clockworkgeek / https://github.com/clockworkgeek
  14759. * @author timothypratley / https://github.com/timothypratley
  14760. * @author WestLangley / http://github.com/WestLangley
  14761. * @author Mugen87 / https://github.com/Mugen87
  14762. */
  14763. // PolyhedronGeometry
  14764. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14765. Geometry.call( this );
  14766. this.type = 'PolyhedronGeometry';
  14767. this.parameters = {
  14768. vertices: vertices,
  14769. indices: indices,
  14770. radius: radius,
  14771. detail: detail
  14772. };
  14773. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14774. this.mergeVertices();
  14775. }
  14776. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14777. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14778. // PolyhedronBufferGeometry
  14779. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14780. BufferGeometry.call( this );
  14781. this.type = 'PolyhedronBufferGeometry';
  14782. this.parameters = {
  14783. vertices: vertices,
  14784. indices: indices,
  14785. radius: radius,
  14786. detail: detail
  14787. };
  14788. radius = radius || 1;
  14789. detail = detail || 0;
  14790. // default buffer data
  14791. var vertexBuffer = [];
  14792. var uvBuffer = [];
  14793. // the subdivision creates the vertex buffer data
  14794. subdivide( detail );
  14795. // all vertices should lie on a conceptual sphere with a given radius
  14796. appplyRadius( radius );
  14797. // finally, create the uv data
  14798. generateUVs();
  14799. // build non-indexed geometry
  14800. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14801. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14802. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14803. if ( detail === 0 ) {
  14804. this.computeVertexNormals(); // flat normals
  14805. } else {
  14806. this.normalizeNormals(); // smooth normals
  14807. }
  14808. // helper functions
  14809. function subdivide( detail ) {
  14810. var a = new Vector3();
  14811. var b = new Vector3();
  14812. var c = new Vector3();
  14813. // iterate over all faces and apply a subdivison with the given detail value
  14814. for ( var i = 0; i < indices.length; i += 3 ) {
  14815. // get the vertices of the face
  14816. getVertexByIndex( indices[ i + 0 ], a );
  14817. getVertexByIndex( indices[ i + 1 ], b );
  14818. getVertexByIndex( indices[ i + 2 ], c );
  14819. // perform subdivision
  14820. subdivideFace( a, b, c, detail );
  14821. }
  14822. }
  14823. function subdivideFace( a, b, c, detail ) {
  14824. var cols = Math.pow( 2, detail );
  14825. // we use this multidimensional array as a data structure for creating the subdivision
  14826. var v = [];
  14827. var i, j;
  14828. // construct all of the vertices for this subdivision
  14829. for ( i = 0; i <= cols; i ++ ) {
  14830. v[ i ] = [];
  14831. var aj = a.clone().lerp( c, i / cols );
  14832. var bj = b.clone().lerp( c, i / cols );
  14833. var rows = cols - i;
  14834. for ( j = 0; j <= rows; j ++ ) {
  14835. if ( j === 0 && i === cols ) {
  14836. v[ i ][ j ] = aj;
  14837. } else {
  14838. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14839. }
  14840. }
  14841. }
  14842. // construct all of the faces
  14843. for ( i = 0; i < cols; i ++ ) {
  14844. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14845. var k = Math.floor( j / 2 );
  14846. if ( j % 2 === 0 ) {
  14847. pushVertex( v[ i ][ k + 1 ] );
  14848. pushVertex( v[ i + 1 ][ k ] );
  14849. pushVertex( v[ i ][ k ] );
  14850. } else {
  14851. pushVertex( v[ i ][ k + 1 ] );
  14852. pushVertex( v[ i + 1 ][ k + 1 ] );
  14853. pushVertex( v[ i + 1 ][ k ] );
  14854. }
  14855. }
  14856. }
  14857. }
  14858. function appplyRadius( radius ) {
  14859. var vertex = new Vector3();
  14860. // iterate over the entire buffer and apply the radius to each vertex
  14861. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14862. vertex.x = vertexBuffer[ i + 0 ];
  14863. vertex.y = vertexBuffer[ i + 1 ];
  14864. vertex.z = vertexBuffer[ i + 2 ];
  14865. vertex.normalize().multiplyScalar( radius );
  14866. vertexBuffer[ i + 0 ] = vertex.x;
  14867. vertexBuffer[ i + 1 ] = vertex.y;
  14868. vertexBuffer[ i + 2 ] = vertex.z;
  14869. }
  14870. }
  14871. function generateUVs() {
  14872. var vertex = new Vector3();
  14873. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14874. vertex.x = vertexBuffer[ i + 0 ];
  14875. vertex.y = vertexBuffer[ i + 1 ];
  14876. vertex.z = vertexBuffer[ i + 2 ];
  14877. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14878. var v = inclination( vertex ) / Math.PI + 0.5;
  14879. uvBuffer.push( u, 1 - v );
  14880. }
  14881. correctUVs();
  14882. correctSeam();
  14883. }
  14884. function correctSeam() {
  14885. // handle case when face straddles the seam, see #3269
  14886. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14887. // uv data of a single face
  14888. var x0 = uvBuffer[ i + 0 ];
  14889. var x1 = uvBuffer[ i + 2 ];
  14890. var x2 = uvBuffer[ i + 4 ];
  14891. var max = Math.max( x0, x1, x2 );
  14892. var min = Math.min( x0, x1, x2 );
  14893. // 0.9 is somewhat arbitrary
  14894. if ( max > 0.9 && min < 0.1 ) {
  14895. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14896. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14897. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14898. }
  14899. }
  14900. }
  14901. function pushVertex( vertex ) {
  14902. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14903. }
  14904. function getVertexByIndex( index, vertex ) {
  14905. var stride = index * 3;
  14906. vertex.x = vertices[ stride + 0 ];
  14907. vertex.y = vertices[ stride + 1 ];
  14908. vertex.z = vertices[ stride + 2 ];
  14909. }
  14910. function correctUVs() {
  14911. var a = new Vector3();
  14912. var b = new Vector3();
  14913. var c = new Vector3();
  14914. var centroid = new Vector3();
  14915. var uvA = new Vector2();
  14916. var uvB = new Vector2();
  14917. var uvC = new Vector2();
  14918. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14919. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14920. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14921. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14922. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14923. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14924. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14925. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14926. var azi = azimuth( centroid );
  14927. correctUV( uvA, j + 0, a, azi );
  14928. correctUV( uvB, j + 2, b, azi );
  14929. correctUV( uvC, j + 4, c, azi );
  14930. }
  14931. }
  14932. function correctUV( uv, stride, vector, azimuth ) {
  14933. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14934. uvBuffer[ stride ] = uv.x - 1;
  14935. }
  14936. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14937. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14938. }
  14939. }
  14940. // Angle around the Y axis, counter-clockwise when looking from above.
  14941. function azimuth( vector ) {
  14942. return Math.atan2( vector.z, - vector.x );
  14943. }
  14944. // Angle above the XZ plane.
  14945. function inclination( vector ) {
  14946. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14947. }
  14948. }
  14949. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14950. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14951. /**
  14952. * @author timothypratley / https://github.com/timothypratley
  14953. * @author Mugen87 / https://github.com/Mugen87
  14954. */
  14955. // TetrahedronGeometry
  14956. function TetrahedronGeometry( radius, detail ) {
  14957. Geometry.call( this );
  14958. this.type = 'TetrahedronGeometry';
  14959. this.parameters = {
  14960. radius: radius,
  14961. detail: detail
  14962. };
  14963. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14964. this.mergeVertices();
  14965. }
  14966. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14967. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14968. // TetrahedronBufferGeometry
  14969. function TetrahedronBufferGeometry( radius, detail ) {
  14970. var vertices = [
  14971. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14972. ];
  14973. var indices = [
  14974. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14975. ];
  14976. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14977. this.type = 'TetrahedronBufferGeometry';
  14978. this.parameters = {
  14979. radius: radius,
  14980. detail: detail
  14981. };
  14982. }
  14983. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14984. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14985. /**
  14986. * @author timothypratley / https://github.com/timothypratley
  14987. * @author Mugen87 / https://github.com/Mugen87
  14988. */
  14989. // OctahedronGeometry
  14990. function OctahedronGeometry( radius, detail ) {
  14991. Geometry.call( this );
  14992. this.type = 'OctahedronGeometry';
  14993. this.parameters = {
  14994. radius: radius,
  14995. detail: detail
  14996. };
  14997. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14998. this.mergeVertices();
  14999. }
  15000. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  15001. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  15002. // OctahedronBufferGeometry
  15003. function OctahedronBufferGeometry( radius, detail ) {
  15004. var vertices = [
  15005. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  15006. ];
  15007. var indices = [
  15008. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  15009. ];
  15010. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15011. this.type = 'OctahedronBufferGeometry';
  15012. this.parameters = {
  15013. radius: radius,
  15014. detail: detail
  15015. };
  15016. }
  15017. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15018. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  15019. /**
  15020. * @author timothypratley / https://github.com/timothypratley
  15021. * @author Mugen87 / https://github.com/Mugen87
  15022. */
  15023. // IcosahedronGeometry
  15024. function IcosahedronGeometry( radius, detail ) {
  15025. Geometry.call( this );
  15026. this.type = 'IcosahedronGeometry';
  15027. this.parameters = {
  15028. radius: radius,
  15029. detail: detail
  15030. };
  15031. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  15032. this.mergeVertices();
  15033. }
  15034. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  15035. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  15036. // IcosahedronBufferGeometry
  15037. function IcosahedronBufferGeometry( radius, detail ) {
  15038. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15039. var vertices = [
  15040. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  15041. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  15042. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  15043. ];
  15044. var indices = [
  15045. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15046. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15047. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15048. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15049. ];
  15050. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15051. this.type = 'IcosahedronBufferGeometry';
  15052. this.parameters = {
  15053. radius: radius,
  15054. detail: detail
  15055. };
  15056. }
  15057. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15058. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  15059. /**
  15060. * @author Abe Pazos / https://hamoid.com
  15061. * @author Mugen87 / https://github.com/Mugen87
  15062. */
  15063. // DodecahedronGeometry
  15064. function DodecahedronGeometry( radius, detail ) {
  15065. Geometry.call( this );
  15066. this.type = 'DodecahedronGeometry';
  15067. this.parameters = {
  15068. radius: radius,
  15069. detail: detail
  15070. };
  15071. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  15072. this.mergeVertices();
  15073. }
  15074. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  15075. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  15076. // DodecahedronBufferGeometry
  15077. function DodecahedronBufferGeometry( radius, detail ) {
  15078. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15079. var r = 1 / t;
  15080. var vertices = [
  15081. // (±1, ±1, ±1)
  15082. - 1, - 1, - 1, - 1, - 1, 1,
  15083. - 1, 1, - 1, - 1, 1, 1,
  15084. 1, - 1, - 1, 1, - 1, 1,
  15085. 1, 1, - 1, 1, 1, 1,
  15086. // (0, ±1/φ, ±φ)
  15087. 0, - r, - t, 0, - r, t,
  15088. 0, r, - t, 0, r, t,
  15089. // (±1/φ, ±φ, 0)
  15090. - r, - t, 0, - r, t, 0,
  15091. r, - t, 0, r, t, 0,
  15092. // (±φ, 0, ±1/φ)
  15093. - t, 0, - r, t, 0, - r,
  15094. - t, 0, r, t, 0, r
  15095. ];
  15096. var indices = [
  15097. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  15098. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  15099. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  15100. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  15101. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  15102. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  15103. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  15104. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  15105. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  15106. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  15107. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  15108. 1, 12, 14, 1, 14, 5, 1, 5, 9
  15109. ];
  15110. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15111. this.type = 'DodecahedronBufferGeometry';
  15112. this.parameters = {
  15113. radius: radius,
  15114. detail: detail
  15115. };
  15116. }
  15117. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15118. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  15119. /**
  15120. * @author oosmoxiecode / https://github.com/oosmoxiecode
  15121. * @author WestLangley / https://github.com/WestLangley
  15122. * @author zz85 / https://github.com/zz85
  15123. * @author miningold / https://github.com/miningold
  15124. * @author jonobr1 / https://github.com/jonobr1
  15125. * @author Mugen87 / https://github.com/Mugen87
  15126. *
  15127. */
  15128. // TubeGeometry
  15129. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  15130. Geometry.call( this );
  15131. this.type = 'TubeGeometry';
  15132. this.parameters = {
  15133. path: path,
  15134. tubularSegments: tubularSegments,
  15135. radius: radius,
  15136. radialSegments: radialSegments,
  15137. closed: closed
  15138. };
  15139. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  15140. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  15141. // expose internals
  15142. this.tangents = bufferGeometry.tangents;
  15143. this.normals = bufferGeometry.normals;
  15144. this.binormals = bufferGeometry.binormals;
  15145. // create geometry
  15146. this.fromBufferGeometry( bufferGeometry );
  15147. this.mergeVertices();
  15148. }
  15149. TubeGeometry.prototype = Object.create( Geometry.prototype );
  15150. TubeGeometry.prototype.constructor = TubeGeometry;
  15151. // TubeBufferGeometry
  15152. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  15153. BufferGeometry.call( this );
  15154. this.type = 'TubeBufferGeometry';
  15155. this.parameters = {
  15156. path: path,
  15157. tubularSegments: tubularSegments,
  15158. radius: radius,
  15159. radialSegments: radialSegments,
  15160. closed: closed
  15161. };
  15162. tubularSegments = tubularSegments || 64;
  15163. radius = radius || 1;
  15164. radialSegments = radialSegments || 8;
  15165. closed = closed || false;
  15166. var frames = path.computeFrenetFrames( tubularSegments, closed );
  15167. // expose internals
  15168. this.tangents = frames.tangents;
  15169. this.normals = frames.normals;
  15170. this.binormals = frames.binormals;
  15171. // helper variables
  15172. var vertex = new Vector3();
  15173. var normal = new Vector3();
  15174. var uv = new Vector2();
  15175. var i, j;
  15176. // buffer
  15177. var vertices = [];
  15178. var normals = [];
  15179. var uvs = [];
  15180. var indices = [];
  15181. // create buffer data
  15182. generateBufferData();
  15183. // build geometry
  15184. this.setIndex( indices );
  15185. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15186. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15187. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15188. // functions
  15189. function generateBufferData() {
  15190. for ( i = 0; i < tubularSegments; i ++ ) {
  15191. generateSegment( i );
  15192. }
  15193. // if the geometry is not closed, generate the last row of vertices and normals
  15194. // at the regular position on the given path
  15195. //
  15196. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15197. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15198. // uvs are generated in a separate function.
  15199. // this makes it easy compute correct values for closed geometries
  15200. generateUVs();
  15201. // finally create faces
  15202. generateIndices();
  15203. }
  15204. function generateSegment( i ) {
  15205. // we use getPointAt to sample evenly distributed points from the given path
  15206. var P = path.getPointAt( i / tubularSegments );
  15207. // retrieve corresponding normal and binormal
  15208. var N = frames.normals[ i ];
  15209. var B = frames.binormals[ i ];
  15210. // generate normals and vertices for the current segment
  15211. for ( j = 0; j <= radialSegments; j ++ ) {
  15212. var v = j / radialSegments * Math.PI * 2;
  15213. var sin = Math.sin( v );
  15214. var cos = - Math.cos( v );
  15215. // normal
  15216. normal.x = ( cos * N.x + sin * B.x );
  15217. normal.y = ( cos * N.y + sin * B.y );
  15218. normal.z = ( cos * N.z + sin * B.z );
  15219. normal.normalize();
  15220. normals.push( normal.x, normal.y, normal.z );
  15221. // vertex
  15222. vertex.x = P.x + radius * normal.x;
  15223. vertex.y = P.y + radius * normal.y;
  15224. vertex.z = P.z + radius * normal.z;
  15225. vertices.push( vertex.x, vertex.y, vertex.z );
  15226. }
  15227. }
  15228. function generateIndices() {
  15229. for ( j = 1; j <= tubularSegments; j ++ ) {
  15230. for ( i = 1; i <= radialSegments; i ++ ) {
  15231. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15232. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15233. var c = ( radialSegments + 1 ) * j + i;
  15234. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15235. // faces
  15236. indices.push( a, b, d );
  15237. indices.push( b, c, d );
  15238. }
  15239. }
  15240. }
  15241. function generateUVs() {
  15242. for ( i = 0; i <= tubularSegments; i ++ ) {
  15243. for ( j = 0; j <= radialSegments; j ++ ) {
  15244. uv.x = i / tubularSegments;
  15245. uv.y = j / radialSegments;
  15246. uvs.push( uv.x, uv.y );
  15247. }
  15248. }
  15249. }
  15250. }
  15251. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15252. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15253. /**
  15254. * @author oosmoxiecode
  15255. * @author Mugen87 / https://github.com/Mugen87
  15256. *
  15257. * based on http://www.blackpawn.com/texts/pqtorus/
  15258. */
  15259. // TorusKnotGeometry
  15260. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15261. Geometry.call( this );
  15262. this.type = 'TorusKnotGeometry';
  15263. this.parameters = {
  15264. radius: radius,
  15265. tube: tube,
  15266. tubularSegments: tubularSegments,
  15267. radialSegments: radialSegments,
  15268. p: p,
  15269. q: q
  15270. };
  15271. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15272. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15273. this.mergeVertices();
  15274. }
  15275. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15276. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15277. // TorusKnotBufferGeometry
  15278. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15279. BufferGeometry.call( this );
  15280. this.type = 'TorusKnotBufferGeometry';
  15281. this.parameters = {
  15282. radius: radius,
  15283. tube: tube,
  15284. tubularSegments: tubularSegments,
  15285. radialSegments: radialSegments,
  15286. p: p,
  15287. q: q
  15288. };
  15289. radius = radius || 100;
  15290. tube = tube || 40;
  15291. tubularSegments = Math.floor( tubularSegments ) || 64;
  15292. radialSegments = Math.floor( radialSegments ) || 8;
  15293. p = p || 2;
  15294. q = q || 3;
  15295. // buffers
  15296. var indices = [];
  15297. var vertices = [];
  15298. var normals = [];
  15299. var uvs = [];
  15300. // helper variables
  15301. var i, j;
  15302. var vertex = new Vector3();
  15303. var normal = new Vector3();
  15304. var P1 = new Vector3();
  15305. var P2 = new Vector3();
  15306. var B = new Vector3();
  15307. var T = new Vector3();
  15308. var N = new Vector3();
  15309. // generate vertices, normals and uvs
  15310. for ( i = 0; i <= tubularSegments; ++ i ) {
  15311. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15312. var u = i / tubularSegments * p * Math.PI * 2;
  15313. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15314. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15315. calculatePositionOnCurve( u, p, q, radius, P1 );
  15316. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15317. // calculate orthonormal basis
  15318. T.subVectors( P2, P1 );
  15319. N.addVectors( P2, P1 );
  15320. B.crossVectors( T, N );
  15321. N.crossVectors( B, T );
  15322. // normalize B, N. T can be ignored, we don't use it
  15323. B.normalize();
  15324. N.normalize();
  15325. for ( j = 0; j <= radialSegments; ++ j ) {
  15326. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15327. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15328. var v = j / radialSegments * Math.PI * 2;
  15329. var cx = - tube * Math.cos( v );
  15330. var cy = tube * Math.sin( v );
  15331. // now calculate the final vertex position.
  15332. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15333. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15334. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15335. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15336. vertices.push( vertex.x, vertex.y, vertex.z );
  15337. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15338. normal.subVectors( vertex, P1 ).normalize();
  15339. normals.push( normal.x, normal.y, normal.z );
  15340. // uv
  15341. uvs.push( i / tubularSegments );
  15342. uvs.push( j / radialSegments );
  15343. }
  15344. }
  15345. // generate indices
  15346. for ( j = 1; j <= tubularSegments; j ++ ) {
  15347. for ( i = 1; i <= radialSegments; i ++ ) {
  15348. // indices
  15349. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15350. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15351. var c = ( radialSegments + 1 ) * j + i;
  15352. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15353. // faces
  15354. indices.push( a, b, d );
  15355. indices.push( b, c, d );
  15356. }
  15357. }
  15358. // build geometry
  15359. this.setIndex( indices );
  15360. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15361. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15362. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15363. // this function calculates the current position on the torus curve
  15364. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15365. var cu = Math.cos( u );
  15366. var su = Math.sin( u );
  15367. var quOverP = q / p * u;
  15368. var cs = Math.cos( quOverP );
  15369. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15370. position.y = radius * ( 2 + cs ) * su * 0.5;
  15371. position.z = radius * Math.sin( quOverP ) * 0.5;
  15372. }
  15373. }
  15374. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15375. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15376. /**
  15377. * @author oosmoxiecode
  15378. * @author mrdoob / http://mrdoob.com/
  15379. * @author Mugen87 / https://github.com/Mugen87
  15380. */
  15381. // TorusGeometry
  15382. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15383. Geometry.call( this );
  15384. this.type = 'TorusGeometry';
  15385. this.parameters = {
  15386. radius: radius,
  15387. tube: tube,
  15388. radialSegments: radialSegments,
  15389. tubularSegments: tubularSegments,
  15390. arc: arc
  15391. };
  15392. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15393. this.mergeVertices();
  15394. }
  15395. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15396. TorusGeometry.prototype.constructor = TorusGeometry;
  15397. // TorusBufferGeometry
  15398. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15399. BufferGeometry.call( this );
  15400. this.type = 'TorusBufferGeometry';
  15401. this.parameters = {
  15402. radius: radius,
  15403. tube: tube,
  15404. radialSegments: radialSegments,
  15405. tubularSegments: tubularSegments,
  15406. arc: arc
  15407. };
  15408. radius = radius || 100;
  15409. tube = tube || 40;
  15410. radialSegments = Math.floor( radialSegments ) || 8;
  15411. tubularSegments = Math.floor( tubularSegments ) || 6;
  15412. arc = arc || Math.PI * 2;
  15413. // buffers
  15414. var indices = [];
  15415. var vertices = [];
  15416. var normals = [];
  15417. var uvs = [];
  15418. // helper variables
  15419. var center = new Vector3();
  15420. var vertex = new Vector3();
  15421. var normal = new Vector3();
  15422. var j, i;
  15423. // generate vertices, normals and uvs
  15424. for ( j = 0; j <= radialSegments; j ++ ) {
  15425. for ( i = 0; i <= tubularSegments; i ++ ) {
  15426. var u = i / tubularSegments * arc;
  15427. var v = j / radialSegments * Math.PI * 2;
  15428. // vertex
  15429. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15430. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15431. vertex.z = tube * Math.sin( v );
  15432. vertices.push( vertex.x, vertex.y, vertex.z );
  15433. // normal
  15434. center.x = radius * Math.cos( u );
  15435. center.y = radius * Math.sin( u );
  15436. normal.subVectors( vertex, center ).normalize();
  15437. normals.push( normal.x, normal.y, normal.z );
  15438. // uv
  15439. uvs.push( i / tubularSegments );
  15440. uvs.push( j / radialSegments );
  15441. }
  15442. }
  15443. // generate indices
  15444. for ( j = 1; j <= radialSegments; j ++ ) {
  15445. for ( i = 1; i <= tubularSegments; i ++ ) {
  15446. // indices
  15447. var a = ( tubularSegments + 1 ) * j + i - 1;
  15448. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15449. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15450. var d = ( tubularSegments + 1 ) * j + i;
  15451. // faces
  15452. indices.push( a, b, d );
  15453. indices.push( b, c, d );
  15454. }
  15455. }
  15456. // build geometry
  15457. this.setIndex( indices );
  15458. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15459. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15460. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15461. }
  15462. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15463. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15464. /**
  15465. * @author zz85 / http://www.lab4games.net/zz85/blog
  15466. */
  15467. var ShapeUtils = {
  15468. // calculate area of the contour polygon
  15469. area: function ( contour ) {
  15470. var n = contour.length;
  15471. var a = 0.0;
  15472. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15473. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15474. }
  15475. return a * 0.5;
  15476. },
  15477. triangulate: ( function () {
  15478. /**
  15479. * This code is a quick port of code written in C++ which was submitted to
  15480. * flipcode.com by John W. Ratcliff // July 22, 2000
  15481. * See original code and more information here:
  15482. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15483. *
  15484. * ported to actionscript by Zevan Rosser
  15485. * www.actionsnippet.com
  15486. *
  15487. * ported to javascript by Joshua Koo
  15488. * http://www.lab4games.net/zz85/blog
  15489. *
  15490. */
  15491. function snip( contour, u, v, w, n, verts ) {
  15492. var p;
  15493. var ax, ay, bx, by;
  15494. var cx, cy, px, py;
  15495. ax = contour[ verts[ u ] ].x;
  15496. ay = contour[ verts[ u ] ].y;
  15497. bx = contour[ verts[ v ] ].x;
  15498. by = contour[ verts[ v ] ].y;
  15499. cx = contour[ verts[ w ] ].x;
  15500. cy = contour[ verts[ w ] ].y;
  15501. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15502. var aX, aY, bX, bY, cX, cY;
  15503. var apx, apy, bpx, bpy, cpx, cpy;
  15504. var cCROSSap, bCROSScp, aCROSSbp;
  15505. aX = cx - bx; aY = cy - by;
  15506. bX = ax - cx; bY = ay - cy;
  15507. cX = bx - ax; cY = by - ay;
  15508. for ( p = 0; p < n; p ++ ) {
  15509. px = contour[ verts[ p ] ].x;
  15510. py = contour[ verts[ p ] ].y;
  15511. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15512. ( ( px === bx ) && ( py === by ) ) ||
  15513. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15514. apx = px - ax; apy = py - ay;
  15515. bpx = px - bx; bpy = py - by;
  15516. cpx = px - cx; cpy = py - cy;
  15517. // see if p is inside triangle abc
  15518. aCROSSbp = aX * bpy - aY * bpx;
  15519. cCROSSap = cX * apy - cY * apx;
  15520. bCROSScp = bX * cpy - bY * cpx;
  15521. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15522. }
  15523. return true;
  15524. }
  15525. // takes in an contour array and returns
  15526. return function triangulate( contour, indices ) {
  15527. var n = contour.length;
  15528. if ( n < 3 ) return null;
  15529. var result = [],
  15530. verts = [],
  15531. vertIndices = [];
  15532. /* we want a counter-clockwise polygon in verts */
  15533. var u, v, w;
  15534. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15535. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15536. } else {
  15537. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15538. }
  15539. var nv = n;
  15540. /* remove nv - 2 vertices, creating 1 triangle every time */
  15541. var count = 2 * nv; /* error detection */
  15542. for ( v = nv - 1; nv > 2; ) {
  15543. /* if we loop, it is probably a non-simple polygon */
  15544. if ( ( count -- ) <= 0 ) {
  15545. //** Triangulate: ERROR - probable bad polygon!
  15546. //throw ( "Warning, unable to triangulate polygon!" );
  15547. //return null;
  15548. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15549. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15550. if ( indices ) return vertIndices;
  15551. return result;
  15552. }
  15553. /* three consecutive vertices in current polygon, <u,v,w> */
  15554. u = v; if ( nv <= u ) u = 0; /* previous */
  15555. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15556. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15557. if ( snip( contour, u, v, w, nv, verts ) ) {
  15558. var a, b, c, s, t;
  15559. /* true names of the vertices */
  15560. a = verts[ u ];
  15561. b = verts[ v ];
  15562. c = verts[ w ];
  15563. /* output Triangle */
  15564. result.push( [ contour[ a ],
  15565. contour[ b ],
  15566. contour[ c ] ] );
  15567. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15568. /* remove v from the remaining polygon */
  15569. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15570. verts[ s ] = verts[ t ];
  15571. }
  15572. nv --;
  15573. /* reset error detection counter */
  15574. count = 2 * nv;
  15575. }
  15576. }
  15577. if ( indices ) return vertIndices;
  15578. return result;
  15579. }
  15580. } )(),
  15581. triangulateShape: function ( contour, holes ) {
  15582. function removeDupEndPts(points) {
  15583. var l = points.length;
  15584. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15585. points.pop();
  15586. }
  15587. }
  15588. removeDupEndPts( contour );
  15589. holes.forEach( removeDupEndPts );
  15590. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15591. // inOtherPt needs to be collinear to the inSegment
  15592. if ( inSegPt1.x !== inSegPt2.x ) {
  15593. if ( inSegPt1.x < inSegPt2.x ) {
  15594. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15595. } else {
  15596. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15597. }
  15598. } else {
  15599. if ( inSegPt1.y < inSegPt2.y ) {
  15600. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15601. } else {
  15602. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15603. }
  15604. }
  15605. }
  15606. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15607. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15608. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15609. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15610. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15611. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15612. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15613. if ( Math.abs( limit ) > Number.EPSILON ) {
  15614. // not parallel
  15615. var perpSeg2;
  15616. if ( limit > 0 ) {
  15617. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15618. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15619. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15620. } else {
  15621. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15622. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15623. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15624. }
  15625. // i.e. to reduce rounding errors
  15626. // intersection at endpoint of segment#1?
  15627. if ( perpSeg2 === 0 ) {
  15628. if ( ( inExcludeAdjacentSegs ) &&
  15629. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15630. return [ inSeg1Pt1 ];
  15631. }
  15632. if ( perpSeg2 === limit ) {
  15633. if ( ( inExcludeAdjacentSegs ) &&
  15634. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15635. return [ inSeg1Pt2 ];
  15636. }
  15637. // intersection at endpoint of segment#2?
  15638. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15639. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15640. // return real intersection point
  15641. var factorSeg1 = perpSeg2 / limit;
  15642. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15643. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15644. } else {
  15645. // parallel or collinear
  15646. if ( ( perpSeg1 !== 0 ) ||
  15647. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15648. // they are collinear or degenerate
  15649. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15650. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15651. // both segments are points
  15652. if ( seg1Pt && seg2Pt ) {
  15653. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15654. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15655. return [ inSeg1Pt1 ]; // they are the same point
  15656. }
  15657. // segment#1 is a single point
  15658. if ( seg1Pt ) {
  15659. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15660. return [ inSeg1Pt1 ];
  15661. }
  15662. // segment#2 is a single point
  15663. if ( seg2Pt ) {
  15664. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15665. return [ inSeg2Pt1 ];
  15666. }
  15667. // they are collinear segments, which might overlap
  15668. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15669. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15670. if ( seg1dx !== 0 ) {
  15671. // the segments are NOT on a vertical line
  15672. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15673. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15674. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15675. } else {
  15676. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15677. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15678. }
  15679. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15680. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15681. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15682. } else {
  15683. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15684. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15685. }
  15686. } else {
  15687. // the segments are on a vertical line
  15688. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15689. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15690. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15691. } else {
  15692. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15693. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15694. }
  15695. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15696. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15697. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15698. } else {
  15699. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15700. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15701. }
  15702. }
  15703. if ( seg1minVal <= seg2minVal ) {
  15704. if ( seg1maxVal < seg2minVal ) return [];
  15705. if ( seg1maxVal === seg2minVal ) {
  15706. if ( inExcludeAdjacentSegs ) return [];
  15707. return [ seg2min ];
  15708. }
  15709. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15710. return [ seg2min, seg2max ];
  15711. } else {
  15712. if ( seg1minVal > seg2maxVal ) return [];
  15713. if ( seg1minVal === seg2maxVal ) {
  15714. if ( inExcludeAdjacentSegs ) return [];
  15715. return [ seg1min ];
  15716. }
  15717. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15718. return [ seg1min, seg2max ];
  15719. }
  15720. }
  15721. }
  15722. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15723. // The order of legs is important
  15724. // translation of all points, so that Vertex is at (0,0)
  15725. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15726. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15727. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15728. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15729. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15730. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15731. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15732. // angle != 180 deg.
  15733. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15734. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15735. if ( from2toAngle > 0 ) {
  15736. // main angle < 180 deg.
  15737. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15738. } else {
  15739. // main angle > 180 deg.
  15740. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15741. }
  15742. } else {
  15743. // angle == 180 deg.
  15744. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15745. return ( from2otherAngle > 0 );
  15746. }
  15747. }
  15748. function removeHoles( contour, holes ) {
  15749. var shape = contour.concat(); // work on this shape
  15750. var hole;
  15751. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15752. // Check if hole point lies within angle around shape point
  15753. var lastShapeIdx = shape.length - 1;
  15754. var prevShapeIdx = inShapeIdx - 1;
  15755. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15756. var nextShapeIdx = inShapeIdx + 1;
  15757. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15758. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15759. if ( ! insideAngle ) {
  15760. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15761. return false;
  15762. }
  15763. // Check if shape point lies within angle around hole point
  15764. var lastHoleIdx = hole.length - 1;
  15765. var prevHoleIdx = inHoleIdx - 1;
  15766. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15767. var nextHoleIdx = inHoleIdx + 1;
  15768. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15769. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15770. if ( ! insideAngle ) {
  15771. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15772. return false;
  15773. }
  15774. return true;
  15775. }
  15776. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15777. // checks for intersections with shape edges
  15778. var sIdx, nextIdx, intersection;
  15779. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15780. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15781. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15782. if ( intersection.length > 0 ) return true;
  15783. }
  15784. return false;
  15785. }
  15786. var indepHoles = [];
  15787. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15788. // checks for intersections with hole edges
  15789. var ihIdx, chkHole,
  15790. hIdx, nextIdx, intersection;
  15791. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15792. chkHole = holes[ indepHoles[ ihIdx ]];
  15793. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15794. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15795. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15796. if ( intersection.length > 0 ) return true;
  15797. }
  15798. }
  15799. return false;
  15800. }
  15801. var holeIndex, shapeIndex,
  15802. shapePt, holePt,
  15803. holeIdx, cutKey, failedCuts = [],
  15804. tmpShape1, tmpShape2,
  15805. tmpHole1, tmpHole2;
  15806. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15807. indepHoles.push( h );
  15808. }
  15809. var minShapeIndex = 0;
  15810. var counter = indepHoles.length * 2;
  15811. while ( indepHoles.length > 0 ) {
  15812. counter --;
  15813. if ( counter < 0 ) {
  15814. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15815. break;
  15816. }
  15817. // search for shape-vertex and hole-vertex,
  15818. // which can be connected without intersections
  15819. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15820. shapePt = shape[ shapeIndex ];
  15821. holeIndex = - 1;
  15822. // search for hole which can be reached without intersections
  15823. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15824. holeIdx = indepHoles[ h ];
  15825. // prevent multiple checks
  15826. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15827. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15828. hole = holes[ holeIdx ];
  15829. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15830. holePt = hole[ h2 ];
  15831. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15832. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15833. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15834. holeIndex = h2;
  15835. indepHoles.splice( h, 1 );
  15836. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15837. tmpShape2 = shape.slice( shapeIndex );
  15838. tmpHole1 = hole.slice( holeIndex );
  15839. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15840. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15841. minShapeIndex = shapeIndex;
  15842. // Debug only, to show the selected cuts
  15843. // glob_CutLines.push( [ shapePt, holePt ] );
  15844. break;
  15845. }
  15846. if ( holeIndex >= 0 ) break; // hole-vertex found
  15847. failedCuts[ cutKey ] = true; // remember failure
  15848. }
  15849. if ( holeIndex >= 0 ) break; // hole-vertex found
  15850. }
  15851. }
  15852. return shape; /* shape with no holes */
  15853. }
  15854. var i, il, f, face,
  15855. key, index,
  15856. allPointsMap = {};
  15857. // 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.
  15858. var allpoints = contour.concat();
  15859. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15860. Array.prototype.push.apply( allpoints, holes[ h ] );
  15861. }
  15862. //console.log( "allpoints",allpoints, allpoints.length );
  15863. // prepare all points map
  15864. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15865. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15866. if ( allPointsMap[ key ] !== undefined ) {
  15867. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15868. }
  15869. allPointsMap[ key ] = i;
  15870. }
  15871. // remove holes by cutting paths to holes and adding them to the shape
  15872. var shapeWithoutHoles = removeHoles( contour, holes );
  15873. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15874. //console.log( "triangles",triangles, triangles.length );
  15875. // check all face vertices against all points map
  15876. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15877. face = triangles[ i ];
  15878. for ( f = 0; f < 3; f ++ ) {
  15879. key = face[ f ].x + ":" + face[ f ].y;
  15880. index = allPointsMap[ key ];
  15881. if ( index !== undefined ) {
  15882. face[ f ] = index;
  15883. }
  15884. }
  15885. }
  15886. return triangles.concat();
  15887. },
  15888. isClockWise: function ( pts ) {
  15889. return ShapeUtils.area( pts ) < 0;
  15890. }
  15891. };
  15892. /**
  15893. * @author zz85 / http://www.lab4games.net/zz85/blog
  15894. *
  15895. * Creates extruded geometry from a path shape.
  15896. *
  15897. * parameters = {
  15898. *
  15899. * curveSegments: <int>, // number of points on the curves
  15900. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15901. * amount: <int>, // Depth to extrude the shape
  15902. *
  15903. * bevelEnabled: <bool>, // turn on bevel
  15904. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15905. * bevelSize: <float>, // how far from shape outline is bevel
  15906. * bevelSegments: <int>, // number of bevel layers
  15907. *
  15908. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15909. * frames: <Object> // containing arrays of tangents, normals, binormals
  15910. *
  15911. * UVGenerator: <Object> // object that provides UV generator functions
  15912. *
  15913. * }
  15914. */
  15915. // ExtrudeGeometry
  15916. function ExtrudeGeometry( shapes, options ) {
  15917. Geometry.call( this );
  15918. this.type = 'ExtrudeGeometry';
  15919. this.parameters = {
  15920. shapes: shapes,
  15921. options: options
  15922. };
  15923. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  15924. this.mergeVertices();
  15925. }
  15926. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15927. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15928. // ExtrudeBufferGeometry
  15929. function ExtrudeBufferGeometry( shapes, options ) {
  15930. if ( typeof ( shapes ) === "undefined" ) {
  15931. return;
  15932. }
  15933. BufferGeometry.call( this );
  15934. this.type = 'ExtrudeBufferGeometry';
  15935. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15936. this.addShapeList( shapes, options );
  15937. this.computeVertexNormals();
  15938. // can't really use automatic vertex normals
  15939. // as then front and back sides get smoothed too
  15940. // should do separate smoothing just for sides
  15941. //this.computeVertexNormals();
  15942. //console.log( "took", ( Date.now() - startTime ) );
  15943. }
  15944. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15945. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  15946. ExtrudeBufferGeometry.prototype.getArrays = function () {
  15947. var positionAttribute = this.getAttribute( "position" );
  15948. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  15949. var uvAttribute = this.getAttribute( "uv" );
  15950. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  15951. var IndexAttribute = this.index;
  15952. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  15953. return {
  15954. position: verticesArray,
  15955. uv: uvArray,
  15956. index: indicesArray
  15957. };
  15958. };
  15959. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  15960. var sl = shapes.length;
  15961. options.arrays = this.getArrays();
  15962. for ( var s = 0; s < sl; s ++ ) {
  15963. var shape = shapes[ s ];
  15964. this.addShape( shape, options );
  15965. }
  15966. this.setIndex( options.arrays.index );
  15967. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  15968. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  15969. };
  15970. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  15971. var arrays = options.arrays ? options.arrays : this.getArrays();
  15972. var verticesArray = arrays.position;
  15973. var indicesArray = arrays.index;
  15974. var uvArray = arrays.uv;
  15975. var placeholder = [];
  15976. var amount = options.amount !== undefined ? options.amount : 100;
  15977. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15978. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15979. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15980. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15981. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15982. var steps = options.steps !== undefined ? options.steps : 1;
  15983. var extrudePath = options.extrudePath;
  15984. var extrudePts, extrudeByPath = false;
  15985. // Use default WorldUVGenerator if no UV generators are specified.
  15986. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15987. var splineTube, binormal, normal, position2;
  15988. if ( extrudePath ) {
  15989. extrudePts = extrudePath.getSpacedPoints( steps );
  15990. extrudeByPath = true;
  15991. bevelEnabled = false; // bevels not supported for path extrusion
  15992. // SETUP TNB variables
  15993. // TODO1 - have a .isClosed in spline?
  15994. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15995. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15996. binormal = new Vector3();
  15997. normal = new Vector3();
  15998. position2 = new Vector3();
  15999. }
  16000. // Safeguards if bevels are not enabled
  16001. if ( ! bevelEnabled ) {
  16002. bevelSegments = 0;
  16003. bevelThickness = 0;
  16004. bevelSize = 0;
  16005. }
  16006. // Variables initialization
  16007. var ahole, h, hl; // looping of holes
  16008. var scope = this;
  16009. var shapePoints = shape.extractPoints( curveSegments );
  16010. var vertices = shapePoints.shape;
  16011. var holes = shapePoints.holes;
  16012. var reverse = ! ShapeUtils.isClockWise( vertices );
  16013. if ( reverse ) {
  16014. vertices = vertices.reverse();
  16015. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  16016. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16017. ahole = holes[ h ];
  16018. if ( ShapeUtils.isClockWise( ahole ) ) {
  16019. holes[ h ] = ahole.reverse();
  16020. }
  16021. }
  16022. }
  16023. var faces = ShapeUtils.triangulateShape( vertices, holes );
  16024. /* Vertices */
  16025. var contour = vertices; // vertices has all points but contour has only points of circumference
  16026. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16027. ahole = holes[ h ];
  16028. vertices = vertices.concat( ahole );
  16029. }
  16030. function scalePt2( pt, vec, size ) {
  16031. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  16032. return vec.clone().multiplyScalar( size ).add( pt );
  16033. }
  16034. var b, bs, t, z,
  16035. vert, vlen = vertices.length,
  16036. face, flen = faces.length;
  16037. // Find directions for point movement
  16038. function getBevelVec( inPt, inPrev, inNext ) {
  16039. // computes for inPt the corresponding point inPt' on a new contour
  16040. // shifted by 1 unit (length of normalized vector) to the left
  16041. // if we walk along contour clockwise, this new contour is outside the old one
  16042. //
  16043. // inPt' is the intersection of the two lines parallel to the two
  16044. // adjacent edges of inPt at a distance of 1 unit on the left side.
  16045. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  16046. // good reading for geometry algorithms (here: line-line intersection)
  16047. // http://geomalgorithms.com/a05-_intersect-1.html
  16048. var v_prev_x = inPt.x - inPrev.x,
  16049. v_prev_y = inPt.y - inPrev.y;
  16050. var v_next_x = inNext.x - inPt.x,
  16051. v_next_y = inNext.y - inPt.y;
  16052. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  16053. // check for collinear edges
  16054. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16055. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  16056. // not collinear
  16057. // length of vectors for normalizing
  16058. var v_prev_len = Math.sqrt( v_prev_lensq );
  16059. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  16060. // shift adjacent points by unit vectors to the left
  16061. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  16062. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  16063. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  16064. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  16065. // scaling factor for v_prev to intersection point
  16066. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  16067. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  16068. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16069. // vector from inPt to intersection point
  16070. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  16071. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  16072. // Don't normalize!, otherwise sharp corners become ugly
  16073. // but prevent crazy spikes
  16074. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  16075. if ( v_trans_lensq <= 2 ) {
  16076. return new Vector2( v_trans_x, v_trans_y );
  16077. } else {
  16078. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  16079. }
  16080. } else {
  16081. // handle special case of collinear edges
  16082. var direction_eq = false; // assumes: opposite
  16083. if ( v_prev_x > Number.EPSILON ) {
  16084. if ( v_next_x > Number.EPSILON ) {
  16085. direction_eq = true;
  16086. }
  16087. } else {
  16088. if ( v_prev_x < - Number.EPSILON ) {
  16089. if ( v_next_x < - Number.EPSILON ) {
  16090. direction_eq = true;
  16091. }
  16092. } else {
  16093. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  16094. direction_eq = true;
  16095. }
  16096. }
  16097. }
  16098. if ( direction_eq ) {
  16099. // console.log("Warning: lines are a straight sequence");
  16100. v_trans_x = - v_prev_y;
  16101. v_trans_y = v_prev_x;
  16102. shrink_by = Math.sqrt( v_prev_lensq );
  16103. } else {
  16104. // console.log("Warning: lines are a straight spike");
  16105. v_trans_x = v_prev_x;
  16106. v_trans_y = v_prev_y;
  16107. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  16108. }
  16109. }
  16110. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  16111. }
  16112. var contourMovements = [];
  16113. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16114. if ( j === il ) j = 0;
  16115. if ( k === il ) k = 0;
  16116. // (j)---(i)---(k)
  16117. // console.log('i,j,k', i, j , k)
  16118. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  16119. }
  16120. var holesMovements = [],
  16121. oneHoleMovements, verticesMovements = contourMovements.concat();
  16122. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16123. ahole = holes[ h ];
  16124. oneHoleMovements = [];
  16125. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16126. if ( j === il ) j = 0;
  16127. if ( k === il ) k = 0;
  16128. // (j)---(i)---(k)
  16129. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  16130. }
  16131. holesMovements.push( oneHoleMovements );
  16132. verticesMovements = verticesMovements.concat( oneHoleMovements );
  16133. }
  16134. // Loop bevelSegments, 1 for the front, 1 for the back
  16135. for ( b = 0; b < bevelSegments; b ++ ) {
  16136. //for ( b = bevelSegments; b > 0; b -- ) {
  16137. t = b / bevelSegments;
  16138. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16139. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16140. // contract shape
  16141. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16142. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16143. v( vert.x, vert.y, - z );
  16144. }
  16145. // expand holes
  16146. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16147. ahole = holes[ h ];
  16148. oneHoleMovements = holesMovements[ h ];
  16149. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16150. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16151. v( vert.x, vert.y, - z );
  16152. }
  16153. }
  16154. }
  16155. bs = bevelSize;
  16156. // Back facing vertices
  16157. for ( i = 0; i < vlen; i ++ ) {
  16158. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16159. if ( ! extrudeByPath ) {
  16160. v( vert.x, vert.y, 0 );
  16161. } else {
  16162. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  16163. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  16164. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  16165. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  16166. v( position2.x, position2.y, position2.z );
  16167. }
  16168. }
  16169. // Add stepped vertices...
  16170. // Including front facing vertices
  16171. var s;
  16172. for ( s = 1; s <= steps; s ++ ) {
  16173. for ( i = 0; i < vlen; i ++ ) {
  16174. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16175. if ( ! extrudeByPath ) {
  16176. v( vert.x, vert.y, amount / steps * s );
  16177. } else {
  16178. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  16179. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  16180. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  16181. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  16182. v( position2.x, position2.y, position2.z );
  16183. }
  16184. }
  16185. }
  16186. // Add bevel segments planes
  16187. //for ( b = 1; b <= bevelSegments; b ++ ) {
  16188. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  16189. t = b / bevelSegments;
  16190. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16191. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16192. // contract shape
  16193. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16194. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16195. v( vert.x, vert.y, amount + z );
  16196. }
  16197. // expand holes
  16198. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16199. ahole = holes[ h ];
  16200. oneHoleMovements = holesMovements[ h ];
  16201. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16202. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16203. if ( ! extrudeByPath ) {
  16204. v( vert.x, vert.y, amount + z );
  16205. } else {
  16206. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  16207. }
  16208. }
  16209. }
  16210. }
  16211. /* Faces */
  16212. // Top and bottom faces
  16213. buildLidFaces();
  16214. // Sides faces
  16215. buildSideFaces();
  16216. ///// Internal functions
  16217. function buildLidFaces() {
  16218. var start = verticesArray.length/3;
  16219. if ( bevelEnabled ) {
  16220. var layer = 0; // steps + 1
  16221. var offset = vlen * layer;
  16222. // Bottom faces
  16223. for ( i = 0; i < flen; i ++ ) {
  16224. face = faces[ i ];
  16225. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16226. }
  16227. layer = steps + bevelSegments * 2;
  16228. offset = vlen * layer;
  16229. // Top faces
  16230. for ( i = 0; i < flen; i ++ ) {
  16231. face = faces[ i ];
  16232. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16233. }
  16234. } else {
  16235. // Bottom faces
  16236. for ( i = 0; i < flen; i ++ ) {
  16237. face = faces[ i ];
  16238. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16239. }
  16240. // Top faces
  16241. for ( i = 0; i < flen; i ++ ) {
  16242. face = faces[ i ];
  16243. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16244. }
  16245. }
  16246. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16247. }
  16248. // Create faces for the z-sides of the shape
  16249. function buildSideFaces() {
  16250. var start = verticesArray.length/3;
  16251. var layeroffset = 0;
  16252. sidewalls( contour, layeroffset );
  16253. layeroffset += contour.length;
  16254. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16255. ahole = holes[ h ];
  16256. sidewalls( ahole, layeroffset );
  16257. //, true
  16258. layeroffset += ahole.length;
  16259. }
  16260. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16261. }
  16262. function sidewalls( contour, layeroffset ) {
  16263. var j, k;
  16264. i = contour.length;
  16265. while ( -- i >= 0 ) {
  16266. j = i;
  16267. k = i - 1;
  16268. if ( k < 0 ) k = contour.length - 1;
  16269. //console.log('b', i,j, i-1, k,vertices.length);
  16270. var s = 0,
  16271. sl = steps + bevelSegments * 2;
  16272. for ( s = 0; s < sl; s ++ ) {
  16273. var slen1 = vlen * s;
  16274. var slen2 = vlen * ( s + 1 );
  16275. var a = layeroffset + j + slen1,
  16276. b = layeroffset + k + slen1,
  16277. c = layeroffset + k + slen2,
  16278. d = layeroffset + j + slen2;
  16279. f4( a, b, c, d, contour, s, sl, j, k );
  16280. }
  16281. }
  16282. }
  16283. function v( x, y, z ) {
  16284. placeholder.push( x );
  16285. placeholder.push( y );
  16286. placeholder.push( z );
  16287. }
  16288. function f3( a, b, c ) {
  16289. addVertex( a );
  16290. addVertex( b );
  16291. addVertex( c );
  16292. var nextIndex = verticesArray.length / 3;
  16293. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16294. addUV( uvs[ 0 ] );
  16295. addUV( uvs[ 1 ] );
  16296. addUV( uvs[ 2 ] );
  16297. }
  16298. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16299. addVertex( a );
  16300. addVertex( b );
  16301. addVertex( d );
  16302. addVertex( b );
  16303. addVertex( c );
  16304. addVertex( d );
  16305. var nextIndex = verticesArray.length / 3;
  16306. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16307. addUV( uvs[ 0 ] );
  16308. addUV( uvs[ 1 ] );
  16309. addUV( uvs[ 3 ] );
  16310. addUV( uvs[ 1 ] );
  16311. addUV( uvs[ 2 ] );
  16312. addUV( uvs[ 3 ] );
  16313. }
  16314. function addVertex( index ) {
  16315. indicesArray.push( verticesArray.length / 3 );
  16316. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16317. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16318. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16319. }
  16320. function addUV( vector2 ) {
  16321. uvArray.push( vector2.x );
  16322. uvArray.push( vector2.y );
  16323. }
  16324. if ( ! options.arrays ) {
  16325. this.setIndex( indicesArray );
  16326. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16327. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16328. }
  16329. };
  16330. ExtrudeGeometry.WorldUVGenerator = {
  16331. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16332. var a_x = vertices[ indexA * 3 ];
  16333. var a_y = vertices[ indexA * 3 + 1 ];
  16334. var b_x = vertices[ indexB * 3 ];
  16335. var b_y = vertices[ indexB * 3 + 1 ];
  16336. var c_x = vertices[ indexC * 3 ];
  16337. var c_y = vertices[ indexC * 3 + 1 ];
  16338. return [
  16339. new Vector2( a_x, a_y ),
  16340. new Vector2( b_x, b_y ),
  16341. new Vector2( c_x, c_y )
  16342. ];
  16343. },
  16344. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16345. var a_x = vertices[ indexA * 3 ];
  16346. var a_y = vertices[ indexA * 3 + 1 ];
  16347. var a_z = vertices[ indexA * 3 + 2 ];
  16348. var b_x = vertices[ indexB * 3 ];
  16349. var b_y = vertices[ indexB * 3 + 1 ];
  16350. var b_z = vertices[ indexB * 3 + 2 ];
  16351. var c_x = vertices[ indexC * 3 ];
  16352. var c_y = vertices[ indexC * 3 + 1 ];
  16353. var c_z = vertices[ indexC * 3 + 2 ];
  16354. var d_x = vertices[ indexD * 3 ];
  16355. var d_y = vertices[ indexD * 3 + 1 ];
  16356. var d_z = vertices[ indexD * 3 + 2 ];
  16357. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16358. return [
  16359. new Vector2( a_x, 1 - a_z ),
  16360. new Vector2( b_x, 1 - b_z ),
  16361. new Vector2( c_x, 1 - c_z ),
  16362. new Vector2( d_x, 1 - d_z )
  16363. ];
  16364. } else {
  16365. return [
  16366. new Vector2( a_y, 1 - a_z ),
  16367. new Vector2( b_y, 1 - b_z ),
  16368. new Vector2( c_y, 1 - c_z ),
  16369. new Vector2( d_y, 1 - d_z )
  16370. ];
  16371. }
  16372. }
  16373. };
  16374. /**
  16375. * @author zz85 / http://www.lab4games.net/zz85/blog
  16376. * @author alteredq / http://alteredqualia.com/
  16377. *
  16378. * Text = 3D Text
  16379. *
  16380. * parameters = {
  16381. * font: <THREE.Font>, // font
  16382. *
  16383. * size: <float>, // size of the text
  16384. * height: <float>, // thickness to extrude text
  16385. * curveSegments: <int>, // number of points on the curves
  16386. *
  16387. * bevelEnabled: <bool>, // turn on bevel
  16388. * bevelThickness: <float>, // how deep into text bevel goes
  16389. * bevelSize: <float> // how far from text outline is bevel
  16390. * }
  16391. */
  16392. // TextGeometry
  16393. function TextGeometry( text, parameters ) {
  16394. Geometry.call( this );
  16395. this.type = 'TextGeometry';
  16396. this.parameters = {
  16397. text: text,
  16398. parameters: parameters
  16399. };
  16400. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16401. this.mergeVertices();
  16402. }
  16403. TextGeometry.prototype = Object.create( Geometry.prototype );
  16404. TextGeometry.prototype.constructor = TextGeometry;
  16405. // TextBufferGeometry
  16406. function TextBufferGeometry( text, parameters ) {
  16407. parameters = parameters || {};
  16408. var font = parameters.font;
  16409. if ( ! ( font && font.isFont ) ) {
  16410. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16411. return new Geometry();
  16412. }
  16413. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16414. // translate parameters to ExtrudeGeometry API
  16415. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16416. // defaults
  16417. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16418. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16419. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16420. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16421. this.type = 'TextBufferGeometry';
  16422. }
  16423. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16424. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16425. /**
  16426. * @author mrdoob / http://mrdoob.com/
  16427. * @author benaadams / https://twitter.com/ben_a_adams
  16428. * @author Mugen87 / https://github.com/Mugen87
  16429. */
  16430. // SphereGeometry
  16431. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16432. Geometry.call( this );
  16433. this.type = 'SphereGeometry';
  16434. this.parameters = {
  16435. radius: radius,
  16436. widthSegments: widthSegments,
  16437. heightSegments: heightSegments,
  16438. phiStart: phiStart,
  16439. phiLength: phiLength,
  16440. thetaStart: thetaStart,
  16441. thetaLength: thetaLength
  16442. };
  16443. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16444. this.mergeVertices();
  16445. }
  16446. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16447. SphereGeometry.prototype.constructor = SphereGeometry;
  16448. // SphereBufferGeometry
  16449. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16450. BufferGeometry.call( this );
  16451. this.type = 'SphereBufferGeometry';
  16452. this.parameters = {
  16453. radius: radius,
  16454. widthSegments: widthSegments,
  16455. heightSegments: heightSegments,
  16456. phiStart: phiStart,
  16457. phiLength: phiLength,
  16458. thetaStart: thetaStart,
  16459. thetaLength: thetaLength
  16460. };
  16461. radius = radius || 50;
  16462. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16463. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16464. phiStart = phiStart !== undefined ? phiStart : 0;
  16465. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16466. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16467. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16468. var thetaEnd = thetaStart + thetaLength;
  16469. var ix, iy;
  16470. var index = 0;
  16471. var grid = [];
  16472. var vertex = new Vector3();
  16473. var normal = new Vector3();
  16474. // buffers
  16475. var indices = [];
  16476. var vertices = [];
  16477. var normals = [];
  16478. var uvs = [];
  16479. // generate vertices, normals and uvs
  16480. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16481. var verticesRow = [];
  16482. var v = iy / heightSegments;
  16483. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16484. var u = ix / widthSegments;
  16485. // vertex
  16486. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16487. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16488. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16489. vertices.push( vertex.x, vertex.y, vertex.z );
  16490. // normal
  16491. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16492. normals.push( normal.x, normal.y, normal.z );
  16493. // uv
  16494. uvs.push( u, 1 - v );
  16495. verticesRow.push( index ++ );
  16496. }
  16497. grid.push( verticesRow );
  16498. }
  16499. // indices
  16500. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16501. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16502. var a = grid[ iy ][ ix + 1 ];
  16503. var b = grid[ iy ][ ix ];
  16504. var c = grid[ iy + 1 ][ ix ];
  16505. var d = grid[ iy + 1 ][ ix + 1 ];
  16506. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16507. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16508. }
  16509. }
  16510. // build geometry
  16511. this.setIndex( indices );
  16512. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16513. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16514. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16515. }
  16516. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16517. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16518. /**
  16519. * @author Kaleb Murphy
  16520. * @author Mugen87 / https://github.com/Mugen87
  16521. */
  16522. // RingGeometry
  16523. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16524. Geometry.call( this );
  16525. this.type = 'RingGeometry';
  16526. this.parameters = {
  16527. innerRadius: innerRadius,
  16528. outerRadius: outerRadius,
  16529. thetaSegments: thetaSegments,
  16530. phiSegments: phiSegments,
  16531. thetaStart: thetaStart,
  16532. thetaLength: thetaLength
  16533. };
  16534. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16535. this.mergeVertices();
  16536. }
  16537. RingGeometry.prototype = Object.create( Geometry.prototype );
  16538. RingGeometry.prototype.constructor = RingGeometry;
  16539. // RingBufferGeometry
  16540. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16541. BufferGeometry.call( this );
  16542. this.type = 'RingBufferGeometry';
  16543. this.parameters = {
  16544. innerRadius: innerRadius,
  16545. outerRadius: outerRadius,
  16546. thetaSegments: thetaSegments,
  16547. phiSegments: phiSegments,
  16548. thetaStart: thetaStart,
  16549. thetaLength: thetaLength
  16550. };
  16551. innerRadius = innerRadius || 20;
  16552. outerRadius = outerRadius || 50;
  16553. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16554. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16555. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16556. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16557. // buffers
  16558. var indices = [];
  16559. var vertices = [];
  16560. var normals = [];
  16561. var uvs = [];
  16562. // some helper variables
  16563. var segment;
  16564. var radius = innerRadius;
  16565. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16566. var vertex = new Vector3();
  16567. var uv = new Vector2();
  16568. var j, i;
  16569. // generate vertices, normals and uvs
  16570. for ( j = 0; j <= phiSegments; j ++ ) {
  16571. for ( i = 0; i <= thetaSegments; i ++ ) {
  16572. // values are generate from the inside of the ring to the outside
  16573. segment = thetaStart + i / thetaSegments * thetaLength;
  16574. // vertex
  16575. vertex.x = radius * Math.cos( segment );
  16576. vertex.y = radius * Math.sin( segment );
  16577. vertices.push( vertex.x, vertex.y, vertex.z );
  16578. // normal
  16579. normals.push( 0, 0, 1 );
  16580. // uv
  16581. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16582. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16583. uvs.push( uv.x, uv.y );
  16584. }
  16585. // increase the radius for next row of vertices
  16586. radius += radiusStep;
  16587. }
  16588. // indices
  16589. for ( j = 0; j < phiSegments; j ++ ) {
  16590. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16591. for ( i = 0; i < thetaSegments; i ++ ) {
  16592. segment = i + thetaSegmentLevel;
  16593. var a = segment;
  16594. var b = segment + thetaSegments + 1;
  16595. var c = segment + thetaSegments + 2;
  16596. var d = segment + 1;
  16597. // faces
  16598. indices.push( a, b, d );
  16599. indices.push( b, c, d );
  16600. }
  16601. }
  16602. // build geometry
  16603. this.setIndex( indices );
  16604. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16605. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16606. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16607. }
  16608. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16609. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16610. /**
  16611. * @author astrodud / http://astrodud.isgreat.org/
  16612. * @author zz85 / https://github.com/zz85
  16613. * @author bhouston / http://clara.io
  16614. * @author Mugen87 / https://github.com/Mugen87
  16615. */
  16616. // LatheGeometry
  16617. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16618. Geometry.call( this );
  16619. this.type = 'LatheGeometry';
  16620. this.parameters = {
  16621. points: points,
  16622. segments: segments,
  16623. phiStart: phiStart,
  16624. phiLength: phiLength
  16625. };
  16626. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16627. this.mergeVertices();
  16628. }
  16629. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16630. LatheGeometry.prototype.constructor = LatheGeometry;
  16631. // LatheBufferGeometry
  16632. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16633. BufferGeometry.call( this );
  16634. this.type = 'LatheBufferGeometry';
  16635. this.parameters = {
  16636. points: points,
  16637. segments: segments,
  16638. phiStart: phiStart,
  16639. phiLength: phiLength
  16640. };
  16641. segments = Math.floor( segments ) || 12;
  16642. phiStart = phiStart || 0;
  16643. phiLength = phiLength || Math.PI * 2;
  16644. // clamp phiLength so it's in range of [ 0, 2PI ]
  16645. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16646. // buffers
  16647. var indices = [];
  16648. var vertices = [];
  16649. var uvs = [];
  16650. // helper variables
  16651. var base;
  16652. var inverseSegments = 1.0 / segments;
  16653. var vertex = new Vector3();
  16654. var uv = new Vector2();
  16655. var i, j;
  16656. // generate vertices and uvs
  16657. for ( i = 0; i <= segments; i ++ ) {
  16658. var phi = phiStart + i * inverseSegments * phiLength;
  16659. var sin = Math.sin( phi );
  16660. var cos = Math.cos( phi );
  16661. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16662. // vertex
  16663. vertex.x = points[ j ].x * sin;
  16664. vertex.y = points[ j ].y;
  16665. vertex.z = points[ j ].x * cos;
  16666. vertices.push( vertex.x, vertex.y, vertex.z );
  16667. // uv
  16668. uv.x = i / segments;
  16669. uv.y = j / ( points.length - 1 );
  16670. uvs.push( uv.x, uv.y );
  16671. }
  16672. }
  16673. // indices
  16674. for ( i = 0; i < segments; i ++ ) {
  16675. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16676. base = j + i * points.length;
  16677. var a = base;
  16678. var b = base + points.length;
  16679. var c = base + points.length + 1;
  16680. var d = base + 1;
  16681. // faces
  16682. indices.push( a, b, d );
  16683. indices.push( b, c, d );
  16684. }
  16685. }
  16686. // build geometry
  16687. this.setIndex( indices );
  16688. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16689. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16690. // generate normals
  16691. this.computeVertexNormals();
  16692. // if the geometry is closed, we need to average the normals along the seam.
  16693. // because the corresponding vertices are identical (but still have different UVs).
  16694. if ( phiLength === Math.PI * 2 ) {
  16695. var normals = this.attributes.normal.array;
  16696. var n1 = new Vector3();
  16697. var n2 = new Vector3();
  16698. var n = new Vector3();
  16699. // this is the buffer offset for the last line of vertices
  16700. base = segments * points.length * 3;
  16701. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16702. // select the normal of the vertex in the first line
  16703. n1.x = normals[ j + 0 ];
  16704. n1.y = normals[ j + 1 ];
  16705. n1.z = normals[ j + 2 ];
  16706. // select the normal of the vertex in the last line
  16707. n2.x = normals[ base + j + 0 ];
  16708. n2.y = normals[ base + j + 1 ];
  16709. n2.z = normals[ base + j + 2 ];
  16710. // average normals
  16711. n.addVectors( n1, n2 ).normalize();
  16712. // assign the new values to both normals
  16713. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16714. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16715. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16716. }
  16717. }
  16718. }
  16719. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16720. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16721. /**
  16722. * @author jonobr1 / http://jonobr1.com
  16723. * @author Mugen87 / https://github.com/Mugen87
  16724. */
  16725. // ShapeGeometry
  16726. function ShapeGeometry( shapes, curveSegments ) {
  16727. Geometry.call( this );
  16728. this.type = 'ShapeGeometry';
  16729. if ( typeof curveSegments === 'object' ) {
  16730. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16731. curveSegments = curveSegments.curveSegments;
  16732. }
  16733. this.parameters = {
  16734. shapes: shapes,
  16735. curveSegments: curveSegments
  16736. };
  16737. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16738. this.mergeVertices();
  16739. }
  16740. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16741. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16742. // ShapeBufferGeometry
  16743. function ShapeBufferGeometry( shapes, curveSegments ) {
  16744. BufferGeometry.call( this );
  16745. this.type = 'ShapeBufferGeometry';
  16746. this.parameters = {
  16747. shapes: shapes,
  16748. curveSegments: curveSegments
  16749. };
  16750. curveSegments = curveSegments || 12;
  16751. // buffers
  16752. var indices = [];
  16753. var vertices = [];
  16754. var normals = [];
  16755. var uvs = [];
  16756. // helper variables
  16757. var groupStart = 0;
  16758. var groupCount = 0;
  16759. // allow single and array values for "shapes" parameter
  16760. if ( Array.isArray( shapes ) === false ) {
  16761. addShape( shapes );
  16762. } else {
  16763. for ( var i = 0; i < shapes.length; i ++ ) {
  16764. addShape( shapes[ i ] );
  16765. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16766. groupStart += groupCount;
  16767. groupCount = 0;
  16768. }
  16769. }
  16770. // build geometry
  16771. this.setIndex( indices );
  16772. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16773. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16774. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16775. // helper functions
  16776. function addShape( shape ) {
  16777. var i, l, shapeHole;
  16778. var indexOffset = vertices.length / 3;
  16779. var points = shape.extractPoints( curveSegments );
  16780. var shapeVertices = points.shape;
  16781. var shapeHoles = points.holes;
  16782. // check direction of vertices
  16783. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16784. shapeVertices = shapeVertices.reverse();
  16785. // also check if holes are in the opposite direction
  16786. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16787. shapeHole = shapeHoles[ i ];
  16788. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16789. shapeHoles[ i ] = shapeHole.reverse();
  16790. }
  16791. }
  16792. }
  16793. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16794. // join vertices of inner and outer paths to a single array
  16795. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16796. shapeHole = shapeHoles[ i ];
  16797. shapeVertices = shapeVertices.concat( shapeHole );
  16798. }
  16799. // vertices, normals, uvs
  16800. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16801. var vertex = shapeVertices[ i ];
  16802. vertices.push( vertex.x, vertex.y, 0 );
  16803. normals.push( 0, 0, 1 );
  16804. uvs.push( vertex.x, vertex.y ); // world uvs
  16805. }
  16806. // incides
  16807. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16808. var face = faces[ i ];
  16809. var a = face[ 0 ] + indexOffset;
  16810. var b = face[ 1 ] + indexOffset;
  16811. var c = face[ 2 ] + indexOffset;
  16812. indices.push( a, b, c );
  16813. groupCount += 3;
  16814. }
  16815. }
  16816. }
  16817. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16818. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16819. /**
  16820. * @author WestLangley / http://github.com/WestLangley
  16821. * @author Mugen87 / https://github.com/Mugen87
  16822. */
  16823. function EdgesGeometry( geometry, thresholdAngle ) {
  16824. BufferGeometry.call( this );
  16825. this.type = 'EdgesGeometry';
  16826. this.parameters = {
  16827. thresholdAngle: thresholdAngle
  16828. };
  16829. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16830. // buffer
  16831. var vertices = [];
  16832. // helper variables
  16833. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16834. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16835. var key, keys = [ 'a', 'b', 'c' ];
  16836. // prepare source geometry
  16837. var geometry2;
  16838. if ( geometry.isBufferGeometry ) {
  16839. geometry2 = new Geometry();
  16840. geometry2.fromBufferGeometry( geometry );
  16841. } else {
  16842. geometry2 = geometry.clone();
  16843. }
  16844. geometry2.mergeVertices();
  16845. geometry2.computeFaceNormals();
  16846. var sourceVertices = geometry2.vertices;
  16847. var faces = geometry2.faces;
  16848. // now create a data structure where each entry represents an edge with its adjoining faces
  16849. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16850. var face = faces[ i ];
  16851. for ( var j = 0; j < 3; j ++ ) {
  16852. edge1 = face[ keys[ j ] ];
  16853. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16854. edge[ 0 ] = Math.min( edge1, edge2 );
  16855. edge[ 1 ] = Math.max( edge1, edge2 );
  16856. key = edge[ 0 ] + ',' + edge[ 1 ];
  16857. if ( edges[ key ] === undefined ) {
  16858. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  16859. } else {
  16860. edges[ key ].face2 = i;
  16861. }
  16862. }
  16863. }
  16864. // generate vertices
  16865. for ( key in edges ) {
  16866. var e = edges[ key ];
  16867. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16868. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  16869. var vertex = sourceVertices[ e.index1 ];
  16870. vertices.push( vertex.x, vertex.y, vertex.z );
  16871. vertex = sourceVertices[ e.index2 ];
  16872. vertices.push( vertex.x, vertex.y, vertex.z );
  16873. }
  16874. }
  16875. // build geometry
  16876. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16877. }
  16878. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16879. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16880. /**
  16881. * @author mrdoob / http://mrdoob.com/
  16882. * @author Mugen87 / https://github.com/Mugen87
  16883. */
  16884. // CylinderGeometry
  16885. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16886. Geometry.call( this );
  16887. this.type = 'CylinderGeometry';
  16888. this.parameters = {
  16889. radiusTop: radiusTop,
  16890. radiusBottom: radiusBottom,
  16891. height: height,
  16892. radialSegments: radialSegments,
  16893. heightSegments: heightSegments,
  16894. openEnded: openEnded,
  16895. thetaStart: thetaStart,
  16896. thetaLength: thetaLength
  16897. };
  16898. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16899. this.mergeVertices();
  16900. }
  16901. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16902. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16903. // CylinderBufferGeometry
  16904. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16905. BufferGeometry.call( this );
  16906. this.type = 'CylinderBufferGeometry';
  16907. this.parameters = {
  16908. radiusTop: radiusTop,
  16909. radiusBottom: radiusBottom,
  16910. height: height,
  16911. radialSegments: radialSegments,
  16912. heightSegments: heightSegments,
  16913. openEnded: openEnded,
  16914. thetaStart: thetaStart,
  16915. thetaLength: thetaLength
  16916. };
  16917. var scope = this;
  16918. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16919. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16920. height = height !== undefined ? height : 100;
  16921. radialSegments = Math.floor( radialSegments ) || 8;
  16922. heightSegments = Math.floor( heightSegments ) || 1;
  16923. openEnded = openEnded !== undefined ? openEnded : false;
  16924. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16925. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16926. // buffers
  16927. var indices = [];
  16928. var vertices = [];
  16929. var normals = [];
  16930. var uvs = [];
  16931. // helper variables
  16932. var index = 0;
  16933. var indexArray = [];
  16934. var halfHeight = height / 2;
  16935. var groupStart = 0;
  16936. // generate geometry
  16937. generateTorso();
  16938. if ( openEnded === false ) {
  16939. if ( radiusTop > 0 ) generateCap( true );
  16940. if ( radiusBottom > 0 ) generateCap( false );
  16941. }
  16942. // build geometry
  16943. this.setIndex( indices );
  16944. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16945. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16946. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16947. function generateTorso() {
  16948. var x, y;
  16949. var normal = new Vector3();
  16950. var vertex = new Vector3();
  16951. var groupCount = 0;
  16952. // this will be used to calculate the normal
  16953. var slope = ( radiusBottom - radiusTop ) / height;
  16954. // generate vertices, normals and uvs
  16955. for ( y = 0; y <= heightSegments; y ++ ) {
  16956. var indexRow = [];
  16957. var v = y / heightSegments;
  16958. // calculate the radius of the current row
  16959. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16960. for ( x = 0; x <= radialSegments; x ++ ) {
  16961. var u = x / radialSegments;
  16962. var theta = u * thetaLength + thetaStart;
  16963. var sinTheta = Math.sin( theta );
  16964. var cosTheta = Math.cos( theta );
  16965. // vertex
  16966. vertex.x = radius * sinTheta;
  16967. vertex.y = - v * height + halfHeight;
  16968. vertex.z = radius * cosTheta;
  16969. vertices.push( vertex.x, vertex.y, vertex.z );
  16970. // normal
  16971. normal.set( sinTheta, slope, cosTheta ).normalize();
  16972. normals.push( normal.x, normal.y, normal.z );
  16973. // uv
  16974. uvs.push( u, 1 - v );
  16975. // save index of vertex in respective row
  16976. indexRow.push( index ++ );
  16977. }
  16978. // now save vertices of the row in our index array
  16979. indexArray.push( indexRow );
  16980. }
  16981. // generate indices
  16982. for ( x = 0; x < radialSegments; x ++ ) {
  16983. for ( y = 0; y < heightSegments; y ++ ) {
  16984. // we use the index array to access the correct indices
  16985. var a = indexArray[ y ][ x ];
  16986. var b = indexArray[ y + 1 ][ x ];
  16987. var c = indexArray[ y + 1 ][ x + 1 ];
  16988. var d = indexArray[ y ][ x + 1 ];
  16989. // faces
  16990. indices.push( a, b, d );
  16991. indices.push( b, c, d );
  16992. // update group counter
  16993. groupCount += 6;
  16994. }
  16995. }
  16996. // add a group to the geometry. this will ensure multi material support
  16997. scope.addGroup( groupStart, groupCount, 0 );
  16998. // calculate new start value for groups
  16999. groupStart += groupCount;
  17000. }
  17001. function generateCap( top ) {
  17002. var x, centerIndexStart, centerIndexEnd;
  17003. var uv = new Vector2();
  17004. var vertex = new Vector3();
  17005. var groupCount = 0;
  17006. var radius = ( top === true ) ? radiusTop : radiusBottom;
  17007. var sign = ( top === true ) ? 1 : - 1;
  17008. // save the index of the first center vertex
  17009. centerIndexStart = index;
  17010. // first we generate the center vertex data of the cap.
  17011. // because the geometry needs one set of uvs per face,
  17012. // we must generate a center vertex per face/segment
  17013. for ( x = 1; x <= radialSegments; x ++ ) {
  17014. // vertex
  17015. vertices.push( 0, halfHeight * sign, 0 );
  17016. // normal
  17017. normals.push( 0, sign, 0 );
  17018. // uv
  17019. uvs.push( 0.5, 0.5 );
  17020. // increase index
  17021. index ++;
  17022. }
  17023. // save the index of the last center vertex
  17024. centerIndexEnd = index;
  17025. // now we generate the surrounding vertices, normals and uvs
  17026. for ( x = 0; x <= radialSegments; x ++ ) {
  17027. var u = x / radialSegments;
  17028. var theta = u * thetaLength + thetaStart;
  17029. var cosTheta = Math.cos( theta );
  17030. var sinTheta = Math.sin( theta );
  17031. // vertex
  17032. vertex.x = radius * sinTheta;
  17033. vertex.y = halfHeight * sign;
  17034. vertex.z = radius * cosTheta;
  17035. vertices.push( vertex.x, vertex.y, vertex.z );
  17036. // normal
  17037. normals.push( 0, sign, 0 );
  17038. // uv
  17039. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17040. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17041. uvs.push( uv.x, uv.y );
  17042. // increase index
  17043. index ++;
  17044. }
  17045. // generate indices
  17046. for ( x = 0; x < radialSegments; x ++ ) {
  17047. var c = centerIndexStart + x;
  17048. var i = centerIndexEnd + x;
  17049. if ( top === true ) {
  17050. // face top
  17051. indices.push( i, i + 1, c );
  17052. } else {
  17053. // face bottom
  17054. indices.push( i + 1, i, c );
  17055. }
  17056. groupCount += 3;
  17057. }
  17058. // add a group to the geometry. this will ensure multi material support
  17059. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17060. // calculate new start value for groups
  17061. groupStart += groupCount;
  17062. }
  17063. }
  17064. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17065. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  17066. /**
  17067. * @author abelnation / http://github.com/abelnation
  17068. */
  17069. // ConeGeometry
  17070. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17071. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17072. this.type = 'ConeGeometry';
  17073. this.parameters = {
  17074. radius: radius,
  17075. height: height,
  17076. radialSegments: radialSegments,
  17077. heightSegments: heightSegments,
  17078. openEnded: openEnded,
  17079. thetaStart: thetaStart,
  17080. thetaLength: thetaLength
  17081. };
  17082. }
  17083. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  17084. ConeGeometry.prototype.constructor = ConeGeometry;
  17085. // ConeBufferGeometry
  17086. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17087. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17088. this.type = 'ConeBufferGeometry';
  17089. this.parameters = {
  17090. radius: radius,
  17091. height: height,
  17092. radialSegments: radialSegments,
  17093. heightSegments: heightSegments,
  17094. openEnded: openEnded,
  17095. thetaStart: thetaStart,
  17096. thetaLength: thetaLength
  17097. };
  17098. }
  17099. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  17100. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  17101. /**
  17102. * @author benaadams / https://twitter.com/ben_a_adams
  17103. * @author Mugen87 / https://github.com/Mugen87
  17104. * @author hughes
  17105. */
  17106. // CircleGeometry
  17107. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  17108. Geometry.call( this );
  17109. this.type = 'CircleGeometry';
  17110. this.parameters = {
  17111. radius: radius,
  17112. segments: segments,
  17113. thetaStart: thetaStart,
  17114. thetaLength: thetaLength
  17115. };
  17116. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17117. this.mergeVertices();
  17118. }
  17119. CircleGeometry.prototype = Object.create( Geometry.prototype );
  17120. CircleGeometry.prototype.constructor = CircleGeometry;
  17121. // CircleBufferGeometry
  17122. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  17123. BufferGeometry.call( this );
  17124. this.type = 'CircleBufferGeometry';
  17125. this.parameters = {
  17126. radius: radius,
  17127. segments: segments,
  17128. thetaStart: thetaStart,
  17129. thetaLength: thetaLength
  17130. };
  17131. radius = radius || 50;
  17132. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17133. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17134. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17135. // buffers
  17136. var indices = [];
  17137. var vertices = [];
  17138. var normals = [];
  17139. var uvs = [];
  17140. // helper variables
  17141. var i, s;
  17142. var vertex = new Vector3();
  17143. var uv = new Vector2();
  17144. // center point
  17145. vertices.push( 0, 0, 0 );
  17146. normals.push( 0, 0, 1 );
  17147. uvs.push( 0.5, 0.5 );
  17148. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17149. var segment = thetaStart + s / segments * thetaLength;
  17150. // vertex
  17151. vertex.x = radius * Math.cos( segment );
  17152. vertex.y = radius * Math.sin( segment );
  17153. vertices.push( vertex.x, vertex.y, vertex.z );
  17154. // normal
  17155. normals.push( 0, 0, 1 );
  17156. // uvs
  17157. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17158. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17159. uvs.push( uv.x, uv.y );
  17160. }
  17161. // indices
  17162. for ( i = 1; i <= segments; i ++ ) {
  17163. indices.push( i, i + 1, 0 );
  17164. }
  17165. // build geometry
  17166. this.setIndex( indices );
  17167. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17168. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17169. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17170. }
  17171. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17172. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  17173. var Geometries = Object.freeze({
  17174. WireframeGeometry: WireframeGeometry,
  17175. ParametricGeometry: ParametricGeometry,
  17176. ParametricBufferGeometry: ParametricBufferGeometry,
  17177. TetrahedronGeometry: TetrahedronGeometry,
  17178. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  17179. OctahedronGeometry: OctahedronGeometry,
  17180. OctahedronBufferGeometry: OctahedronBufferGeometry,
  17181. IcosahedronGeometry: IcosahedronGeometry,
  17182. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  17183. DodecahedronGeometry: DodecahedronGeometry,
  17184. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  17185. PolyhedronGeometry: PolyhedronGeometry,
  17186. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  17187. TubeGeometry: TubeGeometry,
  17188. TubeBufferGeometry: TubeBufferGeometry,
  17189. TorusKnotGeometry: TorusKnotGeometry,
  17190. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  17191. TorusGeometry: TorusGeometry,
  17192. TorusBufferGeometry: TorusBufferGeometry,
  17193. TextGeometry: TextGeometry,
  17194. TextBufferGeometry: TextBufferGeometry,
  17195. SphereGeometry: SphereGeometry,
  17196. SphereBufferGeometry: SphereBufferGeometry,
  17197. RingGeometry: RingGeometry,
  17198. RingBufferGeometry: RingBufferGeometry,
  17199. PlaneGeometry: PlaneGeometry,
  17200. PlaneBufferGeometry: PlaneBufferGeometry,
  17201. LatheGeometry: LatheGeometry,
  17202. LatheBufferGeometry: LatheBufferGeometry,
  17203. ShapeGeometry: ShapeGeometry,
  17204. ShapeBufferGeometry: ShapeBufferGeometry,
  17205. ExtrudeGeometry: ExtrudeGeometry,
  17206. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  17207. EdgesGeometry: EdgesGeometry,
  17208. ConeGeometry: ConeGeometry,
  17209. ConeBufferGeometry: ConeBufferGeometry,
  17210. CylinderGeometry: CylinderGeometry,
  17211. CylinderBufferGeometry: CylinderBufferGeometry,
  17212. CircleGeometry: CircleGeometry,
  17213. CircleBufferGeometry: CircleBufferGeometry,
  17214. BoxGeometry: BoxGeometry,
  17215. BoxBufferGeometry: BoxBufferGeometry
  17216. });
  17217. /**
  17218. * @author mrdoob / http://mrdoob.com/
  17219. *
  17220. * parameters = {
  17221. * opacity: <float>
  17222. * }
  17223. */
  17224. function ShadowMaterial( parameters ) {
  17225. ShaderMaterial.call( this, {
  17226. uniforms: UniformsUtils.merge( [
  17227. UniformsLib.lights,
  17228. {
  17229. opacity: { value: 1.0 }
  17230. }
  17231. ] ),
  17232. vertexShader: ShaderChunk[ 'shadow_vert' ],
  17233. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  17234. } );
  17235. this.lights = true;
  17236. this.transparent = true;
  17237. Object.defineProperties( this, {
  17238. opacity: {
  17239. enumerable: true,
  17240. get: function () {
  17241. return this.uniforms.opacity.value;
  17242. },
  17243. set: function ( value ) {
  17244. this.uniforms.opacity.value = value;
  17245. }
  17246. }
  17247. } );
  17248. this.setValues( parameters );
  17249. }
  17250. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17251. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17252. ShadowMaterial.prototype.isShadowMaterial = true;
  17253. /**
  17254. * @author mrdoob / http://mrdoob.com/
  17255. */
  17256. function RawShaderMaterial( parameters ) {
  17257. ShaderMaterial.call( this, parameters );
  17258. this.type = 'RawShaderMaterial';
  17259. }
  17260. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17261. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17262. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17263. /**
  17264. * @author WestLangley / http://github.com/WestLangley
  17265. *
  17266. * parameters = {
  17267. * color: <hex>,
  17268. * roughness: <float>,
  17269. * metalness: <float>,
  17270. * opacity: <float>,
  17271. *
  17272. * map: new THREE.Texture( <Image> ),
  17273. *
  17274. * lightMap: new THREE.Texture( <Image> ),
  17275. * lightMapIntensity: <float>
  17276. *
  17277. * aoMap: new THREE.Texture( <Image> ),
  17278. * aoMapIntensity: <float>
  17279. *
  17280. * emissive: <hex>,
  17281. * emissiveIntensity: <float>
  17282. * emissiveMap: new THREE.Texture( <Image> ),
  17283. *
  17284. * bumpMap: new THREE.Texture( <Image> ),
  17285. * bumpScale: <float>,
  17286. *
  17287. * normalMap: new THREE.Texture( <Image> ),
  17288. * normalScale: <Vector2>,
  17289. *
  17290. * displacementMap: new THREE.Texture( <Image> ),
  17291. * displacementScale: <float>,
  17292. * displacementBias: <float>,
  17293. *
  17294. * roughnessMap: new THREE.Texture( <Image> ),
  17295. *
  17296. * metalnessMap: new THREE.Texture( <Image> ),
  17297. *
  17298. * alphaMap: new THREE.Texture( <Image> ),
  17299. *
  17300. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17301. * envMapIntensity: <float>
  17302. *
  17303. * refractionRatio: <float>,
  17304. *
  17305. * wireframe: <boolean>,
  17306. * wireframeLinewidth: <float>,
  17307. *
  17308. * skinning: <bool>,
  17309. * morphTargets: <bool>,
  17310. * morphNormals: <bool>
  17311. * }
  17312. */
  17313. function MeshStandardMaterial( parameters ) {
  17314. Material.call( this );
  17315. this.defines = { 'STANDARD': '' };
  17316. this.type = 'MeshStandardMaterial';
  17317. this.color = new Color( 0xffffff ); // diffuse
  17318. this.roughness = 0.5;
  17319. this.metalness = 0.5;
  17320. this.map = null;
  17321. this.lightMap = null;
  17322. this.lightMapIntensity = 1.0;
  17323. this.aoMap = null;
  17324. this.aoMapIntensity = 1.0;
  17325. this.emissive = new Color( 0x000000 );
  17326. this.emissiveIntensity = 1.0;
  17327. this.emissiveMap = null;
  17328. this.bumpMap = null;
  17329. this.bumpScale = 1;
  17330. this.normalMap = null;
  17331. this.normalScale = new Vector2( 1, 1 );
  17332. this.displacementMap = null;
  17333. this.displacementScale = 1;
  17334. this.displacementBias = 0;
  17335. this.roughnessMap = null;
  17336. this.metalnessMap = null;
  17337. this.alphaMap = null;
  17338. this.envMap = null;
  17339. this.envMapIntensity = 1.0;
  17340. this.refractionRatio = 0.98;
  17341. this.wireframe = false;
  17342. this.wireframeLinewidth = 1;
  17343. this.wireframeLinecap = 'round';
  17344. this.wireframeLinejoin = 'round';
  17345. this.skinning = false;
  17346. this.morphTargets = false;
  17347. this.morphNormals = false;
  17348. this.setValues( parameters );
  17349. }
  17350. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17351. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17352. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17353. MeshStandardMaterial.prototype.copy = function ( source ) {
  17354. Material.prototype.copy.call( this, source );
  17355. this.defines = { 'STANDARD': '' };
  17356. this.color.copy( source.color );
  17357. this.roughness = source.roughness;
  17358. this.metalness = source.metalness;
  17359. this.map = source.map;
  17360. this.lightMap = source.lightMap;
  17361. this.lightMapIntensity = source.lightMapIntensity;
  17362. this.aoMap = source.aoMap;
  17363. this.aoMapIntensity = source.aoMapIntensity;
  17364. this.emissive.copy( source.emissive );
  17365. this.emissiveMap = source.emissiveMap;
  17366. this.emissiveIntensity = source.emissiveIntensity;
  17367. this.bumpMap = source.bumpMap;
  17368. this.bumpScale = source.bumpScale;
  17369. this.normalMap = source.normalMap;
  17370. this.normalScale.copy( source.normalScale );
  17371. this.displacementMap = source.displacementMap;
  17372. this.displacementScale = source.displacementScale;
  17373. this.displacementBias = source.displacementBias;
  17374. this.roughnessMap = source.roughnessMap;
  17375. this.metalnessMap = source.metalnessMap;
  17376. this.alphaMap = source.alphaMap;
  17377. this.envMap = source.envMap;
  17378. this.envMapIntensity = source.envMapIntensity;
  17379. this.refractionRatio = source.refractionRatio;
  17380. this.wireframe = source.wireframe;
  17381. this.wireframeLinewidth = source.wireframeLinewidth;
  17382. this.wireframeLinecap = source.wireframeLinecap;
  17383. this.wireframeLinejoin = source.wireframeLinejoin;
  17384. this.skinning = source.skinning;
  17385. this.morphTargets = source.morphTargets;
  17386. this.morphNormals = source.morphNormals;
  17387. return this;
  17388. };
  17389. /**
  17390. * @author WestLangley / http://github.com/WestLangley
  17391. *
  17392. * parameters = {
  17393. * reflectivity: <float>
  17394. * }
  17395. */
  17396. function MeshPhysicalMaterial( parameters ) {
  17397. MeshStandardMaterial.call( this );
  17398. this.defines = { 'PHYSICAL': '' };
  17399. this.type = 'MeshPhysicalMaterial';
  17400. this.reflectivity = 0.5; // maps to F0 = 0.04
  17401. this.clearCoat = 0.0;
  17402. this.clearCoatRoughness = 0.0;
  17403. this.setValues( parameters );
  17404. }
  17405. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17406. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17407. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17408. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17409. MeshStandardMaterial.prototype.copy.call( this, source );
  17410. this.defines = { 'PHYSICAL': '' };
  17411. this.reflectivity = source.reflectivity;
  17412. this.clearCoat = source.clearCoat;
  17413. this.clearCoatRoughness = source.clearCoatRoughness;
  17414. return this;
  17415. };
  17416. /**
  17417. * @author mrdoob / http://mrdoob.com/
  17418. * @author alteredq / http://alteredqualia.com/
  17419. *
  17420. * parameters = {
  17421. * color: <hex>,
  17422. * specular: <hex>,
  17423. * shininess: <float>,
  17424. * opacity: <float>,
  17425. *
  17426. * map: new THREE.Texture( <Image> ),
  17427. *
  17428. * lightMap: new THREE.Texture( <Image> ),
  17429. * lightMapIntensity: <float>
  17430. *
  17431. * aoMap: new THREE.Texture( <Image> ),
  17432. * aoMapIntensity: <float>
  17433. *
  17434. * emissive: <hex>,
  17435. * emissiveIntensity: <float>
  17436. * emissiveMap: new THREE.Texture( <Image> ),
  17437. *
  17438. * bumpMap: new THREE.Texture( <Image> ),
  17439. * bumpScale: <float>,
  17440. *
  17441. * normalMap: new THREE.Texture( <Image> ),
  17442. * normalScale: <Vector2>,
  17443. *
  17444. * displacementMap: new THREE.Texture( <Image> ),
  17445. * displacementScale: <float>,
  17446. * displacementBias: <float>,
  17447. *
  17448. * specularMap: new THREE.Texture( <Image> ),
  17449. *
  17450. * alphaMap: new THREE.Texture( <Image> ),
  17451. *
  17452. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17453. * combine: THREE.Multiply,
  17454. * reflectivity: <float>,
  17455. * refractionRatio: <float>,
  17456. *
  17457. * wireframe: <boolean>,
  17458. * wireframeLinewidth: <float>,
  17459. *
  17460. * skinning: <bool>,
  17461. * morphTargets: <bool>,
  17462. * morphNormals: <bool>
  17463. * }
  17464. */
  17465. function MeshPhongMaterial( parameters ) {
  17466. Material.call( this );
  17467. this.type = 'MeshPhongMaterial';
  17468. this.color = new Color( 0xffffff ); // diffuse
  17469. this.specular = new Color( 0x111111 );
  17470. this.shininess = 30;
  17471. this.map = null;
  17472. this.lightMap = null;
  17473. this.lightMapIntensity = 1.0;
  17474. this.aoMap = null;
  17475. this.aoMapIntensity = 1.0;
  17476. this.emissive = new Color( 0x000000 );
  17477. this.emissiveIntensity = 1.0;
  17478. this.emissiveMap = null;
  17479. this.bumpMap = null;
  17480. this.bumpScale = 1;
  17481. this.normalMap = null;
  17482. this.normalScale = new Vector2( 1, 1 );
  17483. this.displacementMap = null;
  17484. this.displacementScale = 1;
  17485. this.displacementBias = 0;
  17486. this.specularMap = null;
  17487. this.alphaMap = null;
  17488. this.envMap = null;
  17489. this.combine = MultiplyOperation;
  17490. this.reflectivity = 1;
  17491. this.refractionRatio = 0.98;
  17492. this.wireframe = false;
  17493. this.wireframeLinewidth = 1;
  17494. this.wireframeLinecap = 'round';
  17495. this.wireframeLinejoin = 'round';
  17496. this.skinning = false;
  17497. this.morphTargets = false;
  17498. this.morphNormals = false;
  17499. this.setValues( parameters );
  17500. }
  17501. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17502. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17503. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17504. MeshPhongMaterial.prototype.copy = function ( source ) {
  17505. Material.prototype.copy.call( this, source );
  17506. this.color.copy( source.color );
  17507. this.specular.copy( source.specular );
  17508. this.shininess = source.shininess;
  17509. this.map = source.map;
  17510. this.lightMap = source.lightMap;
  17511. this.lightMapIntensity = source.lightMapIntensity;
  17512. this.aoMap = source.aoMap;
  17513. this.aoMapIntensity = source.aoMapIntensity;
  17514. this.emissive.copy( source.emissive );
  17515. this.emissiveMap = source.emissiveMap;
  17516. this.emissiveIntensity = source.emissiveIntensity;
  17517. this.bumpMap = source.bumpMap;
  17518. this.bumpScale = source.bumpScale;
  17519. this.normalMap = source.normalMap;
  17520. this.normalScale.copy( source.normalScale );
  17521. this.displacementMap = source.displacementMap;
  17522. this.displacementScale = source.displacementScale;
  17523. this.displacementBias = source.displacementBias;
  17524. this.specularMap = source.specularMap;
  17525. this.alphaMap = source.alphaMap;
  17526. this.envMap = source.envMap;
  17527. this.combine = source.combine;
  17528. this.reflectivity = source.reflectivity;
  17529. this.refractionRatio = source.refractionRatio;
  17530. this.wireframe = source.wireframe;
  17531. this.wireframeLinewidth = source.wireframeLinewidth;
  17532. this.wireframeLinecap = source.wireframeLinecap;
  17533. this.wireframeLinejoin = source.wireframeLinejoin;
  17534. this.skinning = source.skinning;
  17535. this.morphTargets = source.morphTargets;
  17536. this.morphNormals = source.morphNormals;
  17537. return this;
  17538. };
  17539. /**
  17540. * @author takahirox / http://github.com/takahirox
  17541. *
  17542. * parameters = {
  17543. * gradientMap: new THREE.Texture( <Image> )
  17544. * }
  17545. */
  17546. function MeshToonMaterial( parameters ) {
  17547. MeshPhongMaterial.call( this );
  17548. this.defines = { 'TOON': '' };
  17549. this.type = 'MeshToonMaterial';
  17550. this.gradientMap = null;
  17551. this.setValues( parameters );
  17552. }
  17553. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17554. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17555. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17556. MeshToonMaterial.prototype.copy = function ( source ) {
  17557. MeshPhongMaterial.prototype.copy.call( this, source );
  17558. this.gradientMap = source.gradientMap;
  17559. return this;
  17560. };
  17561. /**
  17562. * @author mrdoob / http://mrdoob.com/
  17563. * @author WestLangley / http://github.com/WestLangley
  17564. *
  17565. * parameters = {
  17566. * opacity: <float>,
  17567. *
  17568. * bumpMap: new THREE.Texture( <Image> ),
  17569. * bumpScale: <float>,
  17570. *
  17571. * normalMap: new THREE.Texture( <Image> ),
  17572. * normalScale: <Vector2>,
  17573. *
  17574. * displacementMap: new THREE.Texture( <Image> ),
  17575. * displacementScale: <float>,
  17576. * displacementBias: <float>,
  17577. *
  17578. * wireframe: <boolean>,
  17579. * wireframeLinewidth: <float>
  17580. *
  17581. * skinning: <bool>,
  17582. * morphTargets: <bool>,
  17583. * morphNormals: <bool>
  17584. * }
  17585. */
  17586. function MeshNormalMaterial( parameters ) {
  17587. Material.call( this );
  17588. this.type = 'MeshNormalMaterial';
  17589. this.bumpMap = null;
  17590. this.bumpScale = 1;
  17591. this.normalMap = null;
  17592. this.normalScale = new Vector2( 1, 1 );
  17593. this.displacementMap = null;
  17594. this.displacementScale = 1;
  17595. this.displacementBias = 0;
  17596. this.wireframe = false;
  17597. this.wireframeLinewidth = 1;
  17598. this.fog = false;
  17599. this.lights = false;
  17600. this.skinning = false;
  17601. this.morphTargets = false;
  17602. this.morphNormals = false;
  17603. this.setValues( parameters );
  17604. }
  17605. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17606. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17607. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17608. MeshNormalMaterial.prototype.copy = function ( source ) {
  17609. Material.prototype.copy.call( this, source );
  17610. this.bumpMap = source.bumpMap;
  17611. this.bumpScale = source.bumpScale;
  17612. this.normalMap = source.normalMap;
  17613. this.normalScale.copy( source.normalScale );
  17614. this.displacementMap = source.displacementMap;
  17615. this.displacementScale = source.displacementScale;
  17616. this.displacementBias = source.displacementBias;
  17617. this.wireframe = source.wireframe;
  17618. this.wireframeLinewidth = source.wireframeLinewidth;
  17619. this.skinning = source.skinning;
  17620. this.morphTargets = source.morphTargets;
  17621. this.morphNormals = source.morphNormals;
  17622. return this;
  17623. };
  17624. /**
  17625. * @author mrdoob / http://mrdoob.com/
  17626. * @author alteredq / http://alteredqualia.com/
  17627. *
  17628. * parameters = {
  17629. * color: <hex>,
  17630. * opacity: <float>,
  17631. *
  17632. * map: new THREE.Texture( <Image> ),
  17633. *
  17634. * lightMap: new THREE.Texture( <Image> ),
  17635. * lightMapIntensity: <float>
  17636. *
  17637. * aoMap: new THREE.Texture( <Image> ),
  17638. * aoMapIntensity: <float>
  17639. *
  17640. * emissive: <hex>,
  17641. * emissiveIntensity: <float>
  17642. * emissiveMap: new THREE.Texture( <Image> ),
  17643. *
  17644. * specularMap: new THREE.Texture( <Image> ),
  17645. *
  17646. * alphaMap: new THREE.Texture( <Image> ),
  17647. *
  17648. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17649. * combine: THREE.Multiply,
  17650. * reflectivity: <float>,
  17651. * refractionRatio: <float>,
  17652. *
  17653. * wireframe: <boolean>,
  17654. * wireframeLinewidth: <float>,
  17655. *
  17656. * skinning: <bool>,
  17657. * morphTargets: <bool>,
  17658. * morphNormals: <bool>
  17659. * }
  17660. */
  17661. function MeshLambertMaterial( parameters ) {
  17662. Material.call( this );
  17663. this.type = 'MeshLambertMaterial';
  17664. this.color = new Color( 0xffffff ); // diffuse
  17665. this.map = null;
  17666. this.lightMap = null;
  17667. this.lightMapIntensity = 1.0;
  17668. this.aoMap = null;
  17669. this.aoMapIntensity = 1.0;
  17670. this.emissive = new Color( 0x000000 );
  17671. this.emissiveIntensity = 1.0;
  17672. this.emissiveMap = null;
  17673. this.specularMap = null;
  17674. this.alphaMap = null;
  17675. this.envMap = null;
  17676. this.combine = MultiplyOperation;
  17677. this.reflectivity = 1;
  17678. this.refractionRatio = 0.98;
  17679. this.wireframe = false;
  17680. this.wireframeLinewidth = 1;
  17681. this.wireframeLinecap = 'round';
  17682. this.wireframeLinejoin = 'round';
  17683. this.skinning = false;
  17684. this.morphTargets = false;
  17685. this.morphNormals = false;
  17686. this.setValues( parameters );
  17687. }
  17688. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17689. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17690. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17691. MeshLambertMaterial.prototype.copy = function ( source ) {
  17692. Material.prototype.copy.call( this, source );
  17693. this.color.copy( source.color );
  17694. this.map = source.map;
  17695. this.lightMap = source.lightMap;
  17696. this.lightMapIntensity = source.lightMapIntensity;
  17697. this.aoMap = source.aoMap;
  17698. this.aoMapIntensity = source.aoMapIntensity;
  17699. this.emissive.copy( source.emissive );
  17700. this.emissiveMap = source.emissiveMap;
  17701. this.emissiveIntensity = source.emissiveIntensity;
  17702. this.specularMap = source.specularMap;
  17703. this.alphaMap = source.alphaMap;
  17704. this.envMap = source.envMap;
  17705. this.combine = source.combine;
  17706. this.reflectivity = source.reflectivity;
  17707. this.refractionRatio = source.refractionRatio;
  17708. this.wireframe = source.wireframe;
  17709. this.wireframeLinewidth = source.wireframeLinewidth;
  17710. this.wireframeLinecap = source.wireframeLinecap;
  17711. this.wireframeLinejoin = source.wireframeLinejoin;
  17712. this.skinning = source.skinning;
  17713. this.morphTargets = source.morphTargets;
  17714. this.morphNormals = source.morphNormals;
  17715. return this;
  17716. };
  17717. /**
  17718. * @author alteredq / http://alteredqualia.com/
  17719. *
  17720. * parameters = {
  17721. * color: <hex>,
  17722. * opacity: <float>,
  17723. *
  17724. * linewidth: <float>,
  17725. *
  17726. * scale: <float>,
  17727. * dashSize: <float>,
  17728. * gapSize: <float>
  17729. * }
  17730. */
  17731. function LineDashedMaterial( parameters ) {
  17732. Material.call( this );
  17733. this.type = 'LineDashedMaterial';
  17734. this.color = new Color( 0xffffff );
  17735. this.linewidth = 1;
  17736. this.scale = 1;
  17737. this.dashSize = 3;
  17738. this.gapSize = 1;
  17739. this.lights = false;
  17740. this.setValues( parameters );
  17741. }
  17742. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17743. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17744. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17745. LineDashedMaterial.prototype.copy = function ( source ) {
  17746. Material.prototype.copy.call( this, source );
  17747. this.color.copy( source.color );
  17748. this.linewidth = source.linewidth;
  17749. this.scale = source.scale;
  17750. this.dashSize = source.dashSize;
  17751. this.gapSize = source.gapSize;
  17752. return this;
  17753. };
  17754. var Materials = Object.freeze({
  17755. ShadowMaterial: ShadowMaterial,
  17756. SpriteMaterial: SpriteMaterial,
  17757. RawShaderMaterial: RawShaderMaterial,
  17758. ShaderMaterial: ShaderMaterial,
  17759. PointsMaterial: PointsMaterial,
  17760. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17761. MeshStandardMaterial: MeshStandardMaterial,
  17762. MeshPhongMaterial: MeshPhongMaterial,
  17763. MeshToonMaterial: MeshToonMaterial,
  17764. MeshNormalMaterial: MeshNormalMaterial,
  17765. MeshLambertMaterial: MeshLambertMaterial,
  17766. MeshDepthMaterial: MeshDepthMaterial,
  17767. MeshBasicMaterial: MeshBasicMaterial,
  17768. LineDashedMaterial: LineDashedMaterial,
  17769. LineBasicMaterial: LineBasicMaterial,
  17770. Material: Material
  17771. });
  17772. /**
  17773. * @author mrdoob / http://mrdoob.com/
  17774. */
  17775. var Cache = {
  17776. enabled: false,
  17777. files: {},
  17778. add: function ( key, file ) {
  17779. if ( this.enabled === false ) return;
  17780. // console.log( 'THREE.Cache', 'Adding key:', key );
  17781. this.files[ key ] = file;
  17782. },
  17783. get: function ( key ) {
  17784. if ( this.enabled === false ) return;
  17785. // console.log( 'THREE.Cache', 'Checking key:', key );
  17786. return this.files[ key ];
  17787. },
  17788. remove: function ( key ) {
  17789. delete this.files[ key ];
  17790. },
  17791. clear: function () {
  17792. this.files = {};
  17793. }
  17794. };
  17795. /**
  17796. * @author mrdoob / http://mrdoob.com/
  17797. */
  17798. function LoadingManager( onLoad, onProgress, onError ) {
  17799. var scope = this;
  17800. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17801. this.onStart = undefined;
  17802. this.onLoad = onLoad;
  17803. this.onProgress = onProgress;
  17804. this.onError = onError;
  17805. this.itemStart = function ( url ) {
  17806. itemsTotal ++;
  17807. if ( isLoading === false ) {
  17808. if ( scope.onStart !== undefined ) {
  17809. scope.onStart( url, itemsLoaded, itemsTotal );
  17810. }
  17811. }
  17812. isLoading = true;
  17813. };
  17814. this.itemEnd = function ( url ) {
  17815. itemsLoaded ++;
  17816. if ( scope.onProgress !== undefined ) {
  17817. scope.onProgress( url, itemsLoaded, itemsTotal );
  17818. }
  17819. if ( itemsLoaded === itemsTotal ) {
  17820. isLoading = false;
  17821. if ( scope.onLoad !== undefined ) {
  17822. scope.onLoad();
  17823. }
  17824. }
  17825. };
  17826. this.itemError = function ( url ) {
  17827. if ( scope.onError !== undefined ) {
  17828. scope.onError( url );
  17829. }
  17830. };
  17831. }
  17832. var DefaultLoadingManager = new LoadingManager();
  17833. /**
  17834. * @author mrdoob / http://mrdoob.com/
  17835. */
  17836. function FileLoader( manager ) {
  17837. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17838. }
  17839. Object.assign( FileLoader.prototype, {
  17840. load: function ( url, onLoad, onProgress, onError ) {
  17841. if ( url === undefined ) url = '';
  17842. if ( this.path !== undefined ) url = this.path + url;
  17843. var scope = this;
  17844. var cached = Cache.get( url );
  17845. if ( cached !== undefined ) {
  17846. scope.manager.itemStart( url );
  17847. setTimeout( function () {
  17848. if ( onLoad ) onLoad( cached );
  17849. scope.manager.itemEnd( url );
  17850. }, 0 );
  17851. return cached;
  17852. }
  17853. // Check for data: URI
  17854. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17855. var dataUriRegexResult = url.match( dataUriRegex );
  17856. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17857. if ( dataUriRegexResult ) {
  17858. var mimeType = dataUriRegexResult[ 1 ];
  17859. var isBase64 = !! dataUriRegexResult[ 2 ];
  17860. var data = dataUriRegexResult[ 3 ];
  17861. data = window.decodeURIComponent( data );
  17862. if ( isBase64 ) data = window.atob( data );
  17863. try {
  17864. var response;
  17865. var responseType = ( this.responseType || '' ).toLowerCase();
  17866. switch ( responseType ) {
  17867. case 'arraybuffer':
  17868. case 'blob':
  17869. response = new ArrayBuffer( data.length );
  17870. var view = new Uint8Array( response );
  17871. for ( var i = 0; i < data.length; i ++ ) {
  17872. view[ i ] = data.charCodeAt( i );
  17873. }
  17874. if ( responseType === 'blob' ) {
  17875. response = new Blob( [ response ], { type: mimeType } );
  17876. }
  17877. break;
  17878. case 'document':
  17879. var parser = new DOMParser();
  17880. response = parser.parseFromString( data, mimeType );
  17881. break;
  17882. case 'json':
  17883. response = JSON.parse( data );
  17884. break;
  17885. default: // 'text' or other
  17886. response = data;
  17887. break;
  17888. }
  17889. // Wait for next browser tick
  17890. window.setTimeout( function () {
  17891. if ( onLoad ) onLoad( response );
  17892. scope.manager.itemEnd( url );
  17893. }, 0 );
  17894. } catch ( error ) {
  17895. // Wait for next browser tick
  17896. window.setTimeout( function () {
  17897. if ( onError ) onError( error );
  17898. scope.manager.itemEnd( url );
  17899. scope.manager.itemError( url );
  17900. }, 0 );
  17901. }
  17902. } else {
  17903. var request = new XMLHttpRequest();
  17904. request.open( 'GET', url, true );
  17905. request.addEventListener( 'load', function ( event ) {
  17906. var response = event.target.response;
  17907. Cache.add( url, response );
  17908. if ( this.status === 200 ) {
  17909. if ( onLoad ) onLoad( response );
  17910. scope.manager.itemEnd( url );
  17911. } else if ( this.status === 0 ) {
  17912. // Some browsers return HTTP Status 0 when using non-http protocol
  17913. // e.g. 'file://' or 'data://'. Handle as success.
  17914. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17915. if ( onLoad ) onLoad( response );
  17916. scope.manager.itemEnd( url );
  17917. } else {
  17918. if ( onError ) onError( event );
  17919. scope.manager.itemEnd( url );
  17920. scope.manager.itemError( url );
  17921. }
  17922. }, false );
  17923. if ( onProgress !== undefined ) {
  17924. request.addEventListener( 'progress', function ( event ) {
  17925. onProgress( event );
  17926. }, false );
  17927. }
  17928. request.addEventListener( 'error', function ( event ) {
  17929. if ( onError ) onError( event );
  17930. scope.manager.itemEnd( url );
  17931. scope.manager.itemError( url );
  17932. }, false );
  17933. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17934. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17935. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17936. for ( var header in this.requestHeader ) {
  17937. request.setRequestHeader( header, this.requestHeader[ header ] );
  17938. }
  17939. request.send( null );
  17940. }
  17941. scope.manager.itemStart( url );
  17942. return request;
  17943. },
  17944. setPath: function ( value ) {
  17945. this.path = value;
  17946. return this;
  17947. },
  17948. setResponseType: function ( value ) {
  17949. this.responseType = value;
  17950. return this;
  17951. },
  17952. setWithCredentials: function ( value ) {
  17953. this.withCredentials = value;
  17954. return this;
  17955. },
  17956. setMimeType: function ( value ) {
  17957. this.mimeType = value;
  17958. return this;
  17959. },
  17960. setRequestHeader: function ( value ) {
  17961. this.requestHeader = value;
  17962. return this;
  17963. }
  17964. } );
  17965. /**
  17966. * @author mrdoob / http://mrdoob.com/
  17967. *
  17968. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17969. */
  17970. function CompressedTextureLoader( manager ) {
  17971. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17972. // override in sub classes
  17973. this._parser = null;
  17974. }
  17975. Object.assign( CompressedTextureLoader.prototype, {
  17976. load: function ( url, onLoad, onProgress, onError ) {
  17977. var scope = this;
  17978. var images = [];
  17979. var texture = new CompressedTexture();
  17980. texture.image = images;
  17981. var loader = new FileLoader( this.manager );
  17982. loader.setPath( this.path );
  17983. loader.setResponseType( 'arraybuffer' );
  17984. function loadTexture( i ) {
  17985. loader.load( url[ i ], function ( buffer ) {
  17986. var texDatas = scope._parser( buffer, true );
  17987. images[ i ] = {
  17988. width: texDatas.width,
  17989. height: texDatas.height,
  17990. format: texDatas.format,
  17991. mipmaps: texDatas.mipmaps
  17992. };
  17993. loaded += 1;
  17994. if ( loaded === 6 ) {
  17995. if ( texDatas.mipmapCount === 1 )
  17996. texture.minFilter = LinearFilter;
  17997. texture.format = texDatas.format;
  17998. texture.needsUpdate = true;
  17999. if ( onLoad ) onLoad( texture );
  18000. }
  18001. }, onProgress, onError );
  18002. }
  18003. if ( Array.isArray( url ) ) {
  18004. var loaded = 0;
  18005. for ( var i = 0, il = url.length; i < il; ++ i ) {
  18006. loadTexture( i );
  18007. }
  18008. } else {
  18009. // compressed cubemap texture stored in a single DDS file
  18010. loader.load( url, function ( buffer ) {
  18011. var texDatas = scope._parser( buffer, true );
  18012. if ( texDatas.isCubemap ) {
  18013. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  18014. for ( var f = 0; f < faces; f ++ ) {
  18015. images[ f ] = { mipmaps : [] };
  18016. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  18017. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  18018. images[ f ].format = texDatas.format;
  18019. images[ f ].width = texDatas.width;
  18020. images[ f ].height = texDatas.height;
  18021. }
  18022. }
  18023. } else {
  18024. texture.image.width = texDatas.width;
  18025. texture.image.height = texDatas.height;
  18026. texture.mipmaps = texDatas.mipmaps;
  18027. }
  18028. if ( texDatas.mipmapCount === 1 ) {
  18029. texture.minFilter = LinearFilter;
  18030. }
  18031. texture.format = texDatas.format;
  18032. texture.needsUpdate = true;
  18033. if ( onLoad ) onLoad( texture );
  18034. }, onProgress, onError );
  18035. }
  18036. return texture;
  18037. },
  18038. setPath: function ( value ) {
  18039. this.path = value;
  18040. return this;
  18041. }
  18042. } );
  18043. /**
  18044. * @author Nikos M. / https://github.com/foo123/
  18045. *
  18046. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18047. */
  18048. function DataTextureLoader( manager ) {
  18049. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18050. // override in sub classes
  18051. this._parser = null;
  18052. }
  18053. Object.assign( DataTextureLoader.prototype, {
  18054. load: function ( url, onLoad, onProgress, onError ) {
  18055. var scope = this;
  18056. var texture = new DataTexture();
  18057. var loader = new FileLoader( this.manager );
  18058. loader.setResponseType( 'arraybuffer' );
  18059. loader.load( url, function ( buffer ) {
  18060. var texData = scope._parser( buffer );
  18061. if ( ! texData ) return;
  18062. if ( undefined !== texData.image ) {
  18063. texture.image = texData.image;
  18064. } else if ( undefined !== texData.data ) {
  18065. texture.image.width = texData.width;
  18066. texture.image.height = texData.height;
  18067. texture.image.data = texData.data;
  18068. }
  18069. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  18070. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  18071. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  18072. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  18073. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  18074. if ( undefined !== texData.format ) {
  18075. texture.format = texData.format;
  18076. }
  18077. if ( undefined !== texData.type ) {
  18078. texture.type = texData.type;
  18079. }
  18080. if ( undefined !== texData.mipmaps ) {
  18081. texture.mipmaps = texData.mipmaps;
  18082. }
  18083. if ( 1 === texData.mipmapCount ) {
  18084. texture.minFilter = LinearFilter;
  18085. }
  18086. texture.needsUpdate = true;
  18087. if ( onLoad ) onLoad( texture, texData );
  18088. }, onProgress, onError );
  18089. return texture;
  18090. }
  18091. } );
  18092. /**
  18093. * @author mrdoob / http://mrdoob.com/
  18094. */
  18095. function ImageLoader( manager ) {
  18096. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18097. }
  18098. Object.assign( ImageLoader.prototype, {
  18099. load: function ( url, onLoad, onProgress, onError ) {
  18100. if ( url === undefined ) url = '';
  18101. if ( this.path !== undefined ) url = this.path + url;
  18102. var scope = this;
  18103. var cached = Cache.get( url );
  18104. if ( cached !== undefined ) {
  18105. scope.manager.itemStart( url );
  18106. setTimeout( function () {
  18107. if ( onLoad ) onLoad( cached );
  18108. scope.manager.itemEnd( url );
  18109. }, 0 );
  18110. return cached;
  18111. }
  18112. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  18113. image.addEventListener( 'load', function () {
  18114. Cache.add( url, this );
  18115. if ( onLoad ) onLoad( this );
  18116. scope.manager.itemEnd( url );
  18117. }, false );
  18118. /*
  18119. image.addEventListener( 'progress', function ( event ) {
  18120. if ( onProgress ) onProgress( event );
  18121. }, false );
  18122. */
  18123. image.addEventListener( 'error', function ( event ) {
  18124. if ( onError ) onError( event );
  18125. scope.manager.itemEnd( url );
  18126. scope.manager.itemError( url );
  18127. }, false );
  18128. if ( url.substr( 0, 5 ) !== 'data:' ) {
  18129. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18130. }
  18131. scope.manager.itemStart( url );
  18132. image.src = url;
  18133. return image;
  18134. },
  18135. setCrossOrigin: function ( value ) {
  18136. this.crossOrigin = value;
  18137. return this;
  18138. },
  18139. setPath: function ( value ) {
  18140. this.path = value;
  18141. return this;
  18142. }
  18143. } );
  18144. /**
  18145. * @author mrdoob / http://mrdoob.com/
  18146. */
  18147. function CubeTextureLoader( manager ) {
  18148. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18149. }
  18150. Object.assign( CubeTextureLoader.prototype, {
  18151. load: function ( urls, onLoad, onProgress, onError ) {
  18152. var texture = new CubeTexture();
  18153. var loader = new ImageLoader( this.manager );
  18154. loader.setCrossOrigin( this.crossOrigin );
  18155. loader.setPath( this.path );
  18156. var loaded = 0;
  18157. function loadTexture( i ) {
  18158. loader.load( urls[ i ], function ( image ) {
  18159. texture.images[ i ] = image;
  18160. loaded ++;
  18161. if ( loaded === 6 ) {
  18162. texture.needsUpdate = true;
  18163. if ( onLoad ) onLoad( texture );
  18164. }
  18165. }, undefined, onError );
  18166. }
  18167. for ( var i = 0; i < urls.length; ++ i ) {
  18168. loadTexture( i );
  18169. }
  18170. return texture;
  18171. },
  18172. setCrossOrigin: function ( value ) {
  18173. this.crossOrigin = value;
  18174. return this;
  18175. },
  18176. setPath: function ( value ) {
  18177. this.path = value;
  18178. return this;
  18179. }
  18180. } );
  18181. /**
  18182. * @author mrdoob / http://mrdoob.com/
  18183. */
  18184. function TextureLoader( manager ) {
  18185. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18186. }
  18187. Object.assign( TextureLoader.prototype, {
  18188. load: function ( url, onLoad, onProgress, onError ) {
  18189. var loader = new ImageLoader( this.manager );
  18190. loader.setCrossOrigin( this.crossOrigin );
  18191. loader.setPath( this.path );
  18192. var texture = new Texture();
  18193. texture.image = loader.load( url, function () {
  18194. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  18195. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  18196. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  18197. texture.needsUpdate = true;
  18198. if ( onLoad !== undefined ) {
  18199. onLoad( texture );
  18200. }
  18201. }, onProgress, onError );
  18202. return texture;
  18203. },
  18204. setCrossOrigin: function ( value ) {
  18205. this.crossOrigin = value;
  18206. return this;
  18207. },
  18208. setPath: function ( value ) {
  18209. this.path = value;
  18210. return this;
  18211. }
  18212. } );
  18213. /**
  18214. * @author mrdoob / http://mrdoob.com/
  18215. * @author alteredq / http://alteredqualia.com/
  18216. */
  18217. function Light( color, intensity ) {
  18218. Object3D.call( this );
  18219. this.type = 'Light';
  18220. this.color = new Color( color );
  18221. this.intensity = intensity !== undefined ? intensity : 1;
  18222. this.receiveShadow = undefined;
  18223. }
  18224. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18225. constructor: Light,
  18226. isLight: true,
  18227. copy: function ( source ) {
  18228. Object3D.prototype.copy.call( this, source );
  18229. this.color.copy( source.color );
  18230. this.intensity = source.intensity;
  18231. return this;
  18232. },
  18233. toJSON: function ( meta ) {
  18234. var data = Object3D.prototype.toJSON.call( this, meta );
  18235. data.object.color = this.color.getHex();
  18236. data.object.intensity = this.intensity;
  18237. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18238. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18239. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18240. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18241. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18242. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18243. return data;
  18244. }
  18245. } );
  18246. /**
  18247. * @author alteredq / http://alteredqualia.com/
  18248. */
  18249. function HemisphereLight( skyColor, groundColor, intensity ) {
  18250. Light.call( this, skyColor, intensity );
  18251. this.type = 'HemisphereLight';
  18252. this.castShadow = undefined;
  18253. this.position.copy( Object3D.DefaultUp );
  18254. this.updateMatrix();
  18255. this.groundColor = new Color( groundColor );
  18256. }
  18257. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18258. constructor: HemisphereLight,
  18259. isHemisphereLight: true,
  18260. copy: function ( source ) {
  18261. Light.prototype.copy.call( this, source );
  18262. this.groundColor.copy( source.groundColor );
  18263. return this;
  18264. }
  18265. } );
  18266. /**
  18267. * @author mrdoob / http://mrdoob.com/
  18268. */
  18269. function LightShadow( camera ) {
  18270. this.camera = camera;
  18271. this.bias = 0;
  18272. this.radius = 1;
  18273. this.mapSize = new Vector2( 512, 512 );
  18274. this.map = null;
  18275. this.matrix = new Matrix4();
  18276. }
  18277. Object.assign( LightShadow.prototype, {
  18278. copy: function ( source ) {
  18279. this.camera = source.camera.clone();
  18280. this.bias = source.bias;
  18281. this.radius = source.radius;
  18282. this.mapSize.copy( source.mapSize );
  18283. return this;
  18284. },
  18285. clone: function () {
  18286. return new this.constructor().copy( this );
  18287. },
  18288. toJSON: function () {
  18289. var object = {};
  18290. if ( this.bias !== 0 ) object.bias = this.bias;
  18291. if ( this.radius !== 1 ) object.radius = this.radius;
  18292. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18293. object.camera = this.camera.toJSON( false ).object;
  18294. delete object.camera.matrix;
  18295. return object;
  18296. }
  18297. } );
  18298. /**
  18299. * @author mrdoob / http://mrdoob.com/
  18300. */
  18301. function SpotLightShadow() {
  18302. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18303. }
  18304. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18305. constructor: SpotLightShadow,
  18306. isSpotLightShadow: true,
  18307. update: function ( light ) {
  18308. var camera = this.camera;
  18309. var fov = _Math.RAD2DEG * 2 * light.angle;
  18310. var aspect = this.mapSize.width / this.mapSize.height;
  18311. var far = light.distance || camera.far;
  18312. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18313. camera.fov = fov;
  18314. camera.aspect = aspect;
  18315. camera.far = far;
  18316. camera.updateProjectionMatrix();
  18317. }
  18318. }
  18319. } );
  18320. /**
  18321. * @author alteredq / http://alteredqualia.com/
  18322. */
  18323. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18324. Light.call( this, color, intensity );
  18325. this.type = 'SpotLight';
  18326. this.position.copy( Object3D.DefaultUp );
  18327. this.updateMatrix();
  18328. this.target = new Object3D();
  18329. Object.defineProperty( this, 'power', {
  18330. get: function () {
  18331. // intensity = power per solid angle.
  18332. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18333. return this.intensity * Math.PI;
  18334. },
  18335. set: function ( power ) {
  18336. // intensity = power per solid angle.
  18337. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18338. this.intensity = power / Math.PI;
  18339. }
  18340. } );
  18341. this.distance = ( distance !== undefined ) ? distance : 0;
  18342. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18343. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18344. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18345. this.shadow = new SpotLightShadow();
  18346. }
  18347. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18348. constructor: SpotLight,
  18349. isSpotLight: true,
  18350. copy: function ( source ) {
  18351. Light.prototype.copy.call( this, source );
  18352. this.distance = source.distance;
  18353. this.angle = source.angle;
  18354. this.penumbra = source.penumbra;
  18355. this.decay = source.decay;
  18356. this.target = source.target.clone();
  18357. this.shadow = source.shadow.clone();
  18358. return this;
  18359. }
  18360. } );
  18361. /**
  18362. * @author mrdoob / http://mrdoob.com/
  18363. */
  18364. function PointLight( color, intensity, distance, decay ) {
  18365. Light.call( this, color, intensity );
  18366. this.type = 'PointLight';
  18367. Object.defineProperty( this, 'power', {
  18368. get: function () {
  18369. // intensity = power per solid angle.
  18370. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18371. return this.intensity * 4 * Math.PI;
  18372. },
  18373. set: function ( power ) {
  18374. // intensity = power per solid angle.
  18375. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18376. this.intensity = power / ( 4 * Math.PI );
  18377. }
  18378. } );
  18379. this.distance = ( distance !== undefined ) ? distance : 0;
  18380. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18381. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18382. }
  18383. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18384. constructor: PointLight,
  18385. isPointLight: true,
  18386. copy: function ( source ) {
  18387. Light.prototype.copy.call( this, source );
  18388. this.distance = source.distance;
  18389. this.decay = source.decay;
  18390. this.shadow = source.shadow.clone();
  18391. return this;
  18392. }
  18393. } );
  18394. /**
  18395. * @author mrdoob / http://mrdoob.com/
  18396. */
  18397. function DirectionalLightShadow( ) {
  18398. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18399. }
  18400. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18401. constructor: DirectionalLightShadow
  18402. } );
  18403. /**
  18404. * @author mrdoob / http://mrdoob.com/
  18405. * @author alteredq / http://alteredqualia.com/
  18406. */
  18407. function DirectionalLight( color, intensity ) {
  18408. Light.call( this, color, intensity );
  18409. this.type = 'DirectionalLight';
  18410. this.position.copy( Object3D.DefaultUp );
  18411. this.updateMatrix();
  18412. this.target = new Object3D();
  18413. this.shadow = new DirectionalLightShadow();
  18414. }
  18415. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18416. constructor: DirectionalLight,
  18417. isDirectionalLight: true,
  18418. copy: function ( source ) {
  18419. Light.prototype.copy.call( this, source );
  18420. this.target = source.target.clone();
  18421. this.shadow = source.shadow.clone();
  18422. return this;
  18423. }
  18424. } );
  18425. /**
  18426. * @author mrdoob / http://mrdoob.com/
  18427. */
  18428. function AmbientLight( color, intensity ) {
  18429. Light.call( this, color, intensity );
  18430. this.type = 'AmbientLight';
  18431. this.castShadow = undefined;
  18432. }
  18433. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18434. constructor: AmbientLight,
  18435. isAmbientLight: true
  18436. } );
  18437. /**
  18438. * @author abelnation / http://github.com/abelnation
  18439. */
  18440. function RectAreaLight( color, intensity, width, height ) {
  18441. Light.call( this, color, intensity );
  18442. this.type = 'RectAreaLight';
  18443. this.position.set( 0, 1, 0 );
  18444. this.updateMatrix();
  18445. this.width = ( width !== undefined ) ? width : 10;
  18446. this.height = ( height !== undefined ) ? height : 10;
  18447. // TODO (abelnation): distance/decay
  18448. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18449. // TODO (abelnation): shadows
  18450. }
  18451. // TODO (abelnation): RectAreaLight update when light shape is changed
  18452. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18453. constructor: RectAreaLight,
  18454. isRectAreaLight: true,
  18455. copy: function ( source ) {
  18456. Light.prototype.copy.call( this, source );
  18457. this.width = source.width;
  18458. this.height = source.height;
  18459. return this;
  18460. },
  18461. toJSON: function ( meta ) {
  18462. var data = Light.prototype.toJSON.call( this, meta );
  18463. data.object.width = this.width;
  18464. data.object.height = this.height;
  18465. return data;
  18466. }
  18467. } );
  18468. /**
  18469. * @author tschw
  18470. * @author Ben Houston / http://clara.io/
  18471. * @author David Sarno / http://lighthaus.us/
  18472. */
  18473. var AnimationUtils = {
  18474. // same as Array.prototype.slice, but also works on typed arrays
  18475. arraySlice: function ( array, from, to ) {
  18476. if ( AnimationUtils.isTypedArray( array ) ) {
  18477. // in ios9 array.subarray(from, undefined) will return empty array
  18478. // but array.subarray(from) or array.subarray(from, len) is correct
  18479. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18480. }
  18481. return array.slice( from, to );
  18482. },
  18483. // converts an array to a specific type
  18484. convertArray: function ( array, type, forceClone ) {
  18485. if ( ! array || // let 'undefined' and 'null' pass
  18486. ! forceClone && array.constructor === type ) return array;
  18487. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18488. return new type( array ); // create typed array
  18489. }
  18490. return Array.prototype.slice.call( array ); // create Array
  18491. },
  18492. isTypedArray: function ( object ) {
  18493. return ArrayBuffer.isView( object ) &&
  18494. ! ( object instanceof DataView );
  18495. },
  18496. // returns an array by which times and values can be sorted
  18497. getKeyframeOrder: function ( times ) {
  18498. function compareTime( i, j ) {
  18499. return times[ i ] - times[ j ];
  18500. }
  18501. var n = times.length;
  18502. var result = new Array( n );
  18503. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18504. result.sort( compareTime );
  18505. return result;
  18506. },
  18507. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18508. sortedArray: function ( values, stride, order ) {
  18509. var nValues = values.length;
  18510. var result = new values.constructor( nValues );
  18511. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18512. var srcOffset = order[ i ] * stride;
  18513. for ( var j = 0; j !== stride; ++ j ) {
  18514. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18515. }
  18516. }
  18517. return result;
  18518. },
  18519. // function for parsing AOS keyframe formats
  18520. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18521. var i = 1, key = jsonKeys[ 0 ];
  18522. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18523. key = jsonKeys[ i ++ ];
  18524. }
  18525. if ( key === undefined ) return; // no data
  18526. var value = key[ valuePropertyName ];
  18527. if ( value === undefined ) return; // no data
  18528. if ( Array.isArray( value ) ) {
  18529. do {
  18530. value = key[ valuePropertyName ];
  18531. if ( value !== undefined ) {
  18532. times.push( key.time );
  18533. values.push.apply( values, value ); // push all elements
  18534. }
  18535. key = jsonKeys[ i ++ ];
  18536. } while ( key !== undefined );
  18537. } else if ( value.toArray !== undefined ) {
  18538. // ...assume THREE.Math-ish
  18539. do {
  18540. value = key[ valuePropertyName ];
  18541. if ( value !== undefined ) {
  18542. times.push( key.time );
  18543. value.toArray( values, values.length );
  18544. }
  18545. key = jsonKeys[ i ++ ];
  18546. } while ( key !== undefined );
  18547. } else {
  18548. // otherwise push as-is
  18549. do {
  18550. value = key[ valuePropertyName ];
  18551. if ( value !== undefined ) {
  18552. times.push( key.time );
  18553. values.push( value );
  18554. }
  18555. key = jsonKeys[ i ++ ];
  18556. } while ( key !== undefined );
  18557. }
  18558. }
  18559. };
  18560. /**
  18561. * Abstract base class of interpolants over parametric samples.
  18562. *
  18563. * The parameter domain is one dimensional, typically the time or a path
  18564. * along a curve defined by the data.
  18565. *
  18566. * The sample values can have any dimensionality and derived classes may
  18567. * apply special interpretations to the data.
  18568. *
  18569. * This class provides the interval seek in a Template Method, deferring
  18570. * the actual interpolation to derived classes.
  18571. *
  18572. * Time complexity is O(1) for linear access crossing at most two points
  18573. * and O(log N) for random access, where N is the number of positions.
  18574. *
  18575. * References:
  18576. *
  18577. * http://www.oodesign.com/template-method-pattern.html
  18578. *
  18579. * @author tschw
  18580. */
  18581. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18582. this.parameterPositions = parameterPositions;
  18583. this._cachedIndex = 0;
  18584. this.resultBuffer = resultBuffer !== undefined ?
  18585. resultBuffer : new sampleValues.constructor( sampleSize );
  18586. this.sampleValues = sampleValues;
  18587. this.valueSize = sampleSize;
  18588. }
  18589. Object.assign( Interpolant.prototype, {
  18590. evaluate: function( t ) {
  18591. var pp = this.parameterPositions,
  18592. i1 = this._cachedIndex,
  18593. t1 = pp[ i1 ],
  18594. t0 = pp[ i1 - 1 ];
  18595. validate_interval: {
  18596. seek: {
  18597. var right;
  18598. linear_scan: {
  18599. //- See http://jsperf.com/comparison-to-undefined/3
  18600. //- slower code:
  18601. //-
  18602. //- if ( t >= t1 || t1 === undefined ) {
  18603. forward_scan: if ( ! ( t < t1 ) ) {
  18604. for ( var giveUpAt = i1 + 2; ;) {
  18605. if ( t1 === undefined ) {
  18606. if ( t < t0 ) break forward_scan;
  18607. // after end
  18608. i1 = pp.length;
  18609. this._cachedIndex = i1;
  18610. return this.afterEnd_( i1 - 1, t, t0 );
  18611. }
  18612. if ( i1 === giveUpAt ) break; // this loop
  18613. t0 = t1;
  18614. t1 = pp[ ++ i1 ];
  18615. if ( t < t1 ) {
  18616. // we have arrived at the sought interval
  18617. break seek;
  18618. }
  18619. }
  18620. // prepare binary search on the right side of the index
  18621. right = pp.length;
  18622. break linear_scan;
  18623. }
  18624. //- slower code:
  18625. //- if ( t < t0 || t0 === undefined ) {
  18626. if ( ! ( t >= t0 ) ) {
  18627. // looping?
  18628. var t1global = pp[ 1 ];
  18629. if ( t < t1global ) {
  18630. i1 = 2; // + 1, using the scan for the details
  18631. t0 = t1global;
  18632. }
  18633. // linear reverse scan
  18634. for ( var giveUpAt = i1 - 2; ;) {
  18635. if ( t0 === undefined ) {
  18636. // before start
  18637. this._cachedIndex = 0;
  18638. return this.beforeStart_( 0, t, t1 );
  18639. }
  18640. if ( i1 === giveUpAt ) break; // this loop
  18641. t1 = t0;
  18642. t0 = pp[ -- i1 - 1 ];
  18643. if ( t >= t0 ) {
  18644. // we have arrived at the sought interval
  18645. break seek;
  18646. }
  18647. }
  18648. // prepare binary search on the left side of the index
  18649. right = i1;
  18650. i1 = 0;
  18651. break linear_scan;
  18652. }
  18653. // the interval is valid
  18654. break validate_interval;
  18655. } // linear scan
  18656. // binary search
  18657. while ( i1 < right ) {
  18658. var mid = ( i1 + right ) >>> 1;
  18659. if ( t < pp[ mid ] ) {
  18660. right = mid;
  18661. } else {
  18662. i1 = mid + 1;
  18663. }
  18664. }
  18665. t1 = pp[ i1 ];
  18666. t0 = pp[ i1 - 1 ];
  18667. // check boundary cases, again
  18668. if ( t0 === undefined ) {
  18669. this._cachedIndex = 0;
  18670. return this.beforeStart_( 0, t, t1 );
  18671. }
  18672. if ( t1 === undefined ) {
  18673. i1 = pp.length;
  18674. this._cachedIndex = i1;
  18675. return this.afterEnd_( i1 - 1, t0, t );
  18676. }
  18677. } // seek
  18678. this._cachedIndex = i1;
  18679. this.intervalChanged_( i1, t0, t1 );
  18680. } // validate_interval
  18681. return this.interpolate_( i1, t0, t, t1 );
  18682. },
  18683. settings: null, // optional, subclass-specific settings structure
  18684. // Note: The indirection allows central control of many interpolants.
  18685. // --- Protected interface
  18686. DefaultSettings_: {},
  18687. getSettings_: function() {
  18688. return this.settings || this.DefaultSettings_;
  18689. },
  18690. copySampleValue_: function( index ) {
  18691. // copies a sample value to the result buffer
  18692. var result = this.resultBuffer,
  18693. values = this.sampleValues,
  18694. stride = this.valueSize,
  18695. offset = index * stride;
  18696. for ( var i = 0; i !== stride; ++ i ) {
  18697. result[ i ] = values[ offset + i ];
  18698. }
  18699. return result;
  18700. },
  18701. // Template methods for derived classes:
  18702. interpolate_: function( i1, t0, t, t1 ) {
  18703. throw new Error( "call to abstract method" );
  18704. // implementations shall return this.resultBuffer
  18705. },
  18706. intervalChanged_: function( i1, t0, t1 ) {
  18707. // empty
  18708. }
  18709. } );
  18710. //!\ DECLARE ALIAS AFTER assign prototype !
  18711. Object.assign( Interpolant.prototype, {
  18712. //( 0, t, t0 ), returns this.resultBuffer
  18713. beforeStart_: Interpolant.prototype.copySampleValue_,
  18714. //( N-1, tN-1, t ), returns this.resultBuffer
  18715. afterEnd_: Interpolant.prototype.copySampleValue_,
  18716. } );
  18717. /**
  18718. * Fast and simple cubic spline interpolant.
  18719. *
  18720. * It was derived from a Hermitian construction setting the first derivative
  18721. * at each sample position to the linear slope between neighboring positions
  18722. * over their parameter interval.
  18723. *
  18724. * @author tschw
  18725. */
  18726. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18727. Interpolant.call(
  18728. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18729. this._weightPrev = -0;
  18730. this._offsetPrev = -0;
  18731. this._weightNext = -0;
  18732. this._offsetNext = -0;
  18733. }
  18734. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18735. constructor: CubicInterpolant,
  18736. DefaultSettings_: {
  18737. endingStart: ZeroCurvatureEnding,
  18738. endingEnd: ZeroCurvatureEnding
  18739. },
  18740. intervalChanged_: function( i1, t0, t1 ) {
  18741. var pp = this.parameterPositions,
  18742. iPrev = i1 - 2,
  18743. iNext = i1 + 1,
  18744. tPrev = pp[ iPrev ],
  18745. tNext = pp[ iNext ];
  18746. if ( tPrev === undefined ) {
  18747. switch ( this.getSettings_().endingStart ) {
  18748. case ZeroSlopeEnding:
  18749. // f'(t0) = 0
  18750. iPrev = i1;
  18751. tPrev = 2 * t0 - t1;
  18752. break;
  18753. case WrapAroundEnding:
  18754. // use the other end of the curve
  18755. iPrev = pp.length - 2;
  18756. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18757. break;
  18758. default: // ZeroCurvatureEnding
  18759. // f''(t0) = 0 a.k.a. Natural Spline
  18760. iPrev = i1;
  18761. tPrev = t1;
  18762. }
  18763. }
  18764. if ( tNext === undefined ) {
  18765. switch ( this.getSettings_().endingEnd ) {
  18766. case ZeroSlopeEnding:
  18767. // f'(tN) = 0
  18768. iNext = i1;
  18769. tNext = 2 * t1 - t0;
  18770. break;
  18771. case WrapAroundEnding:
  18772. // use the other end of the curve
  18773. iNext = 1;
  18774. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18775. break;
  18776. default: // ZeroCurvatureEnding
  18777. // f''(tN) = 0, a.k.a. Natural Spline
  18778. iNext = i1 - 1;
  18779. tNext = t0;
  18780. }
  18781. }
  18782. var halfDt = ( t1 - t0 ) * 0.5,
  18783. stride = this.valueSize;
  18784. this._weightPrev = halfDt / ( t0 - tPrev );
  18785. this._weightNext = halfDt / ( tNext - t1 );
  18786. this._offsetPrev = iPrev * stride;
  18787. this._offsetNext = iNext * stride;
  18788. },
  18789. interpolate_: function( i1, t0, t, t1 ) {
  18790. var result = this.resultBuffer,
  18791. values = this.sampleValues,
  18792. stride = this.valueSize,
  18793. o1 = i1 * stride, o0 = o1 - stride,
  18794. oP = this._offsetPrev, oN = this._offsetNext,
  18795. wP = this._weightPrev, wN = this._weightNext,
  18796. p = ( t - t0 ) / ( t1 - t0 ),
  18797. pp = p * p,
  18798. ppp = pp * p;
  18799. // evaluate polynomials
  18800. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18801. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18802. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18803. var sN = wN * ppp - wN * pp;
  18804. // combine data linearly
  18805. for ( var i = 0; i !== stride; ++ i ) {
  18806. result[ i ] =
  18807. sP * values[ oP + i ] +
  18808. s0 * values[ o0 + i ] +
  18809. s1 * values[ o1 + i ] +
  18810. sN * values[ oN + i ];
  18811. }
  18812. return result;
  18813. }
  18814. } );
  18815. /**
  18816. * @author tschw
  18817. */
  18818. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18819. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18820. }
  18821. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18822. constructor: LinearInterpolant,
  18823. interpolate_: function( i1, t0, t, t1 ) {
  18824. var result = this.resultBuffer,
  18825. values = this.sampleValues,
  18826. stride = this.valueSize,
  18827. offset1 = i1 * stride,
  18828. offset0 = offset1 - stride,
  18829. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18830. weight0 = 1 - weight1;
  18831. for ( var i = 0; i !== stride; ++ i ) {
  18832. result[ i ] =
  18833. values[ offset0 + i ] * weight0 +
  18834. values[ offset1 + i ] * weight1;
  18835. }
  18836. return result;
  18837. }
  18838. } );
  18839. /**
  18840. *
  18841. * Interpolant that evaluates to the sample value at the position preceeding
  18842. * the parameter.
  18843. *
  18844. * @author tschw
  18845. */
  18846. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18847. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18848. }
  18849. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18850. constructor: DiscreteInterpolant,
  18851. interpolate_: function( i1, t0, t, t1 ) {
  18852. return this.copySampleValue_( i1 - 1 );
  18853. }
  18854. } );
  18855. var KeyframeTrackPrototype;
  18856. KeyframeTrackPrototype = {
  18857. TimeBufferType: Float32Array,
  18858. ValueBufferType: Float32Array,
  18859. DefaultInterpolation: InterpolateLinear,
  18860. InterpolantFactoryMethodDiscrete: function ( result ) {
  18861. return new DiscreteInterpolant(
  18862. this.times, this.values, this.getValueSize(), result );
  18863. },
  18864. InterpolantFactoryMethodLinear: function ( result ) {
  18865. return new LinearInterpolant(
  18866. this.times, this.values, this.getValueSize(), result );
  18867. },
  18868. InterpolantFactoryMethodSmooth: function ( result ) {
  18869. return new CubicInterpolant(
  18870. this.times, this.values, this.getValueSize(), result );
  18871. },
  18872. setInterpolation: function ( interpolation ) {
  18873. var factoryMethod;
  18874. switch ( interpolation ) {
  18875. case InterpolateDiscrete:
  18876. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18877. break;
  18878. case InterpolateLinear:
  18879. factoryMethod = this.InterpolantFactoryMethodLinear;
  18880. break;
  18881. case InterpolateSmooth:
  18882. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18883. break;
  18884. }
  18885. if ( factoryMethod === undefined ) {
  18886. var message = "unsupported interpolation for " +
  18887. this.ValueTypeName + " keyframe track named " + this.name;
  18888. if ( this.createInterpolant === undefined ) {
  18889. // fall back to default, unless the default itself is messed up
  18890. if ( interpolation !== this.DefaultInterpolation ) {
  18891. this.setInterpolation( this.DefaultInterpolation );
  18892. } else {
  18893. throw new Error( message ); // fatal, in this case
  18894. }
  18895. }
  18896. console.warn( 'THREE.KeyframeTrackPrototype:', message );
  18897. return;
  18898. }
  18899. this.createInterpolant = factoryMethod;
  18900. },
  18901. getInterpolation: function () {
  18902. switch ( this.createInterpolant ) {
  18903. case this.InterpolantFactoryMethodDiscrete:
  18904. return InterpolateDiscrete;
  18905. case this.InterpolantFactoryMethodLinear:
  18906. return InterpolateLinear;
  18907. case this.InterpolantFactoryMethodSmooth:
  18908. return InterpolateSmooth;
  18909. }
  18910. },
  18911. getValueSize: function () {
  18912. return this.values.length / this.times.length;
  18913. },
  18914. // move all keyframes either forwards or backwards in time
  18915. shift: function ( timeOffset ) {
  18916. if ( timeOffset !== 0.0 ) {
  18917. var times = this.times;
  18918. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18919. times[ i ] += timeOffset;
  18920. }
  18921. }
  18922. return this;
  18923. },
  18924. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18925. scale: function ( timeScale ) {
  18926. if ( timeScale !== 1.0 ) {
  18927. var times = this.times;
  18928. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18929. times[ i ] *= timeScale;
  18930. }
  18931. }
  18932. return this;
  18933. },
  18934. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18935. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18936. trim: function ( startTime, endTime ) {
  18937. var times = this.times,
  18938. nKeys = times.length,
  18939. from = 0,
  18940. to = nKeys - 1;
  18941. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18942. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18943. ++ to; // inclusive -> exclusive bound
  18944. if ( from !== 0 || to !== nKeys ) {
  18945. // empty tracks are forbidden, so keep at least one keyframe
  18946. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18947. var stride = this.getValueSize();
  18948. this.times = AnimationUtils.arraySlice( times, from, to );
  18949. this.values = AnimationUtils.
  18950. arraySlice( this.values, from * stride, to * stride );
  18951. }
  18952. return this;
  18953. },
  18954. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18955. validate: function () {
  18956. var valid = true;
  18957. var valueSize = this.getValueSize();
  18958. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18959. console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this );
  18960. valid = false;
  18961. }
  18962. var times = this.times,
  18963. values = this.values,
  18964. nKeys = times.length;
  18965. if ( nKeys === 0 ) {
  18966. console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this );
  18967. valid = false;
  18968. }
  18969. var prevTime = null;
  18970. for ( var i = 0; i !== nKeys; i ++ ) {
  18971. var currTime = times[ i ];
  18972. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18973. console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime );
  18974. valid = false;
  18975. break;
  18976. }
  18977. if ( prevTime !== null && prevTime > currTime ) {
  18978. console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime );
  18979. valid = false;
  18980. break;
  18981. }
  18982. prevTime = currTime;
  18983. }
  18984. if ( values !== undefined ) {
  18985. if ( AnimationUtils.isTypedArray( values ) ) {
  18986. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18987. var value = values[ i ];
  18988. if ( isNaN( value ) ) {
  18989. console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value );
  18990. valid = false;
  18991. break;
  18992. }
  18993. }
  18994. }
  18995. }
  18996. return valid;
  18997. },
  18998. // removes equivalent sequential keys as common in morph target sequences
  18999. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19000. optimize: function () {
  19001. var times = this.times,
  19002. values = this.values,
  19003. stride = this.getValueSize(),
  19004. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19005. writeIndex = 1,
  19006. lastIndex = times.length - 1;
  19007. for ( var i = 1; i < lastIndex; ++ i ) {
  19008. var keep = false;
  19009. var time = times[ i ];
  19010. var timeNext = times[ i + 1 ];
  19011. // remove adjacent keyframes scheduled at the same time
  19012. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  19013. if ( ! smoothInterpolation ) {
  19014. // remove unnecessary keyframes same as their neighbors
  19015. var offset = i * stride,
  19016. offsetP = offset - stride,
  19017. offsetN = offset + stride;
  19018. for ( var j = 0; j !== stride; ++ j ) {
  19019. var value = values[ offset + j ];
  19020. if ( value !== values[ offsetP + j ] ||
  19021. value !== values[ offsetN + j ] ) {
  19022. keep = true;
  19023. break;
  19024. }
  19025. }
  19026. } else keep = true;
  19027. }
  19028. // in-place compaction
  19029. if ( keep ) {
  19030. if ( i !== writeIndex ) {
  19031. times[ writeIndex ] = times[ i ];
  19032. var readOffset = i * stride,
  19033. writeOffset = writeIndex * stride;
  19034. for ( var j = 0; j !== stride; ++ j )
  19035. values[ writeOffset + j ] = values[ readOffset + j ];
  19036. }
  19037. ++ writeIndex;
  19038. }
  19039. }
  19040. // flush last keyframe (compaction looks ahead)
  19041. if ( lastIndex > 0 ) {
  19042. times[ writeIndex ] = times[ lastIndex ];
  19043. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  19044. values[ writeOffset + j ] = values[ readOffset + j ];
  19045. ++ writeIndex;
  19046. }
  19047. if ( writeIndex !== times.length ) {
  19048. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  19049. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  19050. }
  19051. return this;
  19052. }
  19053. };
  19054. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  19055. if ( name === undefined ) throw new Error( "track name is undefined" );
  19056. if ( times === undefined || times.length === 0 ) {
  19057. throw new Error( "no keyframes in track named " + name );
  19058. }
  19059. this.name = name;
  19060. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19061. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19062. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19063. this.validate();
  19064. this.optimize();
  19065. }
  19066. /**
  19067. *
  19068. * A Track of vectored keyframe values.
  19069. *
  19070. *
  19071. * @author Ben Houston / http://clara.io/
  19072. * @author David Sarno / http://lighthaus.us/
  19073. * @author tschw
  19074. */
  19075. function VectorKeyframeTrack( name, times, values, interpolation ) {
  19076. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19077. }
  19078. VectorKeyframeTrack.prototype =
  19079. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19080. constructor: VectorKeyframeTrack,
  19081. ValueTypeName: 'vector'
  19082. // ValueBufferType is inherited
  19083. // DefaultInterpolation is inherited
  19084. } );
  19085. /**
  19086. * Spherical linear unit quaternion interpolant.
  19087. *
  19088. * @author tschw
  19089. */
  19090. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19091. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19092. }
  19093. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19094. constructor: QuaternionLinearInterpolant,
  19095. interpolate_: function( i1, t0, t, t1 ) {
  19096. var result = this.resultBuffer,
  19097. values = this.sampleValues,
  19098. stride = this.valueSize,
  19099. offset = i1 * stride,
  19100. alpha = ( t - t0 ) / ( t1 - t0 );
  19101. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  19102. Quaternion.slerpFlat( result, 0,
  19103. values, offset - stride, values, offset, alpha );
  19104. }
  19105. return result;
  19106. }
  19107. } );
  19108. /**
  19109. *
  19110. * A Track of quaternion keyframe values.
  19111. *
  19112. * @author Ben Houston / http://clara.io/
  19113. * @author David Sarno / http://lighthaus.us/
  19114. * @author tschw
  19115. */
  19116. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  19117. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19118. }
  19119. QuaternionKeyframeTrack.prototype =
  19120. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19121. constructor: QuaternionKeyframeTrack,
  19122. ValueTypeName: 'quaternion',
  19123. // ValueBufferType is inherited
  19124. DefaultInterpolation: InterpolateLinear,
  19125. InterpolantFactoryMethodLinear: function( result ) {
  19126. return new QuaternionLinearInterpolant(
  19127. this.times, this.values, this.getValueSize(), result );
  19128. },
  19129. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  19130. } );
  19131. /**
  19132. *
  19133. * A Track of numeric keyframe values.
  19134. *
  19135. * @author Ben Houston / http://clara.io/
  19136. * @author David Sarno / http://lighthaus.us/
  19137. * @author tschw
  19138. */
  19139. function NumberKeyframeTrack( name, times, values, interpolation ) {
  19140. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19141. }
  19142. NumberKeyframeTrack.prototype =
  19143. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19144. constructor: NumberKeyframeTrack,
  19145. ValueTypeName: 'number'
  19146. // ValueBufferType is inherited
  19147. // DefaultInterpolation is inherited
  19148. } );
  19149. /**
  19150. *
  19151. * A Track that interpolates Strings
  19152. *
  19153. *
  19154. * @author Ben Houston / http://clara.io/
  19155. * @author David Sarno / http://lighthaus.us/
  19156. * @author tschw
  19157. */
  19158. function StringKeyframeTrack( name, times, values, interpolation ) {
  19159. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19160. }
  19161. StringKeyframeTrack.prototype =
  19162. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19163. constructor: StringKeyframeTrack,
  19164. ValueTypeName: 'string',
  19165. ValueBufferType: Array,
  19166. DefaultInterpolation: InterpolateDiscrete,
  19167. InterpolantFactoryMethodLinear: undefined,
  19168. InterpolantFactoryMethodSmooth: undefined
  19169. } );
  19170. /**
  19171. *
  19172. * A Track of Boolean keyframe values.
  19173. *
  19174. *
  19175. * @author Ben Houston / http://clara.io/
  19176. * @author David Sarno / http://lighthaus.us/
  19177. * @author tschw
  19178. */
  19179. function BooleanKeyframeTrack( name, times, values ) {
  19180. KeyframeTrackConstructor.call( this, name, times, values );
  19181. }
  19182. BooleanKeyframeTrack.prototype =
  19183. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19184. constructor: BooleanKeyframeTrack,
  19185. ValueTypeName: 'bool',
  19186. ValueBufferType: Array,
  19187. DefaultInterpolation: InterpolateDiscrete,
  19188. InterpolantFactoryMethodLinear: undefined,
  19189. InterpolantFactoryMethodSmooth: undefined
  19190. // Note: Actually this track could have a optimized / compressed
  19191. // representation of a single value and a custom interpolant that
  19192. // computes "firstValue ^ isOdd( index )".
  19193. } );
  19194. /**
  19195. *
  19196. * A Track of keyframe values that represent color.
  19197. *
  19198. *
  19199. * @author Ben Houston / http://clara.io/
  19200. * @author David Sarno / http://lighthaus.us/
  19201. * @author tschw
  19202. */
  19203. function ColorKeyframeTrack( name, times, values, interpolation ) {
  19204. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19205. }
  19206. ColorKeyframeTrack.prototype =
  19207. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19208. constructor: ColorKeyframeTrack,
  19209. ValueTypeName: 'color'
  19210. // ValueBufferType is inherited
  19211. // DefaultInterpolation is inherited
  19212. // Note: Very basic implementation and nothing special yet.
  19213. // However, this is the place for color space parameterization.
  19214. } );
  19215. /**
  19216. *
  19217. * A timed sequence of keyframes for a specific property.
  19218. *
  19219. *
  19220. * @author Ben Houston / http://clara.io/
  19221. * @author David Sarno / http://lighthaus.us/
  19222. * @author tschw
  19223. */
  19224. function KeyframeTrack( name, times, values, interpolation ) {
  19225. KeyframeTrackConstructor.apply( this, arguments );
  19226. }
  19227. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19228. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19229. // Static methods:
  19230. Object.assign( KeyframeTrack, {
  19231. // Serialization (in static context, because of constructor invocation
  19232. // and automatic invocation of .toJSON):
  19233. parse: function( json ) {
  19234. if( json.type === undefined ) {
  19235. throw new Error( "track type undefined, can not parse" );
  19236. }
  19237. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19238. if ( json.times === undefined ) {
  19239. var times = [], values = [];
  19240. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19241. json.times = times;
  19242. json.values = values;
  19243. }
  19244. // derived classes can define a static parse method
  19245. if ( trackType.parse !== undefined ) {
  19246. return trackType.parse( json );
  19247. } else {
  19248. // by default, we asssume a constructor compatible with the base
  19249. return new trackType(
  19250. json.name, json.times, json.values, json.interpolation );
  19251. }
  19252. },
  19253. toJSON: function( track ) {
  19254. var trackType = track.constructor;
  19255. var json;
  19256. // derived classes can define a static toJSON method
  19257. if ( trackType.toJSON !== undefined ) {
  19258. json = trackType.toJSON( track );
  19259. } else {
  19260. // by default, we assume the data can be serialized as-is
  19261. json = {
  19262. 'name': track.name,
  19263. 'times': AnimationUtils.convertArray( track.times, Array ),
  19264. 'values': AnimationUtils.convertArray( track.values, Array )
  19265. };
  19266. var interpolation = track.getInterpolation();
  19267. if ( interpolation !== track.DefaultInterpolation ) {
  19268. json.interpolation = interpolation;
  19269. }
  19270. }
  19271. json.type = track.ValueTypeName; // mandatory
  19272. return json;
  19273. },
  19274. _getTrackTypeForValueTypeName: function( typeName ) {
  19275. switch( typeName.toLowerCase() ) {
  19276. case "scalar":
  19277. case "double":
  19278. case "float":
  19279. case "number":
  19280. case "integer":
  19281. return NumberKeyframeTrack;
  19282. case "vector":
  19283. case "vector2":
  19284. case "vector3":
  19285. case "vector4":
  19286. return VectorKeyframeTrack;
  19287. case "color":
  19288. return ColorKeyframeTrack;
  19289. case "quaternion":
  19290. return QuaternionKeyframeTrack;
  19291. case "bool":
  19292. case "boolean":
  19293. return BooleanKeyframeTrack;
  19294. case "string":
  19295. return StringKeyframeTrack;
  19296. }
  19297. throw new Error( "Unsupported typeName: " + typeName );
  19298. }
  19299. } );
  19300. /**
  19301. *
  19302. * Reusable set of Tracks that represent an animation.
  19303. *
  19304. * @author Ben Houston / http://clara.io/
  19305. * @author David Sarno / http://lighthaus.us/
  19306. */
  19307. function AnimationClip( name, duration, tracks ) {
  19308. this.name = name;
  19309. this.tracks = tracks;
  19310. this.duration = ( duration !== undefined ) ? duration : - 1;
  19311. this.uuid = _Math.generateUUID();
  19312. // this means it should figure out its duration by scanning the tracks
  19313. if ( this.duration < 0 ) {
  19314. this.resetDuration();
  19315. }
  19316. this.optimize();
  19317. }
  19318. Object.assign( AnimationClip, {
  19319. parse: function ( json ) {
  19320. var tracks = [],
  19321. jsonTracks = json.tracks,
  19322. frameTime = 1.0 / ( json.fps || 1.0 );
  19323. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19324. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19325. }
  19326. return new AnimationClip( json.name, json.duration, tracks );
  19327. },
  19328. toJSON: function ( clip ) {
  19329. var tracks = [],
  19330. clipTracks = clip.tracks;
  19331. var json = {
  19332. 'name': clip.name,
  19333. 'duration': clip.duration,
  19334. 'tracks': tracks
  19335. };
  19336. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19337. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19338. }
  19339. return json;
  19340. },
  19341. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19342. var numMorphTargets = morphTargetSequence.length;
  19343. var tracks = [];
  19344. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19345. var times = [];
  19346. var values = [];
  19347. times.push(
  19348. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19349. i,
  19350. ( i + 1 ) % numMorphTargets );
  19351. values.push( 0, 1, 0 );
  19352. var order = AnimationUtils.getKeyframeOrder( times );
  19353. times = AnimationUtils.sortedArray( times, 1, order );
  19354. values = AnimationUtils.sortedArray( values, 1, order );
  19355. // if there is a key at the first frame, duplicate it as the
  19356. // last frame as well for perfect loop.
  19357. if ( ! noLoop && times[ 0 ] === 0 ) {
  19358. times.push( numMorphTargets );
  19359. values.push( values[ 0 ] );
  19360. }
  19361. tracks.push(
  19362. new NumberKeyframeTrack(
  19363. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19364. times, values
  19365. ).scale( 1.0 / fps ) );
  19366. }
  19367. return new AnimationClip( name, - 1, tracks );
  19368. },
  19369. findByName: function ( objectOrClipArray, name ) {
  19370. var clipArray = objectOrClipArray;
  19371. if ( ! Array.isArray( objectOrClipArray ) ) {
  19372. var o = objectOrClipArray;
  19373. clipArray = o.geometry && o.geometry.animations || o.animations;
  19374. }
  19375. for ( var i = 0; i < clipArray.length; i ++ ) {
  19376. if ( clipArray[ i ].name === name ) {
  19377. return clipArray[ i ];
  19378. }
  19379. }
  19380. return null;
  19381. },
  19382. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19383. var animationToMorphTargets = {};
  19384. // tested with https://regex101.com/ on trick sequences
  19385. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19386. var pattern = /^([\w-]*?)([\d]+)$/;
  19387. // sort morph target names into animation groups based
  19388. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19389. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19390. var morphTarget = morphTargets[ i ];
  19391. var parts = morphTarget.name.match( pattern );
  19392. if ( parts && parts.length > 1 ) {
  19393. var name = parts[ 1 ];
  19394. var animationMorphTargets = animationToMorphTargets[ name ];
  19395. if ( ! animationMorphTargets ) {
  19396. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19397. }
  19398. animationMorphTargets.push( morphTarget );
  19399. }
  19400. }
  19401. var clips = [];
  19402. for ( var name in animationToMorphTargets ) {
  19403. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19404. }
  19405. return clips;
  19406. },
  19407. // parse the animation.hierarchy format
  19408. parseAnimation: function ( animation, bones ) {
  19409. if ( ! animation ) {
  19410. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  19411. return null;
  19412. }
  19413. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19414. // only return track if there are actually keys.
  19415. if ( animationKeys.length !== 0 ) {
  19416. var times = [];
  19417. var values = [];
  19418. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19419. // empty keys are filtered out, so check again
  19420. if ( times.length !== 0 ) {
  19421. destTracks.push( new trackType( trackName, times, values ) );
  19422. }
  19423. }
  19424. };
  19425. var tracks = [];
  19426. var clipName = animation.name || 'default';
  19427. // automatic length determination in AnimationClip.
  19428. var duration = animation.length || - 1;
  19429. var fps = animation.fps || 30;
  19430. var hierarchyTracks = animation.hierarchy || [];
  19431. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19432. var animationKeys = hierarchyTracks[ h ].keys;
  19433. // skip empty tracks
  19434. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19435. // process morph targets
  19436. if ( animationKeys[ 0 ].morphTargets ) {
  19437. // figure out all morph targets used in this track
  19438. var morphTargetNames = {};
  19439. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19440. if ( animationKeys[ k ].morphTargets ) {
  19441. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19442. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19443. }
  19444. }
  19445. }
  19446. // create a track for each morph target with all zero
  19447. // morphTargetInfluences except for the keys in which
  19448. // the morphTarget is named.
  19449. for ( var morphTargetName in morphTargetNames ) {
  19450. var times = [];
  19451. var values = [];
  19452. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19453. var animationKey = animationKeys[ k ];
  19454. times.push( animationKey.time );
  19455. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19456. }
  19457. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19458. }
  19459. duration = morphTargetNames.length * ( fps || 1.0 );
  19460. } else {
  19461. // ...assume skeletal animation
  19462. var boneName = '.bones[' + bones[ h ].name + ']';
  19463. addNonemptyTrack(
  19464. VectorKeyframeTrack, boneName + '.position',
  19465. animationKeys, 'pos', tracks );
  19466. addNonemptyTrack(
  19467. QuaternionKeyframeTrack, boneName + '.quaternion',
  19468. animationKeys, 'rot', tracks );
  19469. addNonemptyTrack(
  19470. VectorKeyframeTrack, boneName + '.scale',
  19471. animationKeys, 'scl', tracks );
  19472. }
  19473. }
  19474. if ( tracks.length === 0 ) {
  19475. return null;
  19476. }
  19477. var clip = new AnimationClip( clipName, duration, tracks );
  19478. return clip;
  19479. }
  19480. } );
  19481. Object.assign( AnimationClip.prototype, {
  19482. resetDuration: function () {
  19483. var tracks = this.tracks, duration = 0;
  19484. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19485. var track = this.tracks[ i ];
  19486. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19487. }
  19488. this.duration = duration;
  19489. },
  19490. trim: function () {
  19491. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19492. this.tracks[ i ].trim( 0, this.duration );
  19493. }
  19494. return this;
  19495. },
  19496. optimize: function () {
  19497. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19498. this.tracks[ i ].optimize();
  19499. }
  19500. return this;
  19501. }
  19502. } );
  19503. /**
  19504. * @author mrdoob / http://mrdoob.com/
  19505. */
  19506. function MaterialLoader( manager ) {
  19507. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19508. this.textures = {};
  19509. }
  19510. Object.assign( MaterialLoader.prototype, {
  19511. load: function ( url, onLoad, onProgress, onError ) {
  19512. var scope = this;
  19513. var loader = new FileLoader( scope.manager );
  19514. loader.load( url, function ( text ) {
  19515. onLoad( scope.parse( JSON.parse( text ) ) );
  19516. }, onProgress, onError );
  19517. },
  19518. setTextures: function ( value ) {
  19519. this.textures = value;
  19520. },
  19521. parse: function ( json ) {
  19522. var textures = this.textures;
  19523. function getTexture( name ) {
  19524. if ( textures[ name ] === undefined ) {
  19525. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19526. }
  19527. return textures[ name ];
  19528. }
  19529. var material = new Materials[ json.type ]();
  19530. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19531. if ( json.name !== undefined ) material.name = json.name;
  19532. if ( json.color !== undefined ) material.color.setHex( json.color );
  19533. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19534. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19535. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19536. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19537. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19538. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19539. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19540. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19541. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19542. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19543. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19544. if ( json.fog !== undefined ) material.fog = json.fog;
  19545. if ( json.shading !== undefined ) material.shading = json.shading;
  19546. if ( json.blending !== undefined ) material.blending = json.blending;
  19547. if ( json.side !== undefined ) material.side = json.side;
  19548. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19549. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19550. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19551. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19552. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19553. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19554. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19555. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19556. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19557. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19558. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19559. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19560. // for PointsMaterial
  19561. if ( json.size !== undefined ) material.size = json.size;
  19562. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19563. // maps
  19564. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19565. if ( json.alphaMap !== undefined ) {
  19566. material.alphaMap = getTexture( json.alphaMap );
  19567. material.transparent = true;
  19568. }
  19569. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19570. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19571. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19572. if ( json.normalScale !== undefined ) {
  19573. var normalScale = json.normalScale;
  19574. if ( Array.isArray( normalScale ) === false ) {
  19575. // Blender exporter used to export a scalar. See #7459
  19576. normalScale = [ normalScale, normalScale ];
  19577. }
  19578. material.normalScale = new Vector2().fromArray( normalScale );
  19579. }
  19580. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19581. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19582. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19583. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19584. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19585. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19586. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19587. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19588. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19589. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19590. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19591. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19592. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19593. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19594. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19595. return material;
  19596. }
  19597. } );
  19598. /**
  19599. * @author mrdoob / http://mrdoob.com/
  19600. */
  19601. function BufferGeometryLoader( manager ) {
  19602. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19603. }
  19604. Object.assign( BufferGeometryLoader.prototype, {
  19605. load: function ( url, onLoad, onProgress, onError ) {
  19606. var scope = this;
  19607. var loader = new FileLoader( scope.manager );
  19608. loader.load( url, function ( text ) {
  19609. onLoad( scope.parse( JSON.parse( text ) ) );
  19610. }, onProgress, onError );
  19611. },
  19612. parse: function ( json ) {
  19613. var geometry = new BufferGeometry();
  19614. var index = json.data.index;
  19615. if ( index !== undefined ) {
  19616. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19617. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19618. }
  19619. var attributes = json.data.attributes;
  19620. for ( var key in attributes ) {
  19621. var attribute = attributes[ key ];
  19622. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19623. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19624. }
  19625. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19626. if ( groups !== undefined ) {
  19627. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19628. var group = groups[ i ];
  19629. geometry.addGroup( group.start, group.count, group.materialIndex );
  19630. }
  19631. }
  19632. var boundingSphere = json.data.boundingSphere;
  19633. if ( boundingSphere !== undefined ) {
  19634. var center = new Vector3();
  19635. if ( boundingSphere.center !== undefined ) {
  19636. center.fromArray( boundingSphere.center );
  19637. }
  19638. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19639. }
  19640. return geometry;
  19641. }
  19642. } );
  19643. var TYPED_ARRAYS = {
  19644. Int8Array: Int8Array,
  19645. Uint8Array: Uint8Array,
  19646. // Workaround for IE11 pre KB2929437. See #11440
  19647. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  19648. Int16Array: Int16Array,
  19649. Uint16Array: Uint16Array,
  19650. Int32Array: Int32Array,
  19651. Uint32Array: Uint32Array,
  19652. Float32Array: Float32Array,
  19653. Float64Array: Float64Array
  19654. };
  19655. /**
  19656. * @author alteredq / http://alteredqualia.com/
  19657. */
  19658. function Loader() {
  19659. this.onLoadStart = function () {};
  19660. this.onLoadProgress = function () {};
  19661. this.onLoadComplete = function () {};
  19662. }
  19663. Loader.Handlers = {
  19664. handlers: [],
  19665. add: function ( regex, loader ) {
  19666. this.handlers.push( regex, loader );
  19667. },
  19668. get: function ( file ) {
  19669. var handlers = this.handlers;
  19670. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19671. var regex = handlers[ i ];
  19672. var loader = handlers[ i + 1 ];
  19673. if ( regex.test( file ) ) {
  19674. return loader;
  19675. }
  19676. }
  19677. return null;
  19678. }
  19679. };
  19680. Object.assign( Loader.prototype, {
  19681. crossOrigin: undefined,
  19682. extractUrlBase: function ( url ) {
  19683. var parts = url.split( '/' );
  19684. if ( parts.length === 1 ) return './';
  19685. parts.pop();
  19686. return parts.join( '/' ) + '/';
  19687. },
  19688. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19689. var array = [];
  19690. for ( var i = 0; i < materials.length; ++ i ) {
  19691. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19692. }
  19693. return array;
  19694. },
  19695. createMaterial: ( function () {
  19696. var BlendingMode = {
  19697. NoBlending: NoBlending,
  19698. NormalBlending: NormalBlending,
  19699. AdditiveBlending: AdditiveBlending,
  19700. SubtractiveBlending: SubtractiveBlending,
  19701. MultiplyBlending: MultiplyBlending,
  19702. CustomBlending: CustomBlending
  19703. };
  19704. var color = new Color();
  19705. var textureLoader = new TextureLoader();
  19706. var materialLoader = new MaterialLoader();
  19707. return function createMaterial( m, texturePath, crossOrigin ) {
  19708. // convert from old material format
  19709. var textures = {};
  19710. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19711. var fullPath = texturePath + path;
  19712. var loader = Loader.Handlers.get( fullPath );
  19713. var texture;
  19714. if ( loader !== null ) {
  19715. texture = loader.load( fullPath );
  19716. } else {
  19717. textureLoader.setCrossOrigin( crossOrigin );
  19718. texture = textureLoader.load( fullPath );
  19719. }
  19720. if ( repeat !== undefined ) {
  19721. texture.repeat.fromArray( repeat );
  19722. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19723. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19724. }
  19725. if ( offset !== undefined ) {
  19726. texture.offset.fromArray( offset );
  19727. }
  19728. if ( wrap !== undefined ) {
  19729. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19730. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19731. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19732. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19733. }
  19734. if ( anisotropy !== undefined ) {
  19735. texture.anisotropy = anisotropy;
  19736. }
  19737. var uuid = _Math.generateUUID();
  19738. textures[ uuid ] = texture;
  19739. return uuid;
  19740. }
  19741. //
  19742. var json = {
  19743. uuid: _Math.generateUUID(),
  19744. type: 'MeshLambertMaterial'
  19745. };
  19746. for ( var name in m ) {
  19747. var value = m[ name ];
  19748. switch ( name ) {
  19749. case 'DbgColor':
  19750. case 'DbgIndex':
  19751. case 'opticalDensity':
  19752. case 'illumination':
  19753. break;
  19754. case 'DbgName':
  19755. json.name = value;
  19756. break;
  19757. case 'blending':
  19758. json.blending = BlendingMode[ value ];
  19759. break;
  19760. case 'colorAmbient':
  19761. case 'mapAmbient':
  19762. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19763. break;
  19764. case 'colorDiffuse':
  19765. json.color = color.fromArray( value ).getHex();
  19766. break;
  19767. case 'colorSpecular':
  19768. json.specular = color.fromArray( value ).getHex();
  19769. break;
  19770. case 'colorEmissive':
  19771. json.emissive = color.fromArray( value ).getHex();
  19772. break;
  19773. case 'specularCoef':
  19774. json.shininess = value;
  19775. break;
  19776. case 'shading':
  19777. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19778. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19779. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19780. break;
  19781. case 'mapDiffuse':
  19782. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19783. break;
  19784. case 'mapDiffuseRepeat':
  19785. case 'mapDiffuseOffset':
  19786. case 'mapDiffuseWrap':
  19787. case 'mapDiffuseAnisotropy':
  19788. break;
  19789. case 'mapEmissive':
  19790. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19791. break;
  19792. case 'mapEmissiveRepeat':
  19793. case 'mapEmissiveOffset':
  19794. case 'mapEmissiveWrap':
  19795. case 'mapEmissiveAnisotropy':
  19796. break;
  19797. case 'mapLight':
  19798. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19799. break;
  19800. case 'mapLightRepeat':
  19801. case 'mapLightOffset':
  19802. case 'mapLightWrap':
  19803. case 'mapLightAnisotropy':
  19804. break;
  19805. case 'mapAO':
  19806. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19807. break;
  19808. case 'mapAORepeat':
  19809. case 'mapAOOffset':
  19810. case 'mapAOWrap':
  19811. case 'mapAOAnisotropy':
  19812. break;
  19813. case 'mapBump':
  19814. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19815. break;
  19816. case 'mapBumpScale':
  19817. json.bumpScale = value;
  19818. break;
  19819. case 'mapBumpRepeat':
  19820. case 'mapBumpOffset':
  19821. case 'mapBumpWrap':
  19822. case 'mapBumpAnisotropy':
  19823. break;
  19824. case 'mapNormal':
  19825. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19826. break;
  19827. case 'mapNormalFactor':
  19828. json.normalScale = [ value, value ];
  19829. break;
  19830. case 'mapNormalRepeat':
  19831. case 'mapNormalOffset':
  19832. case 'mapNormalWrap':
  19833. case 'mapNormalAnisotropy':
  19834. break;
  19835. case 'mapSpecular':
  19836. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19837. break;
  19838. case 'mapSpecularRepeat':
  19839. case 'mapSpecularOffset':
  19840. case 'mapSpecularWrap':
  19841. case 'mapSpecularAnisotropy':
  19842. break;
  19843. case 'mapMetalness':
  19844. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19845. break;
  19846. case 'mapMetalnessRepeat':
  19847. case 'mapMetalnessOffset':
  19848. case 'mapMetalnessWrap':
  19849. case 'mapMetalnessAnisotropy':
  19850. break;
  19851. case 'mapRoughness':
  19852. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19853. break;
  19854. case 'mapRoughnessRepeat':
  19855. case 'mapRoughnessOffset':
  19856. case 'mapRoughnessWrap':
  19857. case 'mapRoughnessAnisotropy':
  19858. break;
  19859. case 'mapAlpha':
  19860. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19861. break;
  19862. case 'mapAlphaRepeat':
  19863. case 'mapAlphaOffset':
  19864. case 'mapAlphaWrap':
  19865. case 'mapAlphaAnisotropy':
  19866. break;
  19867. case 'flipSided':
  19868. json.side = BackSide;
  19869. break;
  19870. case 'doubleSided':
  19871. json.side = DoubleSide;
  19872. break;
  19873. case 'transparency':
  19874. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19875. json.opacity = value;
  19876. break;
  19877. case 'depthTest':
  19878. case 'depthWrite':
  19879. case 'colorWrite':
  19880. case 'opacity':
  19881. case 'reflectivity':
  19882. case 'transparent':
  19883. case 'visible':
  19884. case 'wireframe':
  19885. json[ name ] = value;
  19886. break;
  19887. case 'vertexColors':
  19888. if ( value === true ) json.vertexColors = VertexColors;
  19889. if ( value === 'face' ) json.vertexColors = FaceColors;
  19890. break;
  19891. default:
  19892. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19893. break;
  19894. }
  19895. }
  19896. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19897. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19898. if ( json.opacity < 1 ) json.transparent = true;
  19899. materialLoader.setTextures( textures );
  19900. return materialLoader.parse( json );
  19901. };
  19902. } )()
  19903. } );
  19904. /**
  19905. * @author mrdoob / http://mrdoob.com/
  19906. * @author alteredq / http://alteredqualia.com/
  19907. */
  19908. function JSONLoader( manager ) {
  19909. if ( typeof manager === 'boolean' ) {
  19910. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19911. manager = undefined;
  19912. }
  19913. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19914. this.withCredentials = false;
  19915. }
  19916. Object.assign( JSONLoader.prototype, {
  19917. load: function ( url, onLoad, onProgress, onError ) {
  19918. var scope = this;
  19919. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19920. var loader = new FileLoader( this.manager );
  19921. loader.setWithCredentials( this.withCredentials );
  19922. loader.load( url, function ( text ) {
  19923. var json = JSON.parse( text );
  19924. var metadata = json.metadata;
  19925. if ( metadata !== undefined ) {
  19926. var type = metadata.type;
  19927. if ( type !== undefined ) {
  19928. if ( type.toLowerCase() === 'object' ) {
  19929. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19930. return;
  19931. }
  19932. if ( type.toLowerCase() === 'scene' ) {
  19933. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19934. return;
  19935. }
  19936. }
  19937. }
  19938. var object = scope.parse( json, texturePath );
  19939. onLoad( object.geometry, object.materials );
  19940. }, onProgress, onError );
  19941. },
  19942. setTexturePath: function ( value ) {
  19943. this.texturePath = value;
  19944. },
  19945. parse: ( function () {
  19946. function parseModel( json, geometry ) {
  19947. function isBitSet( value, position ) {
  19948. return value & ( 1 << position );
  19949. }
  19950. var i, j, fi,
  19951. offset, zLength,
  19952. colorIndex, normalIndex, uvIndex, materialIndex,
  19953. type,
  19954. isQuad,
  19955. hasMaterial,
  19956. hasFaceVertexUv,
  19957. hasFaceNormal, hasFaceVertexNormal,
  19958. hasFaceColor, hasFaceVertexColor,
  19959. vertex, face, faceA, faceB, hex, normal,
  19960. uvLayer, uv, u, v,
  19961. faces = json.faces,
  19962. vertices = json.vertices,
  19963. normals = json.normals,
  19964. colors = json.colors,
  19965. scale = json.scale,
  19966. nUvLayers = 0;
  19967. if ( json.uvs !== undefined ) {
  19968. // disregard empty arrays
  19969. for ( i = 0; i < json.uvs.length; i ++ ) {
  19970. if ( json.uvs[ i ].length ) nUvLayers ++;
  19971. }
  19972. for ( i = 0; i < nUvLayers; i ++ ) {
  19973. geometry.faceVertexUvs[ i ] = [];
  19974. }
  19975. }
  19976. offset = 0;
  19977. zLength = vertices.length;
  19978. while ( offset < zLength ) {
  19979. vertex = new Vector3();
  19980. vertex.x = vertices[ offset ++ ] * scale;
  19981. vertex.y = vertices[ offset ++ ] * scale;
  19982. vertex.z = vertices[ offset ++ ] * scale;
  19983. geometry.vertices.push( vertex );
  19984. }
  19985. offset = 0;
  19986. zLength = faces.length;
  19987. while ( offset < zLength ) {
  19988. type = faces[ offset ++ ];
  19989. isQuad = isBitSet( type, 0 );
  19990. hasMaterial = isBitSet( type, 1 );
  19991. hasFaceVertexUv = isBitSet( type, 3 );
  19992. hasFaceNormal = isBitSet( type, 4 );
  19993. hasFaceVertexNormal = isBitSet( type, 5 );
  19994. hasFaceColor = isBitSet( type, 6 );
  19995. hasFaceVertexColor = isBitSet( type, 7 );
  19996. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19997. if ( isQuad ) {
  19998. faceA = new Face3();
  19999. faceA.a = faces[ offset ];
  20000. faceA.b = faces[ offset + 1 ];
  20001. faceA.c = faces[ offset + 3 ];
  20002. faceB = new Face3();
  20003. faceB.a = faces[ offset + 1 ];
  20004. faceB.b = faces[ offset + 2 ];
  20005. faceB.c = faces[ offset + 3 ];
  20006. offset += 4;
  20007. if ( hasMaterial ) {
  20008. materialIndex = faces[ offset ++ ];
  20009. faceA.materialIndex = materialIndex;
  20010. faceB.materialIndex = materialIndex;
  20011. }
  20012. // to get face <=> uv index correspondence
  20013. fi = geometry.faces.length;
  20014. if ( hasFaceVertexUv ) {
  20015. for ( i = 0; i < nUvLayers; i ++ ) {
  20016. uvLayer = json.uvs[ i ];
  20017. geometry.faceVertexUvs[ i ][ fi ] = [];
  20018. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  20019. for ( j = 0; j < 4; j ++ ) {
  20020. uvIndex = faces[ offset ++ ];
  20021. u = uvLayer[ uvIndex * 2 ];
  20022. v = uvLayer[ uvIndex * 2 + 1 ];
  20023. uv = new Vector2( u, v );
  20024. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20025. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  20026. }
  20027. }
  20028. }
  20029. if ( hasFaceNormal ) {
  20030. normalIndex = faces[ offset ++ ] * 3;
  20031. faceA.normal.set(
  20032. normals[ normalIndex ++ ],
  20033. normals[ normalIndex ++ ],
  20034. normals[ normalIndex ]
  20035. );
  20036. faceB.normal.copy( faceA.normal );
  20037. }
  20038. if ( hasFaceVertexNormal ) {
  20039. for ( i = 0; i < 4; i ++ ) {
  20040. normalIndex = faces[ offset ++ ] * 3;
  20041. normal = new Vector3(
  20042. normals[ normalIndex ++ ],
  20043. normals[ normalIndex ++ ],
  20044. normals[ normalIndex ]
  20045. );
  20046. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  20047. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  20048. }
  20049. }
  20050. if ( hasFaceColor ) {
  20051. colorIndex = faces[ offset ++ ];
  20052. hex = colors[ colorIndex ];
  20053. faceA.color.setHex( hex );
  20054. faceB.color.setHex( hex );
  20055. }
  20056. if ( hasFaceVertexColor ) {
  20057. for ( i = 0; i < 4; i ++ ) {
  20058. colorIndex = faces[ offset ++ ];
  20059. hex = colors[ colorIndex ];
  20060. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  20061. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  20062. }
  20063. }
  20064. geometry.faces.push( faceA );
  20065. geometry.faces.push( faceB );
  20066. } else {
  20067. face = new Face3();
  20068. face.a = faces[ offset ++ ];
  20069. face.b = faces[ offset ++ ];
  20070. face.c = faces[ offset ++ ];
  20071. if ( hasMaterial ) {
  20072. materialIndex = faces[ offset ++ ];
  20073. face.materialIndex = materialIndex;
  20074. }
  20075. // to get face <=> uv index correspondence
  20076. fi = geometry.faces.length;
  20077. if ( hasFaceVertexUv ) {
  20078. for ( i = 0; i < nUvLayers; i ++ ) {
  20079. uvLayer = json.uvs[ i ];
  20080. geometry.faceVertexUvs[ i ][ fi ] = [];
  20081. for ( j = 0; j < 3; j ++ ) {
  20082. uvIndex = faces[ offset ++ ];
  20083. u = uvLayer[ uvIndex * 2 ];
  20084. v = uvLayer[ uvIndex * 2 + 1 ];
  20085. uv = new Vector2( u, v );
  20086. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20087. }
  20088. }
  20089. }
  20090. if ( hasFaceNormal ) {
  20091. normalIndex = faces[ offset ++ ] * 3;
  20092. face.normal.set(
  20093. normals[ normalIndex ++ ],
  20094. normals[ normalIndex ++ ],
  20095. normals[ normalIndex ]
  20096. );
  20097. }
  20098. if ( hasFaceVertexNormal ) {
  20099. for ( i = 0; i < 3; i ++ ) {
  20100. normalIndex = faces[ offset ++ ] * 3;
  20101. normal = new Vector3(
  20102. normals[ normalIndex ++ ],
  20103. normals[ normalIndex ++ ],
  20104. normals[ normalIndex ]
  20105. );
  20106. face.vertexNormals.push( normal );
  20107. }
  20108. }
  20109. if ( hasFaceColor ) {
  20110. colorIndex = faces[ offset ++ ];
  20111. face.color.setHex( colors[ colorIndex ] );
  20112. }
  20113. if ( hasFaceVertexColor ) {
  20114. for ( i = 0; i < 3; i ++ ) {
  20115. colorIndex = faces[ offset ++ ];
  20116. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  20117. }
  20118. }
  20119. geometry.faces.push( face );
  20120. }
  20121. }
  20122. }
  20123. function parseSkin( json, geometry ) {
  20124. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  20125. if ( json.skinWeights ) {
  20126. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  20127. var x = json.skinWeights[ i ];
  20128. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  20129. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  20130. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  20131. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  20132. }
  20133. }
  20134. if ( json.skinIndices ) {
  20135. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  20136. var a = json.skinIndices[ i ];
  20137. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  20138. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  20139. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  20140. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  20141. }
  20142. }
  20143. geometry.bones = json.bones;
  20144. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  20145. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  20146. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  20147. }
  20148. }
  20149. function parseMorphing( json, geometry ) {
  20150. var scale = json.scale;
  20151. if ( json.morphTargets !== undefined ) {
  20152. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20153. geometry.morphTargets[ i ] = {};
  20154. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20155. geometry.morphTargets[ i ].vertices = [];
  20156. var dstVertices = geometry.morphTargets[ i ].vertices;
  20157. var srcVertices = json.morphTargets[ i ].vertices;
  20158. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20159. var vertex = new Vector3();
  20160. vertex.x = srcVertices[ v ] * scale;
  20161. vertex.y = srcVertices[ v + 1 ] * scale;
  20162. vertex.z = srcVertices[ v + 2 ] * scale;
  20163. dstVertices.push( vertex );
  20164. }
  20165. }
  20166. }
  20167. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  20168. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  20169. var faces = geometry.faces;
  20170. var morphColors = json.morphColors[ 0 ].colors;
  20171. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20172. faces[ i ].color.fromArray( morphColors, i * 3 );
  20173. }
  20174. }
  20175. }
  20176. function parseAnimations( json, geometry ) {
  20177. var outputAnimations = [];
  20178. // parse old style Bone/Hierarchy animations
  20179. var animations = [];
  20180. if ( json.animation !== undefined ) {
  20181. animations.push( json.animation );
  20182. }
  20183. if ( json.animations !== undefined ) {
  20184. if ( json.animations.length ) {
  20185. animations = animations.concat( json.animations );
  20186. } else {
  20187. animations.push( json.animations );
  20188. }
  20189. }
  20190. for ( var i = 0; i < animations.length; i ++ ) {
  20191. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  20192. if ( clip ) outputAnimations.push( clip );
  20193. }
  20194. // parse implicit morph animations
  20195. if ( geometry.morphTargets ) {
  20196. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  20197. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  20198. outputAnimations = outputAnimations.concat( morphAnimationClips );
  20199. }
  20200. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  20201. }
  20202. return function ( json, texturePath ) {
  20203. if ( json.data !== undefined ) {
  20204. // Geometry 4.0 spec
  20205. json = json.data;
  20206. }
  20207. if ( json.scale !== undefined ) {
  20208. json.scale = 1.0 / json.scale;
  20209. } else {
  20210. json.scale = 1.0;
  20211. }
  20212. var geometry = new Geometry();
  20213. parseModel( json, geometry );
  20214. parseSkin( json, geometry );
  20215. parseMorphing( json, geometry );
  20216. parseAnimations( json, geometry );
  20217. geometry.computeFaceNormals();
  20218. geometry.computeBoundingSphere();
  20219. if ( json.materials === undefined || json.materials.length === 0 ) {
  20220. return { geometry: geometry };
  20221. } else {
  20222. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20223. return { geometry: geometry, materials: materials };
  20224. }
  20225. };
  20226. } )()
  20227. } );
  20228. /**
  20229. * @author mrdoob / http://mrdoob.com/
  20230. */
  20231. function ObjectLoader( manager ) {
  20232. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20233. this.texturePath = '';
  20234. }
  20235. Object.assign( ObjectLoader.prototype, {
  20236. load: function ( url, onLoad, onProgress, onError ) {
  20237. if ( this.texturePath === '' ) {
  20238. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20239. }
  20240. var scope = this;
  20241. var loader = new FileLoader( scope.manager );
  20242. loader.load( url, function ( text ) {
  20243. var json = null;
  20244. try {
  20245. json = JSON.parse( text );
  20246. } catch ( error ) {
  20247. if ( onError !== undefined ) onError( error );
  20248. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20249. return;
  20250. }
  20251. var metadata = json.metadata;
  20252. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20253. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20254. return;
  20255. }
  20256. scope.parse( json, onLoad );
  20257. }, onProgress, onError );
  20258. },
  20259. setTexturePath: function ( value ) {
  20260. this.texturePath = value;
  20261. },
  20262. setCrossOrigin: function ( value ) {
  20263. this.crossOrigin = value;
  20264. },
  20265. parse: function ( json, onLoad ) {
  20266. var geometries = this.parseGeometries( json.geometries );
  20267. var images = this.parseImages( json.images, function () {
  20268. if ( onLoad !== undefined ) onLoad( object );
  20269. } );
  20270. var textures = this.parseTextures( json.textures, images );
  20271. var materials = this.parseMaterials( json.materials, textures );
  20272. var object = this.parseObject( json.object, geometries, materials );
  20273. if ( json.animations ) {
  20274. object.animations = this.parseAnimations( json.animations );
  20275. }
  20276. if ( json.images === undefined || json.images.length === 0 ) {
  20277. if ( onLoad !== undefined ) onLoad( object );
  20278. }
  20279. return object;
  20280. },
  20281. parseGeometries: function ( json ) {
  20282. var geometries = {};
  20283. if ( json !== undefined ) {
  20284. var geometryLoader = new JSONLoader();
  20285. var bufferGeometryLoader = new BufferGeometryLoader();
  20286. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20287. var geometry;
  20288. var data = json[ i ];
  20289. switch ( data.type ) {
  20290. case 'PlaneGeometry':
  20291. case 'PlaneBufferGeometry':
  20292. geometry = new Geometries[ data.type ](
  20293. data.width,
  20294. data.height,
  20295. data.widthSegments,
  20296. data.heightSegments
  20297. );
  20298. break;
  20299. case 'BoxGeometry':
  20300. case 'BoxBufferGeometry':
  20301. case 'CubeGeometry': // backwards compatible
  20302. geometry = new Geometries[ data.type ](
  20303. data.width,
  20304. data.height,
  20305. data.depth,
  20306. data.widthSegments,
  20307. data.heightSegments,
  20308. data.depthSegments
  20309. );
  20310. break;
  20311. case 'CircleGeometry':
  20312. case 'CircleBufferGeometry':
  20313. geometry = new Geometries[ data.type ](
  20314. data.radius,
  20315. data.segments,
  20316. data.thetaStart,
  20317. data.thetaLength
  20318. );
  20319. break;
  20320. case 'CylinderGeometry':
  20321. case 'CylinderBufferGeometry':
  20322. geometry = new Geometries[ data.type ](
  20323. data.radiusTop,
  20324. data.radiusBottom,
  20325. data.height,
  20326. data.radialSegments,
  20327. data.heightSegments,
  20328. data.openEnded,
  20329. data.thetaStart,
  20330. data.thetaLength
  20331. );
  20332. break;
  20333. case 'ConeGeometry':
  20334. case 'ConeBufferGeometry':
  20335. geometry = new Geometries[ data.type ](
  20336. data.radius,
  20337. data.height,
  20338. data.radialSegments,
  20339. data.heightSegments,
  20340. data.openEnded,
  20341. data.thetaStart,
  20342. data.thetaLength
  20343. );
  20344. break;
  20345. case 'SphereGeometry':
  20346. case 'SphereBufferGeometry':
  20347. geometry = new Geometries[ data.type ](
  20348. data.radius,
  20349. data.widthSegments,
  20350. data.heightSegments,
  20351. data.phiStart,
  20352. data.phiLength,
  20353. data.thetaStart,
  20354. data.thetaLength
  20355. );
  20356. break;
  20357. case 'DodecahedronGeometry':
  20358. case 'IcosahedronGeometry':
  20359. case 'OctahedronGeometry':
  20360. case 'TetrahedronGeometry':
  20361. geometry = new Geometries[ data.type ](
  20362. data.radius,
  20363. data.detail
  20364. );
  20365. break;
  20366. case 'RingGeometry':
  20367. case 'RingBufferGeometry':
  20368. geometry = new Geometries[ data.type ](
  20369. data.innerRadius,
  20370. data.outerRadius,
  20371. data.thetaSegments,
  20372. data.phiSegments,
  20373. data.thetaStart,
  20374. data.thetaLength
  20375. );
  20376. break;
  20377. case 'TorusGeometry':
  20378. case 'TorusBufferGeometry':
  20379. geometry = new Geometries[ data.type ](
  20380. data.radius,
  20381. data.tube,
  20382. data.radialSegments,
  20383. data.tubularSegments,
  20384. data.arc
  20385. );
  20386. break;
  20387. case 'TorusKnotGeometry':
  20388. case 'TorusKnotBufferGeometry':
  20389. geometry = new Geometries[ data.type ](
  20390. data.radius,
  20391. data.tube,
  20392. data.tubularSegments,
  20393. data.radialSegments,
  20394. data.p,
  20395. data.q
  20396. );
  20397. break;
  20398. case 'LatheGeometry':
  20399. case 'LatheBufferGeometry':
  20400. geometry = new Geometries[ data.type ](
  20401. data.points,
  20402. data.segments,
  20403. data.phiStart,
  20404. data.phiLength
  20405. );
  20406. break;
  20407. case 'BufferGeometry':
  20408. geometry = bufferGeometryLoader.parse( data );
  20409. break;
  20410. case 'Geometry':
  20411. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20412. break;
  20413. default:
  20414. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20415. continue;
  20416. }
  20417. geometry.uuid = data.uuid;
  20418. if ( data.name !== undefined ) geometry.name = data.name;
  20419. geometries[ data.uuid ] = geometry;
  20420. }
  20421. }
  20422. return geometries;
  20423. },
  20424. parseMaterials: function ( json, textures ) {
  20425. var materials = {};
  20426. if ( json !== undefined ) {
  20427. var loader = new MaterialLoader();
  20428. loader.setTextures( textures );
  20429. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20430. var data = json[ i ];
  20431. if ( data.type === 'MultiMaterial' ) {
  20432. // Deprecated
  20433. var array = [];
  20434. for ( var j = 0; j < data.materials.length; j ++ ) {
  20435. array.push( loader.parse( data.materials[ j ] ) );
  20436. }
  20437. materials[ data.uuid ] = array;
  20438. } else {
  20439. materials[ data.uuid ] = loader.parse( data );
  20440. }
  20441. }
  20442. }
  20443. return materials;
  20444. },
  20445. parseAnimations: function ( json ) {
  20446. var animations = [];
  20447. for ( var i = 0; i < json.length; i ++ ) {
  20448. var clip = AnimationClip.parse( json[ i ] );
  20449. animations.push( clip );
  20450. }
  20451. return animations;
  20452. },
  20453. parseImages: function ( json, onLoad ) {
  20454. var scope = this;
  20455. var images = {};
  20456. function loadImage( url ) {
  20457. scope.manager.itemStart( url );
  20458. return loader.load( url, function () {
  20459. scope.manager.itemEnd( url );
  20460. }, undefined, function () {
  20461. scope.manager.itemEnd( url );
  20462. scope.manager.itemError( url );
  20463. } );
  20464. }
  20465. if ( json !== undefined && json.length > 0 ) {
  20466. var manager = new LoadingManager( onLoad );
  20467. var loader = new ImageLoader( manager );
  20468. loader.setCrossOrigin( this.crossOrigin );
  20469. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20470. var image = json[ i ];
  20471. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20472. images[ image.uuid ] = loadImage( path );
  20473. }
  20474. }
  20475. return images;
  20476. },
  20477. parseTextures: function ( json, images ) {
  20478. function parseConstant( value, type ) {
  20479. if ( typeof( value ) === 'number' ) return value;
  20480. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20481. return type[ value ];
  20482. }
  20483. var textures = {};
  20484. if ( json !== undefined ) {
  20485. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20486. var data = json[ i ];
  20487. if ( data.image === undefined ) {
  20488. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20489. }
  20490. if ( images[ data.image ] === undefined ) {
  20491. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20492. }
  20493. var texture = new Texture( images[ data.image ] );
  20494. texture.needsUpdate = true;
  20495. texture.uuid = data.uuid;
  20496. if ( data.name !== undefined ) texture.name = data.name;
  20497. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20498. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20499. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20500. if ( data.wrap !== undefined ) {
  20501. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20502. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20503. }
  20504. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20505. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20506. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20507. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20508. textures[ data.uuid ] = texture;
  20509. }
  20510. }
  20511. return textures;
  20512. },
  20513. parseObject: function () {
  20514. var matrix = new Matrix4();
  20515. return function parseObject( data, geometries, materials ) {
  20516. var object;
  20517. function getGeometry( name ) {
  20518. if ( geometries[ name ] === undefined ) {
  20519. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20520. }
  20521. return geometries[ name ];
  20522. }
  20523. function getMaterial( name ) {
  20524. if ( name === undefined ) return undefined;
  20525. if ( Array.isArray( name ) ) {
  20526. var array = [];
  20527. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20528. var uuid = name[ i ];
  20529. if ( materials[ uuid ] === undefined ) {
  20530. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20531. }
  20532. array.push( materials[ uuid ] );
  20533. }
  20534. return array;
  20535. }
  20536. if ( materials[ name ] === undefined ) {
  20537. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20538. }
  20539. return materials[ name ];
  20540. }
  20541. switch ( data.type ) {
  20542. case 'Scene':
  20543. object = new Scene();
  20544. if ( data.background !== undefined ) {
  20545. if ( Number.isInteger( data.background ) ) {
  20546. object.background = new Color( data.background );
  20547. }
  20548. }
  20549. if ( data.fog !== undefined ) {
  20550. if ( data.fog.type === 'Fog' ) {
  20551. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20552. } else if ( data.fog.type === 'FogExp2' ) {
  20553. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20554. }
  20555. }
  20556. break;
  20557. case 'PerspectiveCamera':
  20558. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20559. if ( data.focus !== undefined ) object.focus = data.focus;
  20560. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20561. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20562. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20563. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20564. break;
  20565. case 'OrthographicCamera':
  20566. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20567. break;
  20568. case 'AmbientLight':
  20569. object = new AmbientLight( data.color, data.intensity );
  20570. break;
  20571. case 'DirectionalLight':
  20572. object = new DirectionalLight( data.color, data.intensity );
  20573. break;
  20574. case 'PointLight':
  20575. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20576. break;
  20577. case 'RectAreaLight':
  20578. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20579. break;
  20580. case 'SpotLight':
  20581. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20582. break;
  20583. case 'HemisphereLight':
  20584. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20585. break;
  20586. case 'SkinnedMesh':
  20587. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20588. case 'Mesh':
  20589. var geometry = getGeometry( data.geometry );
  20590. var material = getMaterial( data.material );
  20591. if ( geometry.bones && geometry.bones.length > 0 ) {
  20592. object = new SkinnedMesh( geometry, material );
  20593. } else {
  20594. object = new Mesh( geometry, material );
  20595. }
  20596. break;
  20597. case 'LOD':
  20598. object = new LOD();
  20599. break;
  20600. case 'Line':
  20601. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20602. break;
  20603. case 'LineLoop':
  20604. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20605. break;
  20606. case 'LineSegments':
  20607. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20608. break;
  20609. case 'PointCloud':
  20610. case 'Points':
  20611. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20612. break;
  20613. case 'Sprite':
  20614. object = new Sprite( getMaterial( data.material ) );
  20615. break;
  20616. case 'Group':
  20617. object = new Group();
  20618. break;
  20619. default:
  20620. object = new Object3D();
  20621. }
  20622. object.uuid = data.uuid;
  20623. if ( data.name !== undefined ) object.name = data.name;
  20624. if ( data.matrix !== undefined ) {
  20625. matrix.fromArray( data.matrix );
  20626. matrix.decompose( object.position, object.quaternion, object.scale );
  20627. } else {
  20628. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20629. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20630. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20631. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20632. }
  20633. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20634. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20635. if ( data.shadow ) {
  20636. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20637. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20638. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20639. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20640. }
  20641. if ( data.visible !== undefined ) object.visible = data.visible;
  20642. if ( data.userData !== undefined ) object.userData = data.userData;
  20643. if ( data.children !== undefined ) {
  20644. for ( var child in data.children ) {
  20645. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20646. }
  20647. }
  20648. if ( data.type === 'LOD' ) {
  20649. var levels = data.levels;
  20650. for ( var l = 0; l < levels.length; l ++ ) {
  20651. var level = levels[ l ];
  20652. var child = object.getObjectByProperty( 'uuid', level.object );
  20653. if ( child !== undefined ) {
  20654. object.addLevel( child, level.distance );
  20655. }
  20656. }
  20657. }
  20658. return object;
  20659. };
  20660. }()
  20661. } );
  20662. var TEXTURE_MAPPING = {
  20663. UVMapping: UVMapping,
  20664. CubeReflectionMapping: CubeReflectionMapping,
  20665. CubeRefractionMapping: CubeRefractionMapping,
  20666. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20667. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20668. SphericalReflectionMapping: SphericalReflectionMapping,
  20669. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20670. CubeUVRefractionMapping: CubeUVRefractionMapping
  20671. };
  20672. var TEXTURE_WRAPPING = {
  20673. RepeatWrapping: RepeatWrapping,
  20674. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20675. MirroredRepeatWrapping: MirroredRepeatWrapping
  20676. };
  20677. var TEXTURE_FILTER = {
  20678. NearestFilter: NearestFilter,
  20679. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20680. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20681. LinearFilter: LinearFilter,
  20682. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20683. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20684. };
  20685. /**
  20686. * @author zz85 / http://www.lab4games.net/zz85/blog
  20687. *
  20688. * Bezier Curves formulas obtained from
  20689. * http://en.wikipedia.org/wiki/Bézier_curve
  20690. */
  20691. function CatmullRom( t, p0, p1, p2, p3 ) {
  20692. var v0 = ( p2 - p0 ) * 0.5;
  20693. var v1 = ( p3 - p1 ) * 0.5;
  20694. var t2 = t * t;
  20695. var t3 = t * t2;
  20696. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20697. }
  20698. //
  20699. function QuadraticBezierP0( t, p ) {
  20700. var k = 1 - t;
  20701. return k * k * p;
  20702. }
  20703. function QuadraticBezierP1( t, p ) {
  20704. return 2 * ( 1 - t ) * t * p;
  20705. }
  20706. function QuadraticBezierP2( t, p ) {
  20707. return t * t * p;
  20708. }
  20709. function QuadraticBezier( t, p0, p1, p2 ) {
  20710. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20711. QuadraticBezierP2( t, p2 );
  20712. }
  20713. //
  20714. function CubicBezierP0( t, p ) {
  20715. var k = 1 - t;
  20716. return k * k * k * p;
  20717. }
  20718. function CubicBezierP1( t, p ) {
  20719. var k = 1 - t;
  20720. return 3 * k * k * t * p;
  20721. }
  20722. function CubicBezierP2( t, p ) {
  20723. return 3 * ( 1 - t ) * t * t * p;
  20724. }
  20725. function CubicBezierP3( t, p ) {
  20726. return t * t * t * p;
  20727. }
  20728. function CubicBezier( t, p0, p1, p2, p3 ) {
  20729. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20730. CubicBezierP3( t, p3 );
  20731. }
  20732. /**
  20733. * @author zz85 / http://www.lab4games.net/zz85/blog
  20734. * Extensible curve object
  20735. *
  20736. * Some common of curve methods:
  20737. * .getPoint(t), getTangent(t)
  20738. * .getPointAt(u), getTangentAt(u)
  20739. * .getPoints(), .getSpacedPoints()
  20740. * .getLength()
  20741. * .updateArcLengths()
  20742. *
  20743. * This following curves inherit from THREE.Curve:
  20744. *
  20745. * -- 2D curves --
  20746. * THREE.ArcCurve
  20747. * THREE.CubicBezierCurve
  20748. * THREE.EllipseCurve
  20749. * THREE.LineCurve
  20750. * THREE.QuadraticBezierCurve
  20751. * THREE.SplineCurve
  20752. *
  20753. * -- 3D curves --
  20754. * THREE.CatmullRomCurve3
  20755. * THREE.CubicBezierCurve3
  20756. * THREE.LineCurve3
  20757. * THREE.QuadraticBezierCurve3
  20758. *
  20759. * A series of curves can be represented as a THREE.CurvePath.
  20760. *
  20761. **/
  20762. /**************************************************************
  20763. * Abstract Curve base class
  20764. **************************************************************/
  20765. function Curve() {
  20766. this.arcLengthDivisions = 200;
  20767. }
  20768. Object.assign( Curve.prototype, {
  20769. // Virtual base class method to overwrite and implement in subclasses
  20770. // - t [0 .. 1]
  20771. getPoint: function () {
  20772. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20773. return null;
  20774. },
  20775. // Get point at relative position in curve according to arc length
  20776. // - u [0 .. 1]
  20777. getPointAt: function ( u ) {
  20778. var t = this.getUtoTmapping( u );
  20779. return this.getPoint( t );
  20780. },
  20781. // Get sequence of points using getPoint( t )
  20782. getPoints: function ( divisions ) {
  20783. if ( divisions === undefined ) divisions = 5;
  20784. var points = [];
  20785. for ( var d = 0; d <= divisions; d ++ ) {
  20786. points.push( this.getPoint( d / divisions ) );
  20787. }
  20788. return points;
  20789. },
  20790. // Get sequence of points using getPointAt( u )
  20791. getSpacedPoints: function ( divisions ) {
  20792. if ( divisions === undefined ) divisions = 5;
  20793. var points = [];
  20794. for ( var d = 0; d <= divisions; d ++ ) {
  20795. points.push( this.getPointAt( d / divisions ) );
  20796. }
  20797. return points;
  20798. },
  20799. // Get total curve arc length
  20800. getLength: function () {
  20801. var lengths = this.getLengths();
  20802. return lengths[ lengths.length - 1 ];
  20803. },
  20804. // Get list of cumulative segment lengths
  20805. getLengths: function ( divisions ) {
  20806. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20807. if ( this.cacheArcLengths &&
  20808. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20809. ! this.needsUpdate ) {
  20810. return this.cacheArcLengths;
  20811. }
  20812. this.needsUpdate = false;
  20813. var cache = [];
  20814. var current, last = this.getPoint( 0 );
  20815. var p, sum = 0;
  20816. cache.push( 0 );
  20817. for ( p = 1; p <= divisions; p ++ ) {
  20818. current = this.getPoint( p / divisions );
  20819. sum += current.distanceTo( last );
  20820. cache.push( sum );
  20821. last = current;
  20822. }
  20823. this.cacheArcLengths = cache;
  20824. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20825. },
  20826. updateArcLengths: function () {
  20827. this.needsUpdate = true;
  20828. this.getLengths();
  20829. },
  20830. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20831. getUtoTmapping: function ( u, distance ) {
  20832. var arcLengths = this.getLengths();
  20833. var i = 0, il = arcLengths.length;
  20834. var targetArcLength; // The targeted u distance value to get
  20835. if ( distance ) {
  20836. targetArcLength = distance;
  20837. } else {
  20838. targetArcLength = u * arcLengths[ il - 1 ];
  20839. }
  20840. // binary search for the index with largest value smaller than target u distance
  20841. var low = 0, high = il - 1, comparison;
  20842. while ( low <= high ) {
  20843. 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
  20844. comparison = arcLengths[ i ] - targetArcLength;
  20845. if ( comparison < 0 ) {
  20846. low = i + 1;
  20847. } else if ( comparison > 0 ) {
  20848. high = i - 1;
  20849. } else {
  20850. high = i;
  20851. break;
  20852. // DONE
  20853. }
  20854. }
  20855. i = high;
  20856. if ( arcLengths[ i ] === targetArcLength ) {
  20857. return i / ( il - 1 );
  20858. }
  20859. // we could get finer grain at lengths, or use simple interpolation between two points
  20860. var lengthBefore = arcLengths[ i ];
  20861. var lengthAfter = arcLengths[ i + 1 ];
  20862. var segmentLength = lengthAfter - lengthBefore;
  20863. // determine where we are between the 'before' and 'after' points
  20864. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20865. // add that fractional amount to t
  20866. var t = ( i + segmentFraction ) / ( il - 1 );
  20867. return t;
  20868. },
  20869. // Returns a unit vector tangent at t
  20870. // In case any sub curve does not implement its tangent derivation,
  20871. // 2 points a small delta apart will be used to find its gradient
  20872. // which seems to give a reasonable approximation
  20873. getTangent: function ( t ) {
  20874. var delta = 0.0001;
  20875. var t1 = t - delta;
  20876. var t2 = t + delta;
  20877. // Capping in case of danger
  20878. if ( t1 < 0 ) t1 = 0;
  20879. if ( t2 > 1 ) t2 = 1;
  20880. var pt1 = this.getPoint( t1 );
  20881. var pt2 = this.getPoint( t2 );
  20882. var vec = pt2.clone().sub( pt1 );
  20883. return vec.normalize();
  20884. },
  20885. getTangentAt: function ( u ) {
  20886. var t = this.getUtoTmapping( u );
  20887. return this.getTangent( t );
  20888. },
  20889. computeFrenetFrames: function ( segments, closed ) {
  20890. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20891. var normal = new Vector3();
  20892. var tangents = [];
  20893. var normals = [];
  20894. var binormals = [];
  20895. var vec = new Vector3();
  20896. var mat = new Matrix4();
  20897. var i, u, theta;
  20898. // compute the tangent vectors for each segment on the curve
  20899. for ( i = 0; i <= segments; i ++ ) {
  20900. u = i / segments;
  20901. tangents[ i ] = this.getTangentAt( u );
  20902. tangents[ i ].normalize();
  20903. }
  20904. // select an initial normal vector perpendicular to the first tangent vector,
  20905. // and in the direction of the minimum tangent xyz component
  20906. normals[ 0 ] = new Vector3();
  20907. binormals[ 0 ] = new Vector3();
  20908. var min = Number.MAX_VALUE;
  20909. var tx = Math.abs( tangents[ 0 ].x );
  20910. var ty = Math.abs( tangents[ 0 ].y );
  20911. var tz = Math.abs( tangents[ 0 ].z );
  20912. if ( tx <= min ) {
  20913. min = tx;
  20914. normal.set( 1, 0, 0 );
  20915. }
  20916. if ( ty <= min ) {
  20917. min = ty;
  20918. normal.set( 0, 1, 0 );
  20919. }
  20920. if ( tz <= min ) {
  20921. normal.set( 0, 0, 1 );
  20922. }
  20923. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20924. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20925. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20926. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20927. for ( i = 1; i <= segments; i ++ ) {
  20928. normals[ i ] = normals[ i - 1 ].clone();
  20929. binormals[ i ] = binormals[ i - 1 ].clone();
  20930. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20931. if ( vec.length() > Number.EPSILON ) {
  20932. vec.normalize();
  20933. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20934. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20935. }
  20936. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20937. }
  20938. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20939. if ( closed === true ) {
  20940. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20941. theta /= segments;
  20942. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20943. theta = - theta;
  20944. }
  20945. for ( i = 1; i <= segments; i ++ ) {
  20946. // twist a little...
  20947. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20948. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20949. }
  20950. }
  20951. return {
  20952. tangents: tangents,
  20953. normals: normals,
  20954. binormals: binormals
  20955. };
  20956. }
  20957. } );
  20958. function LineCurve( v1, v2 ) {
  20959. Curve.call( this );
  20960. this.v1 = v1;
  20961. this.v2 = v2;
  20962. }
  20963. LineCurve.prototype = Object.create( Curve.prototype );
  20964. LineCurve.prototype.constructor = LineCurve;
  20965. LineCurve.prototype.isLineCurve = true;
  20966. LineCurve.prototype.getPoint = function ( t ) {
  20967. if ( t === 1 ) {
  20968. return this.v2.clone();
  20969. }
  20970. var point = this.v2.clone().sub( this.v1 );
  20971. point.multiplyScalar( t ).add( this.v1 );
  20972. return point;
  20973. };
  20974. // Line curve is linear, so we can overwrite default getPointAt
  20975. LineCurve.prototype.getPointAt = function ( u ) {
  20976. return this.getPoint( u );
  20977. };
  20978. LineCurve.prototype.getTangent = function ( t ) {
  20979. var tangent = this.v2.clone().sub( this.v1 );
  20980. return tangent.normalize();
  20981. };
  20982. /**
  20983. * @author zz85 / http://www.lab4games.net/zz85/blog
  20984. *
  20985. **/
  20986. /**************************************************************
  20987. * Curved Path - a curve path is simply a array of connected
  20988. * curves, but retains the api of a curve
  20989. **************************************************************/
  20990. function CurvePath() {
  20991. Curve.call( this );
  20992. this.curves = [];
  20993. this.autoClose = false; // Automatically closes the path
  20994. }
  20995. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20996. constructor: CurvePath,
  20997. add: function ( curve ) {
  20998. this.curves.push( curve );
  20999. },
  21000. closePath: function () {
  21001. // Add a line curve if start and end of lines are not connected
  21002. var startPoint = this.curves[ 0 ].getPoint( 0 );
  21003. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21004. if ( ! startPoint.equals( endPoint ) ) {
  21005. this.curves.push( new LineCurve( endPoint, startPoint ) );
  21006. }
  21007. },
  21008. // To get accurate point with reference to
  21009. // entire path distance at time t,
  21010. // following has to be done:
  21011. // 1. Length of each sub path have to be known
  21012. // 2. Locate and identify type of curve
  21013. // 3. Get t for the curve
  21014. // 4. Return curve.getPointAt(t')
  21015. getPoint: function ( t ) {
  21016. var d = t * this.getLength();
  21017. var curveLengths = this.getCurveLengths();
  21018. var i = 0;
  21019. // To think about boundaries points.
  21020. while ( i < curveLengths.length ) {
  21021. if ( curveLengths[ i ] >= d ) {
  21022. var diff = curveLengths[ i ] - d;
  21023. var curve = this.curves[ i ];
  21024. var segmentLength = curve.getLength();
  21025. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21026. return curve.getPointAt( u );
  21027. }
  21028. i ++;
  21029. }
  21030. return null;
  21031. // loop where sum != 0, sum > d , sum+1 <d
  21032. },
  21033. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21034. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21035. // getPoint() depends on getLength
  21036. getLength: function () {
  21037. var lens = this.getCurveLengths();
  21038. return lens[ lens.length - 1 ];
  21039. },
  21040. // cacheLengths must be recalculated.
  21041. updateArcLengths: function () {
  21042. this.needsUpdate = true;
  21043. this.cacheLengths = null;
  21044. this.getCurveLengths();
  21045. },
  21046. // Compute lengths and cache them
  21047. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21048. getCurveLengths: function () {
  21049. // We use cache values if curves and cache array are same length
  21050. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21051. return this.cacheLengths;
  21052. }
  21053. // Get length of sub-curve
  21054. // Push sums into cached array
  21055. var lengths = [], sums = 0;
  21056. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  21057. sums += this.curves[ i ].getLength();
  21058. lengths.push( sums );
  21059. }
  21060. this.cacheLengths = lengths;
  21061. return lengths;
  21062. },
  21063. getSpacedPoints: function ( divisions ) {
  21064. if ( divisions === undefined ) divisions = 40;
  21065. var points = [];
  21066. for ( var i = 0; i <= divisions; i ++ ) {
  21067. points.push( this.getPoint( i / divisions ) );
  21068. }
  21069. if ( this.autoClose ) {
  21070. points.push( points[ 0 ] );
  21071. }
  21072. return points;
  21073. },
  21074. getPoints: function ( divisions ) {
  21075. divisions = divisions || 12;
  21076. var points = [], last;
  21077. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21078. var curve = curves[ i ];
  21079. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  21080. : (curve && curve.isLineCurve) ? 1
  21081. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  21082. : divisions;
  21083. var pts = curve.getPoints( resolution );
  21084. for ( var j = 0; j < pts.length; j++ ) {
  21085. var point = pts[ j ];
  21086. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21087. points.push( point );
  21088. last = point;
  21089. }
  21090. }
  21091. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21092. points.push( points[ 0 ] );
  21093. }
  21094. return points;
  21095. },
  21096. /**************************************************************
  21097. * Create Geometries Helpers
  21098. **************************************************************/
  21099. /// Generate geometry from path points (for Line or Points objects)
  21100. createPointsGeometry: function ( divisions ) {
  21101. var pts = this.getPoints( divisions );
  21102. return this.createGeometry( pts );
  21103. },
  21104. // Generate geometry from equidistant sampling along the path
  21105. createSpacedPointsGeometry: function ( divisions ) {
  21106. var pts = this.getSpacedPoints( divisions );
  21107. return this.createGeometry( pts );
  21108. },
  21109. createGeometry: function ( points ) {
  21110. var geometry = new Geometry();
  21111. for ( var i = 0, l = points.length; i < l; i ++ ) {
  21112. var point = points[ i ];
  21113. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  21114. }
  21115. return geometry;
  21116. }
  21117. } );
  21118. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21119. Curve.call( this );
  21120. this.aX = aX;
  21121. this.aY = aY;
  21122. this.xRadius = xRadius;
  21123. this.yRadius = yRadius;
  21124. this.aStartAngle = aStartAngle;
  21125. this.aEndAngle = aEndAngle;
  21126. this.aClockwise = aClockwise;
  21127. this.aRotation = aRotation || 0;
  21128. }
  21129. EllipseCurve.prototype = Object.create( Curve.prototype );
  21130. EllipseCurve.prototype.constructor = EllipseCurve;
  21131. EllipseCurve.prototype.isEllipseCurve = true;
  21132. EllipseCurve.prototype.getPoint = function ( t ) {
  21133. var twoPi = Math.PI * 2;
  21134. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21135. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21136. // ensures that deltaAngle is 0 .. 2 PI
  21137. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21138. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21139. if ( deltaAngle < Number.EPSILON ) {
  21140. if ( samePoints ) {
  21141. deltaAngle = 0;
  21142. } else {
  21143. deltaAngle = twoPi;
  21144. }
  21145. }
  21146. if ( this.aClockwise === true && ! samePoints ) {
  21147. if ( deltaAngle === twoPi ) {
  21148. deltaAngle = - twoPi;
  21149. } else {
  21150. deltaAngle = deltaAngle - twoPi;
  21151. }
  21152. }
  21153. var angle = this.aStartAngle + t * deltaAngle;
  21154. var x = this.aX + this.xRadius * Math.cos( angle );
  21155. var y = this.aY + this.yRadius * Math.sin( angle );
  21156. if ( this.aRotation !== 0 ) {
  21157. var cos = Math.cos( this.aRotation );
  21158. var sin = Math.sin( this.aRotation );
  21159. var tx = x - this.aX;
  21160. var ty = y - this.aY;
  21161. // Rotate the point about the center of the ellipse.
  21162. x = tx * cos - ty * sin + this.aX;
  21163. y = tx * sin + ty * cos + this.aY;
  21164. }
  21165. return new Vector2( x, y );
  21166. };
  21167. function SplineCurve( points /* array of Vector2 */ ) {
  21168. Curve.call( this );
  21169. this.points = ( points === undefined ) ? [] : points;
  21170. }
  21171. SplineCurve.prototype = Object.create( Curve.prototype );
  21172. SplineCurve.prototype.constructor = SplineCurve;
  21173. SplineCurve.prototype.isSplineCurve = true;
  21174. SplineCurve.prototype.getPoint = function ( t ) {
  21175. var points = this.points;
  21176. var point = ( points.length - 1 ) * t;
  21177. var intPoint = Math.floor( point );
  21178. var weight = point - intPoint;
  21179. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21180. var point1 = points[ intPoint ];
  21181. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21182. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21183. return new Vector2(
  21184. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  21185. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  21186. );
  21187. };
  21188. function CubicBezierCurve( v0, v1, v2, v3 ) {
  21189. Curve.call( this );
  21190. this.v0 = v0;
  21191. this.v1 = v1;
  21192. this.v2 = v2;
  21193. this.v3 = v3;
  21194. }
  21195. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  21196. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  21197. CubicBezierCurve.prototype.getPoint = function ( t ) {
  21198. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21199. return new Vector2(
  21200. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21201. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21202. );
  21203. };
  21204. function QuadraticBezierCurve( v0, v1, v2 ) {
  21205. Curve.call( this );
  21206. this.v0 = v0;
  21207. this.v1 = v1;
  21208. this.v2 = v2;
  21209. }
  21210. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  21211. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  21212. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21213. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21214. return new Vector2(
  21215. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21216. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21217. );
  21218. };
  21219. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21220. fromPoints: function ( vectors ) {
  21221. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21222. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21223. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21224. }
  21225. },
  21226. moveTo: function ( x, y ) {
  21227. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21228. },
  21229. lineTo: function ( x, y ) {
  21230. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21231. this.curves.push( curve );
  21232. this.currentPoint.set( x, y );
  21233. },
  21234. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21235. var curve = new QuadraticBezierCurve(
  21236. this.currentPoint.clone(),
  21237. new Vector2( aCPx, aCPy ),
  21238. new Vector2( aX, aY )
  21239. );
  21240. this.curves.push( curve );
  21241. this.currentPoint.set( aX, aY );
  21242. },
  21243. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21244. var curve = new CubicBezierCurve(
  21245. this.currentPoint.clone(),
  21246. new Vector2( aCP1x, aCP1y ),
  21247. new Vector2( aCP2x, aCP2y ),
  21248. new Vector2( aX, aY )
  21249. );
  21250. this.curves.push( curve );
  21251. this.currentPoint.set( aX, aY );
  21252. },
  21253. splineThru: function ( pts /*Array of Vector*/ ) {
  21254. var npts = [ this.currentPoint.clone() ].concat( pts );
  21255. var curve = new SplineCurve( npts );
  21256. this.curves.push( curve );
  21257. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21258. },
  21259. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21260. var x0 = this.currentPoint.x;
  21261. var y0 = this.currentPoint.y;
  21262. this.absarc( aX + x0, aY + y0, aRadius,
  21263. aStartAngle, aEndAngle, aClockwise );
  21264. },
  21265. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21266. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21267. },
  21268. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21269. var x0 = this.currentPoint.x;
  21270. var y0 = this.currentPoint.y;
  21271. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21272. },
  21273. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21274. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21275. if ( this.curves.length > 0 ) {
  21276. // if a previous curve is present, attempt to join
  21277. var firstPoint = curve.getPoint( 0 );
  21278. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21279. this.lineTo( firstPoint.x, firstPoint.y );
  21280. }
  21281. }
  21282. this.curves.push( curve );
  21283. var lastPoint = curve.getPoint( 1 );
  21284. this.currentPoint.copy( lastPoint );
  21285. }
  21286. } );
  21287. /**
  21288. * @author zz85 / http://www.lab4games.net/zz85/blog
  21289. * Creates free form 2d path using series of points, lines or curves.
  21290. **/
  21291. function Path( points ) {
  21292. CurvePath.call( this );
  21293. this.currentPoint = new Vector2();
  21294. if ( points ) {
  21295. this.fromPoints( points );
  21296. }
  21297. }
  21298. Path.prototype = PathPrototype;
  21299. PathPrototype.constructor = Path;
  21300. /**
  21301. * @author zz85 / http://www.lab4games.net/zz85/blog
  21302. * Defines a 2d shape plane using paths.
  21303. **/
  21304. // STEP 1 Create a path.
  21305. // STEP 2 Turn path into shape.
  21306. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21307. // STEP 3a - Extract points from each shape, turn to vertices
  21308. // STEP 3b - Triangulate each shape, add faces.
  21309. function Shape() {
  21310. Path.apply( this, arguments );
  21311. this.holes = [];
  21312. }
  21313. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21314. constructor: Shape,
  21315. getPointsHoles: function ( divisions ) {
  21316. var holesPts = [];
  21317. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21318. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21319. }
  21320. return holesPts;
  21321. },
  21322. // Get points of shape and holes (keypoints based on segments parameter)
  21323. extractAllPoints: function ( divisions ) {
  21324. return {
  21325. shape: this.getPoints( divisions ),
  21326. holes: this.getPointsHoles( divisions )
  21327. };
  21328. },
  21329. extractPoints: function ( divisions ) {
  21330. return this.extractAllPoints( divisions );
  21331. }
  21332. } );
  21333. /**
  21334. * @author zz85 / http://www.lab4games.net/zz85/blog
  21335. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21336. **/
  21337. function ShapePath() {
  21338. this.subPaths = [];
  21339. this.currentPath = null;
  21340. }
  21341. Object.assign( ShapePath.prototype, {
  21342. moveTo: function ( x, y ) {
  21343. this.currentPath = new Path();
  21344. this.subPaths.push( this.currentPath );
  21345. this.currentPath.moveTo( x, y );
  21346. },
  21347. lineTo: function ( x, y ) {
  21348. this.currentPath.lineTo( x, y );
  21349. },
  21350. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21351. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21352. },
  21353. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21354. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21355. },
  21356. splineThru: function ( pts ) {
  21357. this.currentPath.splineThru( pts );
  21358. },
  21359. toShapes: function ( isCCW, noHoles ) {
  21360. function toShapesNoHoles( inSubpaths ) {
  21361. var shapes = [];
  21362. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21363. var tmpPath = inSubpaths[ i ];
  21364. var tmpShape = new Shape();
  21365. tmpShape.curves = tmpPath.curves;
  21366. shapes.push( tmpShape );
  21367. }
  21368. return shapes;
  21369. }
  21370. function isPointInsidePolygon( inPt, inPolygon ) {
  21371. var polyLen = inPolygon.length;
  21372. // inPt on polygon contour => immediate success or
  21373. // toggling of inside/outside at every single! intersection point of an edge
  21374. // with the horizontal line through inPt, left of inPt
  21375. // not counting lowerY endpoints of edges and whole edges on that line
  21376. var inside = false;
  21377. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21378. var edgeLowPt = inPolygon[ p ];
  21379. var edgeHighPt = inPolygon[ q ];
  21380. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21381. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21382. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21383. // not parallel
  21384. if ( edgeDy < 0 ) {
  21385. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21386. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21387. }
  21388. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21389. if ( inPt.y === edgeLowPt.y ) {
  21390. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21391. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21392. } else {
  21393. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21394. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21395. if ( perpEdge < 0 ) continue;
  21396. inside = ! inside; // true intersection left of inPt
  21397. }
  21398. } else {
  21399. // parallel or collinear
  21400. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21401. // edge lies on the same horizontal line as inPt
  21402. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21403. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21404. // continue;
  21405. }
  21406. }
  21407. return inside;
  21408. }
  21409. var isClockWise = ShapeUtils.isClockWise;
  21410. var subPaths = this.subPaths;
  21411. if ( subPaths.length === 0 ) return [];
  21412. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21413. var solid, tmpPath, tmpShape, shapes = [];
  21414. if ( subPaths.length === 1 ) {
  21415. tmpPath = subPaths[ 0 ];
  21416. tmpShape = new Shape();
  21417. tmpShape.curves = tmpPath.curves;
  21418. shapes.push( tmpShape );
  21419. return shapes;
  21420. }
  21421. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21422. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21423. // console.log("Holes first", holesFirst);
  21424. var betterShapeHoles = [];
  21425. var newShapes = [];
  21426. var newShapeHoles = [];
  21427. var mainIdx = 0;
  21428. var tmpPoints;
  21429. newShapes[ mainIdx ] = undefined;
  21430. newShapeHoles[ mainIdx ] = [];
  21431. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21432. tmpPath = subPaths[ i ];
  21433. tmpPoints = tmpPath.getPoints();
  21434. solid = isClockWise( tmpPoints );
  21435. solid = isCCW ? ! solid : solid;
  21436. if ( solid ) {
  21437. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21438. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21439. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21440. if ( holesFirst ) mainIdx ++;
  21441. newShapeHoles[ mainIdx ] = [];
  21442. //console.log('cw', i);
  21443. } else {
  21444. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21445. //console.log('ccw', i);
  21446. }
  21447. }
  21448. // only Holes? -> probably all Shapes with wrong orientation
  21449. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21450. if ( newShapes.length > 1 ) {
  21451. var ambiguous = false;
  21452. var toChange = [];
  21453. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21454. betterShapeHoles[ sIdx ] = [];
  21455. }
  21456. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21457. var sho = newShapeHoles[ sIdx ];
  21458. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21459. var ho = sho[ hIdx ];
  21460. var hole_unassigned = true;
  21461. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21462. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21463. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21464. if ( hole_unassigned ) {
  21465. hole_unassigned = false;
  21466. betterShapeHoles[ s2Idx ].push( ho );
  21467. } else {
  21468. ambiguous = true;
  21469. }
  21470. }
  21471. }
  21472. if ( hole_unassigned ) {
  21473. betterShapeHoles[ sIdx ].push( ho );
  21474. }
  21475. }
  21476. }
  21477. // console.log("ambiguous: ", ambiguous);
  21478. if ( toChange.length > 0 ) {
  21479. // console.log("to change: ", toChange);
  21480. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21481. }
  21482. }
  21483. var tmpHoles;
  21484. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21485. tmpShape = newShapes[ i ].s;
  21486. shapes.push( tmpShape );
  21487. tmpHoles = newShapeHoles[ i ];
  21488. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21489. tmpShape.holes.push( tmpHoles[ j ].h );
  21490. }
  21491. }
  21492. //console.log("shape", shapes);
  21493. return shapes;
  21494. }
  21495. } );
  21496. /**
  21497. * @author zz85 / http://www.lab4games.net/zz85/blog
  21498. * @author mrdoob / http://mrdoob.com/
  21499. */
  21500. function Font( data ) {
  21501. this.data = data;
  21502. }
  21503. Object.assign( Font.prototype, {
  21504. isFont: true,
  21505. generateShapes: function ( text, size, divisions ) {
  21506. function createPaths( text ) {
  21507. var chars = String( text ).split( '' );
  21508. var scale = size / data.resolution;
  21509. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21510. var offsetX = 0, offsetY = 0;
  21511. var paths = [];
  21512. for ( var i = 0; i < chars.length; i ++ ) {
  21513. var char = chars[ i ];
  21514. if ( char === '\n' ) {
  21515. offsetX = 0;
  21516. offsetY -= line_height;
  21517. } else {
  21518. var ret = createPath( char, scale, offsetX, offsetY );
  21519. offsetX += ret.offsetX;
  21520. paths.push( ret.path );
  21521. }
  21522. }
  21523. return paths;
  21524. }
  21525. function createPath( c, scale, offsetX, offsetY ) {
  21526. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21527. if ( ! glyph ) return;
  21528. var path = new ShapePath();
  21529. var pts = [];
  21530. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21531. if ( glyph.o ) {
  21532. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21533. for ( var i = 0, l = outline.length; i < l; ) {
  21534. var action = outline[ i ++ ];
  21535. switch ( action ) {
  21536. case 'm': // moveTo
  21537. x = outline[ i ++ ] * scale + offsetX;
  21538. y = outline[ i ++ ] * scale + offsetY;
  21539. path.moveTo( x, y );
  21540. break;
  21541. case 'l': // lineTo
  21542. x = outline[ i ++ ] * scale + offsetX;
  21543. y = outline[ i ++ ] * scale + offsetY;
  21544. path.lineTo( x, y );
  21545. break;
  21546. case 'q': // quadraticCurveTo
  21547. cpx = outline[ i ++ ] * scale + offsetX;
  21548. cpy = outline[ i ++ ] * scale + offsetY;
  21549. cpx1 = outline[ i ++ ] * scale + offsetX;
  21550. cpy1 = outline[ i ++ ] * scale + offsetY;
  21551. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21552. laste = pts[ pts.length - 1 ];
  21553. if ( laste ) {
  21554. cpx0 = laste.x;
  21555. cpy0 = laste.y;
  21556. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21557. var t = i2 / divisions;
  21558. QuadraticBezier( t, cpx0, cpx1, cpx );
  21559. QuadraticBezier( t, cpy0, cpy1, cpy );
  21560. }
  21561. }
  21562. break;
  21563. case 'b': // bezierCurveTo
  21564. cpx = outline[ i ++ ] * scale + offsetX;
  21565. cpy = outline[ i ++ ] * scale + offsetY;
  21566. cpx1 = outline[ i ++ ] * scale + offsetX;
  21567. cpy1 = outline[ i ++ ] * scale + offsetY;
  21568. cpx2 = outline[ i ++ ] * scale + offsetX;
  21569. cpy2 = outline[ i ++ ] * scale + offsetY;
  21570. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21571. laste = pts[ pts.length - 1 ];
  21572. if ( laste ) {
  21573. cpx0 = laste.x;
  21574. cpy0 = laste.y;
  21575. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21576. var t = i2 / divisions;
  21577. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21578. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21579. }
  21580. }
  21581. break;
  21582. }
  21583. }
  21584. }
  21585. return { offsetX: glyph.ha * scale, path: path };
  21586. }
  21587. //
  21588. if ( size === undefined ) size = 100;
  21589. if ( divisions === undefined ) divisions = 4;
  21590. var data = this.data;
  21591. var paths = createPaths( text );
  21592. var shapes = [];
  21593. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21594. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21595. }
  21596. return shapes;
  21597. }
  21598. } );
  21599. /**
  21600. * @author mrdoob / http://mrdoob.com/
  21601. */
  21602. function FontLoader( manager ) {
  21603. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21604. }
  21605. Object.assign( FontLoader.prototype, {
  21606. load: function ( url, onLoad, onProgress, onError ) {
  21607. var scope = this;
  21608. var loader = new FileLoader( this.manager );
  21609. loader.load( url, function ( text ) {
  21610. var json;
  21611. try {
  21612. json = JSON.parse( text );
  21613. } catch ( e ) {
  21614. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21615. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21616. }
  21617. var font = scope.parse( json );
  21618. if ( onLoad ) onLoad( font );
  21619. }, onProgress, onError );
  21620. },
  21621. parse: function ( json ) {
  21622. return new Font( json );
  21623. }
  21624. } );
  21625. var context;
  21626. var AudioContext = {
  21627. getContext: function () {
  21628. if ( context === undefined ) {
  21629. context = new ( window.AudioContext || window.webkitAudioContext )();
  21630. }
  21631. return context;
  21632. },
  21633. setContext: function ( value ) {
  21634. context = value;
  21635. }
  21636. };
  21637. /**
  21638. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21639. */
  21640. function AudioLoader( manager ) {
  21641. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21642. }
  21643. Object.assign( AudioLoader.prototype, {
  21644. load: function ( url, onLoad, onProgress, onError ) {
  21645. var loader = new FileLoader( this.manager );
  21646. loader.setResponseType( 'arraybuffer' );
  21647. loader.load( url, function ( buffer ) {
  21648. var context = AudioContext.getContext();
  21649. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21650. onLoad( audioBuffer );
  21651. } );
  21652. }, onProgress, onError );
  21653. }
  21654. } );
  21655. /**
  21656. * @author mrdoob / http://mrdoob.com/
  21657. */
  21658. function StereoCamera() {
  21659. this.type = 'StereoCamera';
  21660. this.aspect = 1;
  21661. this.eyeSep = 0.064;
  21662. this.cameraL = new PerspectiveCamera();
  21663. this.cameraL.layers.enable( 1 );
  21664. this.cameraL.matrixAutoUpdate = false;
  21665. this.cameraR = new PerspectiveCamera();
  21666. this.cameraR.layers.enable( 2 );
  21667. this.cameraR.matrixAutoUpdate = false;
  21668. }
  21669. Object.assign( StereoCamera.prototype, {
  21670. update: ( function () {
  21671. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21672. var eyeRight = new Matrix4();
  21673. var eyeLeft = new Matrix4();
  21674. return function update( camera ) {
  21675. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21676. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21677. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21678. if ( needsUpdate ) {
  21679. instance = this;
  21680. focus = camera.focus;
  21681. fov = camera.fov;
  21682. aspect = camera.aspect * this.aspect;
  21683. near = camera.near;
  21684. far = camera.far;
  21685. zoom = camera.zoom;
  21686. // Off-axis stereoscopic effect based on
  21687. // http://paulbourke.net/stereographics/stereorender/
  21688. var projectionMatrix = camera.projectionMatrix.clone();
  21689. eyeSep = this.eyeSep / 2;
  21690. var eyeSepOnProjection = eyeSep * near / focus;
  21691. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21692. var xmin, xmax;
  21693. // translate xOffset
  21694. eyeLeft.elements[ 12 ] = - eyeSep;
  21695. eyeRight.elements[ 12 ] = eyeSep;
  21696. // for left eye
  21697. xmin = - ymax * aspect + eyeSepOnProjection;
  21698. xmax = ymax * aspect + eyeSepOnProjection;
  21699. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21700. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21701. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21702. // for right eye
  21703. xmin = - ymax * aspect - eyeSepOnProjection;
  21704. xmax = ymax * aspect - eyeSepOnProjection;
  21705. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21706. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21707. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21708. }
  21709. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21710. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21711. };
  21712. } )()
  21713. } );
  21714. /**
  21715. * Camera for rendering cube maps
  21716. * - renders scene into axis-aligned cube
  21717. *
  21718. * @author alteredq / http://alteredqualia.com/
  21719. */
  21720. function CubeCamera( near, far, cubeResolution ) {
  21721. Object3D.call( this );
  21722. this.type = 'CubeCamera';
  21723. var fov = 90, aspect = 1;
  21724. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21725. cameraPX.up.set( 0, - 1, 0 );
  21726. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21727. this.add( cameraPX );
  21728. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21729. cameraNX.up.set( 0, - 1, 0 );
  21730. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21731. this.add( cameraNX );
  21732. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21733. cameraPY.up.set( 0, 0, 1 );
  21734. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21735. this.add( cameraPY );
  21736. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21737. cameraNY.up.set( 0, 0, - 1 );
  21738. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21739. this.add( cameraNY );
  21740. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21741. cameraPZ.up.set( 0, - 1, 0 );
  21742. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21743. this.add( cameraPZ );
  21744. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21745. cameraNZ.up.set( 0, - 1, 0 );
  21746. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21747. this.add( cameraNZ );
  21748. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21749. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21750. this.renderTarget.texture.name = "CubeCamera";
  21751. this.updateCubeMap = function ( renderer, scene ) {
  21752. if ( this.parent === null ) this.updateMatrixWorld();
  21753. var renderTarget = this.renderTarget;
  21754. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21755. renderTarget.texture.generateMipmaps = false;
  21756. renderTarget.activeCubeFace = 0;
  21757. renderer.render( scene, cameraPX, renderTarget );
  21758. renderTarget.activeCubeFace = 1;
  21759. renderer.render( scene, cameraNX, renderTarget );
  21760. renderTarget.activeCubeFace = 2;
  21761. renderer.render( scene, cameraPY, renderTarget );
  21762. renderTarget.activeCubeFace = 3;
  21763. renderer.render( scene, cameraNY, renderTarget );
  21764. renderTarget.activeCubeFace = 4;
  21765. renderer.render( scene, cameraPZ, renderTarget );
  21766. renderTarget.texture.generateMipmaps = generateMipmaps;
  21767. renderTarget.activeCubeFace = 5;
  21768. renderer.render( scene, cameraNZ, renderTarget );
  21769. renderer.setRenderTarget( null );
  21770. };
  21771. }
  21772. CubeCamera.prototype = Object.create( Object3D.prototype );
  21773. CubeCamera.prototype.constructor = CubeCamera;
  21774. /**
  21775. * @author mrdoob / http://mrdoob.com/
  21776. */
  21777. function AudioListener() {
  21778. Object3D.call( this );
  21779. this.type = 'AudioListener';
  21780. this.context = AudioContext.getContext();
  21781. this.gain = this.context.createGain();
  21782. this.gain.connect( this.context.destination );
  21783. this.filter = null;
  21784. }
  21785. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21786. constructor: AudioListener,
  21787. getInput: function () {
  21788. return this.gain;
  21789. },
  21790. removeFilter: function ( ) {
  21791. if ( this.filter !== null ) {
  21792. this.gain.disconnect( this.filter );
  21793. this.filter.disconnect( this.context.destination );
  21794. this.gain.connect( this.context.destination );
  21795. this.filter = null;
  21796. }
  21797. },
  21798. getFilter: function () {
  21799. return this.filter;
  21800. },
  21801. setFilter: function ( value ) {
  21802. if ( this.filter !== null ) {
  21803. this.gain.disconnect( this.filter );
  21804. this.filter.disconnect( this.context.destination );
  21805. } else {
  21806. this.gain.disconnect( this.context.destination );
  21807. }
  21808. this.filter = value;
  21809. this.gain.connect( this.filter );
  21810. this.filter.connect( this.context.destination );
  21811. },
  21812. getMasterVolume: function () {
  21813. return this.gain.gain.value;
  21814. },
  21815. setMasterVolume: function ( value ) {
  21816. this.gain.gain.value = value;
  21817. },
  21818. updateMatrixWorld: ( function () {
  21819. var position = new Vector3();
  21820. var quaternion = new Quaternion();
  21821. var scale = new Vector3();
  21822. var orientation = new Vector3();
  21823. return function updateMatrixWorld( force ) {
  21824. Object3D.prototype.updateMatrixWorld.call( this, force );
  21825. var listener = this.context.listener;
  21826. var up = this.up;
  21827. this.matrixWorld.decompose( position, quaternion, scale );
  21828. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21829. if ( listener.positionX ) {
  21830. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21831. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21832. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21833. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21834. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21835. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21836. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21837. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21838. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21839. } else {
  21840. listener.setPosition( position.x, position.y, position.z );
  21841. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21842. }
  21843. };
  21844. } )()
  21845. } );
  21846. /**
  21847. * @author mrdoob / http://mrdoob.com/
  21848. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21849. */
  21850. function Audio( listener ) {
  21851. Object3D.call( this );
  21852. this.type = 'Audio';
  21853. this.context = listener.context;
  21854. this.gain = this.context.createGain();
  21855. this.gain.connect( listener.getInput() );
  21856. this.autoplay = false;
  21857. this.buffer = null;
  21858. this.loop = false;
  21859. this.startTime = 0;
  21860. this.playbackRate = 1;
  21861. this.isPlaying = false;
  21862. this.hasPlaybackControl = true;
  21863. this.sourceType = 'empty';
  21864. this.filters = [];
  21865. }
  21866. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21867. constructor: Audio,
  21868. getOutput: function () {
  21869. return this.gain;
  21870. },
  21871. setNodeSource: function ( audioNode ) {
  21872. this.hasPlaybackControl = false;
  21873. this.sourceType = 'audioNode';
  21874. this.source = audioNode;
  21875. this.connect();
  21876. return this;
  21877. },
  21878. setBuffer: function ( audioBuffer ) {
  21879. this.buffer = audioBuffer;
  21880. this.sourceType = 'buffer';
  21881. if ( this.autoplay ) this.play();
  21882. return this;
  21883. },
  21884. play: function () {
  21885. if ( this.isPlaying === true ) {
  21886. console.warn( 'THREE.Audio: Audio is already playing.' );
  21887. return;
  21888. }
  21889. if ( this.hasPlaybackControl === false ) {
  21890. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21891. return;
  21892. }
  21893. var source = this.context.createBufferSource();
  21894. source.buffer = this.buffer;
  21895. source.loop = this.loop;
  21896. source.onended = this.onEnded.bind( this );
  21897. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21898. source.start( 0, this.startTime );
  21899. this.isPlaying = true;
  21900. this.source = source;
  21901. return this.connect();
  21902. },
  21903. pause: function () {
  21904. if ( this.hasPlaybackControl === false ) {
  21905. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21906. return;
  21907. }
  21908. this.source.stop();
  21909. this.startTime = this.context.currentTime;
  21910. this.isPlaying = false;
  21911. return this;
  21912. },
  21913. stop: function () {
  21914. if ( this.hasPlaybackControl === false ) {
  21915. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21916. return;
  21917. }
  21918. this.source.stop();
  21919. this.startTime = 0;
  21920. this.isPlaying = false;
  21921. return this;
  21922. },
  21923. connect: function () {
  21924. if ( this.filters.length > 0 ) {
  21925. this.source.connect( this.filters[ 0 ] );
  21926. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21927. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21928. }
  21929. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21930. } else {
  21931. this.source.connect( this.getOutput() );
  21932. }
  21933. return this;
  21934. },
  21935. disconnect: function () {
  21936. if ( this.filters.length > 0 ) {
  21937. this.source.disconnect( this.filters[ 0 ] );
  21938. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21939. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21940. }
  21941. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21942. } else {
  21943. this.source.disconnect( this.getOutput() );
  21944. }
  21945. return this;
  21946. },
  21947. getFilters: function () {
  21948. return this.filters;
  21949. },
  21950. setFilters: function ( value ) {
  21951. if ( ! value ) value = [];
  21952. if ( this.isPlaying === true ) {
  21953. this.disconnect();
  21954. this.filters = value;
  21955. this.connect();
  21956. } else {
  21957. this.filters = value;
  21958. }
  21959. return this;
  21960. },
  21961. getFilter: function () {
  21962. return this.getFilters()[ 0 ];
  21963. },
  21964. setFilter: function ( filter ) {
  21965. return this.setFilters( filter ? [ filter ] : [] );
  21966. },
  21967. setPlaybackRate: function ( value ) {
  21968. if ( this.hasPlaybackControl === false ) {
  21969. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21970. return;
  21971. }
  21972. this.playbackRate = value;
  21973. if ( this.isPlaying === true ) {
  21974. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21975. }
  21976. return this;
  21977. },
  21978. getPlaybackRate: function () {
  21979. return this.playbackRate;
  21980. },
  21981. onEnded: function () {
  21982. this.isPlaying = false;
  21983. },
  21984. getLoop: function () {
  21985. if ( this.hasPlaybackControl === false ) {
  21986. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21987. return false;
  21988. }
  21989. return this.loop;
  21990. },
  21991. setLoop: function ( value ) {
  21992. if ( this.hasPlaybackControl === false ) {
  21993. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21994. return;
  21995. }
  21996. this.loop = value;
  21997. if ( this.isPlaying === true ) {
  21998. this.source.loop = this.loop;
  21999. }
  22000. return this;
  22001. },
  22002. getVolume: function () {
  22003. return this.gain.gain.value;
  22004. },
  22005. setVolume: function ( value ) {
  22006. this.gain.gain.value = value;
  22007. return this;
  22008. }
  22009. } );
  22010. /**
  22011. * @author mrdoob / http://mrdoob.com/
  22012. */
  22013. function PositionalAudio( listener ) {
  22014. Audio.call( this, listener );
  22015. this.panner = this.context.createPanner();
  22016. this.panner.connect( this.gain );
  22017. }
  22018. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  22019. constructor: PositionalAudio,
  22020. getOutput: function () {
  22021. return this.panner;
  22022. },
  22023. getRefDistance: function () {
  22024. return this.panner.refDistance;
  22025. },
  22026. setRefDistance: function ( value ) {
  22027. this.panner.refDistance = value;
  22028. },
  22029. getRolloffFactor: function () {
  22030. return this.panner.rolloffFactor;
  22031. },
  22032. setRolloffFactor: function ( value ) {
  22033. this.panner.rolloffFactor = value;
  22034. },
  22035. getDistanceModel: function () {
  22036. return this.panner.distanceModel;
  22037. },
  22038. setDistanceModel: function ( value ) {
  22039. this.panner.distanceModel = value;
  22040. },
  22041. getMaxDistance: function () {
  22042. return this.panner.maxDistance;
  22043. },
  22044. setMaxDistance: function ( value ) {
  22045. this.panner.maxDistance = value;
  22046. },
  22047. updateMatrixWorld: ( function () {
  22048. var position = new Vector3();
  22049. return function updateMatrixWorld( force ) {
  22050. Object3D.prototype.updateMatrixWorld.call( this, force );
  22051. position.setFromMatrixPosition( this.matrixWorld );
  22052. this.panner.setPosition( position.x, position.y, position.z );
  22053. };
  22054. } )()
  22055. } );
  22056. /**
  22057. * @author mrdoob / http://mrdoob.com/
  22058. */
  22059. function AudioAnalyser( audio, fftSize ) {
  22060. this.analyser = audio.context.createAnalyser();
  22061. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  22062. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  22063. audio.getOutput().connect( this.analyser );
  22064. }
  22065. Object.assign( AudioAnalyser.prototype, {
  22066. getFrequencyData: function () {
  22067. this.analyser.getByteFrequencyData( this.data );
  22068. return this.data;
  22069. },
  22070. getAverageFrequency: function () {
  22071. var value = 0, data = this.getFrequencyData();
  22072. for ( var i = 0; i < data.length; i ++ ) {
  22073. value += data[ i ];
  22074. }
  22075. return value / data.length;
  22076. }
  22077. } );
  22078. /**
  22079. *
  22080. * Buffered scene graph property that allows weighted accumulation.
  22081. *
  22082. *
  22083. * @author Ben Houston / http://clara.io/
  22084. * @author David Sarno / http://lighthaus.us/
  22085. * @author tschw
  22086. */
  22087. function PropertyMixer( binding, typeName, valueSize ) {
  22088. this.binding = binding;
  22089. this.valueSize = valueSize;
  22090. var bufferType = Float64Array,
  22091. mixFunction;
  22092. switch ( typeName ) {
  22093. case 'quaternion':
  22094. mixFunction = this._slerp;
  22095. break;
  22096. case 'string':
  22097. case 'bool':
  22098. bufferType = Array;
  22099. mixFunction = this._select;
  22100. break;
  22101. default:
  22102. mixFunction = this._lerp;
  22103. }
  22104. this.buffer = new bufferType( valueSize * 4 );
  22105. // layout: [ incoming | accu0 | accu1 | orig ]
  22106. //
  22107. // interpolators can use .buffer as their .result
  22108. // the data then goes to 'incoming'
  22109. //
  22110. // 'accu0' and 'accu1' are used frame-interleaved for
  22111. // the cumulative result and are compared to detect
  22112. // changes
  22113. //
  22114. // 'orig' stores the original state of the property
  22115. this._mixBufferRegion = mixFunction;
  22116. this.cumulativeWeight = 0;
  22117. this.useCount = 0;
  22118. this.referenceCount = 0;
  22119. }
  22120. Object.assign( PropertyMixer.prototype, {
  22121. // accumulate data in the 'incoming' region into 'accu<i>'
  22122. accumulate: function ( accuIndex, weight ) {
  22123. // note: happily accumulating nothing when weight = 0, the caller knows
  22124. // the weight and shouldn't have made the call in the first place
  22125. var buffer = this.buffer,
  22126. stride = this.valueSize,
  22127. offset = accuIndex * stride + stride,
  22128. currentWeight = this.cumulativeWeight;
  22129. if ( currentWeight === 0 ) {
  22130. // accuN := incoming * weight
  22131. for ( var i = 0; i !== stride; ++ i ) {
  22132. buffer[ offset + i ] = buffer[ i ];
  22133. }
  22134. currentWeight = weight;
  22135. } else {
  22136. // accuN := accuN + incoming * weight
  22137. currentWeight += weight;
  22138. var mix = weight / currentWeight;
  22139. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  22140. }
  22141. this.cumulativeWeight = currentWeight;
  22142. },
  22143. // apply the state of 'accu<i>' to the binding when accus differ
  22144. apply: function ( accuIndex ) {
  22145. var stride = this.valueSize,
  22146. buffer = this.buffer,
  22147. offset = accuIndex * stride + stride,
  22148. weight = this.cumulativeWeight,
  22149. binding = this.binding;
  22150. this.cumulativeWeight = 0;
  22151. if ( weight < 1 ) {
  22152. // accuN := accuN + original * ( 1 - cumulativeWeight )
  22153. var originalValueOffset = stride * 3;
  22154. this._mixBufferRegion(
  22155. buffer, offset, originalValueOffset, 1 - weight, stride );
  22156. }
  22157. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  22158. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  22159. // value has changed -> update scene graph
  22160. binding.setValue( buffer, offset );
  22161. break;
  22162. }
  22163. }
  22164. },
  22165. // remember the state of the bound property and copy it to both accus
  22166. saveOriginalState: function () {
  22167. var binding = this.binding;
  22168. var buffer = this.buffer,
  22169. stride = this.valueSize,
  22170. originalValueOffset = stride * 3;
  22171. binding.getValue( buffer, originalValueOffset );
  22172. // accu[0..1] := orig -- initially detect changes against the original
  22173. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22174. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22175. }
  22176. this.cumulativeWeight = 0;
  22177. },
  22178. // apply the state previously taken via 'saveOriginalState' to the binding
  22179. restoreOriginalState: function () {
  22180. var originalValueOffset = this.valueSize * 3;
  22181. this.binding.setValue( this.buffer, originalValueOffset );
  22182. },
  22183. // mix functions
  22184. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22185. if ( t >= 0.5 ) {
  22186. for ( var i = 0; i !== stride; ++ i ) {
  22187. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22188. }
  22189. }
  22190. },
  22191. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  22192. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22193. },
  22194. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22195. var s = 1 - t;
  22196. for ( var i = 0; i !== stride; ++ i ) {
  22197. var j = dstOffset + i;
  22198. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22199. }
  22200. }
  22201. } );
  22202. /**
  22203. *
  22204. * A reference to a real property in the scene graph.
  22205. *
  22206. *
  22207. * @author Ben Houston / http://clara.io/
  22208. * @author David Sarno / http://lighthaus.us/
  22209. * @author tschw
  22210. */
  22211. function Composite( targetGroup, path, optionalParsedPath ) {
  22212. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22213. this._targetGroup = targetGroup;
  22214. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22215. }
  22216. Object.assign( Composite.prototype, {
  22217. getValue: function ( array, offset ) {
  22218. this.bind(); // bind all binding
  22219. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22220. binding = this._bindings[ firstValidIndex ];
  22221. // and only call .getValue on the first
  22222. if ( binding !== undefined ) binding.getValue( array, offset );
  22223. },
  22224. setValue: function ( array, offset ) {
  22225. var bindings = this._bindings;
  22226. for ( var i = this._targetGroup.nCachedObjects_,
  22227. n = bindings.length; i !== n; ++ i ) {
  22228. bindings[ i ].setValue( array, offset );
  22229. }
  22230. },
  22231. bind: function () {
  22232. var bindings = this._bindings;
  22233. for ( var i = this._targetGroup.nCachedObjects_,
  22234. n = bindings.length; i !== n; ++ i ) {
  22235. bindings[ i ].bind();
  22236. }
  22237. },
  22238. unbind: function () {
  22239. var bindings = this._bindings;
  22240. for ( var i = this._targetGroup.nCachedObjects_,
  22241. n = bindings.length; i !== n; ++ i ) {
  22242. bindings[ i ].unbind();
  22243. }
  22244. }
  22245. } );
  22246. function PropertyBinding( rootNode, path, parsedPath ) {
  22247. this.path = path;
  22248. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22249. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22250. this.rootNode = rootNode;
  22251. }
  22252. Object.assign( PropertyBinding, {
  22253. Composite: Composite,
  22254. create: function ( root, path, parsedPath ) {
  22255. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22256. return new PropertyBinding( root, path, parsedPath );
  22257. } else {
  22258. return new PropertyBinding.Composite( root, path, parsedPath );
  22259. }
  22260. },
  22261. /**
  22262. * Replaces spaces with underscores and removes unsupported characters from
  22263. * node names, to ensure compatibility with parseTrackName().
  22264. *
  22265. * @param {string} name Node name to be sanitized.
  22266. * @return {string}
  22267. */
  22268. sanitizeNodeName: function ( name ) {
  22269. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  22270. },
  22271. parseTrackName: function () {
  22272. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22273. // be matched to parse the rest of the track name.
  22274. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22275. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22276. var nodeRe = /([\w-\.]+)?/;
  22277. // Object on target node, and accessor. Name may contain only word
  22278. // characters. Accessor may contain any character except closing bracket.
  22279. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22280. // Property and accessor. May contain only word characters. Accessor may
  22281. // contain any non-bracket characters.
  22282. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22283. var trackRe = new RegExp(''
  22284. + '^'
  22285. + directoryRe.source
  22286. + nodeRe.source
  22287. + objectRe.source
  22288. + propertyRe.source
  22289. + '$'
  22290. );
  22291. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22292. return function ( trackName ) {
  22293. var matches = trackRe.exec( trackName );
  22294. if ( ! matches ) {
  22295. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22296. }
  22297. var results = {
  22298. // directoryName: matches[ 1 ], // (tschw) currently unused
  22299. nodeName: matches[ 2 ],
  22300. objectName: matches[ 3 ],
  22301. objectIndex: matches[ 4 ],
  22302. propertyName: matches[ 5 ], // required
  22303. propertyIndex: matches[ 6 ]
  22304. };
  22305. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22306. if ( lastDot !== undefined && lastDot !== -1 ) {
  22307. var objectName = results.nodeName.substring( lastDot + 1 );
  22308. // Object names must be checked against a whitelist. Otherwise, there
  22309. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22310. // 'bar' could be the objectName, or part of a nodeName (which can
  22311. // include '.' characters).
  22312. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22313. results.nodeName = results.nodeName.substring( 0, lastDot );
  22314. results.objectName = objectName;
  22315. }
  22316. }
  22317. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22318. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22319. }
  22320. return results;
  22321. };
  22322. }(),
  22323. findNode: function ( root, nodeName ) {
  22324. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22325. return root;
  22326. }
  22327. // search into skeleton bones.
  22328. if ( root.skeleton ) {
  22329. var searchSkeleton = function ( skeleton ) {
  22330. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22331. var bone = skeleton.bones[ i ];
  22332. if ( bone.name === nodeName ) {
  22333. return bone;
  22334. }
  22335. }
  22336. return null;
  22337. };
  22338. var bone = searchSkeleton( root.skeleton );
  22339. if ( bone ) {
  22340. return bone;
  22341. }
  22342. }
  22343. // search into node subtree.
  22344. if ( root.children ) {
  22345. var searchNodeSubtree = function ( children ) {
  22346. for ( var i = 0; i < children.length; i ++ ) {
  22347. var childNode = children[ i ];
  22348. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22349. return childNode;
  22350. }
  22351. var result = searchNodeSubtree( childNode.children );
  22352. if ( result ) return result;
  22353. }
  22354. return null;
  22355. };
  22356. var subTreeNode = searchNodeSubtree( root.children );
  22357. if ( subTreeNode ) {
  22358. return subTreeNode;
  22359. }
  22360. }
  22361. return null;
  22362. }
  22363. } );
  22364. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22365. // these are used to "bind" a nonexistent property
  22366. _getValue_unavailable: function () {},
  22367. _setValue_unavailable: function () {},
  22368. BindingType: {
  22369. Direct: 0,
  22370. EntireArray: 1,
  22371. ArrayElement: 2,
  22372. HasFromToArray: 3
  22373. },
  22374. Versioning: {
  22375. None: 0,
  22376. NeedsUpdate: 1,
  22377. MatrixWorldNeedsUpdate: 2
  22378. },
  22379. GetterByBindingType: [
  22380. function getValue_direct( buffer, offset ) {
  22381. buffer[ offset ] = this.node[ this.propertyName ];
  22382. },
  22383. function getValue_array( buffer, offset ) {
  22384. var source = this.resolvedProperty;
  22385. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22386. buffer[ offset ++ ] = source[ i ];
  22387. }
  22388. },
  22389. function getValue_arrayElement( buffer, offset ) {
  22390. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22391. },
  22392. function getValue_toArray( buffer, offset ) {
  22393. this.resolvedProperty.toArray( buffer, offset );
  22394. }
  22395. ],
  22396. SetterByBindingTypeAndVersioning: [
  22397. [
  22398. // Direct
  22399. function setValue_direct( buffer, offset ) {
  22400. this.node[ this.propertyName ] = buffer[ offset ];
  22401. },
  22402. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22403. this.node[ this.propertyName ] = buffer[ offset ];
  22404. this.targetObject.needsUpdate = true;
  22405. },
  22406. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22407. this.node[ this.propertyName ] = buffer[ offset ];
  22408. this.targetObject.matrixWorldNeedsUpdate = true;
  22409. }
  22410. ], [
  22411. // EntireArray
  22412. function setValue_array( buffer, offset ) {
  22413. var dest = this.resolvedProperty;
  22414. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22415. dest[ i ] = buffer[ offset ++ ];
  22416. }
  22417. },
  22418. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22419. var dest = this.resolvedProperty;
  22420. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22421. dest[ i ] = buffer[ offset ++ ];
  22422. }
  22423. this.targetObject.needsUpdate = true;
  22424. },
  22425. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22426. var dest = this.resolvedProperty;
  22427. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22428. dest[ i ] = buffer[ offset ++ ];
  22429. }
  22430. this.targetObject.matrixWorldNeedsUpdate = true;
  22431. }
  22432. ], [
  22433. // ArrayElement
  22434. function setValue_arrayElement( buffer, offset ) {
  22435. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22436. },
  22437. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22438. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22439. this.targetObject.needsUpdate = true;
  22440. },
  22441. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22442. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22443. this.targetObject.matrixWorldNeedsUpdate = true;
  22444. }
  22445. ], [
  22446. // HasToFromArray
  22447. function setValue_fromArray( buffer, offset ) {
  22448. this.resolvedProperty.fromArray( buffer, offset );
  22449. },
  22450. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22451. this.resolvedProperty.fromArray( buffer, offset );
  22452. this.targetObject.needsUpdate = true;
  22453. },
  22454. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22455. this.resolvedProperty.fromArray( buffer, offset );
  22456. this.targetObject.matrixWorldNeedsUpdate = true;
  22457. }
  22458. ]
  22459. ],
  22460. getValue: function getValue_unbound( targetArray, offset ) {
  22461. this.bind();
  22462. this.getValue( targetArray, offset );
  22463. // Note: This class uses a State pattern on a per-method basis:
  22464. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22465. // prototype version of these methods with one that represents
  22466. // the bound state. When the property is not found, the methods
  22467. // become no-ops.
  22468. },
  22469. setValue: function getValue_unbound( sourceArray, offset ) {
  22470. this.bind();
  22471. this.setValue( sourceArray, offset );
  22472. },
  22473. // create getter / setter pair for a property in the scene graph
  22474. bind: function () {
  22475. var targetObject = this.node,
  22476. parsedPath = this.parsedPath,
  22477. objectName = parsedPath.objectName,
  22478. propertyName = parsedPath.propertyName,
  22479. propertyIndex = parsedPath.propertyIndex;
  22480. if ( ! targetObject ) {
  22481. targetObject = PropertyBinding.findNode(
  22482. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22483. this.node = targetObject;
  22484. }
  22485. // set fail state so we can just 'return' on error
  22486. this.getValue = this._getValue_unavailable;
  22487. this.setValue = this._setValue_unavailable;
  22488. // ensure there is a value node
  22489. if ( ! targetObject ) {
  22490. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  22491. return;
  22492. }
  22493. if ( objectName ) {
  22494. var objectIndex = parsedPath.objectIndex;
  22495. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22496. switch ( objectName ) {
  22497. case 'materials':
  22498. if ( ! targetObject.material ) {
  22499. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  22500. return;
  22501. }
  22502. if ( ! targetObject.material.materials ) {
  22503. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  22504. return;
  22505. }
  22506. targetObject = targetObject.material.materials;
  22507. break;
  22508. case 'bones':
  22509. if ( ! targetObject.skeleton ) {
  22510. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  22511. return;
  22512. }
  22513. // potential future optimization: skip this if propertyIndex is already an integer
  22514. // and convert the integer string to a true integer.
  22515. targetObject = targetObject.skeleton.bones;
  22516. // support resolving morphTarget names into indices.
  22517. for ( var i = 0; i < targetObject.length; i ++ ) {
  22518. if ( targetObject[ i ].name === objectIndex ) {
  22519. objectIndex = i;
  22520. break;
  22521. }
  22522. }
  22523. break;
  22524. default:
  22525. if ( targetObject[ objectName ] === undefined ) {
  22526. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  22527. return;
  22528. }
  22529. targetObject = targetObject[ objectName ];
  22530. }
  22531. if ( objectIndex !== undefined ) {
  22532. if ( targetObject[ objectIndex ] === undefined ) {
  22533. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  22534. return;
  22535. }
  22536. targetObject = targetObject[ objectIndex ];
  22537. }
  22538. }
  22539. // resolve property
  22540. var nodeProperty = targetObject[ propertyName ];
  22541. if ( nodeProperty === undefined ) {
  22542. var nodeName = parsedPath.nodeName;
  22543. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  22544. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  22545. return;
  22546. }
  22547. // determine versioning scheme
  22548. var versioning = this.Versioning.None;
  22549. if ( targetObject.needsUpdate !== undefined ) { // material
  22550. versioning = this.Versioning.NeedsUpdate;
  22551. this.targetObject = targetObject;
  22552. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22553. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22554. this.targetObject = targetObject;
  22555. }
  22556. // determine how the property gets bound
  22557. var bindingType = this.BindingType.Direct;
  22558. if ( propertyIndex !== undefined ) {
  22559. // access a sub element of the property array (only primitives are supported right now)
  22560. if ( propertyName === "morphTargetInfluences" ) {
  22561. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22562. // support resolving morphTarget names into indices.
  22563. if ( ! targetObject.geometry ) {
  22564. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  22565. return;
  22566. }
  22567. if ( targetObject.geometry.isBufferGeometry ) {
  22568. if ( ! targetObject.geometry.morphAttributes ) {
  22569. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  22570. return;
  22571. }
  22572. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  22573. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  22574. propertyIndex = i;
  22575. break;
  22576. }
  22577. }
  22578. } else {
  22579. if ( ! targetObject.geometry.morphTargets ) {
  22580. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  22581. return;
  22582. }
  22583. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22584. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22585. propertyIndex = i;
  22586. break;
  22587. }
  22588. }
  22589. }
  22590. }
  22591. bindingType = this.BindingType.ArrayElement;
  22592. this.resolvedProperty = nodeProperty;
  22593. this.propertyIndex = propertyIndex;
  22594. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22595. // must use copy for Object3D.Euler/Quaternion
  22596. bindingType = this.BindingType.HasFromToArray;
  22597. this.resolvedProperty = nodeProperty;
  22598. } else if ( Array.isArray( nodeProperty ) ) {
  22599. bindingType = this.BindingType.EntireArray;
  22600. this.resolvedProperty = nodeProperty;
  22601. } else {
  22602. this.propertyName = propertyName;
  22603. }
  22604. // select getter / setter
  22605. this.getValue = this.GetterByBindingType[ bindingType ];
  22606. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22607. },
  22608. unbind: function () {
  22609. this.node = null;
  22610. // back to the prototype version of getValue / setValue
  22611. // note: avoiding to mutate the shape of 'this' via 'delete'
  22612. this.getValue = this._getValue_unbound;
  22613. this.setValue = this._setValue_unbound;
  22614. }
  22615. } );
  22616. //!\ DECLARE ALIAS AFTER assign prototype !
  22617. Object.assign( PropertyBinding.prototype, {
  22618. // initial state of these methods that calls 'bind'
  22619. _getValue_unbound: PropertyBinding.prototype.getValue,
  22620. _setValue_unbound: PropertyBinding.prototype.setValue,
  22621. } );
  22622. /**
  22623. *
  22624. * A group of objects that receives a shared animation state.
  22625. *
  22626. * Usage:
  22627. *
  22628. * - Add objects you would otherwise pass as 'root' to the
  22629. * constructor or the .clipAction method of AnimationMixer.
  22630. *
  22631. * - Instead pass this object as 'root'.
  22632. *
  22633. * - You can also add and remove objects later when the mixer
  22634. * is running.
  22635. *
  22636. * Note:
  22637. *
  22638. * Objects of this class appear as one object to the mixer,
  22639. * so cache control of the individual objects must be done
  22640. * on the group.
  22641. *
  22642. * Limitation:
  22643. *
  22644. * - The animated properties must be compatible among the
  22645. * all objects in the group.
  22646. *
  22647. * - A single property can either be controlled through a
  22648. * target group or directly, but not both.
  22649. *
  22650. * @author tschw
  22651. */
  22652. function AnimationObjectGroup( var_args ) {
  22653. this.uuid = _Math.generateUUID();
  22654. // cached objects followed by the active ones
  22655. this._objects = Array.prototype.slice.call( arguments );
  22656. this.nCachedObjects_ = 0; // threshold
  22657. // note: read by PropertyBinding.Composite
  22658. var indices = {};
  22659. this._indicesByUUID = indices; // for bookkeeping
  22660. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22661. indices[ arguments[ i ].uuid ] = i;
  22662. }
  22663. this._paths = []; // inside: string
  22664. this._parsedPaths = []; // inside: { we don't care, here }
  22665. this._bindings = []; // inside: Array< PropertyBinding >
  22666. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22667. var scope = this;
  22668. this.stats = {
  22669. objects: {
  22670. get total() { return scope._objects.length; },
  22671. get inUse() { return this.total - scope.nCachedObjects_; }
  22672. },
  22673. get bindingsPerObject() { return scope._bindings.length; }
  22674. };
  22675. }
  22676. Object.assign( AnimationObjectGroup.prototype, {
  22677. isAnimationObjectGroup: true,
  22678. add: function( var_args ) {
  22679. var objects = this._objects,
  22680. nObjects = objects.length,
  22681. nCachedObjects = this.nCachedObjects_,
  22682. indicesByUUID = this._indicesByUUID,
  22683. paths = this._paths,
  22684. parsedPaths = this._parsedPaths,
  22685. bindings = this._bindings,
  22686. nBindings = bindings.length;
  22687. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22688. var object = arguments[ i ],
  22689. uuid = object.uuid,
  22690. index = indicesByUUID[ uuid ],
  22691. knownObject = undefined;
  22692. if ( index === undefined ) {
  22693. // unknown object -> add it to the ACTIVE region
  22694. index = nObjects ++;
  22695. indicesByUUID[ uuid ] = index;
  22696. objects.push( object );
  22697. // accounting is done, now do the same for all bindings
  22698. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22699. bindings[ j ].push(
  22700. new PropertyBinding(
  22701. object, paths[ j ], parsedPaths[ j ] ) );
  22702. }
  22703. } else if ( index < nCachedObjects ) {
  22704. knownObject = objects[ index ];
  22705. // move existing object to the ACTIVE region
  22706. var firstActiveIndex = -- nCachedObjects,
  22707. lastCachedObject = objects[ firstActiveIndex ];
  22708. indicesByUUID[ lastCachedObject.uuid ] = index;
  22709. objects[ index ] = lastCachedObject;
  22710. indicesByUUID[ uuid ] = firstActiveIndex;
  22711. objects[ firstActiveIndex ] = object;
  22712. // accounting is done, now do the same for all bindings
  22713. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22714. var bindingsForPath = bindings[ j ],
  22715. lastCached = bindingsForPath[ firstActiveIndex ],
  22716. binding = bindingsForPath[ index ];
  22717. bindingsForPath[ index ] = lastCached;
  22718. if ( binding === undefined ) {
  22719. // since we do not bother to create new bindings
  22720. // for objects that are cached, the binding may
  22721. // or may not exist
  22722. binding = new PropertyBinding(
  22723. object, paths[ j ], parsedPaths[ j ] );
  22724. }
  22725. bindingsForPath[ firstActiveIndex ] = binding;
  22726. }
  22727. } else if ( objects[ index ] !== knownObject ) {
  22728. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  22729. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  22730. } // else the object is already where we want it to be
  22731. } // for arguments
  22732. this.nCachedObjects_ = nCachedObjects;
  22733. },
  22734. remove: function( var_args ) {
  22735. var objects = this._objects,
  22736. nCachedObjects = this.nCachedObjects_,
  22737. indicesByUUID = this._indicesByUUID,
  22738. bindings = this._bindings,
  22739. nBindings = bindings.length;
  22740. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22741. var object = arguments[ i ],
  22742. uuid = object.uuid,
  22743. index = indicesByUUID[ uuid ];
  22744. if ( index !== undefined && index >= nCachedObjects ) {
  22745. // move existing object into the CACHED region
  22746. var lastCachedIndex = nCachedObjects ++,
  22747. firstActiveObject = objects[ lastCachedIndex ];
  22748. indicesByUUID[ firstActiveObject.uuid ] = index;
  22749. objects[ index ] = firstActiveObject;
  22750. indicesByUUID[ uuid ] = lastCachedIndex;
  22751. objects[ lastCachedIndex ] = object;
  22752. // accounting is done, now do the same for all bindings
  22753. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22754. var bindingsForPath = bindings[ j ],
  22755. firstActive = bindingsForPath[ lastCachedIndex ],
  22756. binding = bindingsForPath[ index ];
  22757. bindingsForPath[ index ] = firstActive;
  22758. bindingsForPath[ lastCachedIndex ] = binding;
  22759. }
  22760. }
  22761. } // for arguments
  22762. this.nCachedObjects_ = nCachedObjects;
  22763. },
  22764. // remove & forget
  22765. uncache: function( var_args ) {
  22766. var objects = this._objects,
  22767. nObjects = objects.length,
  22768. nCachedObjects = this.nCachedObjects_,
  22769. indicesByUUID = this._indicesByUUID,
  22770. bindings = this._bindings,
  22771. nBindings = bindings.length;
  22772. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22773. var object = arguments[ i ],
  22774. uuid = object.uuid,
  22775. index = indicesByUUID[ uuid ];
  22776. if ( index !== undefined ) {
  22777. delete indicesByUUID[ uuid ];
  22778. if ( index < nCachedObjects ) {
  22779. // object is cached, shrink the CACHED region
  22780. var firstActiveIndex = -- nCachedObjects,
  22781. lastCachedObject = objects[ firstActiveIndex ],
  22782. lastIndex = -- nObjects,
  22783. lastObject = objects[ lastIndex ];
  22784. // last cached object takes this object's place
  22785. indicesByUUID[ lastCachedObject.uuid ] = index;
  22786. objects[ index ] = lastCachedObject;
  22787. // last object goes to the activated slot and pop
  22788. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22789. objects[ firstActiveIndex ] = lastObject;
  22790. objects.pop();
  22791. // accounting is done, now do the same for all bindings
  22792. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22793. var bindingsForPath = bindings[ j ],
  22794. lastCached = bindingsForPath[ firstActiveIndex ],
  22795. last = bindingsForPath[ lastIndex ];
  22796. bindingsForPath[ index ] = lastCached;
  22797. bindingsForPath[ firstActiveIndex ] = last;
  22798. bindingsForPath.pop();
  22799. }
  22800. } else {
  22801. // object is active, just swap with the last and pop
  22802. var lastIndex = -- nObjects,
  22803. lastObject = objects[ lastIndex ];
  22804. indicesByUUID[ lastObject.uuid ] = index;
  22805. objects[ index ] = lastObject;
  22806. objects.pop();
  22807. // accounting is done, now do the same for all bindings
  22808. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22809. var bindingsForPath = bindings[ j ];
  22810. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22811. bindingsForPath.pop();
  22812. }
  22813. } // cached or active
  22814. } // if object is known
  22815. } // for arguments
  22816. this.nCachedObjects_ = nCachedObjects;
  22817. },
  22818. // Internal interface used by befriended PropertyBinding.Composite:
  22819. subscribe_: function ( path, parsedPath ) {
  22820. // returns an array of bindings for the given path that is changed
  22821. // according to the contained objects in the group
  22822. var indicesByPath = this._bindingsIndicesByPath,
  22823. index = indicesByPath[ path ],
  22824. bindings = this._bindings;
  22825. if ( index !== undefined ) return bindings[ index ];
  22826. var paths = this._paths,
  22827. parsedPaths = this._parsedPaths,
  22828. objects = this._objects,
  22829. nObjects = objects.length,
  22830. nCachedObjects = this.nCachedObjects_,
  22831. bindingsForPath = new Array( nObjects );
  22832. index = bindings.length;
  22833. indicesByPath[ path ] = index;
  22834. paths.push( path );
  22835. parsedPaths.push( parsedPath );
  22836. bindings.push( bindingsForPath );
  22837. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22838. var object = objects[ i ];
  22839. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22840. }
  22841. return bindingsForPath;
  22842. },
  22843. unsubscribe_: function ( path ) {
  22844. // tells the group to forget about a property path and no longer
  22845. // update the array previously obtained with 'subscribe_'
  22846. var indicesByPath = this._bindingsIndicesByPath,
  22847. index = indicesByPath[ path ];
  22848. if ( index !== undefined ) {
  22849. var paths = this._paths,
  22850. parsedPaths = this._parsedPaths,
  22851. bindings = this._bindings,
  22852. lastBindingsIndex = bindings.length - 1,
  22853. lastBindings = bindings[ lastBindingsIndex ],
  22854. lastBindingsPath = path[ lastBindingsIndex ];
  22855. indicesByPath[ lastBindingsPath ] = index;
  22856. bindings[ index ] = lastBindings;
  22857. bindings.pop();
  22858. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22859. parsedPaths.pop();
  22860. paths[ index ] = paths[ lastBindingsIndex ];
  22861. paths.pop();
  22862. }
  22863. }
  22864. } );
  22865. /**
  22866. *
  22867. * Action provided by AnimationMixer for scheduling clip playback on specific
  22868. * objects.
  22869. *
  22870. * @author Ben Houston / http://clara.io/
  22871. * @author David Sarno / http://lighthaus.us/
  22872. * @author tschw
  22873. *
  22874. */
  22875. function AnimationAction( mixer, clip, localRoot ) {
  22876. this._mixer = mixer;
  22877. this._clip = clip;
  22878. this._localRoot = localRoot || null;
  22879. var tracks = clip.tracks,
  22880. nTracks = tracks.length,
  22881. interpolants = new Array( nTracks );
  22882. var interpolantSettings = {
  22883. endingStart: ZeroCurvatureEnding,
  22884. endingEnd: ZeroCurvatureEnding
  22885. };
  22886. for ( var i = 0; i !== nTracks; ++ i ) {
  22887. var interpolant = tracks[ i ].createInterpolant( null );
  22888. interpolants[ i ] = interpolant;
  22889. interpolant.settings = interpolantSettings;
  22890. }
  22891. this._interpolantSettings = interpolantSettings;
  22892. this._interpolants = interpolants; // bound by the mixer
  22893. // inside: PropertyMixer (managed by the mixer)
  22894. this._propertyBindings = new Array( nTracks );
  22895. this._cacheIndex = null; // for the memory manager
  22896. this._byClipCacheIndex = null; // for the memory manager
  22897. this._timeScaleInterpolant = null;
  22898. this._weightInterpolant = null;
  22899. this.loop = LoopRepeat;
  22900. this._loopCount = -1;
  22901. // global mixer time when the action is to be started
  22902. // it's set back to 'null' upon start of the action
  22903. this._startTime = null;
  22904. // scaled local time of the action
  22905. // gets clamped or wrapped to 0..clip.duration according to loop
  22906. this.time = 0;
  22907. this.timeScale = 1;
  22908. this._effectiveTimeScale = 1;
  22909. this.weight = 1;
  22910. this._effectiveWeight = 1;
  22911. this.repetitions = Infinity; // no. of repetitions when looping
  22912. this.paused = false; // true -> zero effective time scale
  22913. this.enabled = true; // false -> zero effective weight
  22914. this.clampWhenFinished = false; // keep feeding the last frame?
  22915. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22916. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22917. }
  22918. Object.assign( AnimationAction.prototype, {
  22919. // State & Scheduling
  22920. play: function() {
  22921. this._mixer._activateAction( this );
  22922. return this;
  22923. },
  22924. stop: function() {
  22925. this._mixer._deactivateAction( this );
  22926. return this.reset();
  22927. },
  22928. reset: function() {
  22929. this.paused = false;
  22930. this.enabled = true;
  22931. this.time = 0; // restart clip
  22932. this._loopCount = -1; // forget previous loops
  22933. this._startTime = null; // forget scheduling
  22934. return this.stopFading().stopWarping();
  22935. },
  22936. isRunning: function() {
  22937. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22938. this._startTime === null && this._mixer._isActiveAction( this );
  22939. },
  22940. // return true when play has been called
  22941. isScheduled: function() {
  22942. return this._mixer._isActiveAction( this );
  22943. },
  22944. startAt: function( time ) {
  22945. this._startTime = time;
  22946. return this;
  22947. },
  22948. setLoop: function( mode, repetitions ) {
  22949. this.loop = mode;
  22950. this.repetitions = repetitions;
  22951. return this;
  22952. },
  22953. // Weight
  22954. // set the weight stopping any scheduled fading
  22955. // although .enabled = false yields an effective weight of zero, this
  22956. // method does *not* change .enabled, because it would be confusing
  22957. setEffectiveWeight: function( weight ) {
  22958. this.weight = weight;
  22959. // note: same logic as when updated at runtime
  22960. this._effectiveWeight = this.enabled ? weight : 0;
  22961. return this.stopFading();
  22962. },
  22963. // return the weight considering fading and .enabled
  22964. getEffectiveWeight: function() {
  22965. return this._effectiveWeight;
  22966. },
  22967. fadeIn: function( duration ) {
  22968. return this._scheduleFading( duration, 0, 1 );
  22969. },
  22970. fadeOut: function( duration ) {
  22971. return this._scheduleFading( duration, 1, 0 );
  22972. },
  22973. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22974. fadeOutAction.fadeOut( duration );
  22975. this.fadeIn( duration );
  22976. if( warp ) {
  22977. var fadeInDuration = this._clip.duration,
  22978. fadeOutDuration = fadeOutAction._clip.duration,
  22979. startEndRatio = fadeOutDuration / fadeInDuration,
  22980. endStartRatio = fadeInDuration / fadeOutDuration;
  22981. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22982. this.warp( endStartRatio, 1.0, duration );
  22983. }
  22984. return this;
  22985. },
  22986. crossFadeTo: function( fadeInAction, duration, warp ) {
  22987. return fadeInAction.crossFadeFrom( this, duration, warp );
  22988. },
  22989. stopFading: function() {
  22990. var weightInterpolant = this._weightInterpolant;
  22991. if ( weightInterpolant !== null ) {
  22992. this._weightInterpolant = null;
  22993. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22994. }
  22995. return this;
  22996. },
  22997. // Time Scale Control
  22998. // set the time scale stopping any scheduled warping
  22999. // although .paused = true yields an effective time scale of zero, this
  23000. // method does *not* change .paused, because it would be confusing
  23001. setEffectiveTimeScale: function( timeScale ) {
  23002. this.timeScale = timeScale;
  23003. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  23004. return this.stopWarping();
  23005. },
  23006. // return the time scale considering warping and .paused
  23007. getEffectiveTimeScale: function() {
  23008. return this._effectiveTimeScale;
  23009. },
  23010. setDuration: function( duration ) {
  23011. this.timeScale = this._clip.duration / duration;
  23012. return this.stopWarping();
  23013. },
  23014. syncWith: function( action ) {
  23015. this.time = action.time;
  23016. this.timeScale = action.timeScale;
  23017. return this.stopWarping();
  23018. },
  23019. halt: function( duration ) {
  23020. return this.warp( this._effectiveTimeScale, 0, duration );
  23021. },
  23022. warp: function( startTimeScale, endTimeScale, duration ) {
  23023. var mixer = this._mixer, now = mixer.time,
  23024. interpolant = this._timeScaleInterpolant,
  23025. timeScale = this.timeScale;
  23026. if ( interpolant === null ) {
  23027. interpolant = mixer._lendControlInterpolant();
  23028. this._timeScaleInterpolant = interpolant;
  23029. }
  23030. var times = interpolant.parameterPositions,
  23031. values = interpolant.sampleValues;
  23032. times[ 0 ] = now;
  23033. times[ 1 ] = now + duration;
  23034. values[ 0 ] = startTimeScale / timeScale;
  23035. values[ 1 ] = endTimeScale / timeScale;
  23036. return this;
  23037. },
  23038. stopWarping: function() {
  23039. var timeScaleInterpolant = this._timeScaleInterpolant;
  23040. if ( timeScaleInterpolant !== null ) {
  23041. this._timeScaleInterpolant = null;
  23042. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  23043. }
  23044. return this;
  23045. },
  23046. // Object Accessors
  23047. getMixer: function() {
  23048. return this._mixer;
  23049. },
  23050. getClip: function() {
  23051. return this._clip;
  23052. },
  23053. getRoot: function() {
  23054. return this._localRoot || this._mixer._root;
  23055. },
  23056. // Interna
  23057. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  23058. // called by the mixer
  23059. if ( ! this.enabled ) {
  23060. // call ._updateWeight() to update ._effectiveWeight
  23061. this._updateWeight( time );
  23062. return;
  23063. }
  23064. var startTime = this._startTime;
  23065. if ( startTime !== null ) {
  23066. // check for scheduled start of action
  23067. var timeRunning = ( time - startTime ) * timeDirection;
  23068. if ( timeRunning < 0 || timeDirection === 0 ) {
  23069. return; // yet to come / don't decide when delta = 0
  23070. }
  23071. // start
  23072. this._startTime = null; // unschedule
  23073. deltaTime = timeDirection * timeRunning;
  23074. }
  23075. // apply time scale and advance time
  23076. deltaTime *= this._updateTimeScale( time );
  23077. var clipTime = this._updateTime( deltaTime );
  23078. // note: _updateTime may disable the action resulting in
  23079. // an effective weight of 0
  23080. var weight = this._updateWeight( time );
  23081. if ( weight > 0 ) {
  23082. var interpolants = this._interpolants;
  23083. var propertyMixers = this._propertyBindings;
  23084. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  23085. interpolants[ j ].evaluate( clipTime );
  23086. propertyMixers[ j ].accumulate( accuIndex, weight );
  23087. }
  23088. }
  23089. },
  23090. _updateWeight: function( time ) {
  23091. var weight = 0;
  23092. if ( this.enabled ) {
  23093. weight = this.weight;
  23094. var interpolant = this._weightInterpolant;
  23095. if ( interpolant !== null ) {
  23096. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23097. weight *= interpolantValue;
  23098. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23099. this.stopFading();
  23100. if ( interpolantValue === 0 ) {
  23101. // faded out, disable
  23102. this.enabled = false;
  23103. }
  23104. }
  23105. }
  23106. }
  23107. this._effectiveWeight = weight;
  23108. return weight;
  23109. },
  23110. _updateTimeScale: function( time ) {
  23111. var timeScale = 0;
  23112. if ( ! this.paused ) {
  23113. timeScale = this.timeScale;
  23114. var interpolant = this._timeScaleInterpolant;
  23115. if ( interpolant !== null ) {
  23116. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23117. timeScale *= interpolantValue;
  23118. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23119. this.stopWarping();
  23120. if ( timeScale === 0 ) {
  23121. // motion has halted, pause
  23122. this.paused = true;
  23123. } else {
  23124. // warp done - apply final time scale
  23125. this.timeScale = timeScale;
  23126. }
  23127. }
  23128. }
  23129. }
  23130. this._effectiveTimeScale = timeScale;
  23131. return timeScale;
  23132. },
  23133. _updateTime: function( deltaTime ) {
  23134. var time = this.time + deltaTime;
  23135. if ( deltaTime === 0 ) return time;
  23136. var duration = this._clip.duration,
  23137. loop = this.loop,
  23138. loopCount = this._loopCount;
  23139. if ( loop === LoopOnce ) {
  23140. if ( loopCount === -1 ) {
  23141. // just started
  23142. this._loopCount = 0;
  23143. this._setEndings( true, true, false );
  23144. }
  23145. handle_stop: {
  23146. if ( time >= duration ) {
  23147. time = duration;
  23148. } else if ( time < 0 ) {
  23149. time = 0;
  23150. } else break handle_stop;
  23151. if ( this.clampWhenFinished ) this.paused = true;
  23152. else this.enabled = false;
  23153. this._mixer.dispatchEvent( {
  23154. type: 'finished', action: this,
  23155. direction: deltaTime < 0 ? -1 : 1
  23156. } );
  23157. }
  23158. } else { // repetitive Repeat or PingPong
  23159. var pingPong = ( loop === LoopPingPong );
  23160. if ( loopCount === -1 ) {
  23161. // just started
  23162. if ( deltaTime >= 0 ) {
  23163. loopCount = 0;
  23164. this._setEndings(
  23165. true, this.repetitions === 0, pingPong );
  23166. } else {
  23167. // when looping in reverse direction, the initial
  23168. // transition through zero counts as a repetition,
  23169. // so leave loopCount at -1
  23170. this._setEndings(
  23171. this.repetitions === 0, true, pingPong );
  23172. }
  23173. }
  23174. if ( time >= duration || time < 0 ) {
  23175. // wrap around
  23176. var loopDelta = Math.floor( time / duration ); // signed
  23177. time -= duration * loopDelta;
  23178. loopCount += Math.abs( loopDelta );
  23179. var pending = this.repetitions - loopCount;
  23180. if ( pending < 0 ) {
  23181. // have to stop (switch state, clamp time, fire event)
  23182. if ( this.clampWhenFinished ) this.paused = true;
  23183. else this.enabled = false;
  23184. time = deltaTime > 0 ? duration : 0;
  23185. this._mixer.dispatchEvent( {
  23186. type: 'finished', action: this,
  23187. direction: deltaTime > 0 ? 1 : -1
  23188. } );
  23189. } else {
  23190. // keep running
  23191. if ( pending === 0 ) {
  23192. // entering the last round
  23193. var atStart = deltaTime < 0;
  23194. this._setEndings( atStart, ! atStart, pingPong );
  23195. } else {
  23196. this._setEndings( false, false, pingPong );
  23197. }
  23198. this._loopCount = loopCount;
  23199. this._mixer.dispatchEvent( {
  23200. type: 'loop', action: this, loopDelta: loopDelta
  23201. } );
  23202. }
  23203. }
  23204. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  23205. // invert time for the "pong round"
  23206. this.time = time;
  23207. return duration - time;
  23208. }
  23209. }
  23210. this.time = time;
  23211. return time;
  23212. },
  23213. _setEndings: function( atStart, atEnd, pingPong ) {
  23214. var settings = this._interpolantSettings;
  23215. if ( pingPong ) {
  23216. settings.endingStart = ZeroSlopeEnding;
  23217. settings.endingEnd = ZeroSlopeEnding;
  23218. } else {
  23219. // assuming for LoopOnce atStart == atEnd == true
  23220. if ( atStart ) {
  23221. settings.endingStart = this.zeroSlopeAtStart ?
  23222. ZeroSlopeEnding : ZeroCurvatureEnding;
  23223. } else {
  23224. settings.endingStart = WrapAroundEnding;
  23225. }
  23226. if ( atEnd ) {
  23227. settings.endingEnd = this.zeroSlopeAtEnd ?
  23228. ZeroSlopeEnding : ZeroCurvatureEnding;
  23229. } else {
  23230. settings.endingEnd = WrapAroundEnding;
  23231. }
  23232. }
  23233. },
  23234. _scheduleFading: function( duration, weightNow, weightThen ) {
  23235. var mixer = this._mixer, now = mixer.time,
  23236. interpolant = this._weightInterpolant;
  23237. if ( interpolant === null ) {
  23238. interpolant = mixer._lendControlInterpolant();
  23239. this._weightInterpolant = interpolant;
  23240. }
  23241. var times = interpolant.parameterPositions,
  23242. values = interpolant.sampleValues;
  23243. times[ 0 ] = now; values[ 0 ] = weightNow;
  23244. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23245. return this;
  23246. }
  23247. } );
  23248. /**
  23249. *
  23250. * Player for AnimationClips.
  23251. *
  23252. *
  23253. * @author Ben Houston / http://clara.io/
  23254. * @author David Sarno / http://lighthaus.us/
  23255. * @author tschw
  23256. */
  23257. function AnimationMixer( root ) {
  23258. this._root = root;
  23259. this._initMemoryManager();
  23260. this._accuIndex = 0;
  23261. this.time = 0;
  23262. this.timeScale = 1.0;
  23263. }
  23264. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23265. _bindAction: function ( action, prototypeAction ) {
  23266. var root = action._localRoot || this._root,
  23267. tracks = action._clip.tracks,
  23268. nTracks = tracks.length,
  23269. bindings = action._propertyBindings,
  23270. interpolants = action._interpolants,
  23271. rootUuid = root.uuid,
  23272. bindingsByRoot = this._bindingsByRootAndName,
  23273. bindingsByName = bindingsByRoot[ rootUuid ];
  23274. if ( bindingsByName === undefined ) {
  23275. bindingsByName = {};
  23276. bindingsByRoot[ rootUuid ] = bindingsByName;
  23277. }
  23278. for ( var i = 0; i !== nTracks; ++ i ) {
  23279. var track = tracks[ i ],
  23280. trackName = track.name,
  23281. binding = bindingsByName[ trackName ];
  23282. if ( binding !== undefined ) {
  23283. bindings[ i ] = binding;
  23284. } else {
  23285. binding = bindings[ i ];
  23286. if ( binding !== undefined ) {
  23287. // existing binding, make sure the cache knows
  23288. if ( binding._cacheIndex === null ) {
  23289. ++ binding.referenceCount;
  23290. this._addInactiveBinding( binding, rootUuid, trackName );
  23291. }
  23292. continue;
  23293. }
  23294. var path = prototypeAction && prototypeAction.
  23295. _propertyBindings[ i ].binding.parsedPath;
  23296. binding = new PropertyMixer(
  23297. PropertyBinding.create( root, trackName, path ),
  23298. track.ValueTypeName, track.getValueSize() );
  23299. ++ binding.referenceCount;
  23300. this._addInactiveBinding( binding, rootUuid, trackName );
  23301. bindings[ i ] = binding;
  23302. }
  23303. interpolants[ i ].resultBuffer = binding.buffer;
  23304. }
  23305. },
  23306. _activateAction: function ( action ) {
  23307. if ( ! this._isActiveAction( action ) ) {
  23308. if ( action._cacheIndex === null ) {
  23309. // this action has been forgotten by the cache, but the user
  23310. // appears to be still using it -> rebind
  23311. var rootUuid = ( action._localRoot || this._root ).uuid,
  23312. clipUuid = action._clip.uuid,
  23313. actionsForClip = this._actionsByClip[ clipUuid ];
  23314. this._bindAction( action,
  23315. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23316. this._addInactiveAction( action, clipUuid, rootUuid );
  23317. }
  23318. var bindings = action._propertyBindings;
  23319. // increment reference counts / sort out state
  23320. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23321. var binding = bindings[ i ];
  23322. if ( binding.useCount ++ === 0 ) {
  23323. this._lendBinding( binding );
  23324. binding.saveOriginalState();
  23325. }
  23326. }
  23327. this._lendAction( action );
  23328. }
  23329. },
  23330. _deactivateAction: function ( action ) {
  23331. if ( this._isActiveAction( action ) ) {
  23332. var bindings = action._propertyBindings;
  23333. // decrement reference counts / sort out state
  23334. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23335. var binding = bindings[ i ];
  23336. if ( -- binding.useCount === 0 ) {
  23337. binding.restoreOriginalState();
  23338. this._takeBackBinding( binding );
  23339. }
  23340. }
  23341. this._takeBackAction( action );
  23342. }
  23343. },
  23344. // Memory manager
  23345. _initMemoryManager: function () {
  23346. this._actions = []; // 'nActiveActions' followed by inactive ones
  23347. this._nActiveActions = 0;
  23348. this._actionsByClip = {};
  23349. // inside:
  23350. // {
  23351. // knownActions: Array< AnimationAction > - used as prototypes
  23352. // actionByRoot: AnimationAction - lookup
  23353. // }
  23354. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23355. this._nActiveBindings = 0;
  23356. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23357. this._controlInterpolants = []; // same game as above
  23358. this._nActiveControlInterpolants = 0;
  23359. var scope = this;
  23360. this.stats = {
  23361. actions: {
  23362. get total() { return scope._actions.length; },
  23363. get inUse() { return scope._nActiveActions; }
  23364. },
  23365. bindings: {
  23366. get total() { return scope._bindings.length; },
  23367. get inUse() { return scope._nActiveBindings; }
  23368. },
  23369. controlInterpolants: {
  23370. get total() { return scope._controlInterpolants.length; },
  23371. get inUse() { return scope._nActiveControlInterpolants; }
  23372. }
  23373. };
  23374. },
  23375. // Memory management for AnimationAction objects
  23376. _isActiveAction: function ( action ) {
  23377. var index = action._cacheIndex;
  23378. return index !== null && index < this._nActiveActions;
  23379. },
  23380. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23381. var actions = this._actions,
  23382. actionsByClip = this._actionsByClip,
  23383. actionsForClip = actionsByClip[ clipUuid ];
  23384. if ( actionsForClip === undefined ) {
  23385. actionsForClip = {
  23386. knownActions: [ action ],
  23387. actionByRoot: {}
  23388. };
  23389. action._byClipCacheIndex = 0;
  23390. actionsByClip[ clipUuid ] = actionsForClip;
  23391. } else {
  23392. var knownActions = actionsForClip.knownActions;
  23393. action._byClipCacheIndex = knownActions.length;
  23394. knownActions.push( action );
  23395. }
  23396. action._cacheIndex = actions.length;
  23397. actions.push( action );
  23398. actionsForClip.actionByRoot[ rootUuid ] = action;
  23399. },
  23400. _removeInactiveAction: function ( action ) {
  23401. var actions = this._actions,
  23402. lastInactiveAction = actions[ actions.length - 1 ],
  23403. cacheIndex = action._cacheIndex;
  23404. lastInactiveAction._cacheIndex = cacheIndex;
  23405. actions[ cacheIndex ] = lastInactiveAction;
  23406. actions.pop();
  23407. action._cacheIndex = null;
  23408. var clipUuid = action._clip.uuid,
  23409. actionsByClip = this._actionsByClip,
  23410. actionsForClip = actionsByClip[ clipUuid ],
  23411. knownActionsForClip = actionsForClip.knownActions,
  23412. lastKnownAction =
  23413. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23414. byClipCacheIndex = action._byClipCacheIndex;
  23415. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23416. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23417. knownActionsForClip.pop();
  23418. action._byClipCacheIndex = null;
  23419. var actionByRoot = actionsForClip.actionByRoot,
  23420. rootUuid = ( action._localRoot || this._root ).uuid;
  23421. delete actionByRoot[ rootUuid ];
  23422. if ( knownActionsForClip.length === 0 ) {
  23423. delete actionsByClip[ clipUuid ];
  23424. }
  23425. this._removeInactiveBindingsForAction( action );
  23426. },
  23427. _removeInactiveBindingsForAction: function ( action ) {
  23428. var bindings = action._propertyBindings;
  23429. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23430. var binding = bindings[ i ];
  23431. if ( -- binding.referenceCount === 0 ) {
  23432. this._removeInactiveBinding( binding );
  23433. }
  23434. }
  23435. },
  23436. _lendAction: function ( action ) {
  23437. // [ active actions | inactive actions ]
  23438. // [ active actions >| inactive actions ]
  23439. // s a
  23440. // <-swap->
  23441. // a s
  23442. var actions = this._actions,
  23443. prevIndex = action._cacheIndex,
  23444. lastActiveIndex = this._nActiveActions ++,
  23445. firstInactiveAction = actions[ lastActiveIndex ];
  23446. action._cacheIndex = lastActiveIndex;
  23447. actions[ lastActiveIndex ] = action;
  23448. firstInactiveAction._cacheIndex = prevIndex;
  23449. actions[ prevIndex ] = firstInactiveAction;
  23450. },
  23451. _takeBackAction: function ( action ) {
  23452. // [ active actions | inactive actions ]
  23453. // [ active actions |< inactive actions ]
  23454. // a s
  23455. // <-swap->
  23456. // s a
  23457. var actions = this._actions,
  23458. prevIndex = action._cacheIndex,
  23459. firstInactiveIndex = -- this._nActiveActions,
  23460. lastActiveAction = actions[ firstInactiveIndex ];
  23461. action._cacheIndex = firstInactiveIndex;
  23462. actions[ firstInactiveIndex ] = action;
  23463. lastActiveAction._cacheIndex = prevIndex;
  23464. actions[ prevIndex ] = lastActiveAction;
  23465. },
  23466. // Memory management for PropertyMixer objects
  23467. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23468. var bindingsByRoot = this._bindingsByRootAndName,
  23469. bindingByName = bindingsByRoot[ rootUuid ],
  23470. bindings = this._bindings;
  23471. if ( bindingByName === undefined ) {
  23472. bindingByName = {};
  23473. bindingsByRoot[ rootUuid ] = bindingByName;
  23474. }
  23475. bindingByName[ trackName ] = binding;
  23476. binding._cacheIndex = bindings.length;
  23477. bindings.push( binding );
  23478. },
  23479. _removeInactiveBinding: function ( binding ) {
  23480. var bindings = this._bindings,
  23481. propBinding = binding.binding,
  23482. rootUuid = propBinding.rootNode.uuid,
  23483. trackName = propBinding.path,
  23484. bindingsByRoot = this._bindingsByRootAndName,
  23485. bindingByName = bindingsByRoot[ rootUuid ],
  23486. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23487. cacheIndex = binding._cacheIndex;
  23488. lastInactiveBinding._cacheIndex = cacheIndex;
  23489. bindings[ cacheIndex ] = lastInactiveBinding;
  23490. bindings.pop();
  23491. delete bindingByName[ trackName ];
  23492. remove_empty_map: {
  23493. for ( var _ in bindingByName ) break remove_empty_map;
  23494. delete bindingsByRoot[ rootUuid ];
  23495. }
  23496. },
  23497. _lendBinding: function ( binding ) {
  23498. var bindings = this._bindings,
  23499. prevIndex = binding._cacheIndex,
  23500. lastActiveIndex = this._nActiveBindings ++,
  23501. firstInactiveBinding = bindings[ lastActiveIndex ];
  23502. binding._cacheIndex = lastActiveIndex;
  23503. bindings[ lastActiveIndex ] = binding;
  23504. firstInactiveBinding._cacheIndex = prevIndex;
  23505. bindings[ prevIndex ] = firstInactiveBinding;
  23506. },
  23507. _takeBackBinding: function ( binding ) {
  23508. var bindings = this._bindings,
  23509. prevIndex = binding._cacheIndex,
  23510. firstInactiveIndex = -- this._nActiveBindings,
  23511. lastActiveBinding = bindings[ firstInactiveIndex ];
  23512. binding._cacheIndex = firstInactiveIndex;
  23513. bindings[ firstInactiveIndex ] = binding;
  23514. lastActiveBinding._cacheIndex = prevIndex;
  23515. bindings[ prevIndex ] = lastActiveBinding;
  23516. },
  23517. // Memory management of Interpolants for weight and time scale
  23518. _lendControlInterpolant: function () {
  23519. var interpolants = this._controlInterpolants,
  23520. lastActiveIndex = this._nActiveControlInterpolants ++,
  23521. interpolant = interpolants[ lastActiveIndex ];
  23522. if ( interpolant === undefined ) {
  23523. interpolant = new LinearInterpolant(
  23524. new Float32Array( 2 ), new Float32Array( 2 ),
  23525. 1, this._controlInterpolantsResultBuffer );
  23526. interpolant.__cacheIndex = lastActiveIndex;
  23527. interpolants[ lastActiveIndex ] = interpolant;
  23528. }
  23529. return interpolant;
  23530. },
  23531. _takeBackControlInterpolant: function ( interpolant ) {
  23532. var interpolants = this._controlInterpolants,
  23533. prevIndex = interpolant.__cacheIndex,
  23534. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23535. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23536. interpolant.__cacheIndex = firstInactiveIndex;
  23537. interpolants[ firstInactiveIndex ] = interpolant;
  23538. lastActiveInterpolant.__cacheIndex = prevIndex;
  23539. interpolants[ prevIndex ] = lastActiveInterpolant;
  23540. },
  23541. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23542. // return an action for a clip optionally using a custom root target
  23543. // object (this method allocates a lot of dynamic memory in case a
  23544. // previously unknown clip/root combination is specified)
  23545. clipAction: function ( clip, optionalRoot ) {
  23546. var root = optionalRoot || this._root,
  23547. rootUuid = root.uuid,
  23548. clipObject = typeof clip === 'string' ?
  23549. AnimationClip.findByName( root, clip ) : clip,
  23550. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23551. actionsForClip = this._actionsByClip[ clipUuid ],
  23552. prototypeAction = null;
  23553. if ( actionsForClip !== undefined ) {
  23554. var existingAction =
  23555. actionsForClip.actionByRoot[ rootUuid ];
  23556. if ( existingAction !== undefined ) {
  23557. return existingAction;
  23558. }
  23559. // we know the clip, so we don't have to parse all
  23560. // the bindings again but can just copy
  23561. prototypeAction = actionsForClip.knownActions[ 0 ];
  23562. // also, take the clip from the prototype action
  23563. if ( clipObject === null )
  23564. clipObject = prototypeAction._clip;
  23565. }
  23566. // clip must be known when specified via string
  23567. if ( clipObject === null ) return null;
  23568. // allocate all resources required to run it
  23569. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23570. this._bindAction( newAction, prototypeAction );
  23571. // and make the action known to the memory manager
  23572. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23573. return newAction;
  23574. },
  23575. // get an existing action
  23576. existingAction: function ( clip, optionalRoot ) {
  23577. var root = optionalRoot || this._root,
  23578. rootUuid = root.uuid,
  23579. clipObject = typeof clip === 'string' ?
  23580. AnimationClip.findByName( root, clip ) : clip,
  23581. clipUuid = clipObject ? clipObject.uuid : clip,
  23582. actionsForClip = this._actionsByClip[ clipUuid ];
  23583. if ( actionsForClip !== undefined ) {
  23584. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23585. }
  23586. return null;
  23587. },
  23588. // deactivates all previously scheduled actions
  23589. stopAllAction: function () {
  23590. var actions = this._actions,
  23591. nActions = this._nActiveActions,
  23592. bindings = this._bindings,
  23593. nBindings = this._nActiveBindings;
  23594. this._nActiveActions = 0;
  23595. this._nActiveBindings = 0;
  23596. for ( var i = 0; i !== nActions; ++ i ) {
  23597. actions[ i ].reset();
  23598. }
  23599. for ( var i = 0; i !== nBindings; ++ i ) {
  23600. bindings[ i ].useCount = 0;
  23601. }
  23602. return this;
  23603. },
  23604. // advance the time and update apply the animation
  23605. update: function ( deltaTime ) {
  23606. deltaTime *= this.timeScale;
  23607. var actions = this._actions,
  23608. nActions = this._nActiveActions,
  23609. time = this.time += deltaTime,
  23610. timeDirection = Math.sign( deltaTime ),
  23611. accuIndex = this._accuIndex ^= 1;
  23612. // run active actions
  23613. for ( var i = 0; i !== nActions; ++ i ) {
  23614. var action = actions[ i ];
  23615. action._update( time, deltaTime, timeDirection, accuIndex );
  23616. }
  23617. // update scene graph
  23618. var bindings = this._bindings,
  23619. nBindings = this._nActiveBindings;
  23620. for ( var i = 0; i !== nBindings; ++ i ) {
  23621. bindings[ i ].apply( accuIndex );
  23622. }
  23623. return this;
  23624. },
  23625. // return this mixer's root target object
  23626. getRoot: function () {
  23627. return this._root;
  23628. },
  23629. // free all resources specific to a particular clip
  23630. uncacheClip: function ( clip ) {
  23631. var actions = this._actions,
  23632. clipUuid = clip.uuid,
  23633. actionsByClip = this._actionsByClip,
  23634. actionsForClip = actionsByClip[ clipUuid ];
  23635. if ( actionsForClip !== undefined ) {
  23636. // note: just calling _removeInactiveAction would mess up the
  23637. // iteration state and also require updating the state we can
  23638. // just throw away
  23639. var actionsToRemove = actionsForClip.knownActions;
  23640. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23641. var action = actionsToRemove[ i ];
  23642. this._deactivateAction( action );
  23643. var cacheIndex = action._cacheIndex,
  23644. lastInactiveAction = actions[ actions.length - 1 ];
  23645. action._cacheIndex = null;
  23646. action._byClipCacheIndex = null;
  23647. lastInactiveAction._cacheIndex = cacheIndex;
  23648. actions[ cacheIndex ] = lastInactiveAction;
  23649. actions.pop();
  23650. this._removeInactiveBindingsForAction( action );
  23651. }
  23652. delete actionsByClip[ clipUuid ];
  23653. }
  23654. },
  23655. // free all resources specific to a particular root target object
  23656. uncacheRoot: function ( root ) {
  23657. var rootUuid = root.uuid,
  23658. actionsByClip = this._actionsByClip;
  23659. for ( var clipUuid in actionsByClip ) {
  23660. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23661. action = actionByRoot[ rootUuid ];
  23662. if ( action !== undefined ) {
  23663. this._deactivateAction( action );
  23664. this._removeInactiveAction( action );
  23665. }
  23666. }
  23667. var bindingsByRoot = this._bindingsByRootAndName,
  23668. bindingByName = bindingsByRoot[ rootUuid ];
  23669. if ( bindingByName !== undefined ) {
  23670. for ( var trackName in bindingByName ) {
  23671. var binding = bindingByName[ trackName ];
  23672. binding.restoreOriginalState();
  23673. this._removeInactiveBinding( binding );
  23674. }
  23675. }
  23676. },
  23677. // remove a targeted clip from the cache
  23678. uncacheAction: function ( clip, optionalRoot ) {
  23679. var action = this.existingAction( clip, optionalRoot );
  23680. if ( action !== null ) {
  23681. this._deactivateAction( action );
  23682. this._removeInactiveAction( action );
  23683. }
  23684. }
  23685. } );
  23686. /**
  23687. * @author mrdoob / http://mrdoob.com/
  23688. */
  23689. function Uniform( value ) {
  23690. if ( typeof value === 'string' ) {
  23691. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23692. value = arguments[ 1 ];
  23693. }
  23694. this.value = value;
  23695. }
  23696. Uniform.prototype.clone = function () {
  23697. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23698. };
  23699. /**
  23700. * @author benaadams / https://twitter.com/ben_a_adams
  23701. */
  23702. function InstancedBufferGeometry() {
  23703. BufferGeometry.call( this );
  23704. this.type = 'InstancedBufferGeometry';
  23705. this.maxInstancedCount = undefined;
  23706. }
  23707. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23708. constructor: InstancedBufferGeometry,
  23709. isInstancedBufferGeometry: true,
  23710. addGroup: function ( start, count, materialIndex ) {
  23711. this.groups.push( {
  23712. start: start,
  23713. count: count,
  23714. materialIndex: materialIndex
  23715. } );
  23716. },
  23717. copy: function ( source ) {
  23718. var index = source.index;
  23719. if ( index !== null ) {
  23720. this.setIndex( index.clone() );
  23721. }
  23722. var attributes = source.attributes;
  23723. for ( var name in attributes ) {
  23724. var attribute = attributes[ name ];
  23725. this.addAttribute( name, attribute.clone() );
  23726. }
  23727. var groups = source.groups;
  23728. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23729. var group = groups[ i ];
  23730. this.addGroup( group.start, group.count, group.materialIndex );
  23731. }
  23732. return this;
  23733. }
  23734. } );
  23735. /**
  23736. * @author benaadams / https://twitter.com/ben_a_adams
  23737. */
  23738. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23739. this.uuid = _Math.generateUUID();
  23740. this.data = interleavedBuffer;
  23741. this.itemSize = itemSize;
  23742. this.offset = offset;
  23743. this.normalized = normalized === true;
  23744. }
  23745. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23746. count: {
  23747. get: function () {
  23748. return this.data.count;
  23749. }
  23750. },
  23751. array: {
  23752. get: function () {
  23753. return this.data.array;
  23754. }
  23755. }
  23756. } );
  23757. Object.assign( InterleavedBufferAttribute.prototype, {
  23758. isInterleavedBufferAttribute: true,
  23759. setX: function ( index, x ) {
  23760. this.data.array[ index * this.data.stride + this.offset ] = x;
  23761. return this;
  23762. },
  23763. setY: function ( index, y ) {
  23764. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23765. return this;
  23766. },
  23767. setZ: function ( index, z ) {
  23768. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23769. return this;
  23770. },
  23771. setW: function ( index, w ) {
  23772. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23773. return this;
  23774. },
  23775. getX: function ( index ) {
  23776. return this.data.array[ index * this.data.stride + this.offset ];
  23777. },
  23778. getY: function ( index ) {
  23779. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23780. },
  23781. getZ: function ( index ) {
  23782. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23783. },
  23784. getW: function ( index ) {
  23785. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23786. },
  23787. setXY: function ( index, x, y ) {
  23788. index = index * this.data.stride + this.offset;
  23789. this.data.array[ index + 0 ] = x;
  23790. this.data.array[ index + 1 ] = y;
  23791. return this;
  23792. },
  23793. setXYZ: function ( index, x, y, z ) {
  23794. index = index * this.data.stride + this.offset;
  23795. this.data.array[ index + 0 ] = x;
  23796. this.data.array[ index + 1 ] = y;
  23797. this.data.array[ index + 2 ] = z;
  23798. return this;
  23799. },
  23800. setXYZW: function ( index, x, y, z, w ) {
  23801. index = index * this.data.stride + this.offset;
  23802. this.data.array[ index + 0 ] = x;
  23803. this.data.array[ index + 1 ] = y;
  23804. this.data.array[ index + 2 ] = z;
  23805. this.data.array[ index + 3 ] = w;
  23806. return this;
  23807. }
  23808. } );
  23809. /**
  23810. * @author benaadams / https://twitter.com/ben_a_adams
  23811. */
  23812. function InterleavedBuffer( array, stride ) {
  23813. this.uuid = _Math.generateUUID();
  23814. this.array = array;
  23815. this.stride = stride;
  23816. this.count = array !== undefined ? array.length / stride : 0;
  23817. this.dynamic = false;
  23818. this.updateRange = { offset: 0, count: - 1 };
  23819. this.onUploadCallback = function () {};
  23820. this.version = 0;
  23821. }
  23822. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23823. set: function ( value ) {
  23824. if ( value === true ) this.version ++;
  23825. }
  23826. } );
  23827. Object.assign( InterleavedBuffer.prototype, {
  23828. isInterleavedBuffer: true,
  23829. setArray: function ( array ) {
  23830. if ( Array.isArray( array ) ) {
  23831. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23832. }
  23833. this.count = array !== undefined ? array.length / this.stride : 0;
  23834. this.array = array;
  23835. },
  23836. setDynamic: function ( value ) {
  23837. this.dynamic = value;
  23838. return this;
  23839. },
  23840. copy: function ( source ) {
  23841. this.array = new source.array.constructor( source.array );
  23842. this.count = source.count;
  23843. this.stride = source.stride;
  23844. this.dynamic = source.dynamic;
  23845. return this;
  23846. },
  23847. copyAt: function ( index1, attribute, index2 ) {
  23848. index1 *= this.stride;
  23849. index2 *= attribute.stride;
  23850. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23851. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23852. }
  23853. return this;
  23854. },
  23855. set: function ( value, offset ) {
  23856. if ( offset === undefined ) offset = 0;
  23857. this.array.set( value, offset );
  23858. return this;
  23859. },
  23860. clone: function () {
  23861. return new this.constructor().copy( this );
  23862. },
  23863. onUpload: function ( callback ) {
  23864. this.onUploadCallback = callback;
  23865. return this;
  23866. }
  23867. } );
  23868. /**
  23869. * @author benaadams / https://twitter.com/ben_a_adams
  23870. */
  23871. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23872. InterleavedBuffer.call( this, array, stride );
  23873. this.meshPerAttribute = meshPerAttribute || 1;
  23874. }
  23875. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  23876. constructor: InstancedInterleavedBuffer,
  23877. isInstancedInterleavedBuffer: true,
  23878. copy: function ( source ) {
  23879. InterleavedBuffer.prototype.copy.call( this, source );
  23880. this.meshPerAttribute = source.meshPerAttribute;
  23881. return this;
  23882. }
  23883. } );
  23884. /**
  23885. * @author benaadams / https://twitter.com/ben_a_adams
  23886. */
  23887. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23888. BufferAttribute.call( this, array, itemSize );
  23889. this.meshPerAttribute = meshPerAttribute || 1;
  23890. }
  23891. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  23892. constructor: InstancedBufferAttribute,
  23893. isInstancedBufferAttribute: true,
  23894. copy: function ( source ) {
  23895. BufferAttribute.prototype.copy.call( this, source );
  23896. this.meshPerAttribute = source.meshPerAttribute;
  23897. return this;
  23898. }
  23899. } );
  23900. /**
  23901. * @author mrdoob / http://mrdoob.com/
  23902. * @author bhouston / http://clara.io/
  23903. * @author stephomi / http://stephaneginier.com/
  23904. */
  23905. function Raycaster( origin, direction, near, far ) {
  23906. this.ray = new Ray( origin, direction );
  23907. // direction is assumed to be normalized (for accurate distance calculations)
  23908. this.near = near || 0;
  23909. this.far = far || Infinity;
  23910. this.params = {
  23911. Mesh: {},
  23912. Line: {},
  23913. LOD: {},
  23914. Points: { threshold: 1 },
  23915. Sprite: {}
  23916. };
  23917. Object.defineProperties( this.params, {
  23918. PointCloud: {
  23919. get: function () {
  23920. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23921. return this.Points;
  23922. }
  23923. }
  23924. } );
  23925. }
  23926. function ascSort( a, b ) {
  23927. return a.distance - b.distance;
  23928. }
  23929. function intersectObject( object, raycaster, intersects, recursive ) {
  23930. if ( object.visible === false ) return;
  23931. object.raycast( raycaster, intersects );
  23932. if ( recursive === true ) {
  23933. var children = object.children;
  23934. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23935. intersectObject( children[ i ], raycaster, intersects, true );
  23936. }
  23937. }
  23938. }
  23939. Object.assign( Raycaster.prototype, {
  23940. linePrecision: 1,
  23941. set: function ( origin, direction ) {
  23942. // direction is assumed to be normalized (for accurate distance calculations)
  23943. this.ray.set( origin, direction );
  23944. },
  23945. setFromCamera: function ( coords, camera ) {
  23946. if ( ( camera && camera.isPerspectiveCamera ) ) {
  23947. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23948. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23949. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  23950. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23951. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23952. } else {
  23953. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23954. }
  23955. },
  23956. intersectObject: function ( object, recursive ) {
  23957. var intersects = [];
  23958. intersectObject( object, this, intersects, recursive );
  23959. intersects.sort( ascSort );
  23960. return intersects;
  23961. },
  23962. intersectObjects: function ( objects, recursive ) {
  23963. var intersects = [];
  23964. if ( Array.isArray( objects ) === false ) {
  23965. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23966. return intersects;
  23967. }
  23968. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23969. intersectObject( objects[ i ], this, intersects, recursive );
  23970. }
  23971. intersects.sort( ascSort );
  23972. return intersects;
  23973. }
  23974. } );
  23975. /**
  23976. * @author alteredq / http://alteredqualia.com/
  23977. */
  23978. function Clock( autoStart ) {
  23979. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23980. this.startTime = 0;
  23981. this.oldTime = 0;
  23982. this.elapsedTime = 0;
  23983. this.running = false;
  23984. }
  23985. Object.assign( Clock.prototype, {
  23986. start: function () {
  23987. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  23988. this.oldTime = this.startTime;
  23989. this.elapsedTime = 0;
  23990. this.running = true;
  23991. },
  23992. stop: function () {
  23993. this.getElapsedTime();
  23994. this.running = false;
  23995. this.autoStart = false;
  23996. },
  23997. getElapsedTime: function () {
  23998. this.getDelta();
  23999. return this.elapsedTime;
  24000. },
  24001. getDelta: function () {
  24002. var diff = 0;
  24003. if ( this.autoStart && ! this.running ) {
  24004. this.start();
  24005. return 0;
  24006. }
  24007. if ( this.running ) {
  24008. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  24009. diff = ( newTime - this.oldTime ) / 1000;
  24010. this.oldTime = newTime;
  24011. this.elapsedTime += diff;
  24012. }
  24013. return diff;
  24014. }
  24015. } );
  24016. /**
  24017. * @author bhouston / http://clara.io
  24018. * @author WestLangley / http://github.com/WestLangley
  24019. *
  24020. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  24021. *
  24022. * The poles (phi) are at the positive and negative y axis.
  24023. * The equator starts at positive z.
  24024. */
  24025. function Spherical( radius, phi, theta ) {
  24026. this.radius = ( radius !== undefined ) ? radius : 1.0;
  24027. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  24028. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  24029. return this;
  24030. }
  24031. Object.assign( Spherical.prototype, {
  24032. set: function ( radius, phi, theta ) {
  24033. this.radius = radius;
  24034. this.phi = phi;
  24035. this.theta = theta;
  24036. return this;
  24037. },
  24038. clone: function () {
  24039. return new this.constructor().copy( this );
  24040. },
  24041. copy: function ( other ) {
  24042. this.radius = other.radius;
  24043. this.phi = other.phi;
  24044. this.theta = other.theta;
  24045. return this;
  24046. },
  24047. // restrict phi to be betwee EPS and PI-EPS
  24048. makeSafe: function() {
  24049. var EPS = 0.000001;
  24050. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  24051. return this;
  24052. },
  24053. setFromVector3: function( vec3 ) {
  24054. this.radius = vec3.length();
  24055. if ( this.radius === 0 ) {
  24056. this.theta = 0;
  24057. this.phi = 0;
  24058. } else {
  24059. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  24060. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  24061. }
  24062. return this;
  24063. }
  24064. } );
  24065. /**
  24066. * @author Mugen87 / https://github.com/Mugen87
  24067. *
  24068. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  24069. *
  24070. */
  24071. function Cylindrical( radius, theta, y ) {
  24072. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  24073. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  24074. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  24075. return this;
  24076. }
  24077. Object.assign( Cylindrical.prototype, {
  24078. set: function ( radius, theta, y ) {
  24079. this.radius = radius;
  24080. this.theta = theta;
  24081. this.y = y;
  24082. return this;
  24083. },
  24084. clone: function () {
  24085. return new this.constructor().copy( this );
  24086. },
  24087. copy: function ( other ) {
  24088. this.radius = other.radius;
  24089. this.theta = other.theta;
  24090. this.y = other.y;
  24091. return this;
  24092. },
  24093. setFromVector3: function( vec3 ) {
  24094. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  24095. this.theta = Math.atan2( vec3.x, vec3.z );
  24096. this.y = vec3.y;
  24097. return this;
  24098. }
  24099. } );
  24100. /**
  24101. * @author alteredq / http://alteredqualia.com/
  24102. */
  24103. function MorphBlendMesh( geometry, material ) {
  24104. Mesh.call( this, geometry, material );
  24105. this.animationsMap = {};
  24106. this.animationsList = [];
  24107. // prepare default animation
  24108. // (all frames played together in 1 second)
  24109. var numFrames = this.geometry.morphTargets.length;
  24110. var name = "__default";
  24111. var startFrame = 0;
  24112. var endFrame = numFrames - 1;
  24113. var fps = numFrames / 1;
  24114. this.createAnimation( name, startFrame, endFrame, fps );
  24115. this.setAnimationWeight( name, 1 );
  24116. }
  24117. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  24118. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  24119. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  24120. var animation = {
  24121. start: start,
  24122. end: end,
  24123. length: end - start + 1,
  24124. fps: fps,
  24125. duration: ( end - start ) / fps,
  24126. lastFrame: 0,
  24127. currentFrame: 0,
  24128. active: false,
  24129. time: 0,
  24130. direction: 1,
  24131. weight: 1,
  24132. directionBackwards: false,
  24133. mirroredLoop: false
  24134. };
  24135. this.animationsMap[ name ] = animation;
  24136. this.animationsList.push( animation );
  24137. };
  24138. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  24139. var pattern = /([a-z]+)_?(\d+)/i;
  24140. var firstAnimation, frameRanges = {};
  24141. var geometry = this.geometry;
  24142. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  24143. var morph = geometry.morphTargets[ i ];
  24144. var chunks = morph.name.match( pattern );
  24145. if ( chunks && chunks.length > 1 ) {
  24146. var name = chunks[ 1 ];
  24147. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  24148. var range = frameRanges[ name ];
  24149. if ( i < range.start ) range.start = i;
  24150. if ( i > range.end ) range.end = i;
  24151. if ( ! firstAnimation ) firstAnimation = name;
  24152. }
  24153. }
  24154. for ( var name in frameRanges ) {
  24155. var range = frameRanges[ name ];
  24156. this.createAnimation( name, range.start, range.end, fps );
  24157. }
  24158. this.firstAnimation = firstAnimation;
  24159. };
  24160. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  24161. var animation = this.animationsMap[ name ];
  24162. if ( animation ) {
  24163. animation.direction = 1;
  24164. animation.directionBackwards = false;
  24165. }
  24166. };
  24167. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  24168. var animation = this.animationsMap[ name ];
  24169. if ( animation ) {
  24170. animation.direction = - 1;
  24171. animation.directionBackwards = true;
  24172. }
  24173. };
  24174. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  24175. var animation = this.animationsMap[ name ];
  24176. if ( animation ) {
  24177. animation.fps = fps;
  24178. animation.duration = ( animation.end - animation.start ) / animation.fps;
  24179. }
  24180. };
  24181. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  24182. var animation = this.animationsMap[ name ];
  24183. if ( animation ) {
  24184. animation.duration = duration;
  24185. animation.fps = ( animation.end - animation.start ) / animation.duration;
  24186. }
  24187. };
  24188. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  24189. var animation = this.animationsMap[ name ];
  24190. if ( animation ) {
  24191. animation.weight = weight;
  24192. }
  24193. };
  24194. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  24195. var animation = this.animationsMap[ name ];
  24196. if ( animation ) {
  24197. animation.time = time;
  24198. }
  24199. };
  24200. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  24201. var time = 0;
  24202. var animation = this.animationsMap[ name ];
  24203. if ( animation ) {
  24204. time = animation.time;
  24205. }
  24206. return time;
  24207. };
  24208. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24209. var duration = - 1;
  24210. var animation = this.animationsMap[ name ];
  24211. if ( animation ) {
  24212. duration = animation.duration;
  24213. }
  24214. return duration;
  24215. };
  24216. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24217. var animation = this.animationsMap[ name ];
  24218. if ( animation ) {
  24219. animation.time = 0;
  24220. animation.active = true;
  24221. } else {
  24222. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24223. }
  24224. };
  24225. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24226. var animation = this.animationsMap[ name ];
  24227. if ( animation ) {
  24228. animation.active = false;
  24229. }
  24230. };
  24231. MorphBlendMesh.prototype.update = function ( delta ) {
  24232. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24233. var animation = this.animationsList[ i ];
  24234. if ( ! animation.active ) continue;
  24235. var frameTime = animation.duration / animation.length;
  24236. animation.time += animation.direction * delta;
  24237. if ( animation.mirroredLoop ) {
  24238. if ( animation.time > animation.duration || animation.time < 0 ) {
  24239. animation.direction *= - 1;
  24240. if ( animation.time > animation.duration ) {
  24241. animation.time = animation.duration;
  24242. animation.directionBackwards = true;
  24243. }
  24244. if ( animation.time < 0 ) {
  24245. animation.time = 0;
  24246. animation.directionBackwards = false;
  24247. }
  24248. }
  24249. } else {
  24250. animation.time = animation.time % animation.duration;
  24251. if ( animation.time < 0 ) animation.time += animation.duration;
  24252. }
  24253. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24254. var weight = animation.weight;
  24255. if ( keyframe !== animation.currentFrame ) {
  24256. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24257. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24258. this.morphTargetInfluences[ keyframe ] = 0;
  24259. animation.lastFrame = animation.currentFrame;
  24260. animation.currentFrame = keyframe;
  24261. }
  24262. var mix = ( animation.time % frameTime ) / frameTime;
  24263. if ( animation.directionBackwards ) mix = 1 - mix;
  24264. if ( animation.currentFrame !== animation.lastFrame ) {
  24265. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24266. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24267. } else {
  24268. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24269. }
  24270. }
  24271. };
  24272. /**
  24273. * @author alteredq / http://alteredqualia.com/
  24274. */
  24275. function ImmediateRenderObject( material ) {
  24276. Object3D.call( this );
  24277. this.material = material;
  24278. this.render = function ( renderCallback ) {};
  24279. }
  24280. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24281. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24282. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24283. /**
  24284. * @author mrdoob / http://mrdoob.com/
  24285. * @author WestLangley / http://github.com/WestLangley
  24286. */
  24287. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24288. this.object = object;
  24289. this.size = ( size !== undefined ) ? size : 1;
  24290. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24291. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24292. //
  24293. var nNormals = 0;
  24294. var objGeometry = this.object.geometry;
  24295. if ( objGeometry && objGeometry.isGeometry ) {
  24296. nNormals = objGeometry.faces.length * 3;
  24297. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24298. nNormals = objGeometry.attributes.normal.count;
  24299. }
  24300. //
  24301. var geometry = new BufferGeometry();
  24302. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24303. geometry.addAttribute( 'position', positions );
  24304. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24305. //
  24306. this.matrixAutoUpdate = false;
  24307. this.update();
  24308. }
  24309. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24310. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24311. VertexNormalsHelper.prototype.update = ( function () {
  24312. var v1 = new Vector3();
  24313. var v2 = new Vector3();
  24314. var normalMatrix = new Matrix3();
  24315. return function update() {
  24316. var keys = [ 'a', 'b', 'c' ];
  24317. this.object.updateMatrixWorld( true );
  24318. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24319. var matrixWorld = this.object.matrixWorld;
  24320. var position = this.geometry.attributes.position;
  24321. //
  24322. var objGeometry = this.object.geometry;
  24323. if ( objGeometry && objGeometry.isGeometry ) {
  24324. var vertices = objGeometry.vertices;
  24325. var faces = objGeometry.faces;
  24326. var idx = 0;
  24327. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24328. var face = faces[ i ];
  24329. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24330. var vertex = vertices[ face[ keys[ j ] ] ];
  24331. var normal = face.vertexNormals[ j ];
  24332. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24333. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24334. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24335. idx = idx + 1;
  24336. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24337. idx = idx + 1;
  24338. }
  24339. }
  24340. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24341. var objPos = objGeometry.attributes.position;
  24342. var objNorm = objGeometry.attributes.normal;
  24343. var idx = 0;
  24344. // for simplicity, ignore index and drawcalls, and render every normal
  24345. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24346. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24347. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24348. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24349. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24350. idx = idx + 1;
  24351. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24352. idx = idx + 1;
  24353. }
  24354. }
  24355. position.needsUpdate = true;
  24356. };
  24357. }() );
  24358. /**
  24359. * @author alteredq / http://alteredqualia.com/
  24360. * @author mrdoob / http://mrdoob.com/
  24361. * @author WestLangley / http://github.com/WestLangley
  24362. */
  24363. function SpotLightHelper( light ) {
  24364. Object3D.call( this );
  24365. this.light = light;
  24366. this.light.updateMatrixWorld();
  24367. this.matrix = light.matrixWorld;
  24368. this.matrixAutoUpdate = false;
  24369. var geometry = new BufferGeometry();
  24370. var positions = [
  24371. 0, 0, 0, 0, 0, 1,
  24372. 0, 0, 0, 1, 0, 1,
  24373. 0, 0, 0, - 1, 0, 1,
  24374. 0, 0, 0, 0, 1, 1,
  24375. 0, 0, 0, 0, - 1, 1
  24376. ];
  24377. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24378. var p1 = ( i / l ) * Math.PI * 2;
  24379. var p2 = ( j / l ) * Math.PI * 2;
  24380. positions.push(
  24381. Math.cos( p1 ), Math.sin( p1 ), 1,
  24382. Math.cos( p2 ), Math.sin( p2 ), 1
  24383. );
  24384. }
  24385. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24386. var material = new LineBasicMaterial( { fog: false } );
  24387. this.cone = new LineSegments( geometry, material );
  24388. this.add( this.cone );
  24389. this.update();
  24390. }
  24391. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24392. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24393. SpotLightHelper.prototype.dispose = function () {
  24394. this.cone.geometry.dispose();
  24395. this.cone.material.dispose();
  24396. };
  24397. SpotLightHelper.prototype.update = function () {
  24398. var vector = new Vector3();
  24399. var vector2 = new Vector3();
  24400. return function update() {
  24401. this.light.updateMatrixWorld();
  24402. var coneLength = this.light.distance ? this.light.distance : 1000;
  24403. var coneWidth = coneLength * Math.tan( this.light.angle );
  24404. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24405. vector.setFromMatrixPosition( this.light.matrixWorld );
  24406. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24407. this.cone.lookAt( vector2.sub( vector ) );
  24408. this.cone.material.color.copy( this.light.color );
  24409. };
  24410. }();
  24411. /**
  24412. * @author Sean Griffin / http://twitter.com/sgrif
  24413. * @author Michael Guerrero / http://realitymeltdown.com
  24414. * @author mrdoob / http://mrdoob.com/
  24415. * @author ikerr / http://verold.com
  24416. * @author Mugen87 / https://github.com/Mugen87
  24417. */
  24418. function getBoneList( object ) {
  24419. var boneList = [];
  24420. if ( object && object.isBone ) {
  24421. boneList.push( object );
  24422. }
  24423. for ( var i = 0; i < object.children.length; i ++ ) {
  24424. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  24425. }
  24426. return boneList;
  24427. }
  24428. function SkeletonHelper( object ) {
  24429. var bones = getBoneList( object );
  24430. var geometry = new BufferGeometry();
  24431. var vertices = [];
  24432. var colors = [];
  24433. var color1 = new Color( 0, 0, 1 );
  24434. var color2 = new Color( 0, 1, 0 );
  24435. for ( var i = 0; i < bones.length; i ++ ) {
  24436. var bone = bones[ i ];
  24437. if ( bone.parent && bone.parent.isBone ) {
  24438. vertices.push( 0, 0, 0 );
  24439. vertices.push( 0, 0, 0 );
  24440. colors.push( color1.r, color1.g, color1.b );
  24441. colors.push( color2.r, color2.g, color2.b );
  24442. }
  24443. }
  24444. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24445. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24446. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24447. LineSegments.call( this, geometry, material );
  24448. this.root = object;
  24449. this.bones = bones;
  24450. this.matrix = object.matrixWorld;
  24451. this.matrixAutoUpdate = false;
  24452. this.onBeforeRender();
  24453. }
  24454. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24455. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24456. SkeletonHelper.prototype.onBeforeRender = function () {
  24457. var vector = new Vector3();
  24458. var boneMatrix = new Matrix4();
  24459. var matrixWorldInv = new Matrix4();
  24460. return function onBeforeRender() {
  24461. var bones = this.bones;
  24462. var geometry = this.geometry;
  24463. var position = geometry.getAttribute( 'position' );
  24464. matrixWorldInv.getInverse( this.root.matrixWorld );
  24465. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  24466. var bone = bones[ i ];
  24467. if ( bone.parent && bone.parent.isBone ) {
  24468. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24469. vector.setFromMatrixPosition( boneMatrix );
  24470. position.setXYZ( j, vector.x, vector.y, vector.z );
  24471. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24472. vector.setFromMatrixPosition( boneMatrix );
  24473. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24474. j += 2;
  24475. }
  24476. }
  24477. geometry.getAttribute( 'position' ).needsUpdate = true;
  24478. };
  24479. }();
  24480. /**
  24481. * @author alteredq / http://alteredqualia.com/
  24482. * @author mrdoob / http://mrdoob.com/
  24483. */
  24484. function PointLightHelper( light, sphereSize ) {
  24485. this.light = light;
  24486. this.light.updateMatrixWorld();
  24487. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24488. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24489. material.color.copy( this.light.color );
  24490. Mesh.call( this, geometry, material );
  24491. this.matrix = this.light.matrixWorld;
  24492. this.matrixAutoUpdate = false;
  24493. /*
  24494. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24495. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24496. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24497. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24498. var d = light.distance;
  24499. if ( d === 0.0 ) {
  24500. this.lightDistance.visible = false;
  24501. } else {
  24502. this.lightDistance.scale.set( d, d, d );
  24503. }
  24504. this.add( this.lightDistance );
  24505. */
  24506. }
  24507. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24508. PointLightHelper.prototype.constructor = PointLightHelper;
  24509. PointLightHelper.prototype.dispose = function () {
  24510. this.geometry.dispose();
  24511. this.material.dispose();
  24512. };
  24513. PointLightHelper.prototype.update = function () {
  24514. this.material.color.copy( this.light.color );
  24515. /*
  24516. var d = this.light.distance;
  24517. if ( d === 0.0 ) {
  24518. this.lightDistance.visible = false;
  24519. } else {
  24520. this.lightDistance.visible = true;
  24521. this.lightDistance.scale.set( d, d, d );
  24522. }
  24523. */
  24524. };
  24525. /**
  24526. * @author abelnation / http://github.com/abelnation
  24527. * @author Mugen87 / http://github.com/Mugen87
  24528. * @author WestLangley / http://github.com/WestLangley
  24529. */
  24530. function RectAreaLightHelper( light ) {
  24531. Object3D.call( this );
  24532. this.light = light;
  24533. this.light.updateMatrixWorld();
  24534. this.matrix = light.matrixWorld;
  24535. this.matrixAutoUpdate = false;
  24536. var material = new LineBasicMaterial( { color: light.color } );
  24537. var geometry = new BufferGeometry();
  24538. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24539. this.add( new Line( geometry, material ) );
  24540. this.update();
  24541. }
  24542. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24543. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24544. RectAreaLightHelper.prototype.dispose = function () {
  24545. this.children[ 0 ].geometry.dispose();
  24546. this.children[ 0 ].material.dispose();
  24547. };
  24548. RectAreaLightHelper.prototype.update = function () {
  24549. var line = this.children[ 0 ];
  24550. // update material
  24551. line.material.color.copy( this.light.color );
  24552. // calculate new dimensions of the helper
  24553. var hx = this.light.width * 0.5;
  24554. var hy = this.light.height * 0.5;
  24555. var position = line.geometry.attributes.position;
  24556. var array = position.array;
  24557. // update vertices
  24558. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24559. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24560. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24561. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24562. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24563. position.needsUpdate = true;
  24564. };
  24565. /**
  24566. * @author alteredq / http://alteredqualia.com/
  24567. * @author mrdoob / http://mrdoob.com/
  24568. * @author Mugen87 / https://github.com/Mugen87
  24569. */
  24570. function HemisphereLightHelper( light, size ) {
  24571. Object3D.call( this );
  24572. this.light = light;
  24573. this.light.updateMatrixWorld();
  24574. this.matrix = light.matrixWorld;
  24575. this.matrixAutoUpdate = false;
  24576. var geometry = new OctahedronBufferGeometry( size );
  24577. geometry.rotateY( Math.PI * 0.5 );
  24578. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24579. var position = geometry.getAttribute( 'position' );
  24580. var colors = new Float32Array( position.count * 3 );
  24581. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24582. this.add( new Mesh( geometry, material ) );
  24583. this.update();
  24584. }
  24585. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24586. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24587. HemisphereLightHelper.prototype.dispose = function () {
  24588. this.children[ 0 ].geometry.dispose();
  24589. this.children[ 0 ].material.dispose();
  24590. };
  24591. HemisphereLightHelper.prototype.update = function () {
  24592. var vector = new Vector3();
  24593. var color1 = new Color();
  24594. var color2 = new Color();
  24595. return function update() {
  24596. var mesh = this.children[ 0 ];
  24597. var colors = mesh.geometry.getAttribute( 'color' );
  24598. color1.copy( this.light.color );
  24599. color2.copy( this.light.groundColor );
  24600. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24601. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24602. colors.setXYZ( i, color.r, color.g, color.b );
  24603. }
  24604. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24605. colors.needsUpdate = true;
  24606. };
  24607. }();
  24608. /**
  24609. * @author mrdoob / http://mrdoob.com/
  24610. */
  24611. function GridHelper( size, divisions, color1, color2 ) {
  24612. size = size || 10;
  24613. divisions = divisions || 10;
  24614. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24615. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24616. var center = divisions / 2;
  24617. var step = size / divisions;
  24618. var halfSize = size / 2;
  24619. var vertices = [], colors = [];
  24620. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24621. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24622. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24623. var color = i === center ? color1 : color2;
  24624. color.toArray( colors, j ); j += 3;
  24625. color.toArray( colors, j ); j += 3;
  24626. color.toArray( colors, j ); j += 3;
  24627. color.toArray( colors, j ); j += 3;
  24628. }
  24629. var geometry = new BufferGeometry();
  24630. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24631. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24632. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24633. LineSegments.call( this, geometry, material );
  24634. }
  24635. GridHelper.prototype = Object.create( LineSegments.prototype );
  24636. GridHelper.prototype.constructor = GridHelper;
  24637. /**
  24638. * @author mrdoob / http://mrdoob.com/
  24639. * @author Mugen87 / http://github.com/Mugen87
  24640. * @author Hectate / http://www.github.com/Hectate
  24641. */
  24642. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24643. radius = radius || 10;
  24644. radials = radials || 16;
  24645. circles = circles || 8;
  24646. divisions = divisions || 64;
  24647. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24648. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24649. var vertices = [];
  24650. var colors = [];
  24651. var x, z;
  24652. var v, i, j, r, color;
  24653. // create the radials
  24654. for ( i = 0; i <= radials; i ++ ) {
  24655. v = ( i / radials ) * ( Math.PI * 2 );
  24656. x = Math.sin( v ) * radius;
  24657. z = Math.cos( v ) * radius;
  24658. vertices.push( 0, 0, 0 );
  24659. vertices.push( x, 0, z );
  24660. color = ( i & 1 ) ? color1 : color2;
  24661. colors.push( color.r, color.g, color.b );
  24662. colors.push( color.r, color.g, color.b );
  24663. }
  24664. // create the circles
  24665. for ( i = 0; i <= circles; i ++ ) {
  24666. color = ( i & 1 ) ? color1 : color2;
  24667. r = radius - ( radius / circles * i );
  24668. for ( j = 0; j < divisions; j ++ ) {
  24669. // first vertex
  24670. v = ( j / divisions ) * ( Math.PI * 2 );
  24671. x = Math.sin( v ) * r;
  24672. z = Math.cos( v ) * r;
  24673. vertices.push( x, 0, z );
  24674. colors.push( color.r, color.g, color.b );
  24675. // second vertex
  24676. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24677. x = Math.sin( v ) * r;
  24678. z = Math.cos( v ) * r;
  24679. vertices.push( x, 0, z );
  24680. colors.push( color.r, color.g, color.b );
  24681. }
  24682. }
  24683. var geometry = new BufferGeometry();
  24684. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24685. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24686. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24687. LineSegments.call( this, geometry, material );
  24688. }
  24689. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24690. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24691. /**
  24692. * @author mrdoob / http://mrdoob.com/
  24693. * @author WestLangley / http://github.com/WestLangley
  24694. */
  24695. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24696. // FaceNormalsHelper only supports THREE.Geometry
  24697. this.object = object;
  24698. this.size = ( size !== undefined ) ? size : 1;
  24699. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24700. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24701. //
  24702. var nNormals = 0;
  24703. var objGeometry = this.object.geometry;
  24704. if ( objGeometry && objGeometry.isGeometry ) {
  24705. nNormals = objGeometry.faces.length;
  24706. } else {
  24707. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24708. }
  24709. //
  24710. var geometry = new BufferGeometry();
  24711. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24712. geometry.addAttribute( 'position', positions );
  24713. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24714. //
  24715. this.matrixAutoUpdate = false;
  24716. this.update();
  24717. }
  24718. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24719. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24720. FaceNormalsHelper.prototype.update = ( function () {
  24721. var v1 = new Vector3();
  24722. var v2 = new Vector3();
  24723. var normalMatrix = new Matrix3();
  24724. return function update() {
  24725. this.object.updateMatrixWorld( true );
  24726. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24727. var matrixWorld = this.object.matrixWorld;
  24728. var position = this.geometry.attributes.position;
  24729. //
  24730. var objGeometry = this.object.geometry;
  24731. var vertices = objGeometry.vertices;
  24732. var faces = objGeometry.faces;
  24733. var idx = 0;
  24734. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24735. var face = faces[ i ];
  24736. var normal = face.normal;
  24737. v1.copy( vertices[ face.a ] )
  24738. .add( vertices[ face.b ] )
  24739. .add( vertices[ face.c ] )
  24740. .divideScalar( 3 )
  24741. .applyMatrix4( matrixWorld );
  24742. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24743. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24744. idx = idx + 1;
  24745. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24746. idx = idx + 1;
  24747. }
  24748. position.needsUpdate = true;
  24749. };
  24750. }() );
  24751. /**
  24752. * @author alteredq / http://alteredqualia.com/
  24753. * @author mrdoob / http://mrdoob.com/
  24754. * @author WestLangley / http://github.com/WestLangley
  24755. */
  24756. function DirectionalLightHelper( light, size ) {
  24757. Object3D.call( this );
  24758. this.light = light;
  24759. this.light.updateMatrixWorld();
  24760. this.matrix = light.matrixWorld;
  24761. this.matrixAutoUpdate = false;
  24762. if ( size === undefined ) size = 1;
  24763. var geometry = new BufferGeometry();
  24764. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24765. - size, size, 0,
  24766. size, size, 0,
  24767. size, - size, 0,
  24768. - size, - size, 0,
  24769. - size, size, 0
  24770. ], 3 ) );
  24771. var material = new LineBasicMaterial( { fog: false } );
  24772. this.add( new Line( geometry, material ) );
  24773. geometry = new BufferGeometry();
  24774. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24775. this.add( new Line( geometry, material ));
  24776. this.update();
  24777. }
  24778. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24779. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24780. DirectionalLightHelper.prototype.dispose = function () {
  24781. var lightPlane = this.children[ 0 ];
  24782. var targetLine = this.children[ 1 ];
  24783. lightPlane.geometry.dispose();
  24784. lightPlane.material.dispose();
  24785. targetLine.geometry.dispose();
  24786. targetLine.material.dispose();
  24787. };
  24788. DirectionalLightHelper.prototype.update = function () {
  24789. var v1 = new Vector3();
  24790. var v2 = new Vector3();
  24791. var v3 = new Vector3();
  24792. return function update() {
  24793. v1.setFromMatrixPosition( this.light.matrixWorld );
  24794. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24795. v3.subVectors( v2, v1 );
  24796. var lightPlane = this.children[ 0 ];
  24797. var targetLine = this.children[ 1 ];
  24798. lightPlane.lookAt( v3 );
  24799. lightPlane.material.color.copy( this.light.color );
  24800. targetLine.lookAt( v3 );
  24801. targetLine.scale.z = v3.length();
  24802. };
  24803. }();
  24804. /**
  24805. * @author alteredq / http://alteredqualia.com/
  24806. * @author Mugen87 / https://github.com/Mugen87
  24807. *
  24808. * - shows frustum, line of sight and up of the camera
  24809. * - suitable for fast updates
  24810. * - based on frustum visualization in lightgl.js shadowmap example
  24811. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24812. */
  24813. function CameraHelper( camera ) {
  24814. var geometry = new BufferGeometry();
  24815. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24816. var vertices = [];
  24817. var colors = [];
  24818. var pointMap = {};
  24819. // colors
  24820. var colorFrustum = new Color( 0xffaa00 );
  24821. var colorCone = new Color( 0xff0000 );
  24822. var colorUp = new Color( 0x00aaff );
  24823. var colorTarget = new Color( 0xffffff );
  24824. var colorCross = new Color( 0x333333 );
  24825. // near
  24826. addLine( "n1", "n2", colorFrustum );
  24827. addLine( "n2", "n4", colorFrustum );
  24828. addLine( "n4", "n3", colorFrustum );
  24829. addLine( "n3", "n1", colorFrustum );
  24830. // far
  24831. addLine( "f1", "f2", colorFrustum );
  24832. addLine( "f2", "f4", colorFrustum );
  24833. addLine( "f4", "f3", colorFrustum );
  24834. addLine( "f3", "f1", colorFrustum );
  24835. // sides
  24836. addLine( "n1", "f1", colorFrustum );
  24837. addLine( "n2", "f2", colorFrustum );
  24838. addLine( "n3", "f3", colorFrustum );
  24839. addLine( "n4", "f4", colorFrustum );
  24840. // cone
  24841. addLine( "p", "n1", colorCone );
  24842. addLine( "p", "n2", colorCone );
  24843. addLine( "p", "n3", colorCone );
  24844. addLine( "p", "n4", colorCone );
  24845. // up
  24846. addLine( "u1", "u2", colorUp );
  24847. addLine( "u2", "u3", colorUp );
  24848. addLine( "u3", "u1", colorUp );
  24849. // target
  24850. addLine( "c", "t", colorTarget );
  24851. addLine( "p", "c", colorCross );
  24852. // cross
  24853. addLine( "cn1", "cn2", colorCross );
  24854. addLine( "cn3", "cn4", colorCross );
  24855. addLine( "cf1", "cf2", colorCross );
  24856. addLine( "cf3", "cf4", colorCross );
  24857. function addLine( a, b, color ) {
  24858. addPoint( a, color );
  24859. addPoint( b, color );
  24860. }
  24861. function addPoint( id, color ) {
  24862. vertices.push( 0, 0, 0 );
  24863. colors.push( color.r, color.g, color.b );
  24864. if ( pointMap[ id ] === undefined ) {
  24865. pointMap[ id ] = [];
  24866. }
  24867. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24868. }
  24869. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24870. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24871. LineSegments.call( this, geometry, material );
  24872. this.camera = camera;
  24873. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24874. this.matrix = camera.matrixWorld;
  24875. this.matrixAutoUpdate = false;
  24876. this.pointMap = pointMap;
  24877. this.update();
  24878. }
  24879. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24880. CameraHelper.prototype.constructor = CameraHelper;
  24881. CameraHelper.prototype.update = function () {
  24882. var geometry, pointMap;
  24883. var vector = new Vector3();
  24884. var camera = new Camera();
  24885. function setPoint( point, x, y, z ) {
  24886. vector.set( x, y, z ).unproject( camera );
  24887. var points = pointMap[ point ];
  24888. if ( points !== undefined ) {
  24889. var position = geometry.getAttribute( 'position' );
  24890. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24891. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24892. }
  24893. }
  24894. }
  24895. return function update() {
  24896. geometry = this.geometry;
  24897. pointMap = this.pointMap;
  24898. var w = 1, h = 1;
  24899. // we need just camera projection matrix
  24900. // world matrix must be identity
  24901. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24902. // center / target
  24903. setPoint( "c", 0, 0, - 1 );
  24904. setPoint( "t", 0, 0, 1 );
  24905. // near
  24906. setPoint( "n1", - w, - h, - 1 );
  24907. setPoint( "n2", w, - h, - 1 );
  24908. setPoint( "n3", - w, h, - 1 );
  24909. setPoint( "n4", w, h, - 1 );
  24910. // far
  24911. setPoint( "f1", - w, - h, 1 );
  24912. setPoint( "f2", w, - h, 1 );
  24913. setPoint( "f3", - w, h, 1 );
  24914. setPoint( "f4", w, h, 1 );
  24915. // up
  24916. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24917. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24918. setPoint( "u3", 0, h * 2, - 1 );
  24919. // cross
  24920. setPoint( "cf1", - w, 0, 1 );
  24921. setPoint( "cf2", w, 0, 1 );
  24922. setPoint( "cf3", 0, - h, 1 );
  24923. setPoint( "cf4", 0, h, 1 );
  24924. setPoint( "cn1", - w, 0, - 1 );
  24925. setPoint( "cn2", w, 0, - 1 );
  24926. setPoint( "cn3", 0, - h, - 1 );
  24927. setPoint( "cn4", 0, h, - 1 );
  24928. geometry.getAttribute( 'position' ).needsUpdate = true;
  24929. };
  24930. }();
  24931. /**
  24932. * @author mrdoob / http://mrdoob.com/
  24933. * @author Mugen87 / http://github.com/Mugen87
  24934. */
  24935. function BoxHelper( object, color ) {
  24936. this.object = object;
  24937. if ( color === undefined ) color = 0xffff00;
  24938. 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 ] );
  24939. var positions = new Float32Array( 8 * 3 );
  24940. var geometry = new BufferGeometry();
  24941. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24942. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24943. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24944. this.matrixAutoUpdate = false;
  24945. this.update();
  24946. }
  24947. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24948. BoxHelper.prototype.constructor = BoxHelper;
  24949. BoxHelper.prototype.update = ( function () {
  24950. var box = new Box3();
  24951. return function update( object ) {
  24952. if ( object !== undefined ) {
  24953. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  24954. }
  24955. if ( this.object !== undefined ) {
  24956. box.setFromObject( this.object );
  24957. }
  24958. if ( box.isEmpty() ) return;
  24959. var min = box.min;
  24960. var max = box.max;
  24961. /*
  24962. 5____4
  24963. 1/___0/|
  24964. | 6__|_7
  24965. 2/___3/
  24966. 0: max.x, max.y, max.z
  24967. 1: min.x, max.y, max.z
  24968. 2: min.x, min.y, max.z
  24969. 3: max.x, min.y, max.z
  24970. 4: max.x, max.y, min.z
  24971. 5: min.x, max.y, min.z
  24972. 6: min.x, min.y, min.z
  24973. 7: max.x, min.y, min.z
  24974. */
  24975. var position = this.geometry.attributes.position;
  24976. var array = position.array;
  24977. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24978. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24979. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24980. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24981. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24982. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24983. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24984. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24985. position.needsUpdate = true;
  24986. this.geometry.computeBoundingSphere();
  24987. };
  24988. } )();
  24989. BoxHelper.prototype.setFromObject = function ( object ) {
  24990. this.object = object;
  24991. this.update();
  24992. return this;
  24993. };
  24994. /**
  24995. * @author WestLangley / http://github.com/WestLangley
  24996. * @author zz85 / http://github.com/zz85
  24997. * @author bhouston / http://clara.io
  24998. *
  24999. * Creates an arrow for visualizing directions
  25000. *
  25001. * Parameters:
  25002. * dir - Vector3
  25003. * origin - Vector3
  25004. * length - Number
  25005. * color - color in hex value
  25006. * headLength - Number
  25007. * headWidth - Number
  25008. */
  25009. var lineGeometry;
  25010. var coneGeometry;
  25011. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  25012. // dir is assumed to be normalized
  25013. Object3D.call( this );
  25014. if ( color === undefined ) color = 0xffff00;
  25015. if ( length === undefined ) length = 1;
  25016. if ( headLength === undefined ) headLength = 0.2 * length;
  25017. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25018. if ( lineGeometry === undefined ) {
  25019. lineGeometry = new BufferGeometry();
  25020. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  25021. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  25022. coneGeometry.translate( 0, - 0.5, 0 );
  25023. }
  25024. this.position.copy( origin );
  25025. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  25026. this.line.matrixAutoUpdate = false;
  25027. this.add( this.line );
  25028. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  25029. this.cone.matrixAutoUpdate = false;
  25030. this.add( this.cone );
  25031. this.setDirection( dir );
  25032. this.setLength( length, headLength, headWidth );
  25033. }
  25034. ArrowHelper.prototype = Object.create( Object3D.prototype );
  25035. ArrowHelper.prototype.constructor = ArrowHelper;
  25036. ArrowHelper.prototype.setDirection = ( function () {
  25037. var axis = new Vector3();
  25038. var radians;
  25039. return function setDirection( dir ) {
  25040. // dir is assumed to be normalized
  25041. if ( dir.y > 0.99999 ) {
  25042. this.quaternion.set( 0, 0, 0, 1 );
  25043. } else if ( dir.y < - 0.99999 ) {
  25044. this.quaternion.set( 1, 0, 0, 0 );
  25045. } else {
  25046. axis.set( dir.z, 0, - dir.x ).normalize();
  25047. radians = Math.acos( dir.y );
  25048. this.quaternion.setFromAxisAngle( axis, radians );
  25049. }
  25050. };
  25051. }() );
  25052. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  25053. if ( headLength === undefined ) headLength = 0.2 * length;
  25054. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25055. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  25056. this.line.updateMatrix();
  25057. this.cone.scale.set( headWidth, headLength, headWidth );
  25058. this.cone.position.y = length;
  25059. this.cone.updateMatrix();
  25060. };
  25061. ArrowHelper.prototype.setColor = function ( color ) {
  25062. this.line.material.color.copy( color );
  25063. this.cone.material.color.copy( color );
  25064. };
  25065. /**
  25066. * @author sroucheray / http://sroucheray.org/
  25067. * @author mrdoob / http://mrdoob.com/
  25068. */
  25069. function AxisHelper( size ) {
  25070. size = size || 1;
  25071. var vertices = [
  25072. 0, 0, 0, size, 0, 0,
  25073. 0, 0, 0, 0, size, 0,
  25074. 0, 0, 0, 0, 0, size
  25075. ];
  25076. var colors = [
  25077. 1, 0, 0, 1, 0.6, 0,
  25078. 0, 1, 0, 0.6, 1, 0,
  25079. 0, 0, 1, 0, 0.6, 1
  25080. ];
  25081. var geometry = new BufferGeometry();
  25082. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25083. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  25084. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  25085. LineSegments.call( this, geometry, material );
  25086. }
  25087. AxisHelper.prototype = Object.create( LineSegments.prototype );
  25088. AxisHelper.prototype.constructor = AxisHelper;
  25089. /**
  25090. * @author zz85 https://github.com/zz85
  25091. *
  25092. * Centripetal CatmullRom Curve - which is useful for avoiding
  25093. * cusps and self-intersections in non-uniform catmull rom curves.
  25094. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  25095. *
  25096. * curve.type accepts centripetal(default), chordal and catmullrom
  25097. * curve.tension is used for catmullrom which defaults to 0.5
  25098. */
  25099. /*
  25100. Based on an optimized c++ solution in
  25101. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  25102. - http://ideone.com/NoEbVM
  25103. This CubicPoly class could be used for reusing some variables and calculations,
  25104. but for three.js curve use, it could be possible inlined and flatten into a single function call
  25105. which can be placed in CurveUtils.
  25106. */
  25107. function CubicPoly() {
  25108. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  25109. /*
  25110. * Compute coefficients for a cubic polynomial
  25111. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  25112. * such that
  25113. * p(0) = x0, p(1) = x1
  25114. * and
  25115. * p'(0) = t0, p'(1) = t1.
  25116. */
  25117. function init( x0, x1, t0, t1 ) {
  25118. c0 = x0;
  25119. c1 = t0;
  25120. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  25121. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  25122. }
  25123. return {
  25124. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  25125. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  25126. },
  25127. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  25128. // compute tangents when parameterized in [t1,t2]
  25129. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  25130. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  25131. // rescale tangents for parametrization in [0,1]
  25132. t1 *= dt1;
  25133. t2 *= dt1;
  25134. init( x1, x2, t1, t2 );
  25135. },
  25136. calc: function ( t ) {
  25137. var t2 = t * t;
  25138. var t3 = t2 * t;
  25139. return c0 + c1 * t + c2 * t2 + c3 * t3;
  25140. }
  25141. };
  25142. }
  25143. //
  25144. var tmp = new Vector3();
  25145. var px = new CubicPoly();
  25146. var py = new CubicPoly();
  25147. var pz = new CubicPoly();
  25148. function CatmullRomCurve3( points ) {
  25149. Curve.call( this );
  25150. if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' );
  25151. this.points = points || [];
  25152. this.closed = false;
  25153. }
  25154. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  25155. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  25156. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  25157. var points = this.points;
  25158. var l = points.length;
  25159. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  25160. var intPoint = Math.floor( point );
  25161. var weight = point - intPoint;
  25162. if ( this.closed ) {
  25163. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  25164. } else if ( weight === 0 && intPoint === l - 1 ) {
  25165. intPoint = l - 2;
  25166. weight = 1;
  25167. }
  25168. var p0, p1, p2, p3; // 4 points
  25169. if ( this.closed || intPoint > 0 ) {
  25170. p0 = points[ ( intPoint - 1 ) % l ];
  25171. } else {
  25172. // extrapolate first point
  25173. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  25174. p0 = tmp;
  25175. }
  25176. p1 = points[ intPoint % l ];
  25177. p2 = points[ ( intPoint + 1 ) % l ];
  25178. if ( this.closed || intPoint + 2 < l ) {
  25179. p3 = points[ ( intPoint + 2 ) % l ];
  25180. } else {
  25181. // extrapolate last point
  25182. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  25183. p3 = tmp;
  25184. }
  25185. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  25186. // init Centripetal / Chordal Catmull-Rom
  25187. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  25188. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  25189. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  25190. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  25191. // safety check for repeated points
  25192. if ( dt1 < 1e-4 ) dt1 = 1.0;
  25193. if ( dt0 < 1e-4 ) dt0 = dt1;
  25194. if ( dt2 < 1e-4 ) dt2 = dt1;
  25195. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  25196. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  25197. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  25198. } else if ( this.type === 'catmullrom' ) {
  25199. var tension = this.tension !== undefined ? this.tension : 0.5;
  25200. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  25201. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  25202. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25203. }
  25204. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25205. };
  25206. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25207. Curve.call( this );
  25208. this.v0 = v0;
  25209. this.v1 = v1;
  25210. this.v2 = v2;
  25211. this.v3 = v3;
  25212. }
  25213. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25214. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25215. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25216. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25217. return new Vector3(
  25218. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25219. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25220. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25221. );
  25222. };
  25223. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25224. Curve.call( this );
  25225. this.v0 = v0;
  25226. this.v1 = v1;
  25227. this.v2 = v2;
  25228. }
  25229. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25230. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25231. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25232. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25233. return new Vector3(
  25234. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25235. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25236. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25237. );
  25238. };
  25239. function LineCurve3( v1, v2 ) {
  25240. Curve.call( this );
  25241. this.v1 = v1;
  25242. this.v2 = v2;
  25243. }
  25244. LineCurve3.prototype = Object.create( Curve.prototype );
  25245. LineCurve3.prototype.constructor = LineCurve3;
  25246. LineCurve3.prototype.getPoint = function ( t ) {
  25247. if ( t === 1 ) {
  25248. return this.v2.clone();
  25249. }
  25250. var vector = new Vector3();
  25251. vector.subVectors( this.v2, this.v1 ); // diff
  25252. vector.multiplyScalar( t );
  25253. vector.add( this.v1 );
  25254. return vector;
  25255. };
  25256. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25257. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25258. }
  25259. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25260. ArcCurve.prototype.constructor = ArcCurve;
  25261. /**
  25262. * @author alteredq / http://alteredqualia.com/
  25263. */
  25264. var SceneUtils = {
  25265. createMultiMaterialObject: function ( geometry, materials ) {
  25266. var group = new Group();
  25267. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25268. group.add( new Mesh( geometry, materials[ i ] ) );
  25269. }
  25270. return group;
  25271. },
  25272. detach: function ( child, parent, scene ) {
  25273. child.applyMatrix( parent.matrixWorld );
  25274. parent.remove( child );
  25275. scene.add( child );
  25276. },
  25277. attach: function ( child, scene, parent ) {
  25278. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  25279. scene.remove( child );
  25280. parent.add( child );
  25281. }
  25282. };
  25283. /**
  25284. * @author mrdoob / http://mrdoob.com/
  25285. */
  25286. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25287. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25288. return new Face3( a, b, c, normal, color, materialIndex );
  25289. }
  25290. var LineStrip = 0;
  25291. var LinePieces = 1;
  25292. function MeshFaceMaterial( materials ) {
  25293. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25294. return materials;
  25295. }
  25296. function MultiMaterial( materials ) {
  25297. if ( materials === undefined ) materials = [];
  25298. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25299. materials.isMultiMaterial = true;
  25300. materials.materials = materials;
  25301. materials.clone = function () {
  25302. return materials.slice();
  25303. };
  25304. return materials;
  25305. }
  25306. function PointCloud( geometry, material ) {
  25307. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25308. return new Points( geometry, material );
  25309. }
  25310. function Particle( material ) {
  25311. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25312. return new Sprite( material );
  25313. }
  25314. function ParticleSystem( geometry, material ) {
  25315. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25316. return new Points( geometry, material );
  25317. }
  25318. function PointCloudMaterial( parameters ) {
  25319. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25320. return new PointsMaterial( parameters );
  25321. }
  25322. function ParticleBasicMaterial( parameters ) {
  25323. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25324. return new PointsMaterial( parameters );
  25325. }
  25326. function ParticleSystemMaterial( parameters ) {
  25327. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25328. return new PointsMaterial( parameters );
  25329. }
  25330. function Vertex( x, y, z ) {
  25331. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25332. return new Vector3( x, y, z );
  25333. }
  25334. //
  25335. function DynamicBufferAttribute( array, itemSize ) {
  25336. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25337. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25338. }
  25339. function Int8Attribute( array, itemSize ) {
  25340. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25341. return new Int8BufferAttribute( array, itemSize );
  25342. }
  25343. function Uint8Attribute( array, itemSize ) {
  25344. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25345. return new Uint8BufferAttribute( array, itemSize );
  25346. }
  25347. function Uint8ClampedAttribute( array, itemSize ) {
  25348. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25349. return new Uint8ClampedBufferAttribute( array, itemSize );
  25350. }
  25351. function Int16Attribute( array, itemSize ) {
  25352. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25353. return new Int16BufferAttribute( array, itemSize );
  25354. }
  25355. function Uint16Attribute( array, itemSize ) {
  25356. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25357. return new Uint16BufferAttribute( array, itemSize );
  25358. }
  25359. function Int32Attribute( array, itemSize ) {
  25360. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25361. return new Int32BufferAttribute( array, itemSize );
  25362. }
  25363. function Uint32Attribute( array, itemSize ) {
  25364. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25365. return new Uint32BufferAttribute( array, itemSize );
  25366. }
  25367. function Float32Attribute( array, itemSize ) {
  25368. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25369. return new Float32BufferAttribute( array, itemSize );
  25370. }
  25371. function Float64Attribute( array, itemSize ) {
  25372. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25373. return new Float64BufferAttribute( array, itemSize );
  25374. }
  25375. //
  25376. Curve.create = function ( construct, getPoint ) {
  25377. console.log( 'THREE.Curve.create() has been deprecated' );
  25378. construct.prototype = Object.create( Curve.prototype );
  25379. construct.prototype.constructor = construct;
  25380. construct.prototype.getPoint = getPoint;
  25381. return construct;
  25382. };
  25383. //
  25384. function ClosedSplineCurve3( points ) {
  25385. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25386. CatmullRomCurve3.call( this, points );
  25387. this.type = 'catmullrom';
  25388. this.closed = true;
  25389. }
  25390. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25391. //
  25392. function SplineCurve3( points ) {
  25393. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25394. CatmullRomCurve3.call( this, points );
  25395. this.type = 'catmullrom';
  25396. }
  25397. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25398. //
  25399. function Spline( points ) {
  25400. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25401. CatmullRomCurve3.call( this, points );
  25402. this.type = 'catmullrom';
  25403. }
  25404. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25405. Object.assign( Spline.prototype, {
  25406. initFromArray: function ( a ) {
  25407. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25408. },
  25409. getControlPointsArray: function ( optionalTarget ) {
  25410. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25411. },
  25412. reparametrizeByArcLength: function ( samplingCoef ) {
  25413. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25414. }
  25415. } );
  25416. //
  25417. function BoundingBoxHelper( object, color ) {
  25418. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25419. return new BoxHelper( object, color );
  25420. }
  25421. function EdgesHelper( object, hex ) {
  25422. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25423. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25424. }
  25425. GridHelper.prototype.setColors = function () {
  25426. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25427. };
  25428. SkeletonHelper.prototype.update = function () {
  25429. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  25430. };
  25431. function WireframeHelper( object, hex ) {
  25432. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25433. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25434. }
  25435. //
  25436. function XHRLoader( manager ) {
  25437. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25438. return new FileLoader( manager );
  25439. }
  25440. function BinaryTextureLoader( manager ) {
  25441. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25442. return new DataTextureLoader( manager );
  25443. }
  25444. //
  25445. Object.assign( Box2.prototype, {
  25446. center: function ( optionalTarget ) {
  25447. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25448. return this.getCenter( optionalTarget );
  25449. },
  25450. empty: function () {
  25451. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25452. return this.isEmpty();
  25453. },
  25454. isIntersectionBox: function ( box ) {
  25455. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25456. return this.intersectsBox( box );
  25457. },
  25458. size: function ( optionalTarget ) {
  25459. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25460. return this.getSize( optionalTarget );
  25461. }
  25462. } );
  25463. Object.assign( Box3.prototype, {
  25464. center: function ( optionalTarget ) {
  25465. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25466. return this.getCenter( optionalTarget );
  25467. },
  25468. empty: function () {
  25469. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25470. return this.isEmpty();
  25471. },
  25472. isIntersectionBox: function ( box ) {
  25473. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25474. return this.intersectsBox( box );
  25475. },
  25476. isIntersectionSphere: function ( sphere ) {
  25477. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25478. return this.intersectsSphere( sphere );
  25479. },
  25480. size: function ( optionalTarget ) {
  25481. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25482. return this.getSize( optionalTarget );
  25483. }
  25484. } );
  25485. Line3.prototype.center = function ( optionalTarget ) {
  25486. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25487. return this.getCenter( optionalTarget );
  25488. };
  25489. _Math.random16 = function () {
  25490. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25491. return Math.random();
  25492. };
  25493. Object.assign( Matrix3.prototype, {
  25494. flattenToArrayOffset: function ( array, offset ) {
  25495. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25496. return this.toArray( array, offset );
  25497. },
  25498. multiplyVector3: function ( vector ) {
  25499. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25500. return vector.applyMatrix3( this );
  25501. },
  25502. multiplyVector3Array: function ( a ) {
  25503. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  25504. },
  25505. applyToBuffer: function( buffer, offset, length ) {
  25506. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25507. return this.applyToBufferAttribute( buffer );
  25508. },
  25509. applyToVector3Array: function( array, offset, length ) {
  25510. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25511. }
  25512. } );
  25513. Object.assign( Matrix4.prototype, {
  25514. extractPosition: function ( m ) {
  25515. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25516. return this.copyPosition( m );
  25517. },
  25518. flattenToArrayOffset: function ( array, offset ) {
  25519. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25520. return this.toArray( array, offset );
  25521. },
  25522. getPosition: function () {
  25523. var v1;
  25524. return function getPosition() {
  25525. if ( v1 === undefined ) v1 = new Vector3();
  25526. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25527. return v1.setFromMatrixColumn( this, 3 );
  25528. };
  25529. }(),
  25530. setRotationFromQuaternion: function ( q ) {
  25531. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25532. return this.makeRotationFromQuaternion( q );
  25533. },
  25534. multiplyToArray: function () {
  25535. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25536. },
  25537. multiplyVector3: function ( vector ) {
  25538. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25539. return vector.applyMatrix4( this );
  25540. },
  25541. multiplyVector4: function ( vector ) {
  25542. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25543. return vector.applyMatrix4( this );
  25544. },
  25545. multiplyVector3Array: function ( a ) {
  25546. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  25547. },
  25548. rotateAxis: function ( v ) {
  25549. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25550. v.transformDirection( this );
  25551. },
  25552. crossVector: function ( vector ) {
  25553. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25554. return vector.applyMatrix4( this );
  25555. },
  25556. translate: function () {
  25557. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25558. },
  25559. rotateX: function () {
  25560. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25561. },
  25562. rotateY: function () {
  25563. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25564. },
  25565. rotateZ: function () {
  25566. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25567. },
  25568. rotateByAxis: function () {
  25569. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25570. },
  25571. applyToBuffer: function( buffer, offset, length ) {
  25572. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25573. return this.applyToBufferAttribute( buffer );
  25574. },
  25575. applyToVector3Array: function( array, offset, length ) {
  25576. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25577. },
  25578. makeFrustum: function( left, right, bottom, top, near, far ) {
  25579. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25580. return this.makePerspective( left, right, top, bottom, near, far );
  25581. }
  25582. } );
  25583. Plane.prototype.isIntersectionLine = function ( line ) {
  25584. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25585. return this.intersectsLine( line );
  25586. };
  25587. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25588. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25589. return vector.applyQuaternion( this );
  25590. };
  25591. Object.assign( Ray.prototype, {
  25592. isIntersectionBox: function ( box ) {
  25593. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25594. return this.intersectsBox( box );
  25595. },
  25596. isIntersectionPlane: function ( plane ) {
  25597. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25598. return this.intersectsPlane( plane );
  25599. },
  25600. isIntersectionSphere: function ( sphere ) {
  25601. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25602. return this.intersectsSphere( sphere );
  25603. }
  25604. } );
  25605. Object.assign( Shape.prototype, {
  25606. extrude: function ( options ) {
  25607. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25608. return new ExtrudeGeometry( this, options );
  25609. },
  25610. makeGeometry: function ( options ) {
  25611. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25612. return new ShapeGeometry( this, options );
  25613. }
  25614. } );
  25615. Object.assign( Vector2.prototype, {
  25616. fromAttribute: function ( attribute, index, offset ) {
  25617. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25618. return this.fromBufferAttribute( attribute, index, offset );
  25619. }
  25620. } );
  25621. Object.assign( Vector3.prototype, {
  25622. setEulerFromRotationMatrix: function () {
  25623. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25624. },
  25625. setEulerFromQuaternion: function () {
  25626. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25627. },
  25628. getPositionFromMatrix: function ( m ) {
  25629. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25630. return this.setFromMatrixPosition( m );
  25631. },
  25632. getScaleFromMatrix: function ( m ) {
  25633. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25634. return this.setFromMatrixScale( m );
  25635. },
  25636. getColumnFromMatrix: function ( index, matrix ) {
  25637. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25638. return this.setFromMatrixColumn( matrix, index );
  25639. },
  25640. applyProjection: function ( m ) {
  25641. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25642. return this.applyMatrix4( m );
  25643. },
  25644. fromAttribute: function ( attribute, index, offset ) {
  25645. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25646. return this.fromBufferAttribute( attribute, index, offset );
  25647. }
  25648. } );
  25649. Object.assign( Vector4.prototype, {
  25650. fromAttribute: function ( attribute, index, offset ) {
  25651. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25652. return this.fromBufferAttribute( attribute, index, offset );
  25653. }
  25654. } );
  25655. //
  25656. Geometry.prototype.computeTangents = function () {
  25657. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25658. };
  25659. Object.assign( Object3D.prototype, {
  25660. getChildByName: function ( name ) {
  25661. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25662. return this.getObjectByName( name );
  25663. },
  25664. renderDepth: function () {
  25665. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25666. },
  25667. translate: function ( distance, axis ) {
  25668. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25669. return this.translateOnAxis( axis, distance );
  25670. }
  25671. } );
  25672. Object.defineProperties( Object3D.prototype, {
  25673. eulerOrder: {
  25674. get: function () {
  25675. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25676. return this.rotation.order;
  25677. },
  25678. set: function ( value ) {
  25679. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25680. this.rotation.order = value;
  25681. }
  25682. },
  25683. useQuaternion: {
  25684. get: function () {
  25685. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25686. },
  25687. set: function () {
  25688. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25689. }
  25690. }
  25691. } );
  25692. Object.defineProperties( LOD.prototype, {
  25693. objects: {
  25694. get: function () {
  25695. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25696. return this.levels;
  25697. }
  25698. }
  25699. } );
  25700. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25701. get: function () {
  25702. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25703. },
  25704. set: function () {
  25705. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25706. }
  25707. } );
  25708. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25709. get: function () {
  25710. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25711. return this.arcLengthDivisions;
  25712. },
  25713. set: function ( value ) {
  25714. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25715. this.arcLengthDivisions = value;
  25716. }
  25717. } );
  25718. //
  25719. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25720. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25721. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25722. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25723. this.setFocalLength( focalLength );
  25724. };
  25725. //
  25726. Object.defineProperties( Light.prototype, {
  25727. onlyShadow: {
  25728. set: function () {
  25729. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25730. }
  25731. },
  25732. shadowCameraFov: {
  25733. set: function ( value ) {
  25734. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25735. this.shadow.camera.fov = value;
  25736. }
  25737. },
  25738. shadowCameraLeft: {
  25739. set: function ( value ) {
  25740. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25741. this.shadow.camera.left = value;
  25742. }
  25743. },
  25744. shadowCameraRight: {
  25745. set: function ( value ) {
  25746. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25747. this.shadow.camera.right = value;
  25748. }
  25749. },
  25750. shadowCameraTop: {
  25751. set: function ( value ) {
  25752. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25753. this.shadow.camera.top = value;
  25754. }
  25755. },
  25756. shadowCameraBottom: {
  25757. set: function ( value ) {
  25758. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25759. this.shadow.camera.bottom = value;
  25760. }
  25761. },
  25762. shadowCameraNear: {
  25763. set: function ( value ) {
  25764. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25765. this.shadow.camera.near = value;
  25766. }
  25767. },
  25768. shadowCameraFar: {
  25769. set: function ( value ) {
  25770. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25771. this.shadow.camera.far = value;
  25772. }
  25773. },
  25774. shadowCameraVisible: {
  25775. set: function () {
  25776. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25777. }
  25778. },
  25779. shadowBias: {
  25780. set: function ( value ) {
  25781. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25782. this.shadow.bias = value;
  25783. }
  25784. },
  25785. shadowDarkness: {
  25786. set: function () {
  25787. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25788. }
  25789. },
  25790. shadowMapWidth: {
  25791. set: function ( value ) {
  25792. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25793. this.shadow.mapSize.width = value;
  25794. }
  25795. },
  25796. shadowMapHeight: {
  25797. set: function ( value ) {
  25798. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25799. this.shadow.mapSize.height = value;
  25800. }
  25801. }
  25802. } );
  25803. //
  25804. Object.defineProperties( BufferAttribute.prototype, {
  25805. length: {
  25806. get: function () {
  25807. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25808. return this.array.length;
  25809. }
  25810. }
  25811. } );
  25812. Object.assign( BufferGeometry.prototype, {
  25813. addIndex: function ( index ) {
  25814. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25815. this.setIndex( index );
  25816. },
  25817. addDrawCall: function ( start, count, indexOffset ) {
  25818. if ( indexOffset !== undefined ) {
  25819. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25820. }
  25821. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25822. this.addGroup( start, count );
  25823. },
  25824. clearDrawCalls: function () {
  25825. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25826. this.clearGroups();
  25827. },
  25828. computeTangents: function () {
  25829. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25830. },
  25831. computeOffsets: function () {
  25832. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25833. }
  25834. } );
  25835. Object.defineProperties( BufferGeometry.prototype, {
  25836. drawcalls: {
  25837. get: function () {
  25838. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25839. return this.groups;
  25840. }
  25841. },
  25842. offsets: {
  25843. get: function () {
  25844. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25845. return this.groups;
  25846. }
  25847. }
  25848. } );
  25849. //
  25850. Object.defineProperties( Uniform.prototype, {
  25851. dynamic: {
  25852. set: function () {
  25853. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25854. }
  25855. },
  25856. onUpdate: {
  25857. value: function () {
  25858. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25859. return this;
  25860. }
  25861. }
  25862. } );
  25863. //
  25864. Object.defineProperties( Material.prototype, {
  25865. wrapAround: {
  25866. get: function () {
  25867. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25868. },
  25869. set: function () {
  25870. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25871. }
  25872. },
  25873. wrapRGB: {
  25874. get: function () {
  25875. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  25876. return new Color();
  25877. }
  25878. }
  25879. } );
  25880. Object.defineProperties( MeshPhongMaterial.prototype, {
  25881. metal: {
  25882. get: function () {
  25883. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25884. return false;
  25885. },
  25886. set: function () {
  25887. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25888. }
  25889. }
  25890. } );
  25891. Object.defineProperties( ShaderMaterial.prototype, {
  25892. derivatives: {
  25893. get: function () {
  25894. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25895. return this.extensions.derivatives;
  25896. },
  25897. set: function ( value ) {
  25898. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25899. this.extensions.derivatives = value;
  25900. }
  25901. }
  25902. } );
  25903. //
  25904. Object.assign( WebGLRenderer.prototype, {
  25905. getCurrentRenderTarget: function () {
  25906. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  25907. return this.getRenderTarget();
  25908. },
  25909. supportsFloatTextures: function () {
  25910. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25911. return this.extensions.get( 'OES_texture_float' );
  25912. },
  25913. supportsHalfFloatTextures: function () {
  25914. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25915. return this.extensions.get( 'OES_texture_half_float' );
  25916. },
  25917. supportsStandardDerivatives: function () {
  25918. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25919. return this.extensions.get( 'OES_standard_derivatives' );
  25920. },
  25921. supportsCompressedTextureS3TC: function () {
  25922. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25923. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25924. },
  25925. supportsCompressedTexturePVRTC: function () {
  25926. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25927. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25928. },
  25929. supportsBlendMinMax: function () {
  25930. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25931. return this.extensions.get( 'EXT_blend_minmax' );
  25932. },
  25933. supportsVertexTextures: function () {
  25934. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25935. return this.capabilities.vertexTextures;
  25936. },
  25937. supportsInstancedArrays: function () {
  25938. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25939. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25940. },
  25941. enableScissorTest: function ( boolean ) {
  25942. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25943. this.setScissorTest( boolean );
  25944. },
  25945. initMaterial: function () {
  25946. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25947. },
  25948. addPrePlugin: function () {
  25949. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25950. },
  25951. addPostPlugin: function () {
  25952. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25953. },
  25954. updateShadowMap: function () {
  25955. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25956. }
  25957. } );
  25958. Object.defineProperties( WebGLRenderer.prototype, {
  25959. shadowMapEnabled: {
  25960. get: function () {
  25961. return this.shadowMap.enabled;
  25962. },
  25963. set: function ( value ) {
  25964. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25965. this.shadowMap.enabled = value;
  25966. }
  25967. },
  25968. shadowMapType: {
  25969. get: function () {
  25970. return this.shadowMap.type;
  25971. },
  25972. set: function ( value ) {
  25973. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25974. this.shadowMap.type = value;
  25975. }
  25976. },
  25977. shadowMapCullFace: {
  25978. get: function () {
  25979. return this.shadowMap.cullFace;
  25980. },
  25981. set: function ( value ) {
  25982. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25983. this.shadowMap.cullFace = value;
  25984. }
  25985. }
  25986. } );
  25987. Object.defineProperties( WebGLShadowMap.prototype, {
  25988. cullFace: {
  25989. get: function () {
  25990. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25991. },
  25992. set: function ( cullFace ) {
  25993. var value = ( cullFace !== CullFaceBack );
  25994. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25995. this.renderReverseSided = value;
  25996. }
  25997. }
  25998. } );
  25999. //
  26000. Object.defineProperties( WebGLRenderTarget.prototype, {
  26001. wrapS: {
  26002. get: function () {
  26003. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26004. return this.texture.wrapS;
  26005. },
  26006. set: function ( value ) {
  26007. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26008. this.texture.wrapS = value;
  26009. }
  26010. },
  26011. wrapT: {
  26012. get: function () {
  26013. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26014. return this.texture.wrapT;
  26015. },
  26016. set: function ( value ) {
  26017. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26018. this.texture.wrapT = value;
  26019. }
  26020. },
  26021. magFilter: {
  26022. get: function () {
  26023. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26024. return this.texture.magFilter;
  26025. },
  26026. set: function ( value ) {
  26027. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26028. this.texture.magFilter = value;
  26029. }
  26030. },
  26031. minFilter: {
  26032. get: function () {
  26033. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26034. return this.texture.minFilter;
  26035. },
  26036. set: function ( value ) {
  26037. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26038. this.texture.minFilter = value;
  26039. }
  26040. },
  26041. anisotropy: {
  26042. get: function () {
  26043. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26044. return this.texture.anisotropy;
  26045. },
  26046. set: function ( value ) {
  26047. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26048. this.texture.anisotropy = value;
  26049. }
  26050. },
  26051. offset: {
  26052. get: function () {
  26053. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26054. return this.texture.offset;
  26055. },
  26056. set: function ( value ) {
  26057. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26058. this.texture.offset = value;
  26059. }
  26060. },
  26061. repeat: {
  26062. get: function () {
  26063. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26064. return this.texture.repeat;
  26065. },
  26066. set: function ( value ) {
  26067. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26068. this.texture.repeat = value;
  26069. }
  26070. },
  26071. format: {
  26072. get: function () {
  26073. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26074. return this.texture.format;
  26075. },
  26076. set: function ( value ) {
  26077. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26078. this.texture.format = value;
  26079. }
  26080. },
  26081. type: {
  26082. get: function () {
  26083. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26084. return this.texture.type;
  26085. },
  26086. set: function ( value ) {
  26087. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26088. this.texture.type = value;
  26089. }
  26090. },
  26091. generateMipmaps: {
  26092. get: function () {
  26093. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26094. return this.texture.generateMipmaps;
  26095. },
  26096. set: function ( value ) {
  26097. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26098. this.texture.generateMipmaps = value;
  26099. }
  26100. }
  26101. } );
  26102. //
  26103. Audio.prototype.load = function ( file ) {
  26104. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  26105. var scope = this;
  26106. var audioLoader = new AudioLoader();
  26107. audioLoader.load( file, function ( buffer ) {
  26108. scope.setBuffer( buffer );
  26109. } );
  26110. return this;
  26111. };
  26112. AudioAnalyser.prototype.getData = function () {
  26113. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  26114. return this.getFrequencyData();
  26115. };
  26116. //
  26117. var GeometryUtils = {
  26118. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  26119. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  26120. var matrix;
  26121. if ( geometry2.isMesh ) {
  26122. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  26123. matrix = geometry2.matrix;
  26124. geometry2 = geometry2.geometry;
  26125. }
  26126. geometry1.merge( geometry2, matrix, materialIndexOffset );
  26127. },
  26128. center: function ( geometry ) {
  26129. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  26130. return geometry.center();
  26131. }
  26132. };
  26133. var ImageUtils = {
  26134. crossOrigin: undefined,
  26135. loadTexture: function ( url, mapping, onLoad, onError ) {
  26136. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  26137. var loader = new TextureLoader();
  26138. loader.setCrossOrigin( this.crossOrigin );
  26139. var texture = loader.load( url, onLoad, undefined, onError );
  26140. if ( mapping ) texture.mapping = mapping;
  26141. return texture;
  26142. },
  26143. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  26144. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  26145. var loader = new CubeTextureLoader();
  26146. loader.setCrossOrigin( this.crossOrigin );
  26147. var texture = loader.load( urls, onLoad, undefined, onError );
  26148. if ( mapping ) texture.mapping = mapping;
  26149. return texture;
  26150. },
  26151. loadCompressedTexture: function () {
  26152. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  26153. },
  26154. loadCompressedTextureCube: function () {
  26155. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  26156. }
  26157. };
  26158. //
  26159. function Projector() {
  26160. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  26161. this.projectVector = function ( vector, camera ) {
  26162. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  26163. vector.project( camera );
  26164. };
  26165. this.unprojectVector = function ( vector, camera ) {
  26166. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  26167. vector.unproject( camera );
  26168. };
  26169. this.pickingRay = function () {
  26170. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  26171. };
  26172. }
  26173. //
  26174. function CanvasRenderer() {
  26175. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  26176. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  26177. this.clear = function () {};
  26178. this.render = function () {};
  26179. this.setClearColor = function () {};
  26180. this.setSize = function () {};
  26181. }
  26182. export { WebGLRenderTargetCube, WebGLRenderTarget, WebGLRenderer, ShaderLib, UniformsLib, UniformsUtils, ShaderChunk, FogExp2, Fog, Scene, LensFlare, Sprite, LOD, SkinnedMesh, Skeleton, Bone, Mesh, LineSegments, LineLoop, Line, Points, Group, VideoTexture, DataTexture, CompressedTexture, CubeTexture, CanvasTexture, DepthTexture, Texture, CompressedTextureLoader, 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, ArrayCamera, 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, _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, CubicBezierCurve3, QuadraticBezierCurve3, LineCurve3, ArcCurve, EllipseCurve, SplineCurve, CubicBezierCurve, QuadraticBezierCurve, LineCurve, Shape, Path, ShapePath, Font, CurvePath, Curve, ShapeUtils, SceneUtils, WireframeGeometry, ParametricGeometry, ParametricBufferGeometry, TetrahedronGeometry, TetrahedronBufferGeometry, OctahedronGeometry, OctahedronBufferGeometry, IcosahedronGeometry, IcosahedronBufferGeometry, DodecahedronGeometry, DodecahedronBufferGeometry, PolyhedronGeometry, PolyhedronBufferGeometry, TubeGeometry, TubeBufferGeometry, TorusKnotGeometry, TorusKnotBufferGeometry, TorusGeometry, TorusBufferGeometry, TextGeometry, TextBufferGeometry, SphereGeometry, SphereBufferGeometry, RingGeometry, RingBufferGeometry, PlaneGeometry, PlaneBufferGeometry, LatheGeometry, LatheBufferGeometry, ShapeGeometry, ShapeBufferGeometry, ExtrudeGeometry, ExtrudeBufferGeometry, EdgesGeometry, ConeGeometry, ConeBufferGeometry, CylinderGeometry, CylinderBufferGeometry, CircleGeometry, CircleBufferGeometry, BoxGeometry, BoxBufferGeometry, ShadowMaterial, SpriteMaterial, RawShaderMaterial, ShaderMaterial, PointsMaterial, 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, 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, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter, LinearFilter, LinearMipMapNearestFilter, LinearMipMapLinearFilter, 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, MultiMaterial, PointCloud, Particle, ParticleSystem, PointCloudMaterial, ParticleBasicMaterial, ParticleSystemMaterial, Vertex, DynamicBufferAttribute, Int8Attribute, Uint8Attribute, Uint8ClampedAttribute, Int16Attribute, Uint16Attribute, Int32Attribute, Uint32Attribute, Float32Attribute, Float64Attribute, ClosedSplineCurve3, SplineCurve3, Spline, BoundingBoxHelper, EdgesHelper, WireframeHelper, XHRLoader, BinaryTextureLoader, GeometryUtils, ImageUtils, Projector, CanvasRenderer };