three.module.js 972 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310
  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 = [], i = 0;
  90. var length = listenerArray.length;
  91. for ( i = 0; i < length; i ++ ) {
  92. array[ i ] = listenerArray[ i ];
  93. }
  94. for ( i = 0; i < length; i ++ ) {
  95. array[ i ].call( this, event );
  96. }
  97. }
  98. }
  99. } );
  100. var REVISION = '86dev';
  101. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  102. var CullFaceNone = 0;
  103. var CullFaceBack = 1;
  104. var CullFaceFront = 2;
  105. var CullFaceFrontBack = 3;
  106. var FrontFaceDirectionCW = 0;
  107. var FrontFaceDirectionCCW = 1;
  108. var BasicShadowMap = 0;
  109. var PCFShadowMap = 1;
  110. var PCFSoftShadowMap = 2;
  111. var FrontSide = 0;
  112. var BackSide = 1;
  113. var DoubleSide = 2;
  114. var FlatShading = 1;
  115. var SmoothShading = 2;
  116. var NoColors = 0;
  117. var FaceColors = 1;
  118. var VertexColors = 2;
  119. var NoBlending = 0;
  120. var NormalBlending = 1;
  121. var AdditiveBlending = 2;
  122. var SubtractiveBlending = 3;
  123. var MultiplyBlending = 4;
  124. var CustomBlending = 5;
  125. var AddEquation = 100;
  126. var SubtractEquation = 101;
  127. var ReverseSubtractEquation = 102;
  128. var MinEquation = 103;
  129. var MaxEquation = 104;
  130. var ZeroFactor = 200;
  131. var OneFactor = 201;
  132. var SrcColorFactor = 202;
  133. var OneMinusSrcColorFactor = 203;
  134. var SrcAlphaFactor = 204;
  135. var OneMinusSrcAlphaFactor = 205;
  136. var DstAlphaFactor = 206;
  137. var OneMinusDstAlphaFactor = 207;
  138. var DstColorFactor = 208;
  139. var OneMinusDstColorFactor = 209;
  140. var SrcAlphaSaturateFactor = 210;
  141. var NeverDepth = 0;
  142. var AlwaysDepth = 1;
  143. var LessDepth = 2;
  144. var LessEqualDepth = 3;
  145. var EqualDepth = 4;
  146. var GreaterEqualDepth = 5;
  147. var GreaterDepth = 6;
  148. var NotEqualDepth = 7;
  149. var MultiplyOperation = 0;
  150. var MixOperation = 1;
  151. var AddOperation = 2;
  152. var NoToneMapping = 0;
  153. var LinearToneMapping = 1;
  154. var ReinhardToneMapping = 2;
  155. var Uncharted2ToneMapping = 3;
  156. var CineonToneMapping = 4;
  157. var UVMapping = 300;
  158. var CubeReflectionMapping = 301;
  159. var CubeRefractionMapping = 302;
  160. var EquirectangularReflectionMapping = 303;
  161. var EquirectangularRefractionMapping = 304;
  162. var SphericalReflectionMapping = 305;
  163. var CubeUVReflectionMapping = 306;
  164. var CubeUVRefractionMapping = 307;
  165. var RepeatWrapping = 1000;
  166. var ClampToEdgeWrapping = 1001;
  167. var MirroredRepeatWrapping = 1002;
  168. var NearestFilter = 1003;
  169. var NearestMipMapNearestFilter = 1004;
  170. var NearestMipMapLinearFilter = 1005;
  171. var LinearFilter = 1006;
  172. var LinearMipMapNearestFilter = 1007;
  173. var LinearMipMapLinearFilter = 1008;
  174. var UnsignedByteType = 1009;
  175. var ByteType = 1010;
  176. var ShortType = 1011;
  177. var UnsignedShortType = 1012;
  178. var IntType = 1013;
  179. var UnsignedIntType = 1014;
  180. var FloatType = 1015;
  181. var HalfFloatType = 1016;
  182. var UnsignedShort4444Type = 1017;
  183. var UnsignedShort5551Type = 1018;
  184. var UnsignedShort565Type = 1019;
  185. var UnsignedInt248Type = 1020;
  186. var AlphaFormat = 1021;
  187. var RGBFormat = 1022;
  188. var RGBAFormat = 1023;
  189. var LuminanceFormat = 1024;
  190. var LuminanceAlphaFormat = 1025;
  191. var RGBEFormat = RGBAFormat;
  192. var DepthFormat = 1026;
  193. var DepthStencilFormat = 1027;
  194. var RGB_S3TC_DXT1_Format = 2001;
  195. var RGBA_S3TC_DXT1_Format = 2002;
  196. var RGBA_S3TC_DXT3_Format = 2003;
  197. var RGBA_S3TC_DXT5_Format = 2004;
  198. var RGB_PVRTC_4BPPV1_Format = 2100;
  199. var RGB_PVRTC_2BPPV1_Format = 2101;
  200. var RGBA_PVRTC_4BPPV1_Format = 2102;
  201. var RGBA_PVRTC_2BPPV1_Format = 2103;
  202. var RGB_ETC1_Format = 2151;
  203. var LoopOnce = 2200;
  204. var LoopRepeat = 2201;
  205. var LoopPingPong = 2202;
  206. var InterpolateDiscrete = 2300;
  207. var InterpolateLinear = 2301;
  208. var InterpolateSmooth = 2302;
  209. var ZeroCurvatureEnding = 2400;
  210. var ZeroSlopeEnding = 2401;
  211. var WrapAroundEnding = 2402;
  212. var TrianglesDrawMode = 0;
  213. var TriangleStripDrawMode = 1;
  214. var TriangleFanDrawMode = 2;
  215. var LinearEncoding = 3000;
  216. var sRGBEncoding = 3001;
  217. var GammaEncoding = 3007;
  218. var RGBEEncoding = 3002;
  219. var LogLuvEncoding = 3003;
  220. var RGBM7Encoding = 3004;
  221. var RGBM16Encoding = 3005;
  222. var RGBDEncoding = 3006;
  223. var BasicDepthPacking = 3200;
  224. var RGBADepthPacking = 3201;
  225. /**
  226. * @author alteredq / http://alteredqualia.com/
  227. * @author mrdoob / http://mrdoob.com/
  228. */
  229. var _Math = {
  230. DEG2RAD: Math.PI / 180,
  231. RAD2DEG: 180 / Math.PI,
  232. generateUUID: function () {
  233. // http://www.broofa.com/Tools/Math.uuid.htm
  234. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  235. var uuid = new Array( 36 );
  236. var rnd = 0, r;
  237. return function generateUUID() {
  238. for ( var i = 0; i < 36; i ++ ) {
  239. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  240. uuid[ i ] = '-';
  241. } else if ( i === 14 ) {
  242. uuid[ i ] = '4';
  243. } else {
  244. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  245. r = rnd & 0xf;
  246. rnd = rnd >> 4;
  247. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  248. }
  249. }
  250. return uuid.join( '' );
  251. };
  252. }(),
  253. clamp: function ( value, min, max ) {
  254. return Math.max( min, Math.min( max, value ) );
  255. },
  256. // compute euclidian modulo of m % n
  257. // https://en.wikipedia.org/wiki/Modulo_operation
  258. euclideanModulo: function ( n, m ) {
  259. return ( ( n % m ) + m ) % m;
  260. },
  261. // Linear mapping from range <a1, a2> to range <b1, b2>
  262. mapLinear: function ( x, a1, a2, b1, b2 ) {
  263. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  264. },
  265. // https://en.wikipedia.org/wiki/Linear_interpolation
  266. lerp: function ( x, y, t ) {
  267. return ( 1 - t ) * x + t * y;
  268. },
  269. // http://en.wikipedia.org/wiki/Smoothstep
  270. smoothstep: function ( x, min, max ) {
  271. if ( x <= min ) return 0;
  272. if ( x >= max ) return 1;
  273. x = ( x - min ) / ( max - min );
  274. return x * x * ( 3 - 2 * x );
  275. },
  276. smootherstep: function ( x, min, max ) {
  277. if ( x <= min ) return 0;
  278. if ( x >= max ) return 1;
  279. x = ( x - min ) / ( max - min );
  280. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  281. },
  282. // Random integer from <low, high> interval
  283. randInt: function ( low, high ) {
  284. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  285. },
  286. // Random float from <low, high> interval
  287. randFloat: function ( low, high ) {
  288. return low + Math.random() * ( high - low );
  289. },
  290. // Random float from <-range/2, range/2> interval
  291. randFloatSpread: function ( range ) {
  292. return range * ( 0.5 - Math.random() );
  293. },
  294. degToRad: function ( degrees ) {
  295. return degrees * _Math.DEG2RAD;
  296. },
  297. radToDeg: function ( radians ) {
  298. return radians * _Math.RAD2DEG;
  299. },
  300. isPowerOfTwo: function ( value ) {
  301. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  302. },
  303. nearestPowerOfTwo: function ( value ) {
  304. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  305. },
  306. nextPowerOfTwo: function ( value ) {
  307. value --;
  308. value |= value >> 1;
  309. value |= value >> 2;
  310. value |= value >> 4;
  311. value |= value >> 8;
  312. value |= value >> 16;
  313. value ++;
  314. return value;
  315. }
  316. };
  317. /**
  318. * @author mrdoob / http://mrdoob.com/
  319. * @author philogb / http://blog.thejit.org/
  320. * @author egraether / http://egraether.com/
  321. * @author zz85 / http://www.lab4games.net/zz85/blog
  322. */
  323. function Vector2( x, y ) {
  324. this.x = x || 0;
  325. this.y = y || 0;
  326. }
  327. Object.defineProperties( Vector2.prototype, {
  328. "width" : {
  329. get: function () {
  330. return this.x;
  331. },
  332. set: function ( value ) {
  333. this.x = value;
  334. }
  335. },
  336. "height" : {
  337. get: function () {
  338. return this.y;
  339. },
  340. set: function ( value ) {
  341. this.y = value;
  342. }
  343. }
  344. } );
  345. Object.assign( Vector2.prototype, {
  346. isVector2: true,
  347. set: function ( x, y ) {
  348. this.x = x;
  349. this.y = y;
  350. return this;
  351. },
  352. setScalar: function ( scalar ) {
  353. this.x = scalar;
  354. this.y = scalar;
  355. return this;
  356. },
  357. setX: function ( x ) {
  358. this.x = x;
  359. return this;
  360. },
  361. setY: function ( y ) {
  362. this.y = y;
  363. return this;
  364. },
  365. setComponent: function ( index, value ) {
  366. switch ( index ) {
  367. case 0: this.x = value; break;
  368. case 1: this.y = value; break;
  369. default: throw new Error( 'index is out of range: ' + index );
  370. }
  371. return this;
  372. },
  373. getComponent: function ( index ) {
  374. switch ( index ) {
  375. case 0: return this.x;
  376. case 1: return this.y;
  377. default: throw new Error( 'index is out of range: ' + index );
  378. }
  379. },
  380. clone: function () {
  381. return new this.constructor( this.x, this.y );
  382. },
  383. copy: function ( v ) {
  384. this.x = v.x;
  385. this.y = v.y;
  386. return this;
  387. },
  388. add: function ( v, w ) {
  389. if ( w !== undefined ) {
  390. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  391. return this.addVectors( v, w );
  392. }
  393. this.x += v.x;
  394. this.y += v.y;
  395. return this;
  396. },
  397. addScalar: function ( s ) {
  398. this.x += s;
  399. this.y += s;
  400. return this;
  401. },
  402. addVectors: function ( a, b ) {
  403. this.x = a.x + b.x;
  404. this.y = a.y + b.y;
  405. return this;
  406. },
  407. addScaledVector: function ( v, s ) {
  408. this.x += v.x * s;
  409. this.y += v.y * s;
  410. return this;
  411. },
  412. sub: function ( v, w ) {
  413. if ( w !== undefined ) {
  414. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  415. return this.subVectors( v, w );
  416. }
  417. this.x -= v.x;
  418. this.y -= v.y;
  419. return this;
  420. },
  421. subScalar: function ( s ) {
  422. this.x -= s;
  423. this.y -= s;
  424. return this;
  425. },
  426. subVectors: function ( a, b ) {
  427. this.x = a.x - b.x;
  428. this.y = a.y - b.y;
  429. return this;
  430. },
  431. multiply: function ( v ) {
  432. this.x *= v.x;
  433. this.y *= v.y;
  434. return this;
  435. },
  436. multiplyScalar: function ( scalar ) {
  437. this.x *= scalar;
  438. this.y *= scalar;
  439. return this;
  440. },
  441. divide: function ( v ) {
  442. this.x /= v.x;
  443. this.y /= v.y;
  444. return this;
  445. },
  446. divideScalar: function ( scalar ) {
  447. return this.multiplyScalar( 1 / scalar );
  448. },
  449. min: function ( v ) {
  450. this.x = Math.min( this.x, v.x );
  451. this.y = Math.min( this.y, v.y );
  452. return this;
  453. },
  454. max: function ( v ) {
  455. this.x = Math.max( this.x, v.x );
  456. this.y = Math.max( this.y, v.y );
  457. return this;
  458. },
  459. clamp: function ( min, max ) {
  460. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  461. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  462. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  463. return this;
  464. },
  465. clampScalar: function () {
  466. var min = new Vector2();
  467. var max = new Vector2();
  468. return function clampScalar( minVal, maxVal ) {
  469. min.set( minVal, minVal );
  470. max.set( maxVal, maxVal );
  471. return this.clamp( min, max );
  472. };
  473. }(),
  474. clampLength: function ( min, max ) {
  475. var length = this.length();
  476. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  477. },
  478. floor: function () {
  479. this.x = Math.floor( this.x );
  480. this.y = Math.floor( this.y );
  481. return this;
  482. },
  483. ceil: function () {
  484. this.x = Math.ceil( this.x );
  485. this.y = Math.ceil( this.y );
  486. return this;
  487. },
  488. round: function () {
  489. this.x = Math.round( this.x );
  490. this.y = Math.round( this.y );
  491. return this;
  492. },
  493. roundToZero: function () {
  494. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  495. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  496. return this;
  497. },
  498. negate: function () {
  499. this.x = - this.x;
  500. this.y = - this.y;
  501. return this;
  502. },
  503. dot: function ( v ) {
  504. return this.x * v.x + this.y * v.y;
  505. },
  506. lengthSq: function () {
  507. return this.x * this.x + this.y * this.y;
  508. },
  509. length: function () {
  510. return Math.sqrt( this.x * this.x + this.y * this.y );
  511. },
  512. lengthManhattan: function() {
  513. return Math.abs( this.x ) + Math.abs( this.y );
  514. },
  515. normalize: function () {
  516. return this.divideScalar( this.length() );
  517. },
  518. angle: function () {
  519. // computes the angle in radians with respect to the positive x-axis
  520. var angle = Math.atan2( this.y, this.x );
  521. if ( angle < 0 ) angle += 2 * Math.PI;
  522. return angle;
  523. },
  524. distanceTo: function ( v ) {
  525. return Math.sqrt( this.distanceToSquared( v ) );
  526. },
  527. distanceToSquared: function ( v ) {
  528. var dx = this.x - v.x, dy = this.y - v.y;
  529. return dx * dx + dy * dy;
  530. },
  531. distanceToManhattan: function ( v ) {
  532. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  533. },
  534. setLength: function ( length ) {
  535. return this.multiplyScalar( length / this.length() );
  536. },
  537. lerp: function ( v, alpha ) {
  538. this.x += ( v.x - this.x ) * alpha;
  539. this.y += ( v.y - this.y ) * alpha;
  540. return this;
  541. },
  542. lerpVectors: function ( v1, v2, alpha ) {
  543. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  544. },
  545. equals: function ( v ) {
  546. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  547. },
  548. fromArray: function ( array, offset ) {
  549. if ( offset === undefined ) offset = 0;
  550. this.x = array[ offset ];
  551. this.y = array[ offset + 1 ];
  552. return this;
  553. },
  554. toArray: function ( array, offset ) {
  555. if ( array === undefined ) array = [];
  556. if ( offset === undefined ) offset = 0;
  557. array[ offset ] = this.x;
  558. array[ offset + 1 ] = this.y;
  559. return array;
  560. },
  561. fromBufferAttribute: function ( attribute, index, offset ) {
  562. if ( offset !== undefined ) {
  563. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  564. }
  565. this.x = attribute.getX( index );
  566. this.y = attribute.getY( index );
  567. return this;
  568. },
  569. rotateAround: function ( center, angle ) {
  570. var c = Math.cos( angle ), s = Math.sin( angle );
  571. var x = this.x - center.x;
  572. var y = this.y - center.y;
  573. this.x = x * c - y * s + center.x;
  574. this.y = x * s + y * c + center.y;
  575. return this;
  576. }
  577. } );
  578. /**
  579. * @author mrdoob / http://mrdoob.com/
  580. * @author alteredq / http://alteredqualia.com/
  581. * @author szimek / https://github.com/szimek/
  582. */
  583. var textureId = 0;
  584. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  585. Object.defineProperty( this, 'id', { value: textureId ++ } );
  586. this.uuid = _Math.generateUUID();
  587. this.name = '';
  588. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  589. this.mipmaps = [];
  590. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  591. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  592. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  593. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  594. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  595. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  596. this.format = format !== undefined ? format : RGBAFormat;
  597. this.type = type !== undefined ? type : UnsignedByteType;
  598. this.offset = new Vector2( 0, 0 );
  599. this.repeat = new Vector2( 1, 1 );
  600. this.generateMipmaps = true;
  601. this.premultiplyAlpha = false;
  602. this.flipY = true;
  603. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  604. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  605. //
  606. // Also changing the encoding after already used by a Material will not automatically make the Material
  607. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  608. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  609. this.version = 0;
  610. this.onUpdate = null;
  611. }
  612. Texture.DEFAULT_IMAGE = undefined;
  613. Texture.DEFAULT_MAPPING = UVMapping;
  614. Object.defineProperty( Texture.prototype, "needsUpdate", {
  615. set: function ( value ) {
  616. if ( value === true ) this.version ++;
  617. }
  618. } );
  619. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  620. constructor: Texture,
  621. isTexture: true,
  622. clone: function () {
  623. return new this.constructor().copy( this );
  624. },
  625. copy: function ( source ) {
  626. this.name = source.name;
  627. this.image = source.image;
  628. this.mipmaps = source.mipmaps.slice( 0 );
  629. this.mapping = source.mapping;
  630. this.wrapS = source.wrapS;
  631. this.wrapT = source.wrapT;
  632. this.magFilter = source.magFilter;
  633. this.minFilter = source.minFilter;
  634. this.anisotropy = source.anisotropy;
  635. this.format = source.format;
  636. this.type = source.type;
  637. this.offset.copy( source.offset );
  638. this.repeat.copy( source.repeat );
  639. this.generateMipmaps = source.generateMipmaps;
  640. this.premultiplyAlpha = source.premultiplyAlpha;
  641. this.flipY = source.flipY;
  642. this.unpackAlignment = source.unpackAlignment;
  643. this.encoding = source.encoding;
  644. return this;
  645. },
  646. toJSON: function ( meta ) {
  647. if ( meta.textures[ this.uuid ] !== undefined ) {
  648. return meta.textures[ this.uuid ];
  649. }
  650. function getDataURL( image ) {
  651. var canvas;
  652. if ( image.toDataURL !== undefined ) {
  653. canvas = image;
  654. } else {
  655. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  656. canvas.width = image.width;
  657. canvas.height = image.height;
  658. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  659. }
  660. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  661. return canvas.toDataURL( 'image/jpeg', 0.6 );
  662. } else {
  663. return canvas.toDataURL( 'image/png' );
  664. }
  665. }
  666. var output = {
  667. metadata: {
  668. version: 4.5,
  669. type: 'Texture',
  670. generator: 'Texture.toJSON'
  671. },
  672. uuid: this.uuid,
  673. name: this.name,
  674. mapping: this.mapping,
  675. repeat: [ this.repeat.x, this.repeat.y ],
  676. offset: [ this.offset.x, this.offset.y ],
  677. wrap: [ this.wrapS, this.wrapT ],
  678. minFilter: this.minFilter,
  679. magFilter: this.magFilter,
  680. anisotropy: this.anisotropy,
  681. flipY: this.flipY
  682. };
  683. if ( this.image !== undefined ) {
  684. // TODO: Move to THREE.Image
  685. var image = this.image;
  686. if ( image.uuid === undefined ) {
  687. image.uuid = _Math.generateUUID(); // UGH
  688. }
  689. if ( meta.images[ image.uuid ] === undefined ) {
  690. meta.images[ image.uuid ] = {
  691. uuid: image.uuid,
  692. url: getDataURL( image )
  693. };
  694. }
  695. output.image = image.uuid;
  696. }
  697. meta.textures[ this.uuid ] = output;
  698. return output;
  699. },
  700. dispose: function () {
  701. this.dispatchEvent( { type: 'dispose' } );
  702. },
  703. transformUv: function ( uv ) {
  704. if ( this.mapping !== UVMapping ) return;
  705. uv.multiply( this.repeat );
  706. uv.add( this.offset );
  707. if ( uv.x < 0 || uv.x > 1 ) {
  708. switch ( this.wrapS ) {
  709. case RepeatWrapping:
  710. uv.x = uv.x - Math.floor( uv.x );
  711. break;
  712. case ClampToEdgeWrapping:
  713. uv.x = uv.x < 0 ? 0 : 1;
  714. break;
  715. case MirroredRepeatWrapping:
  716. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  717. uv.x = Math.ceil( uv.x ) - uv.x;
  718. } else {
  719. uv.x = uv.x - Math.floor( uv.x );
  720. }
  721. break;
  722. }
  723. }
  724. if ( uv.y < 0 || uv.y > 1 ) {
  725. switch ( this.wrapT ) {
  726. case RepeatWrapping:
  727. uv.y = uv.y - Math.floor( uv.y );
  728. break;
  729. case ClampToEdgeWrapping:
  730. uv.y = uv.y < 0 ? 0 : 1;
  731. break;
  732. case MirroredRepeatWrapping:
  733. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  734. uv.y = Math.ceil( uv.y ) - uv.y;
  735. } else {
  736. uv.y = uv.y - Math.floor( uv.y );
  737. }
  738. break;
  739. }
  740. }
  741. if ( this.flipY ) {
  742. uv.y = 1 - uv.y;
  743. }
  744. }
  745. } );
  746. /**
  747. * @author supereggbert / http://www.paulbrunt.co.uk/
  748. * @author philogb / http://blog.thejit.org/
  749. * @author mikael emtinger / http://gomo.se/
  750. * @author egraether / http://egraether.com/
  751. * @author WestLangley / http://github.com/WestLangley
  752. */
  753. function Vector4( x, y, z, w ) {
  754. this.x = x || 0;
  755. this.y = y || 0;
  756. this.z = z || 0;
  757. this.w = ( w !== undefined ) ? w : 1;
  758. }
  759. Object.assign( Vector4.prototype, {
  760. isVector4: true,
  761. set: function ( x, y, z, w ) {
  762. this.x = x;
  763. this.y = y;
  764. this.z = z;
  765. this.w = w;
  766. return this;
  767. },
  768. setScalar: function ( scalar ) {
  769. this.x = scalar;
  770. this.y = scalar;
  771. this.z = scalar;
  772. this.w = scalar;
  773. return this;
  774. },
  775. setX: function ( x ) {
  776. this.x = x;
  777. return this;
  778. },
  779. setY: function ( y ) {
  780. this.y = y;
  781. return this;
  782. },
  783. setZ: function ( z ) {
  784. this.z = z;
  785. return this;
  786. },
  787. setW: function ( w ) {
  788. this.w = w;
  789. return this;
  790. },
  791. setComponent: function ( index, value ) {
  792. switch ( index ) {
  793. case 0: this.x = value; break;
  794. case 1: this.y = value; break;
  795. case 2: this.z = value; break;
  796. case 3: this.w = value; break;
  797. default: throw new Error( 'index is out of range: ' + index );
  798. }
  799. return this;
  800. },
  801. getComponent: function ( index ) {
  802. switch ( index ) {
  803. case 0: return this.x;
  804. case 1: return this.y;
  805. case 2: return this.z;
  806. case 3: return this.w;
  807. default: throw new Error( 'index is out of range: ' + index );
  808. }
  809. },
  810. clone: function () {
  811. return new this.constructor( this.x, this.y, this.z, this.w );
  812. },
  813. copy: function ( v ) {
  814. this.x = v.x;
  815. this.y = v.y;
  816. this.z = v.z;
  817. this.w = ( v.w !== undefined ) ? v.w : 1;
  818. return this;
  819. },
  820. add: function ( v, w ) {
  821. if ( w !== undefined ) {
  822. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  823. return this.addVectors( v, w );
  824. }
  825. this.x += v.x;
  826. this.y += v.y;
  827. this.z += v.z;
  828. this.w += v.w;
  829. return this;
  830. },
  831. addScalar: function ( s ) {
  832. this.x += s;
  833. this.y += s;
  834. this.z += s;
  835. this.w += s;
  836. return this;
  837. },
  838. addVectors: function ( a, b ) {
  839. this.x = a.x + b.x;
  840. this.y = a.y + b.y;
  841. this.z = a.z + b.z;
  842. this.w = a.w + b.w;
  843. return this;
  844. },
  845. addScaledVector: function ( v, s ) {
  846. this.x += v.x * s;
  847. this.y += v.y * s;
  848. this.z += v.z * s;
  849. this.w += v.w * s;
  850. return this;
  851. },
  852. sub: function ( v, w ) {
  853. if ( w !== undefined ) {
  854. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  855. return this.subVectors( v, w );
  856. }
  857. this.x -= v.x;
  858. this.y -= v.y;
  859. this.z -= v.z;
  860. this.w -= v.w;
  861. return this;
  862. },
  863. subScalar: function ( s ) {
  864. this.x -= s;
  865. this.y -= s;
  866. this.z -= s;
  867. this.w -= s;
  868. return this;
  869. },
  870. subVectors: function ( a, b ) {
  871. this.x = a.x - b.x;
  872. this.y = a.y - b.y;
  873. this.z = a.z - b.z;
  874. this.w = a.w - b.w;
  875. return this;
  876. },
  877. multiplyScalar: function ( scalar ) {
  878. this.x *= scalar;
  879. this.y *= scalar;
  880. this.z *= scalar;
  881. this.w *= scalar;
  882. return this;
  883. },
  884. applyMatrix4: function ( m ) {
  885. var x = this.x, y = this.y, z = this.z, w = this.w;
  886. var e = m.elements;
  887. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  888. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  889. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  890. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  891. return this;
  892. },
  893. divideScalar: function ( scalar ) {
  894. return this.multiplyScalar( 1 / scalar );
  895. },
  896. setAxisAngleFromQuaternion: function ( q ) {
  897. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  898. // q is assumed to be normalized
  899. this.w = 2 * Math.acos( q.w );
  900. var s = Math.sqrt( 1 - q.w * q.w );
  901. if ( s < 0.0001 ) {
  902. this.x = 1;
  903. this.y = 0;
  904. this.z = 0;
  905. } else {
  906. this.x = q.x / s;
  907. this.y = q.y / s;
  908. this.z = q.z / s;
  909. }
  910. return this;
  911. },
  912. setAxisAngleFromRotationMatrix: function ( m ) {
  913. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  914. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  915. var angle, x, y, z, // variables for result
  916. epsilon = 0.01, // margin to allow for rounding errors
  917. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  918. te = m.elements,
  919. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  920. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  921. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  922. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  923. ( Math.abs( m13 - m31 ) < epsilon ) &&
  924. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  925. // singularity found
  926. // first check for identity matrix which must have +1 for all terms
  927. // in leading diagonal and zero in other terms
  928. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  929. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  930. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  931. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  932. // this singularity is identity matrix so angle = 0
  933. this.set( 1, 0, 0, 0 );
  934. return this; // zero angle, arbitrary axis
  935. }
  936. // otherwise this singularity is angle = 180
  937. angle = Math.PI;
  938. var xx = ( m11 + 1 ) / 2;
  939. var yy = ( m22 + 1 ) / 2;
  940. var zz = ( m33 + 1 ) / 2;
  941. var xy = ( m12 + m21 ) / 4;
  942. var xz = ( m13 + m31 ) / 4;
  943. var yz = ( m23 + m32 ) / 4;
  944. if ( ( xx > yy ) && ( xx > zz ) ) {
  945. // m11 is the largest diagonal term
  946. if ( xx < epsilon ) {
  947. x = 0;
  948. y = 0.707106781;
  949. z = 0.707106781;
  950. } else {
  951. x = Math.sqrt( xx );
  952. y = xy / x;
  953. z = xz / x;
  954. }
  955. } else if ( yy > zz ) {
  956. // m22 is the largest diagonal term
  957. if ( yy < epsilon ) {
  958. x = 0.707106781;
  959. y = 0;
  960. z = 0.707106781;
  961. } else {
  962. y = Math.sqrt( yy );
  963. x = xy / y;
  964. z = yz / y;
  965. }
  966. } else {
  967. // m33 is the largest diagonal term so base result on this
  968. if ( zz < epsilon ) {
  969. x = 0.707106781;
  970. y = 0.707106781;
  971. z = 0;
  972. } else {
  973. z = Math.sqrt( zz );
  974. x = xz / z;
  975. y = yz / z;
  976. }
  977. }
  978. this.set( x, y, z, angle );
  979. return this; // return 180 deg rotation
  980. }
  981. // as we have reached here there are no singularities so we can handle normally
  982. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  983. ( m13 - m31 ) * ( m13 - m31 ) +
  984. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  985. if ( Math.abs( s ) < 0.001 ) s = 1;
  986. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  987. // caught by singularity test above, but I've left it in just in case
  988. this.x = ( m32 - m23 ) / s;
  989. this.y = ( m13 - m31 ) / s;
  990. this.z = ( m21 - m12 ) / s;
  991. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  992. return this;
  993. },
  994. min: function ( v ) {
  995. this.x = Math.min( this.x, v.x );
  996. this.y = Math.min( this.y, v.y );
  997. this.z = Math.min( this.z, v.z );
  998. this.w = Math.min( this.w, v.w );
  999. return this;
  1000. },
  1001. max: function ( v ) {
  1002. this.x = Math.max( this.x, v.x );
  1003. this.y = Math.max( this.y, v.y );
  1004. this.z = Math.max( this.z, v.z );
  1005. this.w = Math.max( this.w, v.w );
  1006. return this;
  1007. },
  1008. clamp: function ( min, max ) {
  1009. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1010. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1011. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1012. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1013. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1014. return this;
  1015. },
  1016. clampScalar: function () {
  1017. var min = new Vector4();
  1018. var max = new Vector4();
  1019. return function clampScalar( minVal, maxVal ) {
  1020. min.set( minVal, minVal, minVal, minVal );
  1021. max.set( maxVal, maxVal, maxVal, maxVal );
  1022. return this.clamp( min, max );
  1023. };
  1024. }(),
  1025. floor: function () {
  1026. this.x = Math.floor( this.x );
  1027. this.y = Math.floor( this.y );
  1028. this.z = Math.floor( this.z );
  1029. this.w = Math.floor( this.w );
  1030. return this;
  1031. },
  1032. ceil: function () {
  1033. this.x = Math.ceil( this.x );
  1034. this.y = Math.ceil( this.y );
  1035. this.z = Math.ceil( this.z );
  1036. this.w = Math.ceil( this.w );
  1037. return this;
  1038. },
  1039. round: function () {
  1040. this.x = Math.round( this.x );
  1041. this.y = Math.round( this.y );
  1042. this.z = Math.round( this.z );
  1043. this.w = Math.round( this.w );
  1044. return this;
  1045. },
  1046. roundToZero: function () {
  1047. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1048. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1049. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1050. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1051. return this;
  1052. },
  1053. negate: function () {
  1054. this.x = - this.x;
  1055. this.y = - this.y;
  1056. this.z = - this.z;
  1057. this.w = - this.w;
  1058. return this;
  1059. },
  1060. dot: function ( v ) {
  1061. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1062. },
  1063. lengthSq: function () {
  1064. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1065. },
  1066. length: function () {
  1067. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1068. },
  1069. lengthManhattan: function () {
  1070. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1071. },
  1072. normalize: function () {
  1073. return this.divideScalar( this.length() );
  1074. },
  1075. setLength: function ( length ) {
  1076. return this.multiplyScalar( length / this.length() );
  1077. },
  1078. lerp: function ( v, alpha ) {
  1079. this.x += ( v.x - this.x ) * alpha;
  1080. this.y += ( v.y - this.y ) * alpha;
  1081. this.z += ( v.z - this.z ) * alpha;
  1082. this.w += ( v.w - this.w ) * alpha;
  1083. return this;
  1084. },
  1085. lerpVectors: function ( v1, v2, alpha ) {
  1086. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1087. },
  1088. equals: function ( v ) {
  1089. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1090. },
  1091. fromArray: function ( array, offset ) {
  1092. if ( offset === undefined ) offset = 0;
  1093. this.x = array[ offset ];
  1094. this.y = array[ offset + 1 ];
  1095. this.z = array[ offset + 2 ];
  1096. this.w = array[ offset + 3 ];
  1097. return this;
  1098. },
  1099. toArray: function ( array, offset ) {
  1100. if ( array === undefined ) array = [];
  1101. if ( offset === undefined ) offset = 0;
  1102. array[ offset ] = this.x;
  1103. array[ offset + 1 ] = this.y;
  1104. array[ offset + 2 ] = this.z;
  1105. array[ offset + 3 ] = this.w;
  1106. return array;
  1107. },
  1108. fromBufferAttribute: function ( attribute, index, offset ) {
  1109. if ( offset !== undefined ) {
  1110. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1111. }
  1112. this.x = attribute.getX( index );
  1113. this.y = attribute.getY( index );
  1114. this.z = attribute.getZ( index );
  1115. this.w = attribute.getW( index );
  1116. return this;
  1117. }
  1118. } );
  1119. /**
  1120. * @author szimek / https://github.com/szimek/
  1121. * @author alteredq / http://alteredqualia.com/
  1122. * @author Marius Kintel / https://github.com/kintel
  1123. */
  1124. /*
  1125. In options, we can specify:
  1126. * Texture parameters for an auto-generated target texture
  1127. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1128. */
  1129. function WebGLRenderTarget( width, height, options ) {
  1130. this.uuid = _Math.generateUUID();
  1131. this.width = width;
  1132. this.height = height;
  1133. this.scissor = new Vector4( 0, 0, width, height );
  1134. this.scissorTest = false;
  1135. this.viewport = new Vector4( 0, 0, width, height );
  1136. options = options || {};
  1137. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1138. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1139. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1140. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1141. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1142. }
  1143. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1144. isWebGLRenderTarget: true,
  1145. setSize: function ( width, height ) {
  1146. if ( this.width !== width || this.height !== height ) {
  1147. this.width = width;
  1148. this.height = height;
  1149. this.dispose();
  1150. }
  1151. this.viewport.set( 0, 0, width, height );
  1152. this.scissor.set( 0, 0, width, height );
  1153. },
  1154. clone: function () {
  1155. return new this.constructor().copy( this );
  1156. },
  1157. copy: function ( source ) {
  1158. this.width = source.width;
  1159. this.height = source.height;
  1160. this.viewport.copy( source.viewport );
  1161. this.texture = source.texture.clone();
  1162. this.depthBuffer = source.depthBuffer;
  1163. this.stencilBuffer = source.stencilBuffer;
  1164. this.depthTexture = source.depthTexture;
  1165. return this;
  1166. },
  1167. dispose: function () {
  1168. this.dispatchEvent( { type: 'dispose' } );
  1169. }
  1170. } );
  1171. /**
  1172. * @author alteredq / http://alteredqualia.com
  1173. */
  1174. function WebGLRenderTargetCube( width, height, options ) {
  1175. WebGLRenderTarget.call( this, width, height, options );
  1176. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1177. this.activeMipMapLevel = 0;
  1178. }
  1179. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1180. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1181. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1182. /**
  1183. * @author mikael emtinger / http://gomo.se/
  1184. * @author alteredq / http://alteredqualia.com/
  1185. * @author WestLangley / http://github.com/WestLangley
  1186. * @author bhouston / http://clara.io
  1187. */
  1188. function Quaternion( x, y, z, w ) {
  1189. this._x = x || 0;
  1190. this._y = y || 0;
  1191. this._z = z || 0;
  1192. this._w = ( w !== undefined ) ? w : 1;
  1193. }
  1194. Object.assign( Quaternion, {
  1195. slerp: function ( qa, qb, qm, t ) {
  1196. return qm.copy( qa ).slerp( qb, t );
  1197. },
  1198. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1199. // fuzz-free, array-based Quaternion SLERP operation
  1200. var x0 = src0[ srcOffset0 + 0 ],
  1201. y0 = src0[ srcOffset0 + 1 ],
  1202. z0 = src0[ srcOffset0 + 2 ],
  1203. w0 = src0[ srcOffset0 + 3 ],
  1204. x1 = src1[ srcOffset1 + 0 ],
  1205. y1 = src1[ srcOffset1 + 1 ],
  1206. z1 = src1[ srcOffset1 + 2 ],
  1207. w1 = src1[ srcOffset1 + 3 ];
  1208. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1209. var s = 1 - t,
  1210. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1211. dir = ( cos >= 0 ? 1 : - 1 ),
  1212. sqrSin = 1 - cos * cos;
  1213. // Skip the Slerp for tiny steps to avoid numeric problems:
  1214. if ( sqrSin > Number.EPSILON ) {
  1215. var sin = Math.sqrt( sqrSin ),
  1216. len = Math.atan2( sin, cos * dir );
  1217. s = Math.sin( s * len ) / sin;
  1218. t = Math.sin( t * len ) / sin;
  1219. }
  1220. var tDir = t * dir;
  1221. x0 = x0 * s + x1 * tDir;
  1222. y0 = y0 * s + y1 * tDir;
  1223. z0 = z0 * s + z1 * tDir;
  1224. w0 = w0 * s + w1 * tDir;
  1225. // Normalize in case we just did a lerp:
  1226. if ( s === 1 - t ) {
  1227. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1228. x0 *= f;
  1229. y0 *= f;
  1230. z0 *= f;
  1231. w0 *= f;
  1232. }
  1233. }
  1234. dst[ dstOffset ] = x0;
  1235. dst[ dstOffset + 1 ] = y0;
  1236. dst[ dstOffset + 2 ] = z0;
  1237. dst[ dstOffset + 3 ] = w0;
  1238. }
  1239. } );
  1240. Object.defineProperties( Quaternion.prototype, {
  1241. x: {
  1242. get: function () {
  1243. return this._x;
  1244. },
  1245. set: function ( value ) {
  1246. this._x = value;
  1247. this.onChangeCallback();
  1248. }
  1249. },
  1250. y: {
  1251. get: function () {
  1252. return this._y;
  1253. },
  1254. set: function ( value ) {
  1255. this._y = value;
  1256. this.onChangeCallback();
  1257. }
  1258. },
  1259. z: {
  1260. get: function () {
  1261. return this._z;
  1262. },
  1263. set: function ( value ) {
  1264. this._z = value;
  1265. this.onChangeCallback();
  1266. }
  1267. },
  1268. w: {
  1269. get: function () {
  1270. return this._w;
  1271. },
  1272. set: function ( value ) {
  1273. this._w = value;
  1274. this.onChangeCallback();
  1275. }
  1276. }
  1277. } );
  1278. Object.assign( Quaternion.prototype, {
  1279. set: function ( x, y, z, w ) {
  1280. this._x = x;
  1281. this._y = y;
  1282. this._z = z;
  1283. this._w = w;
  1284. this.onChangeCallback();
  1285. return this;
  1286. },
  1287. clone: function () {
  1288. return new this.constructor( this._x, this._y, this._z, this._w );
  1289. },
  1290. copy: function ( quaternion ) {
  1291. this._x = quaternion.x;
  1292. this._y = quaternion.y;
  1293. this._z = quaternion.z;
  1294. this._w = quaternion.w;
  1295. this.onChangeCallback();
  1296. return this;
  1297. },
  1298. setFromEuler: function ( euler, update ) {
  1299. if ( ( euler && euler.isEuler ) === false ) {
  1300. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1301. }
  1302. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1303. // http://www.mathworks.com/matlabcentral/fileexchange/
  1304. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1305. // content/SpinCalc.m
  1306. var cos = Math.cos;
  1307. var sin = Math.sin;
  1308. var c1 = cos( x / 2 );
  1309. var c2 = cos( y / 2 );
  1310. var c3 = cos( z / 2 );
  1311. var s1 = sin( x / 2 );
  1312. var s2 = sin( y / 2 );
  1313. var s3 = sin( z / 2 );
  1314. if ( order === 'XYZ' ) {
  1315. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1316. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1317. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1318. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1319. } else if ( order === 'YXZ' ) {
  1320. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1321. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1322. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1323. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1324. } else if ( order === 'ZXY' ) {
  1325. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1326. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1327. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1328. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1329. } else if ( order === 'ZYX' ) {
  1330. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1331. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1332. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1333. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1334. } else if ( order === 'YZX' ) {
  1335. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1336. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1337. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1338. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1339. } else if ( order === 'XZY' ) {
  1340. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1341. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1343. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1344. }
  1345. if ( update !== false ) this.onChangeCallback();
  1346. return this;
  1347. },
  1348. setFromAxisAngle: function ( axis, angle ) {
  1349. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1350. // assumes axis is normalized
  1351. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1352. this._x = axis.x * s;
  1353. this._y = axis.y * s;
  1354. this._z = axis.z * s;
  1355. this._w = Math.cos( halfAngle );
  1356. this.onChangeCallback();
  1357. return this;
  1358. },
  1359. setFromRotationMatrix: function ( m ) {
  1360. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1361. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1362. var te = m.elements,
  1363. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1364. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1365. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1366. trace = m11 + m22 + m33,
  1367. s;
  1368. if ( trace > 0 ) {
  1369. s = 0.5 / Math.sqrt( trace + 1.0 );
  1370. this._w = 0.25 / s;
  1371. this._x = ( m32 - m23 ) * s;
  1372. this._y = ( m13 - m31 ) * s;
  1373. this._z = ( m21 - m12 ) * s;
  1374. } else if ( m11 > m22 && m11 > m33 ) {
  1375. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1376. this._w = ( m32 - m23 ) / s;
  1377. this._x = 0.25 * s;
  1378. this._y = ( m12 + m21 ) / s;
  1379. this._z = ( m13 + m31 ) / s;
  1380. } else if ( m22 > m33 ) {
  1381. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1382. this._w = ( m13 - m31 ) / s;
  1383. this._x = ( m12 + m21 ) / s;
  1384. this._y = 0.25 * s;
  1385. this._z = ( m23 + m32 ) / s;
  1386. } else {
  1387. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1388. this._w = ( m21 - m12 ) / s;
  1389. this._x = ( m13 + m31 ) / s;
  1390. this._y = ( m23 + m32 ) / s;
  1391. this._z = 0.25 * s;
  1392. }
  1393. this.onChangeCallback();
  1394. return this;
  1395. },
  1396. setFromUnitVectors: function () {
  1397. // assumes direction vectors vFrom and vTo are normalized
  1398. var v1 = new Vector3();
  1399. var r;
  1400. var EPS = 0.000001;
  1401. return function setFromUnitVectors( vFrom, vTo ) {
  1402. if ( v1 === undefined ) v1 = new Vector3();
  1403. r = vFrom.dot( vTo ) + 1;
  1404. if ( r < EPS ) {
  1405. r = 0;
  1406. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1407. v1.set( - vFrom.y, vFrom.x, 0 );
  1408. } else {
  1409. v1.set( 0, - vFrom.z, vFrom.y );
  1410. }
  1411. } else {
  1412. v1.crossVectors( vFrom, vTo );
  1413. }
  1414. this._x = v1.x;
  1415. this._y = v1.y;
  1416. this._z = v1.z;
  1417. this._w = r;
  1418. return this.normalize();
  1419. };
  1420. }(),
  1421. inverse: function () {
  1422. return this.conjugate().normalize();
  1423. },
  1424. conjugate: function () {
  1425. this._x *= - 1;
  1426. this._y *= - 1;
  1427. this._z *= - 1;
  1428. this.onChangeCallback();
  1429. return this;
  1430. },
  1431. dot: function ( v ) {
  1432. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1433. },
  1434. lengthSq: function () {
  1435. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1436. },
  1437. length: function () {
  1438. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1439. },
  1440. normalize: function () {
  1441. var l = this.length();
  1442. if ( l === 0 ) {
  1443. this._x = 0;
  1444. this._y = 0;
  1445. this._z = 0;
  1446. this._w = 1;
  1447. } else {
  1448. l = 1 / l;
  1449. this._x = this._x * l;
  1450. this._y = this._y * l;
  1451. this._z = this._z * l;
  1452. this._w = this._w * l;
  1453. }
  1454. this.onChangeCallback();
  1455. return this;
  1456. },
  1457. multiply: function ( q, p ) {
  1458. if ( p !== undefined ) {
  1459. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1460. return this.multiplyQuaternions( q, p );
  1461. }
  1462. return this.multiplyQuaternions( this, q );
  1463. },
  1464. premultiply: function ( q ) {
  1465. return this.multiplyQuaternions( q, this );
  1466. },
  1467. multiplyQuaternions: function ( a, b ) {
  1468. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1469. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1470. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1471. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1472. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1473. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1474. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1475. this.onChangeCallback();
  1476. return this;
  1477. },
  1478. slerp: function ( qb, t ) {
  1479. if ( t === 0 ) return this;
  1480. if ( t === 1 ) return this.copy( qb );
  1481. var x = this._x, y = this._y, z = this._z, w = this._w;
  1482. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1483. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1484. if ( cosHalfTheta < 0 ) {
  1485. this._w = - qb._w;
  1486. this._x = - qb._x;
  1487. this._y = - qb._y;
  1488. this._z = - qb._z;
  1489. cosHalfTheta = - cosHalfTheta;
  1490. } else {
  1491. this.copy( qb );
  1492. }
  1493. if ( cosHalfTheta >= 1.0 ) {
  1494. this._w = w;
  1495. this._x = x;
  1496. this._y = y;
  1497. this._z = z;
  1498. return this;
  1499. }
  1500. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1501. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1502. this._w = 0.5 * ( w + this._w );
  1503. this._x = 0.5 * ( x + this._x );
  1504. this._y = 0.5 * ( y + this._y );
  1505. this._z = 0.5 * ( z + this._z );
  1506. return this;
  1507. }
  1508. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1509. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1510. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1511. this._w = ( w * ratioA + this._w * ratioB );
  1512. this._x = ( x * ratioA + this._x * ratioB );
  1513. this._y = ( y * ratioA + this._y * ratioB );
  1514. this._z = ( z * ratioA + this._z * ratioB );
  1515. this.onChangeCallback();
  1516. return this;
  1517. },
  1518. equals: function ( quaternion ) {
  1519. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1520. },
  1521. fromArray: function ( array, offset ) {
  1522. if ( offset === undefined ) offset = 0;
  1523. this._x = array[ offset ];
  1524. this._y = array[ offset + 1 ];
  1525. this._z = array[ offset + 2 ];
  1526. this._w = array[ offset + 3 ];
  1527. this.onChangeCallback();
  1528. return this;
  1529. },
  1530. toArray: function ( array, offset ) {
  1531. if ( array === undefined ) array = [];
  1532. if ( offset === undefined ) offset = 0;
  1533. array[ offset ] = this._x;
  1534. array[ offset + 1 ] = this._y;
  1535. array[ offset + 2 ] = this._z;
  1536. array[ offset + 3 ] = this._w;
  1537. return array;
  1538. },
  1539. onChange: function ( callback ) {
  1540. this.onChangeCallback = callback;
  1541. return this;
  1542. },
  1543. onChangeCallback: function () {}
  1544. } );
  1545. /**
  1546. * @author mrdoob / http://mrdoob.com/
  1547. * @author *kile / http://kile.stravaganza.org/
  1548. * @author philogb / http://blog.thejit.org/
  1549. * @author mikael emtinger / http://gomo.se/
  1550. * @author egraether / http://egraether.com/
  1551. * @author WestLangley / http://github.com/WestLangley
  1552. */
  1553. function Vector3( x, y, z ) {
  1554. this.x = x || 0;
  1555. this.y = y || 0;
  1556. this.z = z || 0;
  1557. }
  1558. Object.assign( Vector3.prototype, {
  1559. isVector3: true,
  1560. set: function ( x, y, z ) {
  1561. this.x = x;
  1562. this.y = y;
  1563. this.z = z;
  1564. return this;
  1565. },
  1566. setScalar: function ( scalar ) {
  1567. this.x = scalar;
  1568. this.y = scalar;
  1569. this.z = scalar;
  1570. return this;
  1571. },
  1572. setX: function ( x ) {
  1573. this.x = x;
  1574. return this;
  1575. },
  1576. setY: function ( y ) {
  1577. this.y = y;
  1578. return this;
  1579. },
  1580. setZ: function ( z ) {
  1581. this.z = z;
  1582. return this;
  1583. },
  1584. setComponent: function ( index, value ) {
  1585. switch ( index ) {
  1586. case 0: this.x = value; break;
  1587. case 1: this.y = value; break;
  1588. case 2: this.z = value; break;
  1589. default: throw new Error( 'index is out of range: ' + index );
  1590. }
  1591. return this;
  1592. },
  1593. getComponent: function ( index ) {
  1594. switch ( index ) {
  1595. case 0: return this.x;
  1596. case 1: return this.y;
  1597. case 2: return this.z;
  1598. default: throw new Error( 'index is out of range: ' + index );
  1599. }
  1600. },
  1601. clone: function () {
  1602. return new this.constructor( this.x, this.y, this.z );
  1603. },
  1604. copy: function ( v ) {
  1605. this.x = v.x;
  1606. this.y = v.y;
  1607. this.z = v.z;
  1608. return this;
  1609. },
  1610. add: function ( v, w ) {
  1611. if ( w !== undefined ) {
  1612. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1613. return this.addVectors( v, w );
  1614. }
  1615. this.x += v.x;
  1616. this.y += v.y;
  1617. this.z += v.z;
  1618. return this;
  1619. },
  1620. addScalar: function ( s ) {
  1621. this.x += s;
  1622. this.y += s;
  1623. this.z += s;
  1624. return this;
  1625. },
  1626. addVectors: function ( a, b ) {
  1627. this.x = a.x + b.x;
  1628. this.y = a.y + b.y;
  1629. this.z = a.z + b.z;
  1630. return this;
  1631. },
  1632. addScaledVector: function ( v, s ) {
  1633. this.x += v.x * s;
  1634. this.y += v.y * s;
  1635. this.z += v.z * s;
  1636. return this;
  1637. },
  1638. sub: function ( v, w ) {
  1639. if ( w !== undefined ) {
  1640. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1641. return this.subVectors( v, w );
  1642. }
  1643. this.x -= v.x;
  1644. this.y -= v.y;
  1645. this.z -= v.z;
  1646. return this;
  1647. },
  1648. subScalar: function ( s ) {
  1649. this.x -= s;
  1650. this.y -= s;
  1651. this.z -= s;
  1652. return this;
  1653. },
  1654. subVectors: function ( a, b ) {
  1655. this.x = a.x - b.x;
  1656. this.y = a.y - b.y;
  1657. this.z = a.z - b.z;
  1658. return this;
  1659. },
  1660. multiply: function ( v, w ) {
  1661. if ( w !== undefined ) {
  1662. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1663. return this.multiplyVectors( v, w );
  1664. }
  1665. this.x *= v.x;
  1666. this.y *= v.y;
  1667. this.z *= v.z;
  1668. return this;
  1669. },
  1670. multiplyScalar: function ( scalar ) {
  1671. this.x *= scalar;
  1672. this.y *= scalar;
  1673. this.z *= scalar;
  1674. return this;
  1675. },
  1676. multiplyVectors: function ( a, b ) {
  1677. this.x = a.x * b.x;
  1678. this.y = a.y * b.y;
  1679. this.z = a.z * b.z;
  1680. return this;
  1681. },
  1682. applyEuler: function () {
  1683. var quaternion = new Quaternion();
  1684. return function applyEuler( euler ) {
  1685. if ( ( euler && euler.isEuler ) === false ) {
  1686. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1687. }
  1688. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1689. };
  1690. }(),
  1691. applyAxisAngle: function () {
  1692. var quaternion = new Quaternion();
  1693. return function applyAxisAngle( axis, angle ) {
  1694. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1695. };
  1696. }(),
  1697. applyMatrix3: function ( m ) {
  1698. var x = this.x, y = this.y, z = this.z;
  1699. var e = m.elements;
  1700. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1701. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1702. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1703. return this;
  1704. },
  1705. applyMatrix4: function ( m ) {
  1706. var x = this.x, y = this.y, z = this.z;
  1707. var e = m.elements;
  1708. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1709. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1710. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1711. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  1712. return this.divideScalar( w );
  1713. },
  1714. applyQuaternion: function ( q ) {
  1715. var x = this.x, y = this.y, z = this.z;
  1716. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1717. // calculate quat * vector
  1718. var ix = qw * x + qy * z - qz * y;
  1719. var iy = qw * y + qz * x - qx * z;
  1720. var iz = qw * z + qx * y - qy * x;
  1721. var iw = - qx * x - qy * y - qz * z;
  1722. // calculate result * inverse quat
  1723. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1724. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1725. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1726. return this;
  1727. },
  1728. project: function () {
  1729. var matrix = new Matrix4();
  1730. return function project( camera ) {
  1731. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1732. return this.applyMatrix4( matrix );
  1733. };
  1734. }(),
  1735. unproject: function () {
  1736. var matrix = new Matrix4();
  1737. return function unproject( camera ) {
  1738. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1739. return this.applyMatrix4( matrix );
  1740. };
  1741. }(),
  1742. transformDirection: function ( m ) {
  1743. // input: THREE.Matrix4 affine matrix
  1744. // vector interpreted as a direction
  1745. var x = this.x, y = this.y, z = this.z;
  1746. var e = m.elements;
  1747. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1748. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1749. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1750. return this.normalize();
  1751. },
  1752. divide: function ( v ) {
  1753. this.x /= v.x;
  1754. this.y /= v.y;
  1755. this.z /= v.z;
  1756. return this;
  1757. },
  1758. divideScalar: function ( scalar ) {
  1759. return this.multiplyScalar( 1 / scalar );
  1760. },
  1761. min: function ( v ) {
  1762. this.x = Math.min( this.x, v.x );
  1763. this.y = Math.min( this.y, v.y );
  1764. this.z = Math.min( this.z, v.z );
  1765. return this;
  1766. },
  1767. max: function ( v ) {
  1768. this.x = Math.max( this.x, v.x );
  1769. this.y = Math.max( this.y, v.y );
  1770. this.z = Math.max( this.z, v.z );
  1771. return this;
  1772. },
  1773. clamp: function ( min, max ) {
  1774. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1775. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1776. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1777. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1778. return this;
  1779. },
  1780. clampScalar: function () {
  1781. var min = new Vector3();
  1782. var max = new Vector3();
  1783. return function clampScalar( minVal, maxVal ) {
  1784. min.set( minVal, minVal, minVal );
  1785. max.set( maxVal, maxVal, maxVal );
  1786. return this.clamp( min, max );
  1787. };
  1788. }(),
  1789. clampLength: function ( min, max ) {
  1790. var length = this.length();
  1791. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1792. },
  1793. floor: function () {
  1794. this.x = Math.floor( this.x );
  1795. this.y = Math.floor( this.y );
  1796. this.z = Math.floor( this.z );
  1797. return this;
  1798. },
  1799. ceil: function () {
  1800. this.x = Math.ceil( this.x );
  1801. this.y = Math.ceil( this.y );
  1802. this.z = Math.ceil( this.z );
  1803. return this;
  1804. },
  1805. round: function () {
  1806. this.x = Math.round( this.x );
  1807. this.y = Math.round( this.y );
  1808. this.z = Math.round( this.z );
  1809. return this;
  1810. },
  1811. roundToZero: function () {
  1812. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1813. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1814. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1815. return this;
  1816. },
  1817. negate: function () {
  1818. this.x = - this.x;
  1819. this.y = - this.y;
  1820. this.z = - this.z;
  1821. return this;
  1822. },
  1823. dot: function ( v ) {
  1824. return this.x * v.x + this.y * v.y + this.z * v.z;
  1825. },
  1826. // TODO lengthSquared?
  1827. lengthSq: function () {
  1828. return this.x * this.x + this.y * this.y + this.z * this.z;
  1829. },
  1830. length: function () {
  1831. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1832. },
  1833. lengthManhattan: function () {
  1834. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1835. },
  1836. normalize: function () {
  1837. return this.divideScalar( this.length() );
  1838. },
  1839. setLength: function ( length ) {
  1840. return this.multiplyScalar( length / this.length() );
  1841. },
  1842. lerp: function ( v, alpha ) {
  1843. this.x += ( v.x - this.x ) * alpha;
  1844. this.y += ( v.y - this.y ) * alpha;
  1845. this.z += ( v.z - this.z ) * alpha;
  1846. return this;
  1847. },
  1848. lerpVectors: function ( v1, v2, alpha ) {
  1849. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1850. },
  1851. cross: function ( v, w ) {
  1852. if ( w !== undefined ) {
  1853. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1854. return this.crossVectors( v, w );
  1855. }
  1856. var x = this.x, y = this.y, z = this.z;
  1857. this.x = y * v.z - z * v.y;
  1858. this.y = z * v.x - x * v.z;
  1859. this.z = x * v.y - y * v.x;
  1860. return this;
  1861. },
  1862. crossVectors: function ( a, b ) {
  1863. var ax = a.x, ay = a.y, az = a.z;
  1864. var bx = b.x, by = b.y, bz = b.z;
  1865. this.x = ay * bz - az * by;
  1866. this.y = az * bx - ax * bz;
  1867. this.z = ax * by - ay * bx;
  1868. return this;
  1869. },
  1870. projectOnVector: function ( vector ) {
  1871. var scalar = vector.dot( this ) / vector.lengthSq();
  1872. return this.copy( vector ).multiplyScalar( scalar );
  1873. },
  1874. projectOnPlane: function () {
  1875. var v1 = new Vector3();
  1876. return function projectOnPlane( planeNormal ) {
  1877. v1.copy( this ).projectOnVector( planeNormal );
  1878. return this.sub( v1 );
  1879. };
  1880. }(),
  1881. reflect: function () {
  1882. // reflect incident vector off plane orthogonal to normal
  1883. // normal is assumed to have unit length
  1884. var v1 = new Vector3();
  1885. return function reflect( normal ) {
  1886. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1887. };
  1888. }(),
  1889. angleTo: function ( v ) {
  1890. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1891. // clamp, to handle numerical problems
  1892. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1893. },
  1894. distanceTo: function ( v ) {
  1895. return Math.sqrt( this.distanceToSquared( v ) );
  1896. },
  1897. distanceToSquared: function ( v ) {
  1898. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1899. return dx * dx + dy * dy + dz * dz;
  1900. },
  1901. distanceToManhattan: function ( v ) {
  1902. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1903. },
  1904. setFromSpherical: function ( s ) {
  1905. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1906. this.x = sinPhiRadius * Math.sin( s.theta );
  1907. this.y = Math.cos( s.phi ) * s.radius;
  1908. this.z = sinPhiRadius * Math.cos( s.theta );
  1909. return this;
  1910. },
  1911. setFromCylindrical: function ( c ) {
  1912. this.x = c.radius * Math.sin( c.theta );
  1913. this.y = c.y;
  1914. this.z = c.radius * Math.cos( c.theta );
  1915. return this;
  1916. },
  1917. setFromMatrixPosition: function ( m ) {
  1918. return this.setFromMatrixColumn( m, 3 );
  1919. },
  1920. setFromMatrixScale: function ( m ) {
  1921. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1922. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1923. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1924. this.x = sx;
  1925. this.y = sy;
  1926. this.z = sz;
  1927. return this;
  1928. },
  1929. setFromMatrixColumn: function ( m, index ) {
  1930. return this.fromArray( m.elements, index * 4 );
  1931. },
  1932. equals: function ( v ) {
  1933. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1934. },
  1935. fromArray: function ( array, offset ) {
  1936. if ( offset === undefined ) offset = 0;
  1937. this.x = array[ offset ];
  1938. this.y = array[ offset + 1 ];
  1939. this.z = array[ offset + 2 ];
  1940. return this;
  1941. },
  1942. toArray: function ( array, offset ) {
  1943. if ( array === undefined ) array = [];
  1944. if ( offset === undefined ) offset = 0;
  1945. array[ offset ] = this.x;
  1946. array[ offset + 1 ] = this.y;
  1947. array[ offset + 2 ] = this.z;
  1948. return array;
  1949. },
  1950. fromBufferAttribute: function ( attribute, index, offset ) {
  1951. if ( offset !== undefined ) {
  1952. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1953. }
  1954. this.x = attribute.getX( index );
  1955. this.y = attribute.getY( index );
  1956. this.z = attribute.getZ( index );
  1957. return this;
  1958. }
  1959. } );
  1960. /**
  1961. * @author mrdoob / http://mrdoob.com/
  1962. * @author supereggbert / http://www.paulbrunt.co.uk/
  1963. * @author philogb / http://blog.thejit.org/
  1964. * @author jordi_ros / http://plattsoft.com
  1965. * @author D1plo1d / http://github.com/D1plo1d
  1966. * @author alteredq / http://alteredqualia.com/
  1967. * @author mikael emtinger / http://gomo.se/
  1968. * @author timknip / http://www.floorplanner.com/
  1969. * @author bhouston / http://clara.io
  1970. * @author WestLangley / http://github.com/WestLangley
  1971. */
  1972. function Matrix4() {
  1973. this.elements = [
  1974. 1, 0, 0, 0,
  1975. 0, 1, 0, 0,
  1976. 0, 0, 1, 0,
  1977. 0, 0, 0, 1
  1978. ];
  1979. if ( arguments.length > 0 ) {
  1980. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  1981. }
  1982. }
  1983. Object.assign( Matrix4.prototype, {
  1984. isMatrix4: true,
  1985. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1986. var te = this.elements;
  1987. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  1988. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  1989. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  1990. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  1991. return this;
  1992. },
  1993. identity: function () {
  1994. this.set(
  1995. 1, 0, 0, 0,
  1996. 0, 1, 0, 0,
  1997. 0, 0, 1, 0,
  1998. 0, 0, 0, 1
  1999. );
  2000. return this;
  2001. },
  2002. clone: function () {
  2003. return new Matrix4().fromArray( this.elements );
  2004. },
  2005. copy: function ( m ) {
  2006. var te = this.elements;
  2007. var me = m.elements;
  2008. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  2009. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  2010. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  2011. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  2012. return this;
  2013. },
  2014. copyPosition: function ( m ) {
  2015. var te = this.elements, me = m.elements;
  2016. te[ 12 ] = me[ 12 ];
  2017. te[ 13 ] = me[ 13 ];
  2018. te[ 14 ] = me[ 14 ];
  2019. return this;
  2020. },
  2021. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2022. xAxis.setFromMatrixColumn( this, 0 );
  2023. yAxis.setFromMatrixColumn( this, 1 );
  2024. zAxis.setFromMatrixColumn( this, 2 );
  2025. return this;
  2026. },
  2027. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2028. this.set(
  2029. xAxis.x, yAxis.x, zAxis.x, 0,
  2030. xAxis.y, yAxis.y, zAxis.y, 0,
  2031. xAxis.z, yAxis.z, zAxis.z, 0,
  2032. 0, 0, 0, 1
  2033. );
  2034. return this;
  2035. },
  2036. extractRotation: function () {
  2037. var v1 = new Vector3();
  2038. return function extractRotation( m ) {
  2039. var te = this.elements;
  2040. var me = m.elements;
  2041. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2042. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2043. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2044. te[ 0 ] = me[ 0 ] * scaleX;
  2045. te[ 1 ] = me[ 1 ] * scaleX;
  2046. te[ 2 ] = me[ 2 ] * scaleX;
  2047. te[ 4 ] = me[ 4 ] * scaleY;
  2048. te[ 5 ] = me[ 5 ] * scaleY;
  2049. te[ 6 ] = me[ 6 ] * scaleY;
  2050. te[ 8 ] = me[ 8 ] * scaleZ;
  2051. te[ 9 ] = me[ 9 ] * scaleZ;
  2052. te[ 10 ] = me[ 10 ] * scaleZ;
  2053. return this;
  2054. };
  2055. }(),
  2056. makeRotationFromEuler: function ( euler ) {
  2057. if ( ( euler && euler.isEuler ) === false ) {
  2058. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2059. }
  2060. var te = this.elements;
  2061. var x = euler.x, y = euler.y, z = euler.z;
  2062. var a = Math.cos( x ), b = Math.sin( x );
  2063. var c = Math.cos( y ), d = Math.sin( y );
  2064. var e = Math.cos( z ), f = Math.sin( z );
  2065. if ( euler.order === 'XYZ' ) {
  2066. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2067. te[ 0 ] = c * e;
  2068. te[ 4 ] = - c * f;
  2069. te[ 8 ] = d;
  2070. te[ 1 ] = af + be * d;
  2071. te[ 5 ] = ae - bf * d;
  2072. te[ 9 ] = - b * c;
  2073. te[ 2 ] = bf - ae * d;
  2074. te[ 6 ] = be + af * d;
  2075. te[ 10 ] = a * c;
  2076. } else if ( euler.order === 'YXZ' ) {
  2077. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2078. te[ 0 ] = ce + df * b;
  2079. te[ 4 ] = de * b - cf;
  2080. te[ 8 ] = a * d;
  2081. te[ 1 ] = a * f;
  2082. te[ 5 ] = a * e;
  2083. te[ 9 ] = - b;
  2084. te[ 2 ] = cf * b - de;
  2085. te[ 6 ] = df + ce * b;
  2086. te[ 10 ] = a * c;
  2087. } else if ( euler.order === 'ZXY' ) {
  2088. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2089. te[ 0 ] = ce - df * b;
  2090. te[ 4 ] = - a * f;
  2091. te[ 8 ] = de + cf * b;
  2092. te[ 1 ] = cf + de * b;
  2093. te[ 5 ] = a * e;
  2094. te[ 9 ] = df - ce * b;
  2095. te[ 2 ] = - a * d;
  2096. te[ 6 ] = b;
  2097. te[ 10 ] = a * c;
  2098. } else if ( euler.order === 'ZYX' ) {
  2099. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2100. te[ 0 ] = c * e;
  2101. te[ 4 ] = be * d - af;
  2102. te[ 8 ] = ae * d + bf;
  2103. te[ 1 ] = c * f;
  2104. te[ 5 ] = bf * d + ae;
  2105. te[ 9 ] = af * d - be;
  2106. te[ 2 ] = - d;
  2107. te[ 6 ] = b * c;
  2108. te[ 10 ] = a * c;
  2109. } else if ( euler.order === 'YZX' ) {
  2110. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2111. te[ 0 ] = c * e;
  2112. te[ 4 ] = bd - ac * f;
  2113. te[ 8 ] = bc * f + ad;
  2114. te[ 1 ] = f;
  2115. te[ 5 ] = a * e;
  2116. te[ 9 ] = - b * e;
  2117. te[ 2 ] = - d * e;
  2118. te[ 6 ] = ad * f + bc;
  2119. te[ 10 ] = ac - bd * f;
  2120. } else if ( euler.order === 'XZY' ) {
  2121. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2122. te[ 0 ] = c * e;
  2123. te[ 4 ] = - f;
  2124. te[ 8 ] = d * e;
  2125. te[ 1 ] = ac * f + bd;
  2126. te[ 5 ] = a * e;
  2127. te[ 9 ] = ad * f - bc;
  2128. te[ 2 ] = bc * f - ad;
  2129. te[ 6 ] = b * e;
  2130. te[ 10 ] = bd * f + ac;
  2131. }
  2132. // last column
  2133. te[ 3 ] = 0;
  2134. te[ 7 ] = 0;
  2135. te[ 11 ] = 0;
  2136. // bottom row
  2137. te[ 12 ] = 0;
  2138. te[ 13 ] = 0;
  2139. te[ 14 ] = 0;
  2140. te[ 15 ] = 1;
  2141. return this;
  2142. },
  2143. makeRotationFromQuaternion: function ( q ) {
  2144. var te = this.elements;
  2145. var x = q._x, y = q._y, z = q._z, w = q._w;
  2146. var x2 = x + x, y2 = y + y, z2 = z + z;
  2147. var xx = x * x2, xy = x * y2, xz = x * z2;
  2148. var yy = y * y2, yz = y * z2, zz = z * z2;
  2149. var wx = w * x2, wy = w * y2, wz = w * z2;
  2150. te[ 0 ] = 1 - ( yy + zz );
  2151. te[ 4 ] = xy - wz;
  2152. te[ 8 ] = xz + wy;
  2153. te[ 1 ] = xy + wz;
  2154. te[ 5 ] = 1 - ( xx + zz );
  2155. te[ 9 ] = yz - wx;
  2156. te[ 2 ] = xz - wy;
  2157. te[ 6 ] = yz + wx;
  2158. te[ 10 ] = 1 - ( xx + yy );
  2159. // last column
  2160. te[ 3 ] = 0;
  2161. te[ 7 ] = 0;
  2162. te[ 11 ] = 0;
  2163. // bottom row
  2164. te[ 12 ] = 0;
  2165. te[ 13 ] = 0;
  2166. te[ 14 ] = 0;
  2167. te[ 15 ] = 1;
  2168. return this;
  2169. },
  2170. lookAt: function () {
  2171. var x = new Vector3();
  2172. var y = new Vector3();
  2173. var z = new Vector3();
  2174. return function lookAt( eye, target, up ) {
  2175. var te = this.elements;
  2176. z.subVectors( eye, target );
  2177. if ( z.lengthSq() === 0 ) {
  2178. // eye and target are in the same position
  2179. z.z = 1;
  2180. }
  2181. z.normalize();
  2182. x.crossVectors( up, z );
  2183. if ( x.lengthSq() === 0 ) {
  2184. // eye and target are in the same vertical
  2185. z.z += 0.0001;
  2186. x.crossVectors( up, z );
  2187. }
  2188. x.normalize();
  2189. y.crossVectors( z, x );
  2190. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2191. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2192. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2193. return this;
  2194. };
  2195. }(),
  2196. multiply: function ( m, n ) {
  2197. if ( n !== undefined ) {
  2198. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2199. return this.multiplyMatrices( m, n );
  2200. }
  2201. return this.multiplyMatrices( this, m );
  2202. },
  2203. premultiply: function ( m ) {
  2204. return this.multiplyMatrices( m, this );
  2205. },
  2206. multiplyMatrices: function ( a, b ) {
  2207. var ae = a.elements;
  2208. var be = b.elements;
  2209. var te = this.elements;
  2210. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2211. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2212. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2213. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2214. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2215. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2216. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2217. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2218. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2219. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2220. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2221. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2222. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2223. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2224. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2225. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2226. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2227. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2228. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2229. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2230. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2231. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2232. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2233. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2234. return this;
  2235. },
  2236. multiplyScalar: function ( s ) {
  2237. var te = this.elements;
  2238. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2239. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2240. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2241. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2242. return this;
  2243. },
  2244. applyToBufferAttribute: function () {
  2245. var v1 = new Vector3();
  2246. return function applyToBufferAttribute( attribute ) {
  2247. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2248. v1.x = attribute.getX( i );
  2249. v1.y = attribute.getY( i );
  2250. v1.z = attribute.getZ( i );
  2251. v1.applyMatrix4( this );
  2252. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2253. }
  2254. return attribute;
  2255. };
  2256. }(),
  2257. determinant: function () {
  2258. var te = this.elements;
  2259. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2260. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2261. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2262. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2263. //TODO: make this more efficient
  2264. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2265. return (
  2266. n41 * (
  2267. + n14 * n23 * n32
  2268. - n13 * n24 * n32
  2269. - n14 * n22 * n33
  2270. + n12 * n24 * n33
  2271. + n13 * n22 * n34
  2272. - n12 * n23 * n34
  2273. ) +
  2274. n42 * (
  2275. + n11 * n23 * n34
  2276. - n11 * n24 * n33
  2277. + n14 * n21 * n33
  2278. - n13 * n21 * n34
  2279. + n13 * n24 * n31
  2280. - n14 * n23 * n31
  2281. ) +
  2282. n43 * (
  2283. + n11 * n24 * n32
  2284. - n11 * n22 * n34
  2285. - n14 * n21 * n32
  2286. + n12 * n21 * n34
  2287. + n14 * n22 * n31
  2288. - n12 * n24 * n31
  2289. ) +
  2290. n44 * (
  2291. - n13 * n22 * n31
  2292. - n11 * n23 * n32
  2293. + n11 * n22 * n33
  2294. + n13 * n21 * n32
  2295. - n12 * n21 * n33
  2296. + n12 * n23 * n31
  2297. )
  2298. );
  2299. },
  2300. transpose: function () {
  2301. var te = this.elements;
  2302. var tmp;
  2303. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2304. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2305. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2306. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2307. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2308. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2309. return this;
  2310. },
  2311. setPosition: function ( v ) {
  2312. var te = this.elements;
  2313. te[ 12 ] = v.x;
  2314. te[ 13 ] = v.y;
  2315. te[ 14 ] = v.z;
  2316. return this;
  2317. },
  2318. getInverse: function ( m, throwOnDegenerate ) {
  2319. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2320. var te = this.elements,
  2321. me = m.elements,
  2322. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2323. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2324. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2325. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2326. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2327. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2328. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2329. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2330. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2331. if ( det === 0 ) {
  2332. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2333. if ( throwOnDegenerate === true ) {
  2334. throw new Error( msg );
  2335. } else {
  2336. console.warn( msg );
  2337. }
  2338. return this.identity();
  2339. }
  2340. var detInv = 1 / det;
  2341. te[ 0 ] = t11 * detInv;
  2342. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2343. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2344. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2345. te[ 4 ] = t12 * detInv;
  2346. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2347. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2348. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2349. te[ 8 ] = t13 * detInv;
  2350. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2351. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2352. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2353. te[ 12 ] = t14 * detInv;
  2354. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2355. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2356. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2357. return this;
  2358. },
  2359. scale: function ( v ) {
  2360. var te = this.elements;
  2361. var x = v.x, y = v.y, z = v.z;
  2362. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2363. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2364. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2365. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2366. return this;
  2367. },
  2368. getMaxScaleOnAxis: function () {
  2369. var te = this.elements;
  2370. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2371. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2372. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2373. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2374. },
  2375. makeTranslation: function ( x, y, z ) {
  2376. this.set(
  2377. 1, 0, 0, x,
  2378. 0, 1, 0, y,
  2379. 0, 0, 1, z,
  2380. 0, 0, 0, 1
  2381. );
  2382. return this;
  2383. },
  2384. makeRotationX: function ( theta ) {
  2385. var c = Math.cos( theta ), s = Math.sin( theta );
  2386. this.set(
  2387. 1, 0, 0, 0,
  2388. 0, c, - s, 0,
  2389. 0, s, c, 0,
  2390. 0, 0, 0, 1
  2391. );
  2392. return this;
  2393. },
  2394. makeRotationY: function ( theta ) {
  2395. var c = Math.cos( theta ), s = Math.sin( theta );
  2396. this.set(
  2397. c, 0, s, 0,
  2398. 0, 1, 0, 0,
  2399. - s, 0, c, 0,
  2400. 0, 0, 0, 1
  2401. );
  2402. return this;
  2403. },
  2404. makeRotationZ: function ( theta ) {
  2405. var c = Math.cos( theta ), s = Math.sin( theta );
  2406. this.set(
  2407. c, - s, 0, 0,
  2408. s, c, 0, 0,
  2409. 0, 0, 1, 0,
  2410. 0, 0, 0, 1
  2411. );
  2412. return this;
  2413. },
  2414. makeRotationAxis: function ( axis, angle ) {
  2415. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2416. var c = Math.cos( angle );
  2417. var s = Math.sin( angle );
  2418. var t = 1 - c;
  2419. var x = axis.x, y = axis.y, z = axis.z;
  2420. var tx = t * x, ty = t * y;
  2421. this.set(
  2422. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2423. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2424. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2425. 0, 0, 0, 1
  2426. );
  2427. return this;
  2428. },
  2429. makeScale: function ( x, y, z ) {
  2430. this.set(
  2431. x, 0, 0, 0,
  2432. 0, y, 0, 0,
  2433. 0, 0, z, 0,
  2434. 0, 0, 0, 1
  2435. );
  2436. return this;
  2437. },
  2438. makeShear: function ( x, y, z ) {
  2439. this.set(
  2440. 1, y, z, 0,
  2441. x, 1, z, 0,
  2442. x, y, 1, 0,
  2443. 0, 0, 0, 1
  2444. );
  2445. return this;
  2446. },
  2447. compose: function ( position, quaternion, scale ) {
  2448. this.makeRotationFromQuaternion( quaternion );
  2449. this.scale( scale );
  2450. this.setPosition( position );
  2451. return this;
  2452. },
  2453. decompose: function () {
  2454. var vector = new Vector3();
  2455. var matrix = new Matrix4();
  2456. return function decompose( position, quaternion, scale ) {
  2457. var te = this.elements;
  2458. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2459. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2460. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2461. // if determine is negative, we need to invert one scale
  2462. var det = this.determinant();
  2463. if ( det < 0 ) sx = - sx;
  2464. position.x = te[ 12 ];
  2465. position.y = te[ 13 ];
  2466. position.z = te[ 14 ];
  2467. // scale the rotation part
  2468. matrix.copy( this );
  2469. var invSX = 1 / sx;
  2470. var invSY = 1 / sy;
  2471. var invSZ = 1 / sz;
  2472. matrix.elements[ 0 ] *= invSX;
  2473. matrix.elements[ 1 ] *= invSX;
  2474. matrix.elements[ 2 ] *= invSX;
  2475. matrix.elements[ 4 ] *= invSY;
  2476. matrix.elements[ 5 ] *= invSY;
  2477. matrix.elements[ 6 ] *= invSY;
  2478. matrix.elements[ 8 ] *= invSZ;
  2479. matrix.elements[ 9 ] *= invSZ;
  2480. matrix.elements[ 10 ] *= invSZ;
  2481. quaternion.setFromRotationMatrix( matrix );
  2482. scale.x = sx;
  2483. scale.y = sy;
  2484. scale.z = sz;
  2485. return this;
  2486. };
  2487. }(),
  2488. makePerspective: function ( left, right, top, bottom, near, far ) {
  2489. if ( far === undefined ) {
  2490. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2491. }
  2492. var te = this.elements;
  2493. var x = 2 * near / ( right - left );
  2494. var y = 2 * near / ( top - bottom );
  2495. var a = ( right + left ) / ( right - left );
  2496. var b = ( top + bottom ) / ( top - bottom );
  2497. var c = - ( far + near ) / ( far - near );
  2498. var d = - 2 * far * near / ( far - near );
  2499. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2500. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2501. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2502. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2503. return this;
  2504. },
  2505. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2506. var te = this.elements;
  2507. var w = 1.0 / ( right - left );
  2508. var h = 1.0 / ( top - bottom );
  2509. var p = 1.0 / ( far - near );
  2510. var x = ( right + left ) * w;
  2511. var y = ( top + bottom ) * h;
  2512. var z = ( far + near ) * p;
  2513. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2514. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2515. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2516. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2517. return this;
  2518. },
  2519. equals: function ( matrix ) {
  2520. var te = this.elements;
  2521. var me = matrix.elements;
  2522. for ( var i = 0; i < 16; i ++ ) {
  2523. if ( te[ i ] !== me[ i ] ) return false;
  2524. }
  2525. return true;
  2526. },
  2527. fromArray: function ( array, offset ) {
  2528. if ( offset === undefined ) offset = 0;
  2529. for ( var i = 0; i < 16; i ++ ) {
  2530. this.elements[ i ] = array[ i + offset ];
  2531. }
  2532. return this;
  2533. },
  2534. toArray: function ( array, offset ) {
  2535. if ( array === undefined ) array = [];
  2536. if ( offset === undefined ) offset = 0;
  2537. var te = this.elements;
  2538. array[ offset ] = te[ 0 ];
  2539. array[ offset + 1 ] = te[ 1 ];
  2540. array[ offset + 2 ] = te[ 2 ];
  2541. array[ offset + 3 ] = te[ 3 ];
  2542. array[ offset + 4 ] = te[ 4 ];
  2543. array[ offset + 5 ] = te[ 5 ];
  2544. array[ offset + 6 ] = te[ 6 ];
  2545. array[ offset + 7 ] = te[ 7 ];
  2546. array[ offset + 8 ] = te[ 8 ];
  2547. array[ offset + 9 ] = te[ 9 ];
  2548. array[ offset + 10 ] = te[ 10 ];
  2549. array[ offset + 11 ] = te[ 11 ];
  2550. array[ offset + 12 ] = te[ 12 ];
  2551. array[ offset + 13 ] = te[ 13 ];
  2552. array[ offset + 14 ] = te[ 14 ];
  2553. array[ offset + 15 ] = te[ 15 ];
  2554. return array;
  2555. }
  2556. } );
  2557. /**
  2558. * @author alteredq / http://alteredqualia.com/
  2559. */
  2560. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2561. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2562. this.image = { data: data, width: width, height: height };
  2563. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2564. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2565. this.generateMipmaps = false;
  2566. this.flipY = false;
  2567. this.unpackAlignment = 1;
  2568. }
  2569. DataTexture.prototype = Object.create( Texture.prototype );
  2570. DataTexture.prototype.constructor = DataTexture;
  2571. DataTexture.prototype.isDataTexture = true;
  2572. /**
  2573. * @author mrdoob / http://mrdoob.com/
  2574. */
  2575. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2576. images = images !== undefined ? images : [];
  2577. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2578. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2579. this.flipY = false;
  2580. }
  2581. CubeTexture.prototype = Object.create( Texture.prototype );
  2582. CubeTexture.prototype.constructor = CubeTexture;
  2583. CubeTexture.prototype.isCubeTexture = true;
  2584. Object.defineProperty( CubeTexture.prototype, 'images', {
  2585. get: function () {
  2586. return this.image;
  2587. },
  2588. set: function ( value ) {
  2589. this.image = value;
  2590. }
  2591. } );
  2592. /**
  2593. * @author tschw
  2594. *
  2595. * Uniforms of a program.
  2596. * Those form a tree structure with a special top-level container for the root,
  2597. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2598. *
  2599. *
  2600. * Properties of inner nodes including the top-level container:
  2601. *
  2602. * .seq - array of nested uniforms
  2603. * .map - nested uniforms by name
  2604. *
  2605. *
  2606. * Methods of all nodes except the top-level container:
  2607. *
  2608. * .setValue( gl, value, [renderer] )
  2609. *
  2610. * uploads a uniform value(s)
  2611. * the 'renderer' parameter is needed for sampler uniforms
  2612. *
  2613. *
  2614. * Static methods of the top-level container (renderer factorizations):
  2615. *
  2616. * .upload( gl, seq, values, renderer )
  2617. *
  2618. * sets uniforms in 'seq' to 'values[id].value'
  2619. *
  2620. * .seqWithValue( seq, values ) : filteredSeq
  2621. *
  2622. * filters 'seq' entries with corresponding entry in values
  2623. *
  2624. *
  2625. * Methods of the top-level container (renderer factorizations):
  2626. *
  2627. * .setValue( gl, name, value )
  2628. *
  2629. * sets uniform with name 'name' to 'value'
  2630. *
  2631. * .set( gl, obj, prop )
  2632. *
  2633. * sets uniform from object and property with same name than uniform
  2634. *
  2635. * .setOptional( gl, obj, prop )
  2636. *
  2637. * like .set for an optional property of the object
  2638. *
  2639. */
  2640. var emptyTexture = new Texture();
  2641. var emptyCubeTexture = new CubeTexture();
  2642. // --- Base for inner nodes (including the root) ---
  2643. function UniformContainer() {
  2644. this.seq = [];
  2645. this.map = {};
  2646. }
  2647. // --- Utilities ---
  2648. // Array Caches (provide typed arrays for temporary by size)
  2649. var arrayCacheF32 = [];
  2650. var arrayCacheI32 = [];
  2651. // Float32Array caches used for uploading Matrix uniforms
  2652. var mat4array = new Float32Array( 16 );
  2653. var mat3array = new Float32Array( 9 );
  2654. // Flattening for arrays of vectors and matrices
  2655. function flatten( array, nBlocks, blockSize ) {
  2656. var firstElem = array[ 0 ];
  2657. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2658. // unoptimized: ! isNaN( firstElem )
  2659. // see http://jacksondunstan.com/articles/983
  2660. var n = nBlocks * blockSize,
  2661. r = arrayCacheF32[ n ];
  2662. if ( r === undefined ) {
  2663. r = new Float32Array( n );
  2664. arrayCacheF32[ n ] = r;
  2665. }
  2666. if ( nBlocks !== 0 ) {
  2667. firstElem.toArray( r, 0 );
  2668. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2669. offset += blockSize;
  2670. array[ i ].toArray( r, offset );
  2671. }
  2672. }
  2673. return r;
  2674. }
  2675. // Texture unit allocation
  2676. function allocTexUnits( renderer, n ) {
  2677. var r = arrayCacheI32[ n ];
  2678. if ( r === undefined ) {
  2679. r = new Int32Array( n );
  2680. arrayCacheI32[ n ] = r;
  2681. }
  2682. for ( var i = 0; i !== n; ++ i )
  2683. r[ i ] = renderer.allocTextureUnit();
  2684. return r;
  2685. }
  2686. // --- Setters ---
  2687. // Note: Defining these methods externally, because they come in a bunch
  2688. // and this way their names minify.
  2689. // Single scalar
  2690. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2691. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2692. // Single float vector (from flat array or THREE.VectorN)
  2693. function setValue2fv( gl, v ) {
  2694. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2695. else gl.uniform2f( this.addr, v.x, v.y );
  2696. }
  2697. function setValue3fv( gl, v ) {
  2698. if ( v.x !== undefined )
  2699. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2700. else if ( v.r !== undefined )
  2701. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2702. else
  2703. gl.uniform3fv( this.addr, v );
  2704. }
  2705. function setValue4fv( gl, v ) {
  2706. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2707. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2708. }
  2709. // Single matrix (from flat array or MatrixN)
  2710. function setValue2fm( gl, v ) {
  2711. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2712. }
  2713. function setValue3fm( gl, v ) {
  2714. if ( v.elements === undefined ) {
  2715. gl.uniformMatrix3fv( this.addr, false, v );
  2716. } else {
  2717. mat3array.set( v.elements );
  2718. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2719. }
  2720. }
  2721. function setValue4fm( gl, v ) {
  2722. if ( v.elements === undefined ) {
  2723. gl.uniformMatrix4fv( this.addr, false, v );
  2724. } else {
  2725. mat4array.set( v.elements );
  2726. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2727. }
  2728. }
  2729. // Single texture (2D / Cube)
  2730. function setValueT1( gl, v, renderer ) {
  2731. var unit = renderer.allocTextureUnit();
  2732. gl.uniform1i( this.addr, unit );
  2733. renderer.setTexture2D( v || emptyTexture, unit );
  2734. }
  2735. function setValueT6( gl, v, renderer ) {
  2736. var unit = renderer.allocTextureUnit();
  2737. gl.uniform1i( this.addr, unit );
  2738. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2739. }
  2740. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2741. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2742. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2743. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2744. // Helper to pick the right setter for the singular case
  2745. function getSingularSetter( type ) {
  2746. switch ( type ) {
  2747. case 0x1406: return setValue1f; // FLOAT
  2748. case 0x8b50: return setValue2fv; // _VEC2
  2749. case 0x8b51: return setValue3fv; // _VEC3
  2750. case 0x8b52: return setValue4fv; // _VEC4
  2751. case 0x8b5a: return setValue2fm; // _MAT2
  2752. case 0x8b5b: return setValue3fm; // _MAT3
  2753. case 0x8b5c: return setValue4fm; // _MAT4
  2754. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2755. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2756. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2757. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2758. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2759. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2760. }
  2761. }
  2762. // Array of scalars
  2763. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2764. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2765. // Array of vectors (flat or from THREE classes)
  2766. function setValueV2a( gl, v ) {
  2767. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2768. }
  2769. function setValueV3a( gl, v ) {
  2770. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2771. }
  2772. function setValueV4a( gl, v ) {
  2773. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2774. }
  2775. // Array of matrices (flat or from THREE clases)
  2776. function setValueM2a( gl, v ) {
  2777. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2778. }
  2779. function setValueM3a( gl, v ) {
  2780. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2781. }
  2782. function setValueM4a( gl, v ) {
  2783. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2784. }
  2785. // Array of textures (2D / Cube)
  2786. function setValueT1a( gl, v, renderer ) {
  2787. var n = v.length,
  2788. units = allocTexUnits( renderer, n );
  2789. gl.uniform1iv( this.addr, units );
  2790. for ( var i = 0; i !== n; ++ i ) {
  2791. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2792. }
  2793. }
  2794. function setValueT6a( gl, v, renderer ) {
  2795. var n = v.length,
  2796. units = allocTexUnits( renderer, n );
  2797. gl.uniform1iv( this.addr, units );
  2798. for ( var i = 0; i !== n; ++ i ) {
  2799. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2800. }
  2801. }
  2802. // Helper to pick the right setter for a pure (bottom-level) array
  2803. function getPureArraySetter( type ) {
  2804. switch ( type ) {
  2805. case 0x1406: return setValue1fv; // FLOAT
  2806. case 0x8b50: return setValueV2a; // _VEC2
  2807. case 0x8b51: return setValueV3a; // _VEC3
  2808. case 0x8b52: return setValueV4a; // _VEC4
  2809. case 0x8b5a: return setValueM2a; // _MAT2
  2810. case 0x8b5b: return setValueM3a; // _MAT3
  2811. case 0x8b5c: return setValueM4a; // _MAT4
  2812. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2813. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2814. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2815. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2816. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2817. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2818. }
  2819. }
  2820. // --- Uniform Classes ---
  2821. function SingleUniform( id, activeInfo, addr ) {
  2822. this.id = id;
  2823. this.addr = addr;
  2824. this.setValue = getSingularSetter( activeInfo.type );
  2825. // this.path = activeInfo.name; // DEBUG
  2826. }
  2827. function PureArrayUniform( id, activeInfo, addr ) {
  2828. this.id = id;
  2829. this.addr = addr;
  2830. this.size = activeInfo.size;
  2831. this.setValue = getPureArraySetter( activeInfo.type );
  2832. // this.path = activeInfo.name; // DEBUG
  2833. }
  2834. function StructuredUniform( id ) {
  2835. this.id = id;
  2836. UniformContainer.call( this ); // mix-in
  2837. }
  2838. StructuredUniform.prototype.setValue = function ( gl, value ) {
  2839. // Note: Don't need an extra 'renderer' parameter, since samplers
  2840. // are not allowed in structured uniforms.
  2841. var seq = this.seq;
  2842. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2843. var u = seq[ i ];
  2844. u.setValue( gl, value[ u.id ] );
  2845. }
  2846. };
  2847. // --- Top-level ---
  2848. // Parser - builds up the property tree from the path strings
  2849. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2850. // extracts
  2851. // - the identifier (member name or array index)
  2852. // - followed by an optional right bracket (found when array index)
  2853. // - followed by an optional left bracket or dot (type of subscript)
  2854. //
  2855. // Note: These portions can be read in a non-overlapping fashion and
  2856. // allow straightforward parsing of the hierarchy that WebGL encodes
  2857. // in the uniform names.
  2858. function addUniform( container, uniformObject ) {
  2859. container.seq.push( uniformObject );
  2860. container.map[ uniformObject.id ] = uniformObject;
  2861. }
  2862. function parseUniform( activeInfo, addr, container ) {
  2863. var path = activeInfo.name,
  2864. pathLength = path.length;
  2865. // reset RegExp object, because of the early exit of a previous run
  2866. RePathPart.lastIndex = 0;
  2867. for ( ; ; ) {
  2868. var match = RePathPart.exec( path ),
  2869. matchEnd = RePathPart.lastIndex,
  2870. id = match[ 1 ],
  2871. idIsIndex = match[ 2 ] === ']',
  2872. subscript = match[ 3 ];
  2873. if ( idIsIndex ) id = id | 0; // convert to integer
  2874. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  2875. // bare name or "pure" bottom-level array "[0]" suffix
  2876. addUniform( container, subscript === undefined ?
  2877. new SingleUniform( id, activeInfo, addr ) :
  2878. new PureArrayUniform( id, activeInfo, addr ) );
  2879. break;
  2880. } else {
  2881. // step into inner node / create it in case it doesn't exist
  2882. var map = container.map, next = map[ id ];
  2883. if ( next === undefined ) {
  2884. next = new StructuredUniform( id );
  2885. addUniform( container, next );
  2886. }
  2887. container = next;
  2888. }
  2889. }
  2890. }
  2891. // Root Container
  2892. function WebGLUniforms( gl, program, renderer ) {
  2893. UniformContainer.call( this );
  2894. this.renderer = renderer;
  2895. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2896. for ( var i = 0; i < n; ++ i ) {
  2897. var info = gl.getActiveUniform( program, i ),
  2898. path = info.name,
  2899. addr = gl.getUniformLocation( program, path );
  2900. parseUniform( info, addr, this );
  2901. }
  2902. }
  2903. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  2904. var u = this.map[ name ];
  2905. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2906. };
  2907. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  2908. var v = object[ name ];
  2909. if ( v !== undefined ) this.setValue( gl, name, v );
  2910. };
  2911. // Static interface
  2912. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  2913. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2914. var u = seq[ i ],
  2915. v = values[ u.id ];
  2916. if ( v.needsUpdate !== false ) {
  2917. // note: always updating when .needsUpdate is undefined
  2918. u.setValue( gl, v.value, renderer );
  2919. }
  2920. }
  2921. };
  2922. WebGLUniforms.seqWithValue = function ( seq, values ) {
  2923. var r = [];
  2924. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2925. var u = seq[ i ];
  2926. if ( u.id in values ) r.push( u );
  2927. }
  2928. return r;
  2929. };
  2930. /**
  2931. * @author mrdoob / http://mrdoob.com/
  2932. */
  2933. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  2934. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  2935. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  2936. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  2937. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  2938. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  2939. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  2940. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  2941. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  2942. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  2943. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  2944. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  2945. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  2946. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  2947. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  2948. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  2949. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  2950. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  2951. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  2952. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  2953. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  2954. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  2955. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  2956. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  2957. function Color( r, g, b ) {
  2958. if ( g === undefined && b === undefined ) {
  2959. // r is THREE.Color, hex or string
  2960. return this.set( r );
  2961. }
  2962. return this.setRGB( r, g, b );
  2963. }
  2964. Object.assign( Color.prototype, {
  2965. isColor: true,
  2966. r: 1, g: 1, b: 1,
  2967. set: function ( value ) {
  2968. if ( value && value.isColor ) {
  2969. this.copy( value );
  2970. } else if ( typeof value === 'number' ) {
  2971. this.setHex( value );
  2972. } else if ( typeof value === 'string' ) {
  2973. this.setStyle( value );
  2974. }
  2975. return this;
  2976. },
  2977. setScalar: function ( scalar ) {
  2978. this.r = scalar;
  2979. this.g = scalar;
  2980. this.b = scalar;
  2981. return this;
  2982. },
  2983. setHex: function ( hex ) {
  2984. hex = Math.floor( hex );
  2985. this.r = ( hex >> 16 & 255 ) / 255;
  2986. this.g = ( hex >> 8 & 255 ) / 255;
  2987. this.b = ( hex & 255 ) / 255;
  2988. return this;
  2989. },
  2990. setRGB: function ( r, g, b ) {
  2991. this.r = r;
  2992. this.g = g;
  2993. this.b = b;
  2994. return this;
  2995. },
  2996. setHSL: function () {
  2997. function hue2rgb( p, q, t ) {
  2998. if ( t < 0 ) t += 1;
  2999. if ( t > 1 ) t -= 1;
  3000. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3001. if ( t < 1 / 2 ) return q;
  3002. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3003. return p;
  3004. }
  3005. return function setHSL( h, s, l ) {
  3006. // h,s,l ranges are in 0.0 - 1.0
  3007. h = _Math.euclideanModulo( h, 1 );
  3008. s = _Math.clamp( s, 0, 1 );
  3009. l = _Math.clamp( l, 0, 1 );
  3010. if ( s === 0 ) {
  3011. this.r = this.g = this.b = l;
  3012. } else {
  3013. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3014. var q = ( 2 * l ) - p;
  3015. this.r = hue2rgb( q, p, h + 1 / 3 );
  3016. this.g = hue2rgb( q, p, h );
  3017. this.b = hue2rgb( q, p, h - 1 / 3 );
  3018. }
  3019. return this;
  3020. };
  3021. }(),
  3022. setStyle: function ( style ) {
  3023. function handleAlpha( string ) {
  3024. if ( string === undefined ) return;
  3025. if ( parseFloat( string ) < 1 ) {
  3026. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3027. }
  3028. }
  3029. var m;
  3030. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3031. // rgb / hsl
  3032. var color;
  3033. var name = m[ 1 ];
  3034. var components = m[ 2 ];
  3035. switch ( name ) {
  3036. case 'rgb':
  3037. case 'rgba':
  3038. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3039. // rgb(255,0,0) rgba(255,0,0,0.5)
  3040. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3041. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3042. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3043. handleAlpha( color[ 5 ] );
  3044. return this;
  3045. }
  3046. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3047. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3048. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3049. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3050. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3051. handleAlpha( color[ 5 ] );
  3052. return this;
  3053. }
  3054. break;
  3055. case 'hsl':
  3056. case 'hsla':
  3057. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3058. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3059. var h = parseFloat( color[ 1 ] ) / 360;
  3060. var s = parseInt( color[ 2 ], 10 ) / 100;
  3061. var l = parseInt( color[ 3 ], 10 ) / 100;
  3062. handleAlpha( color[ 5 ] );
  3063. return this.setHSL( h, s, l );
  3064. }
  3065. break;
  3066. }
  3067. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3068. // hex color
  3069. var hex = m[ 1 ];
  3070. var size = hex.length;
  3071. if ( size === 3 ) {
  3072. // #ff0
  3073. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3074. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3075. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3076. return this;
  3077. } else if ( size === 6 ) {
  3078. // #ff0000
  3079. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3080. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3081. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3082. return this;
  3083. }
  3084. }
  3085. if ( style && style.length > 0 ) {
  3086. // color keywords
  3087. var hex = ColorKeywords[ style ];
  3088. if ( hex !== undefined ) {
  3089. // red
  3090. this.setHex( hex );
  3091. } else {
  3092. // unknown color
  3093. console.warn( 'THREE.Color: Unknown color ' + style );
  3094. }
  3095. }
  3096. return this;
  3097. },
  3098. clone: function () {
  3099. return new this.constructor( this.r, this.g, this.b );
  3100. },
  3101. copy: function ( color ) {
  3102. this.r = color.r;
  3103. this.g = color.g;
  3104. this.b = color.b;
  3105. return this;
  3106. },
  3107. copyGammaToLinear: function ( color, gammaFactor ) {
  3108. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3109. this.r = Math.pow( color.r, gammaFactor );
  3110. this.g = Math.pow( color.g, gammaFactor );
  3111. this.b = Math.pow( color.b, gammaFactor );
  3112. return this;
  3113. },
  3114. copyLinearToGamma: function ( color, gammaFactor ) {
  3115. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3116. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3117. this.r = Math.pow( color.r, safeInverse );
  3118. this.g = Math.pow( color.g, safeInverse );
  3119. this.b = Math.pow( color.b, safeInverse );
  3120. return this;
  3121. },
  3122. convertGammaToLinear: function () {
  3123. var r = this.r, g = this.g, b = this.b;
  3124. this.r = r * r;
  3125. this.g = g * g;
  3126. this.b = b * b;
  3127. return this;
  3128. },
  3129. convertLinearToGamma: function () {
  3130. this.r = Math.sqrt( this.r );
  3131. this.g = Math.sqrt( this.g );
  3132. this.b = Math.sqrt( this.b );
  3133. return this;
  3134. },
  3135. getHex: function () {
  3136. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3137. },
  3138. getHexString: function () {
  3139. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3140. },
  3141. getHSL: function ( optionalTarget ) {
  3142. // h,s,l ranges are in 0.0 - 1.0
  3143. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3144. var r = this.r, g = this.g, b = this.b;
  3145. var max = Math.max( r, g, b );
  3146. var min = Math.min( r, g, b );
  3147. var hue, saturation;
  3148. var lightness = ( min + max ) / 2.0;
  3149. if ( min === max ) {
  3150. hue = 0;
  3151. saturation = 0;
  3152. } else {
  3153. var delta = max - min;
  3154. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3155. switch ( max ) {
  3156. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3157. case g: hue = ( b - r ) / delta + 2; break;
  3158. case b: hue = ( r - g ) / delta + 4; break;
  3159. }
  3160. hue /= 6;
  3161. }
  3162. hsl.h = hue;
  3163. hsl.s = saturation;
  3164. hsl.l = lightness;
  3165. return hsl;
  3166. },
  3167. getStyle: function () {
  3168. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3169. },
  3170. offsetHSL: function ( h, s, l ) {
  3171. var hsl = this.getHSL();
  3172. hsl.h += h; hsl.s += s; hsl.l += l;
  3173. this.setHSL( hsl.h, hsl.s, hsl.l );
  3174. return this;
  3175. },
  3176. add: function ( color ) {
  3177. this.r += color.r;
  3178. this.g += color.g;
  3179. this.b += color.b;
  3180. return this;
  3181. },
  3182. addColors: function ( color1, color2 ) {
  3183. this.r = color1.r + color2.r;
  3184. this.g = color1.g + color2.g;
  3185. this.b = color1.b + color2.b;
  3186. return this;
  3187. },
  3188. addScalar: function ( s ) {
  3189. this.r += s;
  3190. this.g += s;
  3191. this.b += s;
  3192. return this;
  3193. },
  3194. sub: function( color ) {
  3195. this.r = Math.max( 0, this.r - color.r );
  3196. this.g = Math.max( 0, this.g - color.g );
  3197. this.b = Math.max( 0, this.b - color.b );
  3198. return this;
  3199. },
  3200. multiply: function ( color ) {
  3201. this.r *= color.r;
  3202. this.g *= color.g;
  3203. this.b *= color.b;
  3204. return this;
  3205. },
  3206. multiplyScalar: function ( s ) {
  3207. this.r *= s;
  3208. this.g *= s;
  3209. this.b *= s;
  3210. return this;
  3211. },
  3212. lerp: function ( color, alpha ) {
  3213. this.r += ( color.r - this.r ) * alpha;
  3214. this.g += ( color.g - this.g ) * alpha;
  3215. this.b += ( color.b - this.b ) * alpha;
  3216. return this;
  3217. },
  3218. equals: function ( c ) {
  3219. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3220. },
  3221. fromArray: function ( array, offset ) {
  3222. if ( offset === undefined ) offset = 0;
  3223. this.r = array[ offset ];
  3224. this.g = array[ offset + 1 ];
  3225. this.b = array[ offset + 2 ];
  3226. return this;
  3227. },
  3228. toArray: function ( array, offset ) {
  3229. if ( array === undefined ) array = [];
  3230. if ( offset === undefined ) offset = 0;
  3231. array[ offset ] = this.r;
  3232. array[ offset + 1 ] = this.g;
  3233. array[ offset + 2 ] = this.b;
  3234. return array;
  3235. },
  3236. toJSON: function () {
  3237. return this.getHex();
  3238. }
  3239. } );
  3240. /**
  3241. * Uniforms library for shared webgl shaders
  3242. */
  3243. var UniformsLib = {
  3244. common: {
  3245. diffuse: { value: new Color( 0xeeeeee ) },
  3246. opacity: { value: 1.0 },
  3247. map: { value: null },
  3248. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3249. specularMap: { value: null },
  3250. alphaMap: { value: null },
  3251. envMap: { value: null },
  3252. flipEnvMap: { value: - 1 },
  3253. reflectivity: { value: 1.0 },
  3254. refractionRatio: { value: 0.98 }
  3255. },
  3256. aomap: {
  3257. aoMap: { value: null },
  3258. aoMapIntensity: { value: 1 }
  3259. },
  3260. lightmap: {
  3261. lightMap: { value: null },
  3262. lightMapIntensity: { value: 1 }
  3263. },
  3264. emissivemap: {
  3265. emissiveMap: { value: null }
  3266. },
  3267. bumpmap: {
  3268. bumpMap: { value: null },
  3269. bumpScale: { value: 1 }
  3270. },
  3271. normalmap: {
  3272. normalMap: { value: null },
  3273. normalScale: { value: new Vector2( 1, 1 ) }
  3274. },
  3275. displacementmap: {
  3276. displacementMap: { value: null },
  3277. displacementScale: { value: 1 },
  3278. displacementBias: { value: 0 }
  3279. },
  3280. roughnessmap: {
  3281. roughnessMap: { value: null }
  3282. },
  3283. metalnessmap: {
  3284. metalnessMap: { value: null }
  3285. },
  3286. gradientmap: {
  3287. gradientMap: { value: null }
  3288. },
  3289. fog: {
  3290. fogDensity: { value: 0.00025 },
  3291. fogNear: { value: 1 },
  3292. fogFar: { value: 2000 },
  3293. fogColor: { value: new Color( 0xffffff ) }
  3294. },
  3295. lights: {
  3296. ambientLightColor: { value: [] },
  3297. directionalLights: { value: [], properties: {
  3298. direction: {},
  3299. color: {},
  3300. shadow: {},
  3301. shadowBias: {},
  3302. shadowRadius: {},
  3303. shadowMapSize: {}
  3304. } },
  3305. directionalShadowMap: { value: [] },
  3306. directionalShadowMatrix: { value: [] },
  3307. spotLights: { value: [], properties: {
  3308. color: {},
  3309. position: {},
  3310. direction: {},
  3311. distance: {},
  3312. coneCos: {},
  3313. penumbraCos: {},
  3314. decay: {},
  3315. shadow: {},
  3316. shadowBias: {},
  3317. shadowRadius: {},
  3318. shadowMapSize: {}
  3319. } },
  3320. spotShadowMap: { value: [] },
  3321. spotShadowMatrix: { value: [] },
  3322. pointLights: { value: [], properties: {
  3323. color: {},
  3324. position: {},
  3325. decay: {},
  3326. distance: {},
  3327. shadow: {},
  3328. shadowBias: {},
  3329. shadowRadius: {},
  3330. shadowMapSize: {}
  3331. } },
  3332. pointShadowMap: { value: [] },
  3333. pointShadowMatrix: { value: [] },
  3334. hemisphereLights: { value: [], properties: {
  3335. direction: {},
  3336. skyColor: {},
  3337. groundColor: {}
  3338. } },
  3339. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3340. rectAreaLights: { value: [], properties: {
  3341. color: {},
  3342. position: {},
  3343. width: {},
  3344. height: {}
  3345. } }
  3346. },
  3347. points: {
  3348. diffuse: { value: new Color( 0xeeeeee ) },
  3349. opacity: { value: 1.0 },
  3350. size: { value: 1.0 },
  3351. scale: { value: 1.0 },
  3352. map: { value: null },
  3353. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3354. }
  3355. };
  3356. /**
  3357. * Uniform Utilities
  3358. */
  3359. var UniformsUtils = {
  3360. merge: function ( uniforms ) {
  3361. var merged = {};
  3362. for ( var u = 0; u < uniforms.length; u ++ ) {
  3363. var tmp = this.clone( uniforms[ u ] );
  3364. for ( var p in tmp ) {
  3365. merged[ p ] = tmp[ p ];
  3366. }
  3367. }
  3368. return merged;
  3369. },
  3370. clone: function ( uniforms_src ) {
  3371. var uniforms_dst = {};
  3372. for ( var u in uniforms_src ) {
  3373. uniforms_dst[ u ] = {};
  3374. for ( var p in uniforms_src[ u ] ) {
  3375. var parameter_src = uniforms_src[ u ][ p ];
  3376. if ( parameter_src && ( parameter_src.isColor ||
  3377. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3378. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3379. parameter_src.isTexture ) ) {
  3380. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3381. } else if ( Array.isArray( parameter_src ) ) {
  3382. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3383. } else {
  3384. uniforms_dst[ u ][ p ] = parameter_src;
  3385. }
  3386. }
  3387. }
  3388. return uniforms_dst;
  3389. }
  3390. };
  3391. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3392. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3393. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3394. 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";
  3395. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3396. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3397. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3398. 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";
  3399. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  3400. 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";
  3401. 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";
  3402. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3403. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3404. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3405. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3406. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3407. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3408. 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";
  3409. 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";
  3410. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3411. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3412. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3413. 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";
  3414. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3415. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3416. 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";
  3417. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  3418. 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";
  3419. 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";
  3420. 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";
  3421. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3422. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3423. 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";
  3424. 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";
  3425. 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";
  3426. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3427. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3428. 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";
  3429. 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";
  3430. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3431. 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";
  3432. 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";
  3433. 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";
  3434. 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";
  3435. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3436. 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";
  3437. 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";
  3438. 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";
  3439. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3440. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3441. 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";
  3442. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3443. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3444. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3445. 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";
  3446. 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";
  3447. 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";
  3448. 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";
  3449. 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";
  3450. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3451. 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";
  3452. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3453. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  3454. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3455. 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";
  3456. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3457. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3458. 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\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3459. 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";
  3460. 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";
  3461. 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";
  3462. 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";
  3463. 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";
  3464. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  3465. 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";
  3466. 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";
  3467. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3468. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3469. 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";
  3470. 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";
  3471. 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";
  3472. 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";
  3473. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3474. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3475. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3476. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  3477. 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";
  3478. 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";
  3479. 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";
  3480. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3481. 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";
  3482. 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";
  3483. 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";
  3484. 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";
  3485. 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";
  3486. 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";
  3487. 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";
  3488. 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";
  3489. 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";
  3490. 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";
  3491. 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";
  3492. 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 <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3493. 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";
  3494. 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 <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3495. 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";
  3496. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3497. 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";
  3498. 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";
  3499. 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";
  3500. 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";
  3501. var ShaderChunk = {
  3502. alphamap_fragment: alphamap_fragment,
  3503. alphamap_pars_fragment: alphamap_pars_fragment,
  3504. alphatest_fragment: alphatest_fragment,
  3505. aomap_fragment: aomap_fragment,
  3506. aomap_pars_fragment: aomap_pars_fragment,
  3507. begin_vertex: begin_vertex,
  3508. beginnormal_vertex: beginnormal_vertex,
  3509. bsdfs: bsdfs,
  3510. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3511. clipping_planes_fragment: clipping_planes_fragment,
  3512. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3513. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3514. clipping_planes_vertex: clipping_planes_vertex,
  3515. color_fragment: color_fragment,
  3516. color_pars_fragment: color_pars_fragment,
  3517. color_pars_vertex: color_pars_vertex,
  3518. color_vertex: color_vertex,
  3519. common: common,
  3520. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3521. defaultnormal_vertex: defaultnormal_vertex,
  3522. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3523. displacementmap_vertex: displacementmap_vertex,
  3524. emissivemap_fragment: emissivemap_fragment,
  3525. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3526. encodings_fragment: encodings_fragment,
  3527. encodings_pars_fragment: encodings_pars_fragment,
  3528. envmap_fragment: envmap_fragment,
  3529. envmap_pars_fragment: envmap_pars_fragment,
  3530. envmap_pars_vertex: envmap_pars_vertex,
  3531. envmap_vertex: envmap_vertex,
  3532. fog_vertex: fog_vertex,
  3533. fog_pars_vertex: fog_pars_vertex,
  3534. fog_fragment: fog_fragment,
  3535. fog_pars_fragment: fog_pars_fragment,
  3536. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3537. lightmap_fragment: lightmap_fragment,
  3538. lightmap_pars_fragment: lightmap_pars_fragment,
  3539. lights_lambert_vertex: lights_lambert_vertex,
  3540. lights_pars: lights_pars,
  3541. lights_phong_fragment: lights_phong_fragment,
  3542. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3543. lights_physical_fragment: lights_physical_fragment,
  3544. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3545. lights_template: lights_template,
  3546. logdepthbuf_fragment: logdepthbuf_fragment,
  3547. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3548. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3549. logdepthbuf_vertex: logdepthbuf_vertex,
  3550. map_fragment: map_fragment,
  3551. map_pars_fragment: map_pars_fragment,
  3552. map_particle_fragment: map_particle_fragment,
  3553. map_particle_pars_fragment: map_particle_pars_fragment,
  3554. metalnessmap_fragment: metalnessmap_fragment,
  3555. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3556. morphnormal_vertex: morphnormal_vertex,
  3557. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3558. morphtarget_vertex: morphtarget_vertex,
  3559. normal_flip: normal_flip,
  3560. normal_fragment: normal_fragment,
  3561. normalmap_pars_fragment: normalmap_pars_fragment,
  3562. packing: packing,
  3563. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3564. project_vertex: project_vertex,
  3565. dithering_fragment: dithering_fragment,
  3566. dithering_pars_fragment: dithering_pars_fragment,
  3567. roughnessmap_fragment: roughnessmap_fragment,
  3568. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3569. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3570. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3571. shadowmap_vertex: shadowmap_vertex,
  3572. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3573. skinbase_vertex: skinbase_vertex,
  3574. skinning_pars_vertex: skinning_pars_vertex,
  3575. skinning_vertex: skinning_vertex,
  3576. skinnormal_vertex: skinnormal_vertex,
  3577. specularmap_fragment: specularmap_fragment,
  3578. specularmap_pars_fragment: specularmap_pars_fragment,
  3579. tonemapping_fragment: tonemapping_fragment,
  3580. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3581. uv_pars_fragment: uv_pars_fragment,
  3582. uv_pars_vertex: uv_pars_vertex,
  3583. uv_vertex: uv_vertex,
  3584. uv2_pars_fragment: uv2_pars_fragment,
  3585. uv2_pars_vertex: uv2_pars_vertex,
  3586. uv2_vertex: uv2_vertex,
  3587. worldpos_vertex: worldpos_vertex,
  3588. cube_frag: cube_frag,
  3589. cube_vert: cube_vert,
  3590. depth_frag: depth_frag,
  3591. depth_vert: depth_vert,
  3592. distanceRGBA_frag: distanceRGBA_frag,
  3593. distanceRGBA_vert: distanceRGBA_vert,
  3594. equirect_frag: equirect_frag,
  3595. equirect_vert: equirect_vert,
  3596. linedashed_frag: linedashed_frag,
  3597. linedashed_vert: linedashed_vert,
  3598. meshbasic_frag: meshbasic_frag,
  3599. meshbasic_vert: meshbasic_vert,
  3600. meshlambert_frag: meshlambert_frag,
  3601. meshlambert_vert: meshlambert_vert,
  3602. meshphong_frag: meshphong_frag,
  3603. meshphong_vert: meshphong_vert,
  3604. meshphysical_frag: meshphysical_frag,
  3605. meshphysical_vert: meshphysical_vert,
  3606. normal_frag: normal_frag,
  3607. normal_vert: normal_vert,
  3608. points_frag: points_frag,
  3609. points_vert: points_vert,
  3610. shadow_frag: shadow_frag,
  3611. shadow_vert: shadow_vert
  3612. };
  3613. /**
  3614. * @author alteredq / http://alteredqualia.com/
  3615. * @author mrdoob / http://mrdoob.com/
  3616. * @author mikael emtinger / http://gomo.se/
  3617. */
  3618. var ShaderLib = {
  3619. basic: {
  3620. uniforms: UniformsUtils.merge( [
  3621. UniformsLib.common,
  3622. UniformsLib.aomap,
  3623. UniformsLib.lightmap,
  3624. UniformsLib.fog
  3625. ] ),
  3626. vertexShader: ShaderChunk.meshbasic_vert,
  3627. fragmentShader: ShaderChunk.meshbasic_frag
  3628. },
  3629. lambert: {
  3630. uniforms: UniformsUtils.merge( [
  3631. UniformsLib.common,
  3632. UniformsLib.aomap,
  3633. UniformsLib.lightmap,
  3634. UniformsLib.emissivemap,
  3635. UniformsLib.fog,
  3636. UniformsLib.lights,
  3637. {
  3638. emissive: { value: new Color( 0x000000 ) }
  3639. }
  3640. ] ),
  3641. vertexShader: ShaderChunk.meshlambert_vert,
  3642. fragmentShader: ShaderChunk.meshlambert_frag
  3643. },
  3644. phong: {
  3645. uniforms: UniformsUtils.merge( [
  3646. UniformsLib.common,
  3647. UniformsLib.aomap,
  3648. UniformsLib.lightmap,
  3649. UniformsLib.emissivemap,
  3650. UniformsLib.bumpmap,
  3651. UniformsLib.normalmap,
  3652. UniformsLib.displacementmap,
  3653. UniformsLib.gradientmap,
  3654. UniformsLib.fog,
  3655. UniformsLib.lights,
  3656. {
  3657. emissive: { value: new Color( 0x000000 ) },
  3658. specular: { value: new Color( 0x111111 ) },
  3659. shininess: { value: 30 }
  3660. }
  3661. ] ),
  3662. vertexShader: ShaderChunk.meshphong_vert,
  3663. fragmentShader: ShaderChunk.meshphong_frag
  3664. },
  3665. standard: {
  3666. uniforms: UniformsUtils.merge( [
  3667. UniformsLib.common,
  3668. UniformsLib.aomap,
  3669. UniformsLib.lightmap,
  3670. UniformsLib.emissivemap,
  3671. UniformsLib.bumpmap,
  3672. UniformsLib.normalmap,
  3673. UniformsLib.displacementmap,
  3674. UniformsLib.roughnessmap,
  3675. UniformsLib.metalnessmap,
  3676. UniformsLib.fog,
  3677. UniformsLib.lights,
  3678. {
  3679. emissive: { value: new Color( 0x000000 ) },
  3680. roughness: { value: 0.5 },
  3681. metalness: { value: 0.5 },
  3682. envMapIntensity: { value: 1 } // temporary
  3683. }
  3684. ] ),
  3685. vertexShader: ShaderChunk.meshphysical_vert,
  3686. fragmentShader: ShaderChunk.meshphysical_frag
  3687. },
  3688. points: {
  3689. uniforms: UniformsUtils.merge( [
  3690. UniformsLib.points,
  3691. UniformsLib.fog
  3692. ] ),
  3693. vertexShader: ShaderChunk.points_vert,
  3694. fragmentShader: ShaderChunk.points_frag
  3695. },
  3696. dashed: {
  3697. uniforms: UniformsUtils.merge( [
  3698. UniformsLib.common,
  3699. UniformsLib.fog,
  3700. {
  3701. scale: { value: 1 },
  3702. dashSize: { value: 1 },
  3703. totalSize: { value: 2 }
  3704. }
  3705. ] ),
  3706. vertexShader: ShaderChunk.linedashed_vert,
  3707. fragmentShader: ShaderChunk.linedashed_frag
  3708. },
  3709. depth: {
  3710. uniforms: UniformsUtils.merge( [
  3711. UniformsLib.common,
  3712. UniformsLib.displacementmap
  3713. ] ),
  3714. vertexShader: ShaderChunk.depth_vert,
  3715. fragmentShader: ShaderChunk.depth_frag
  3716. },
  3717. normal: {
  3718. uniforms: UniformsUtils.merge( [
  3719. UniformsLib.common,
  3720. UniformsLib.bumpmap,
  3721. UniformsLib.normalmap,
  3722. UniformsLib.displacementmap,
  3723. {
  3724. opacity: { value: 1.0 }
  3725. }
  3726. ] ),
  3727. vertexShader: ShaderChunk.normal_vert,
  3728. fragmentShader: ShaderChunk.normal_frag
  3729. },
  3730. /* -------------------------------------------------------------------------
  3731. // Cube map shader
  3732. ------------------------------------------------------------------------- */
  3733. cube: {
  3734. uniforms: {
  3735. tCube: { value: null },
  3736. tFlip: { value: - 1 },
  3737. opacity: { value: 1.0 }
  3738. },
  3739. vertexShader: ShaderChunk.cube_vert,
  3740. fragmentShader: ShaderChunk.cube_frag
  3741. },
  3742. /* -------------------------------------------------------------------------
  3743. // Cube map shader
  3744. ------------------------------------------------------------------------- */
  3745. equirect: {
  3746. uniforms: {
  3747. tEquirect: { value: null },
  3748. tFlip: { value: - 1 }
  3749. },
  3750. vertexShader: ShaderChunk.equirect_vert,
  3751. fragmentShader: ShaderChunk.equirect_frag
  3752. },
  3753. distanceRGBA: {
  3754. uniforms: {
  3755. lightPos: { value: new Vector3() }
  3756. },
  3757. vertexShader: ShaderChunk.distanceRGBA_vert,
  3758. fragmentShader: ShaderChunk.distanceRGBA_frag
  3759. }
  3760. };
  3761. ShaderLib.physical = {
  3762. uniforms: UniformsUtils.merge( [
  3763. ShaderLib.standard.uniforms,
  3764. {
  3765. clearCoat: { value: 0 },
  3766. clearCoatRoughness: { value: 0 }
  3767. }
  3768. ] ),
  3769. vertexShader: ShaderChunk.meshphysical_vert,
  3770. fragmentShader: ShaderChunk.meshphysical_frag
  3771. };
  3772. /**
  3773. * @author bhouston / http://clara.io
  3774. */
  3775. function Box2( min, max ) {
  3776. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3777. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3778. }
  3779. Object.assign( Box2.prototype, {
  3780. set: function ( min, max ) {
  3781. this.min.copy( min );
  3782. this.max.copy( max );
  3783. return this;
  3784. },
  3785. setFromPoints: function ( points ) {
  3786. this.makeEmpty();
  3787. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3788. this.expandByPoint( points[ i ] );
  3789. }
  3790. return this;
  3791. },
  3792. setFromCenterAndSize: function () {
  3793. var v1 = new Vector2();
  3794. return function setFromCenterAndSize( center, size ) {
  3795. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3796. this.min.copy( center ).sub( halfSize );
  3797. this.max.copy( center ).add( halfSize );
  3798. return this;
  3799. };
  3800. }(),
  3801. clone: function () {
  3802. return new this.constructor().copy( this );
  3803. },
  3804. copy: function ( box ) {
  3805. this.min.copy( box.min );
  3806. this.max.copy( box.max );
  3807. return this;
  3808. },
  3809. makeEmpty: function () {
  3810. this.min.x = this.min.y = + Infinity;
  3811. this.max.x = this.max.y = - Infinity;
  3812. return this;
  3813. },
  3814. isEmpty: function () {
  3815. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3816. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3817. },
  3818. getCenter: function ( optionalTarget ) {
  3819. var result = optionalTarget || new Vector2();
  3820. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3821. },
  3822. getSize: function ( optionalTarget ) {
  3823. var result = optionalTarget || new Vector2();
  3824. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3825. },
  3826. expandByPoint: function ( point ) {
  3827. this.min.min( point );
  3828. this.max.max( point );
  3829. return this;
  3830. },
  3831. expandByVector: function ( vector ) {
  3832. this.min.sub( vector );
  3833. this.max.add( vector );
  3834. return this;
  3835. },
  3836. expandByScalar: function ( scalar ) {
  3837. this.min.addScalar( - scalar );
  3838. this.max.addScalar( scalar );
  3839. return this;
  3840. },
  3841. containsPoint: function ( point ) {
  3842. return point.x < this.min.x || point.x > this.max.x ||
  3843. point.y < this.min.y || point.y > this.max.y ? false : true;
  3844. },
  3845. containsBox: function ( box ) {
  3846. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3847. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3848. },
  3849. getParameter: function ( point, optionalTarget ) {
  3850. // This can potentially have a divide by zero if the box
  3851. // has a size dimension of 0.
  3852. var result = optionalTarget || new Vector2();
  3853. return result.set(
  3854. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3855. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3856. );
  3857. },
  3858. intersectsBox: function ( box ) {
  3859. // using 4 splitting planes to rule out intersections
  3860. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3861. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3862. },
  3863. clampPoint: function ( point, optionalTarget ) {
  3864. var result = optionalTarget || new Vector2();
  3865. return result.copy( point ).clamp( this.min, this.max );
  3866. },
  3867. distanceToPoint: function () {
  3868. var v1 = new Vector2();
  3869. return function distanceToPoint( point ) {
  3870. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3871. return clampedPoint.sub( point ).length();
  3872. };
  3873. }(),
  3874. intersect: function ( box ) {
  3875. this.min.max( box.min );
  3876. this.max.min( box.max );
  3877. return this;
  3878. },
  3879. union: function ( box ) {
  3880. this.min.min( box.min );
  3881. this.max.max( box.max );
  3882. return this;
  3883. },
  3884. translate: function ( offset ) {
  3885. this.min.add( offset );
  3886. this.max.add( offset );
  3887. return this;
  3888. },
  3889. equals: function ( box ) {
  3890. return box.min.equals( this.min ) && box.max.equals( this.max );
  3891. }
  3892. } );
  3893. /**
  3894. * @author mikael emtinger / http://gomo.se/
  3895. * @author alteredq / http://alteredqualia.com/
  3896. */
  3897. function LensFlarePlugin( renderer, flares ) {
  3898. var gl = renderer.context;
  3899. var state = renderer.state;
  3900. var vertexBuffer, elementBuffer;
  3901. var shader, program, attributes, uniforms;
  3902. var tempTexture, occlusionTexture;
  3903. function init() {
  3904. var vertices = new Float32Array( [
  3905. - 1, - 1, 0, 0,
  3906. 1, - 1, 1, 0,
  3907. 1, 1, 1, 1,
  3908. - 1, 1, 0, 1
  3909. ] );
  3910. var faces = new Uint16Array( [
  3911. 0, 1, 2,
  3912. 0, 2, 3
  3913. ] );
  3914. // buffers
  3915. vertexBuffer = gl.createBuffer();
  3916. elementBuffer = gl.createBuffer();
  3917. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3918. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3919. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3920. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3921. // textures
  3922. tempTexture = gl.createTexture();
  3923. occlusionTexture = gl.createTexture();
  3924. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3925. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3926. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3927. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3928. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3929. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3930. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3931. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3932. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3933. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3934. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3935. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3936. shader = {
  3937. vertexShader: [
  3938. "uniform lowp int renderType;",
  3939. "uniform vec3 screenPosition;",
  3940. "uniform vec2 scale;",
  3941. "uniform float rotation;",
  3942. "uniform sampler2D occlusionMap;",
  3943. "attribute vec2 position;",
  3944. "attribute vec2 uv;",
  3945. "varying vec2 vUV;",
  3946. "varying float vVisibility;",
  3947. "void main() {",
  3948. "vUV = uv;",
  3949. "vec2 pos = position;",
  3950. "if ( renderType == 2 ) {",
  3951. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3952. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3953. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3954. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3955. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3956. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3957. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3958. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3959. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3960. "vVisibility = visibility.r / 9.0;",
  3961. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3962. "vVisibility *= visibility.b / 9.0;",
  3963. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3964. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3965. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3966. "}",
  3967. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3968. "}"
  3969. ].join( "\n" ),
  3970. fragmentShader: [
  3971. "uniform lowp int renderType;",
  3972. "uniform sampler2D map;",
  3973. "uniform float opacity;",
  3974. "uniform vec3 color;",
  3975. "varying vec2 vUV;",
  3976. "varying float vVisibility;",
  3977. "void main() {",
  3978. // pink square
  3979. "if ( renderType == 0 ) {",
  3980. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  3981. // restore
  3982. "} else if ( renderType == 1 ) {",
  3983. "gl_FragColor = texture2D( map, vUV );",
  3984. // flare
  3985. "} else {",
  3986. "vec4 texture = texture2D( map, vUV );",
  3987. "texture.a *= opacity * vVisibility;",
  3988. "gl_FragColor = texture;",
  3989. "gl_FragColor.rgb *= color;",
  3990. "}",
  3991. "}"
  3992. ].join( "\n" )
  3993. };
  3994. program = createProgram( shader );
  3995. attributes = {
  3996. vertex: gl.getAttribLocation ( program, "position" ),
  3997. uv: gl.getAttribLocation ( program, "uv" )
  3998. };
  3999. uniforms = {
  4000. renderType: gl.getUniformLocation( program, "renderType" ),
  4001. map: gl.getUniformLocation( program, "map" ),
  4002. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4003. opacity: gl.getUniformLocation( program, "opacity" ),
  4004. color: gl.getUniformLocation( program, "color" ),
  4005. scale: gl.getUniformLocation( program, "scale" ),
  4006. rotation: gl.getUniformLocation( program, "rotation" ),
  4007. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4008. };
  4009. }
  4010. /*
  4011. * Render lens flares
  4012. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4013. * reads these back and calculates occlusion.
  4014. */
  4015. this.render = function ( scene, camera, viewport ) {
  4016. if ( flares.length === 0 ) return;
  4017. var tempPosition = new Vector3();
  4018. var invAspect = viewport.w / viewport.z,
  4019. halfViewportWidth = viewport.z * 0.5,
  4020. halfViewportHeight = viewport.w * 0.5;
  4021. var size = 16 / viewport.w,
  4022. scale = new Vector2( size * invAspect, size );
  4023. var screenPosition = new Vector3( 1, 1, 0 ),
  4024. screenPositionPixels = new Vector2( 1, 1 );
  4025. var validArea = new Box2();
  4026. validArea.min.set( viewport.x, viewport.y );
  4027. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4028. if ( program === undefined ) {
  4029. init();
  4030. }
  4031. gl.useProgram( program );
  4032. state.initAttributes();
  4033. state.enableAttribute( attributes.vertex );
  4034. state.enableAttribute( attributes.uv );
  4035. state.disableUnusedAttributes();
  4036. // loop through all lens flares to update their occlusion and positions
  4037. // setup gl and common used attribs/uniforms
  4038. gl.uniform1i( uniforms.occlusionMap, 0 );
  4039. gl.uniform1i( uniforms.map, 1 );
  4040. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4041. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4042. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4043. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4044. state.disable( gl.CULL_FACE );
  4045. state.buffers.depth.setMask( false );
  4046. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4047. size = 16 / viewport.w;
  4048. scale.set( size * invAspect, size );
  4049. // calc object screen position
  4050. var flare = flares[ i ];
  4051. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4052. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4053. tempPosition.applyMatrix4( camera.projectionMatrix );
  4054. // setup arrays for gl programs
  4055. screenPosition.copy( tempPosition );
  4056. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4057. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4058. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4059. // screen cull
  4060. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4061. // save current RGB to temp texture
  4062. state.activeTexture( gl.TEXTURE0 );
  4063. state.bindTexture( gl.TEXTURE_2D, null );
  4064. state.activeTexture( gl.TEXTURE1 );
  4065. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4066. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4067. // render pink quad
  4068. gl.uniform1i( uniforms.renderType, 0 );
  4069. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4070. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4071. state.disable( gl.BLEND );
  4072. state.enable( gl.DEPTH_TEST );
  4073. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4074. // copy result to occlusionMap
  4075. state.activeTexture( gl.TEXTURE0 );
  4076. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4077. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4078. // restore graphics
  4079. gl.uniform1i( uniforms.renderType, 1 );
  4080. state.disable( gl.DEPTH_TEST );
  4081. state.activeTexture( gl.TEXTURE1 );
  4082. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4083. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4084. // update object positions
  4085. flare.positionScreen.copy( screenPosition );
  4086. if ( flare.customUpdateCallback ) {
  4087. flare.customUpdateCallback( flare );
  4088. } else {
  4089. flare.updateLensFlares();
  4090. }
  4091. // render flares
  4092. gl.uniform1i( uniforms.renderType, 2 );
  4093. state.enable( gl.BLEND );
  4094. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4095. var sprite = flare.lensFlares[ j ];
  4096. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4097. screenPosition.x = sprite.x;
  4098. screenPosition.y = sprite.y;
  4099. screenPosition.z = sprite.z;
  4100. size = sprite.size * sprite.scale / viewport.w;
  4101. scale.x = size * invAspect;
  4102. scale.y = size;
  4103. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4104. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4105. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4106. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4107. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4108. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4109. renderer.setTexture2D( sprite.texture, 1 );
  4110. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4111. }
  4112. }
  4113. }
  4114. }
  4115. // restore gl
  4116. state.enable( gl.CULL_FACE );
  4117. state.enable( gl.DEPTH_TEST );
  4118. state.buffers.depth.setMask( true );
  4119. renderer.resetGLState();
  4120. };
  4121. function createProgram( shader ) {
  4122. var program = gl.createProgram();
  4123. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4124. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4125. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4126. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4127. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4128. gl.compileShader( fragmentShader );
  4129. gl.compileShader( vertexShader );
  4130. gl.attachShader( program, fragmentShader );
  4131. gl.attachShader( program, vertexShader );
  4132. gl.linkProgram( program );
  4133. return program;
  4134. }
  4135. }
  4136. /**
  4137. * @author mikael emtinger / http://gomo.se/
  4138. * @author alteredq / http://alteredqualia.com/
  4139. */
  4140. function SpritePlugin( renderer, sprites ) {
  4141. var gl = renderer.context;
  4142. var state = renderer.state;
  4143. var vertexBuffer, elementBuffer;
  4144. var program, attributes, uniforms;
  4145. var texture;
  4146. // decompose matrixWorld
  4147. var spritePosition = new Vector3();
  4148. var spriteRotation = new Quaternion();
  4149. var spriteScale = new Vector3();
  4150. function init() {
  4151. var vertices = new Float32Array( [
  4152. - 0.5, - 0.5, 0, 0,
  4153. 0.5, - 0.5, 1, 0,
  4154. 0.5, 0.5, 1, 1,
  4155. - 0.5, 0.5, 0, 1
  4156. ] );
  4157. var faces = new Uint16Array( [
  4158. 0, 1, 2,
  4159. 0, 2, 3
  4160. ] );
  4161. vertexBuffer = gl.createBuffer();
  4162. elementBuffer = gl.createBuffer();
  4163. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4164. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4165. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4166. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4167. program = createProgram();
  4168. attributes = {
  4169. position: gl.getAttribLocation ( program, 'position' ),
  4170. uv: gl.getAttribLocation ( program, 'uv' )
  4171. };
  4172. uniforms = {
  4173. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4174. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4175. rotation: gl.getUniformLocation( program, 'rotation' ),
  4176. scale: gl.getUniformLocation( program, 'scale' ),
  4177. color: gl.getUniformLocation( program, 'color' ),
  4178. map: gl.getUniformLocation( program, 'map' ),
  4179. opacity: gl.getUniformLocation( program, 'opacity' ),
  4180. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4181. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4182. fogType: gl.getUniformLocation( program, 'fogType' ),
  4183. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4184. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4185. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4186. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4187. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4188. };
  4189. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4190. canvas.width = 8;
  4191. canvas.height = 8;
  4192. var context = canvas.getContext( '2d' );
  4193. context.fillStyle = 'white';
  4194. context.fillRect( 0, 0, 8, 8 );
  4195. texture = new Texture( canvas );
  4196. texture.needsUpdate = true;
  4197. }
  4198. this.render = function ( scene, camera ) {
  4199. if ( sprites.length === 0 ) return;
  4200. // setup gl
  4201. if ( program === undefined ) {
  4202. init();
  4203. }
  4204. gl.useProgram( program );
  4205. state.initAttributes();
  4206. state.enableAttribute( attributes.position );
  4207. state.enableAttribute( attributes.uv );
  4208. state.disableUnusedAttributes();
  4209. state.disable( gl.CULL_FACE );
  4210. state.enable( gl.BLEND );
  4211. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4212. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4213. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4214. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4215. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4216. state.activeTexture( gl.TEXTURE0 );
  4217. gl.uniform1i( uniforms.map, 0 );
  4218. var oldFogType = 0;
  4219. var sceneFogType = 0;
  4220. var fog = scene.fog;
  4221. if ( fog ) {
  4222. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4223. if ( fog.isFog ) {
  4224. gl.uniform1f( uniforms.fogNear, fog.near );
  4225. gl.uniform1f( uniforms.fogFar, fog.far );
  4226. gl.uniform1i( uniforms.fogType, 1 );
  4227. oldFogType = 1;
  4228. sceneFogType = 1;
  4229. } else if ( fog.isFogExp2 ) {
  4230. gl.uniform1f( uniforms.fogDensity, fog.density );
  4231. gl.uniform1i( uniforms.fogType, 2 );
  4232. oldFogType = 2;
  4233. sceneFogType = 2;
  4234. }
  4235. } else {
  4236. gl.uniform1i( uniforms.fogType, 0 );
  4237. oldFogType = 0;
  4238. sceneFogType = 0;
  4239. }
  4240. // update positions and sort
  4241. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4242. var sprite = sprites[ i ];
  4243. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4244. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4245. }
  4246. sprites.sort( painterSortStable );
  4247. // render all sprites
  4248. var scale = [];
  4249. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4250. var sprite = sprites[ i ];
  4251. var material = sprite.material;
  4252. if ( material.visible === false ) continue;
  4253. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4254. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4255. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4256. scale[ 0 ] = spriteScale.x;
  4257. scale[ 1 ] = spriteScale.y;
  4258. var fogType = 0;
  4259. if ( scene.fog && material.fog ) {
  4260. fogType = sceneFogType;
  4261. }
  4262. if ( oldFogType !== fogType ) {
  4263. gl.uniform1i( uniforms.fogType, fogType );
  4264. oldFogType = fogType;
  4265. }
  4266. if ( material.map !== null ) {
  4267. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4268. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4269. } else {
  4270. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4271. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4272. }
  4273. gl.uniform1f( uniforms.opacity, material.opacity );
  4274. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4275. gl.uniform1f( uniforms.rotation, material.rotation );
  4276. gl.uniform2fv( uniforms.scale, scale );
  4277. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4278. state.buffers.depth.setTest( material.depthTest );
  4279. state.buffers.depth.setMask( material.depthWrite );
  4280. if ( material.map ) {
  4281. renderer.setTexture2D( material.map, 0 );
  4282. } else {
  4283. renderer.setTexture2D( texture, 0 );
  4284. }
  4285. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4286. }
  4287. // restore gl
  4288. state.enable( gl.CULL_FACE );
  4289. renderer.resetGLState();
  4290. };
  4291. function createProgram() {
  4292. var program = gl.createProgram();
  4293. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4294. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4295. gl.shaderSource( vertexShader, [
  4296. 'precision ' + renderer.getPrecision() + ' float;',
  4297. 'uniform mat4 modelViewMatrix;',
  4298. 'uniform mat4 projectionMatrix;',
  4299. 'uniform float rotation;',
  4300. 'uniform vec2 scale;',
  4301. 'uniform vec2 uvOffset;',
  4302. 'uniform vec2 uvScale;',
  4303. 'attribute vec2 position;',
  4304. 'attribute vec2 uv;',
  4305. 'varying vec2 vUV;',
  4306. 'void main() {',
  4307. 'vUV = uvOffset + uv * uvScale;',
  4308. 'vec2 alignedPosition = position * scale;',
  4309. 'vec2 rotatedPosition;',
  4310. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4311. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4312. 'vec4 finalPosition;',
  4313. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4314. 'finalPosition.xy += rotatedPosition;',
  4315. 'finalPosition = projectionMatrix * finalPosition;',
  4316. 'gl_Position = finalPosition;',
  4317. '}'
  4318. ].join( '\n' ) );
  4319. gl.shaderSource( fragmentShader, [
  4320. 'precision ' + renderer.getPrecision() + ' float;',
  4321. 'uniform vec3 color;',
  4322. 'uniform sampler2D map;',
  4323. 'uniform float opacity;',
  4324. 'uniform int fogType;',
  4325. 'uniform vec3 fogColor;',
  4326. 'uniform float fogDensity;',
  4327. 'uniform float fogNear;',
  4328. 'uniform float fogFar;',
  4329. 'uniform float alphaTest;',
  4330. 'varying vec2 vUV;',
  4331. 'void main() {',
  4332. 'vec4 texture = texture2D( map, vUV );',
  4333. 'if ( texture.a < alphaTest ) discard;',
  4334. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4335. 'if ( fogType > 0 ) {',
  4336. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4337. 'float fogFactor = 0.0;',
  4338. 'if ( fogType == 1 ) {',
  4339. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4340. '} else {',
  4341. 'const float LOG2 = 1.442695;',
  4342. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4343. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4344. '}',
  4345. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4346. '}',
  4347. '}'
  4348. ].join( '\n' ) );
  4349. gl.compileShader( vertexShader );
  4350. gl.compileShader( fragmentShader );
  4351. gl.attachShader( program, vertexShader );
  4352. gl.attachShader( program, fragmentShader );
  4353. gl.linkProgram( program );
  4354. return program;
  4355. }
  4356. function painterSortStable( a, b ) {
  4357. if ( a.renderOrder !== b.renderOrder ) {
  4358. return a.renderOrder - b.renderOrder;
  4359. } else if ( a.z !== b.z ) {
  4360. return b.z - a.z;
  4361. } else {
  4362. return b.id - a.id;
  4363. }
  4364. }
  4365. }
  4366. /**
  4367. * @author mrdoob / http://mrdoob.com/
  4368. * @author alteredq / http://alteredqualia.com/
  4369. */
  4370. var materialId = 0;
  4371. function Material() {
  4372. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4373. this.uuid = _Math.generateUUID();
  4374. this.name = '';
  4375. this.type = 'Material';
  4376. this.fog = true;
  4377. this.lights = true;
  4378. this.blending = NormalBlending;
  4379. this.side = FrontSide;
  4380. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4381. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4382. this.opacity = 1;
  4383. this.transparent = false;
  4384. this.blendSrc = SrcAlphaFactor;
  4385. this.blendDst = OneMinusSrcAlphaFactor;
  4386. this.blendEquation = AddEquation;
  4387. this.blendSrcAlpha = null;
  4388. this.blendDstAlpha = null;
  4389. this.blendEquationAlpha = null;
  4390. this.depthFunc = LessEqualDepth;
  4391. this.depthTest = true;
  4392. this.depthWrite = true;
  4393. this.clippingPlanes = null;
  4394. this.clipIntersection = false;
  4395. this.clipShadows = false;
  4396. this.colorWrite = true;
  4397. this.precision = null; // override the renderer's default precision for this material
  4398. this.polygonOffset = false;
  4399. this.polygonOffsetFactor = 0;
  4400. this.polygonOffsetUnits = 0;
  4401. this.dithering = false;
  4402. this.alphaTest = 0;
  4403. this.premultipliedAlpha = false;
  4404. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4405. this.visible = true;
  4406. this.needsUpdate = true;
  4407. }
  4408. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4409. isMaterial: true,
  4410. setValues: function ( values ) {
  4411. if ( values === undefined ) return;
  4412. for ( var key in values ) {
  4413. var newValue = values[ key ];
  4414. if ( newValue === undefined ) {
  4415. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4416. continue;
  4417. }
  4418. var currentValue = this[ key ];
  4419. if ( currentValue === undefined ) {
  4420. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4421. continue;
  4422. }
  4423. if ( currentValue && currentValue.isColor ) {
  4424. currentValue.set( newValue );
  4425. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4426. currentValue.copy( newValue );
  4427. } else if ( key === 'overdraw' ) {
  4428. // ensure overdraw is backwards-compatible with legacy boolean type
  4429. this[ key ] = Number( newValue );
  4430. } else {
  4431. this[ key ] = newValue;
  4432. }
  4433. }
  4434. },
  4435. toJSON: function ( meta ) {
  4436. var isRoot = meta === undefined;
  4437. if ( isRoot ) {
  4438. meta = {
  4439. textures: {},
  4440. images: {}
  4441. };
  4442. }
  4443. var data = {
  4444. metadata: {
  4445. version: 4.5,
  4446. type: 'Material',
  4447. generator: 'Material.toJSON'
  4448. }
  4449. };
  4450. // standard Material serialization
  4451. data.uuid = this.uuid;
  4452. data.type = this.type;
  4453. if ( this.name !== '' ) data.name = this.name;
  4454. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4455. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4456. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4457. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4458. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4459. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4460. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4461. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4462. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4463. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4464. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4465. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4466. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4467. data.bumpScale = this.bumpScale;
  4468. }
  4469. if ( this.normalMap && this.normalMap.isTexture ) {
  4470. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4471. data.normalScale = this.normalScale.toArray();
  4472. }
  4473. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4474. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4475. data.displacementScale = this.displacementScale;
  4476. data.displacementBias = this.displacementBias;
  4477. }
  4478. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4479. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4480. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4481. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4482. if ( this.envMap && this.envMap.isTexture ) {
  4483. data.envMap = this.envMap.toJSON( meta ).uuid;
  4484. data.reflectivity = this.reflectivity; // Scale behind envMap
  4485. }
  4486. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4487. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4488. }
  4489. if ( this.size !== undefined ) data.size = this.size;
  4490. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4491. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4492. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4493. if ( this.side !== FrontSide ) data.side = this.side;
  4494. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4495. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4496. if ( this.transparent === true ) data.transparent = this.transparent;
  4497. data.depthFunc = this.depthFunc;
  4498. data.depthTest = this.depthTest;
  4499. data.depthWrite = this.depthWrite;
  4500. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4501. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4502. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4503. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4504. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4505. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4506. data.skinning = this.skinning;
  4507. data.morphTargets = this.morphTargets;
  4508. data.dithering = this.dithering;
  4509. // TODO: Copied from Object3D.toJSON
  4510. function extractFromCache( cache ) {
  4511. var values = [];
  4512. for ( var key in cache ) {
  4513. var data = cache[ key ];
  4514. delete data.metadata;
  4515. values.push( data );
  4516. }
  4517. return values;
  4518. }
  4519. if ( isRoot ) {
  4520. var textures = extractFromCache( meta.textures );
  4521. var images = extractFromCache( meta.images );
  4522. if ( textures.length > 0 ) data.textures = textures;
  4523. if ( images.length > 0 ) data.images = images;
  4524. }
  4525. return data;
  4526. },
  4527. clone: function () {
  4528. return new this.constructor().copy( this );
  4529. },
  4530. copy: function ( source ) {
  4531. this.name = source.name;
  4532. this.fog = source.fog;
  4533. this.lights = source.lights;
  4534. this.blending = source.blending;
  4535. this.side = source.side;
  4536. this.shading = source.shading;
  4537. this.vertexColors = source.vertexColors;
  4538. this.opacity = source.opacity;
  4539. this.transparent = source.transparent;
  4540. this.blendSrc = source.blendSrc;
  4541. this.blendDst = source.blendDst;
  4542. this.blendEquation = source.blendEquation;
  4543. this.blendSrcAlpha = source.blendSrcAlpha;
  4544. this.blendDstAlpha = source.blendDstAlpha;
  4545. this.blendEquationAlpha = source.blendEquationAlpha;
  4546. this.depthFunc = source.depthFunc;
  4547. this.depthTest = source.depthTest;
  4548. this.depthWrite = source.depthWrite;
  4549. this.colorWrite = source.colorWrite;
  4550. this.precision = source.precision;
  4551. this.polygonOffset = source.polygonOffset;
  4552. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4553. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4554. this.dithering = source.dithering;
  4555. this.alphaTest = source.alphaTest;
  4556. this.premultipliedAlpha = source.premultipliedAlpha;
  4557. this.overdraw = source.overdraw;
  4558. this.visible = source.visible;
  4559. this.clipShadows = source.clipShadows;
  4560. this.clipIntersection = source.clipIntersection;
  4561. var srcPlanes = source.clippingPlanes,
  4562. dstPlanes = null;
  4563. if ( srcPlanes !== null ) {
  4564. var n = srcPlanes.length;
  4565. dstPlanes = new Array( n );
  4566. for ( var i = 0; i !== n; ++ i )
  4567. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4568. }
  4569. this.clippingPlanes = dstPlanes;
  4570. return this;
  4571. },
  4572. dispose: function () {
  4573. this.dispatchEvent( { type: 'dispose' } );
  4574. }
  4575. } );
  4576. /**
  4577. * @author alteredq / http://alteredqualia.com/
  4578. *
  4579. * parameters = {
  4580. * defines: { "label" : "value" },
  4581. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4582. *
  4583. * fragmentShader: <string>,
  4584. * vertexShader: <string>,
  4585. *
  4586. * wireframe: <boolean>,
  4587. * wireframeLinewidth: <float>,
  4588. *
  4589. * lights: <bool>,
  4590. *
  4591. * skinning: <bool>,
  4592. * morphTargets: <bool>,
  4593. * morphNormals: <bool>
  4594. * }
  4595. */
  4596. function ShaderMaterial( parameters ) {
  4597. Material.call( this );
  4598. this.type = 'ShaderMaterial';
  4599. this.defines = {};
  4600. this.uniforms = {};
  4601. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4602. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4603. this.linewidth = 1;
  4604. this.wireframe = false;
  4605. this.wireframeLinewidth = 1;
  4606. this.fog = false; // set to use scene fog
  4607. this.lights = false; // set to use scene lights
  4608. this.clipping = false; // set to use user-defined clipping planes
  4609. this.skinning = false; // set to use skinning attribute streams
  4610. this.morphTargets = false; // set to use morph targets
  4611. this.morphNormals = false; // set to use morph normals
  4612. this.extensions = {
  4613. derivatives: false, // set to use derivatives
  4614. fragDepth: false, // set to use fragment depth values
  4615. drawBuffers: false, // set to use draw buffers
  4616. shaderTextureLOD: false // set to use shader texture LOD
  4617. };
  4618. // When rendered geometry doesn't include these attributes but the material does,
  4619. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4620. this.defaultAttributeValues = {
  4621. 'color': [ 1, 1, 1 ],
  4622. 'uv': [ 0, 0 ],
  4623. 'uv2': [ 0, 0 ]
  4624. };
  4625. this.index0AttributeName = undefined;
  4626. if ( parameters !== undefined ) {
  4627. if ( parameters.attributes !== undefined ) {
  4628. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4629. }
  4630. this.setValues( parameters );
  4631. }
  4632. }
  4633. ShaderMaterial.prototype = Object.create( Material.prototype );
  4634. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4635. ShaderMaterial.prototype.isShaderMaterial = true;
  4636. ShaderMaterial.prototype.copy = function ( source ) {
  4637. Material.prototype.copy.call( this, source );
  4638. this.fragmentShader = source.fragmentShader;
  4639. this.vertexShader = source.vertexShader;
  4640. this.uniforms = UniformsUtils.clone( source.uniforms );
  4641. this.defines = source.defines;
  4642. this.wireframe = source.wireframe;
  4643. this.wireframeLinewidth = source.wireframeLinewidth;
  4644. this.lights = source.lights;
  4645. this.clipping = source.clipping;
  4646. this.skinning = source.skinning;
  4647. this.morphTargets = source.morphTargets;
  4648. this.morphNormals = source.morphNormals;
  4649. this.extensions = source.extensions;
  4650. return this;
  4651. };
  4652. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4653. var data = Material.prototype.toJSON.call( this, meta );
  4654. data.uniforms = this.uniforms;
  4655. data.vertexShader = this.vertexShader;
  4656. data.fragmentShader = this.fragmentShader;
  4657. return data;
  4658. };
  4659. /**
  4660. * @author mrdoob / http://mrdoob.com/
  4661. * @author alteredq / http://alteredqualia.com/
  4662. * @author bhouston / https://clara.io
  4663. * @author WestLangley / http://github.com/WestLangley
  4664. *
  4665. * parameters = {
  4666. *
  4667. * opacity: <float>,
  4668. *
  4669. * map: new THREE.Texture( <Image> ),
  4670. *
  4671. * alphaMap: new THREE.Texture( <Image> ),
  4672. *
  4673. * displacementMap: new THREE.Texture( <Image> ),
  4674. * displacementScale: <float>,
  4675. * displacementBias: <float>,
  4676. *
  4677. * wireframe: <boolean>,
  4678. * wireframeLinewidth: <float>
  4679. * }
  4680. */
  4681. function MeshDepthMaterial( parameters ) {
  4682. Material.call( this );
  4683. this.type = 'MeshDepthMaterial';
  4684. this.depthPacking = BasicDepthPacking;
  4685. this.skinning = false;
  4686. this.morphTargets = false;
  4687. this.map = null;
  4688. this.alphaMap = null;
  4689. this.displacementMap = null;
  4690. this.displacementScale = 1;
  4691. this.displacementBias = 0;
  4692. this.wireframe = false;
  4693. this.wireframeLinewidth = 1;
  4694. this.fog = false;
  4695. this.lights = false;
  4696. this.setValues( parameters );
  4697. }
  4698. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4699. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4700. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4701. MeshDepthMaterial.prototype.copy = function ( source ) {
  4702. Material.prototype.copy.call( this, source );
  4703. this.depthPacking = source.depthPacking;
  4704. this.skinning = source.skinning;
  4705. this.morphTargets = source.morphTargets;
  4706. this.map = source.map;
  4707. this.alphaMap = source.alphaMap;
  4708. this.displacementMap = source.displacementMap;
  4709. this.displacementScale = source.displacementScale;
  4710. this.displacementBias = source.displacementBias;
  4711. this.wireframe = source.wireframe;
  4712. this.wireframeLinewidth = source.wireframeLinewidth;
  4713. return this;
  4714. };
  4715. /**
  4716. * @author bhouston / http://clara.io
  4717. * @author WestLangley / http://github.com/WestLangley
  4718. */
  4719. function Box3( min, max ) {
  4720. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4721. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4722. }
  4723. Object.assign( Box3.prototype, {
  4724. isBox3: true,
  4725. set: function ( min, max ) {
  4726. this.min.copy( min );
  4727. this.max.copy( max );
  4728. return this;
  4729. },
  4730. setFromArray: function ( array ) {
  4731. var minX = + Infinity;
  4732. var minY = + Infinity;
  4733. var minZ = + Infinity;
  4734. var maxX = - Infinity;
  4735. var maxY = - Infinity;
  4736. var maxZ = - Infinity;
  4737. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4738. var x = array[ i ];
  4739. var y = array[ i + 1 ];
  4740. var z = array[ i + 2 ];
  4741. if ( x < minX ) minX = x;
  4742. if ( y < minY ) minY = y;
  4743. if ( z < minZ ) minZ = z;
  4744. if ( x > maxX ) maxX = x;
  4745. if ( y > maxY ) maxY = y;
  4746. if ( z > maxZ ) maxZ = z;
  4747. }
  4748. this.min.set( minX, minY, minZ );
  4749. this.max.set( maxX, maxY, maxZ );
  4750. return this;
  4751. },
  4752. setFromBufferAttribute: function ( attribute ) {
  4753. var minX = + Infinity;
  4754. var minY = + Infinity;
  4755. var minZ = + Infinity;
  4756. var maxX = - Infinity;
  4757. var maxY = - Infinity;
  4758. var maxZ = - Infinity;
  4759. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4760. var x = attribute.getX( i );
  4761. var y = attribute.getY( i );
  4762. var z = attribute.getZ( i );
  4763. if ( x < minX ) minX = x;
  4764. if ( y < minY ) minY = y;
  4765. if ( z < minZ ) minZ = z;
  4766. if ( x > maxX ) maxX = x;
  4767. if ( y > maxY ) maxY = y;
  4768. if ( z > maxZ ) maxZ = z;
  4769. }
  4770. this.min.set( minX, minY, minZ );
  4771. this.max.set( maxX, maxY, maxZ );
  4772. return this;
  4773. },
  4774. setFromPoints: function ( points ) {
  4775. this.makeEmpty();
  4776. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4777. this.expandByPoint( points[ i ] );
  4778. }
  4779. return this;
  4780. },
  4781. setFromCenterAndSize: function () {
  4782. var v1 = new Vector3();
  4783. return function setFromCenterAndSize( center, size ) {
  4784. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4785. this.min.copy( center ).sub( halfSize );
  4786. this.max.copy( center ).add( halfSize );
  4787. return this;
  4788. };
  4789. }(),
  4790. setFromObject: function ( object ) {
  4791. this.makeEmpty();
  4792. return this.expandByObject( object );
  4793. },
  4794. clone: function () {
  4795. return new this.constructor().copy( this );
  4796. },
  4797. copy: function ( box ) {
  4798. this.min.copy( box.min );
  4799. this.max.copy( box.max );
  4800. return this;
  4801. },
  4802. makeEmpty: function () {
  4803. this.min.x = this.min.y = this.min.z = + Infinity;
  4804. this.max.x = this.max.y = this.max.z = - Infinity;
  4805. return this;
  4806. },
  4807. isEmpty: function () {
  4808. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4809. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4810. },
  4811. getCenter: function ( optionalTarget ) {
  4812. var result = optionalTarget || new Vector3();
  4813. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4814. },
  4815. getSize: function ( optionalTarget ) {
  4816. var result = optionalTarget || new Vector3();
  4817. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4818. },
  4819. expandByPoint: function ( point ) {
  4820. this.min.min( point );
  4821. this.max.max( point );
  4822. return this;
  4823. },
  4824. expandByVector: function ( vector ) {
  4825. this.min.sub( vector );
  4826. this.max.add( vector );
  4827. return this;
  4828. },
  4829. expandByScalar: function ( scalar ) {
  4830. this.min.addScalar( - scalar );
  4831. this.max.addScalar( scalar );
  4832. return this;
  4833. },
  4834. expandByObject: function () {
  4835. // Computes the world-axis-aligned bounding box of an object (including its children),
  4836. // accounting for both the object's, and children's, world transforms
  4837. var v1 = new Vector3();
  4838. return function expandByObject( object ) {
  4839. var scope = this;
  4840. object.updateMatrixWorld( true );
  4841. object.traverse( function ( node ) {
  4842. var i, l;
  4843. var geometry = node.geometry;
  4844. if ( geometry !== undefined ) {
  4845. if ( geometry.isGeometry ) {
  4846. var vertices = geometry.vertices;
  4847. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4848. v1.copy( vertices[ i ] );
  4849. v1.applyMatrix4( node.matrixWorld );
  4850. scope.expandByPoint( v1 );
  4851. }
  4852. } else if ( geometry.isBufferGeometry ) {
  4853. var attribute = geometry.attributes.position;
  4854. if ( attribute !== undefined ) {
  4855. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4856. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4857. scope.expandByPoint( v1 );
  4858. }
  4859. }
  4860. }
  4861. }
  4862. } );
  4863. return this;
  4864. };
  4865. }(),
  4866. containsPoint: function ( point ) {
  4867. return point.x < this.min.x || point.x > this.max.x ||
  4868. point.y < this.min.y || point.y > this.max.y ||
  4869. point.z < this.min.z || point.z > this.max.z ? false : true;
  4870. },
  4871. containsBox: function ( box ) {
  4872. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4873. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4874. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4875. },
  4876. getParameter: function ( point, optionalTarget ) {
  4877. // This can potentially have a divide by zero if the box
  4878. // has a size dimension of 0.
  4879. var result = optionalTarget || new Vector3();
  4880. return result.set(
  4881. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4882. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4883. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4884. );
  4885. },
  4886. intersectsBox: function ( box ) {
  4887. // using 6 splitting planes to rule out intersections.
  4888. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4889. box.max.y < this.min.y || box.min.y > this.max.y ||
  4890. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4891. },
  4892. intersectsSphere: ( function () {
  4893. var closestPoint = new Vector3();
  4894. return function intersectsSphere( sphere ) {
  4895. // Find the point on the AABB closest to the sphere center.
  4896. this.clampPoint( sphere.center, closestPoint );
  4897. // If that point is inside the sphere, the AABB and sphere intersect.
  4898. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4899. };
  4900. } )(),
  4901. intersectsPlane: function ( plane ) {
  4902. // We compute the minimum and maximum dot product values. If those values
  4903. // are on the same side (back or front) of the plane, then there is no intersection.
  4904. var min, max;
  4905. if ( plane.normal.x > 0 ) {
  4906. min = plane.normal.x * this.min.x;
  4907. max = plane.normal.x * this.max.x;
  4908. } else {
  4909. min = plane.normal.x * this.max.x;
  4910. max = plane.normal.x * this.min.x;
  4911. }
  4912. if ( plane.normal.y > 0 ) {
  4913. min += plane.normal.y * this.min.y;
  4914. max += plane.normal.y * this.max.y;
  4915. } else {
  4916. min += plane.normal.y * this.max.y;
  4917. max += plane.normal.y * this.min.y;
  4918. }
  4919. if ( plane.normal.z > 0 ) {
  4920. min += plane.normal.z * this.min.z;
  4921. max += plane.normal.z * this.max.z;
  4922. } else {
  4923. min += plane.normal.z * this.max.z;
  4924. max += plane.normal.z * this.min.z;
  4925. }
  4926. return ( min <= plane.constant && max >= plane.constant );
  4927. },
  4928. clampPoint: function ( point, optionalTarget ) {
  4929. var result = optionalTarget || new Vector3();
  4930. return result.copy( point ).clamp( this.min, this.max );
  4931. },
  4932. distanceToPoint: function () {
  4933. var v1 = new Vector3();
  4934. return function distanceToPoint( point ) {
  4935. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4936. return clampedPoint.sub( point ).length();
  4937. };
  4938. }(),
  4939. getBoundingSphere: function () {
  4940. var v1 = new Vector3();
  4941. return function getBoundingSphere( optionalTarget ) {
  4942. var result = optionalTarget || new Sphere();
  4943. this.getCenter( result.center );
  4944. result.radius = this.getSize( v1 ).length() * 0.5;
  4945. return result;
  4946. };
  4947. }(),
  4948. intersect: function ( box ) {
  4949. this.min.max( box.min );
  4950. this.max.min( box.max );
  4951. // 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.
  4952. if( this.isEmpty() ) this.makeEmpty();
  4953. return this;
  4954. },
  4955. union: function ( box ) {
  4956. this.min.min( box.min );
  4957. this.max.max( box.max );
  4958. return this;
  4959. },
  4960. applyMatrix4: function () {
  4961. var points = [
  4962. new Vector3(),
  4963. new Vector3(),
  4964. new Vector3(),
  4965. new Vector3(),
  4966. new Vector3(),
  4967. new Vector3(),
  4968. new Vector3(),
  4969. new Vector3()
  4970. ];
  4971. return function applyMatrix4( matrix ) {
  4972. // transform of empty box is an empty box.
  4973. if( this.isEmpty() ) return this;
  4974. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4975. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4976. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4977. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4978. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4979. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  4980. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  4981. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  4982. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  4983. this.setFromPoints( points );
  4984. return this;
  4985. };
  4986. }(),
  4987. translate: function ( offset ) {
  4988. this.min.add( offset );
  4989. this.max.add( offset );
  4990. return this;
  4991. },
  4992. equals: function ( box ) {
  4993. return box.min.equals( this.min ) && box.max.equals( this.max );
  4994. }
  4995. } );
  4996. /**
  4997. * @author bhouston / http://clara.io
  4998. * @author mrdoob / http://mrdoob.com/
  4999. */
  5000. function Sphere( center, radius ) {
  5001. this.center = ( center !== undefined ) ? center : new Vector3();
  5002. this.radius = ( radius !== undefined ) ? radius : 0;
  5003. }
  5004. Object.assign( Sphere.prototype, {
  5005. set: function ( center, radius ) {
  5006. this.center.copy( center );
  5007. this.radius = radius;
  5008. return this;
  5009. },
  5010. setFromPoints: function () {
  5011. var box = new Box3();
  5012. return function setFromPoints( points, optionalCenter ) {
  5013. var center = this.center;
  5014. if ( optionalCenter !== undefined ) {
  5015. center.copy( optionalCenter );
  5016. } else {
  5017. box.setFromPoints( points ).getCenter( center );
  5018. }
  5019. var maxRadiusSq = 0;
  5020. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5021. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5022. }
  5023. this.radius = Math.sqrt( maxRadiusSq );
  5024. return this;
  5025. };
  5026. }(),
  5027. clone: function () {
  5028. return new this.constructor().copy( this );
  5029. },
  5030. copy: function ( sphere ) {
  5031. this.center.copy( sphere.center );
  5032. this.radius = sphere.radius;
  5033. return this;
  5034. },
  5035. empty: function () {
  5036. return ( this.radius <= 0 );
  5037. },
  5038. containsPoint: function ( point ) {
  5039. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5040. },
  5041. distanceToPoint: function ( point ) {
  5042. return ( point.distanceTo( this.center ) - this.radius );
  5043. },
  5044. intersectsSphere: function ( sphere ) {
  5045. var radiusSum = this.radius + sphere.radius;
  5046. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5047. },
  5048. intersectsBox: function ( box ) {
  5049. return box.intersectsSphere( this );
  5050. },
  5051. intersectsPlane: function ( plane ) {
  5052. // We use the following equation to compute the signed distance from
  5053. // the center of the sphere to the plane.
  5054. //
  5055. // distance = q * n - d
  5056. //
  5057. // If this distance is greater than the radius of the sphere,
  5058. // then there is no intersection.
  5059. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5060. },
  5061. clampPoint: function ( point, optionalTarget ) {
  5062. var deltaLengthSq = this.center.distanceToSquared( point );
  5063. var result = optionalTarget || new Vector3();
  5064. result.copy( point );
  5065. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5066. result.sub( this.center ).normalize();
  5067. result.multiplyScalar( this.radius ).add( this.center );
  5068. }
  5069. return result;
  5070. },
  5071. getBoundingBox: function ( optionalTarget ) {
  5072. var box = optionalTarget || new Box3();
  5073. box.set( this.center, this.center );
  5074. box.expandByScalar( this.radius );
  5075. return box;
  5076. },
  5077. applyMatrix4: function ( matrix ) {
  5078. this.center.applyMatrix4( matrix );
  5079. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5080. return this;
  5081. },
  5082. translate: function ( offset ) {
  5083. this.center.add( offset );
  5084. return this;
  5085. },
  5086. equals: function ( sphere ) {
  5087. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5088. }
  5089. } );
  5090. /**
  5091. * @author alteredq / http://alteredqualia.com/
  5092. * @author WestLangley / http://github.com/WestLangley
  5093. * @author bhouston / http://clara.io
  5094. * @author tschw
  5095. */
  5096. function Matrix3() {
  5097. this.elements = [
  5098. 1, 0, 0,
  5099. 0, 1, 0,
  5100. 0, 0, 1
  5101. ];
  5102. if ( arguments.length > 0 ) {
  5103. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5104. }
  5105. }
  5106. Object.assign( Matrix3.prototype, {
  5107. isMatrix3: true,
  5108. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5109. var te = this.elements;
  5110. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5111. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5112. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5113. return this;
  5114. },
  5115. identity: function () {
  5116. this.set(
  5117. 1, 0, 0,
  5118. 0, 1, 0,
  5119. 0, 0, 1
  5120. );
  5121. return this;
  5122. },
  5123. clone: function () {
  5124. return new this.constructor().fromArray( this.elements );
  5125. },
  5126. copy: function ( m ) {
  5127. var te = this.elements;
  5128. var me = m.elements;
  5129. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5130. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5131. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5132. return this;
  5133. },
  5134. setFromMatrix4: function ( m ) {
  5135. var me = m.elements;
  5136. this.set(
  5137. me[ 0 ], me[ 4 ], me[ 8 ],
  5138. me[ 1 ], me[ 5 ], me[ 9 ],
  5139. me[ 2 ], me[ 6 ], me[ 10 ]
  5140. );
  5141. return this;
  5142. },
  5143. applyToBufferAttribute: function () {
  5144. var v1 = new Vector3();
  5145. return function applyToBufferAttribute( attribute ) {
  5146. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5147. v1.x = attribute.getX( i );
  5148. v1.y = attribute.getY( i );
  5149. v1.z = attribute.getZ( i );
  5150. v1.applyMatrix3( this );
  5151. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5152. }
  5153. return attribute;
  5154. };
  5155. }(),
  5156. multiply: function ( m ) {
  5157. return this.multiplyMatrices( this, m );
  5158. },
  5159. premultiply: function ( m ) {
  5160. return this.multiplyMatrices( m, this );
  5161. },
  5162. multiplyMatrices: function ( a, b ) {
  5163. var ae = a.elements;
  5164. var be = b.elements;
  5165. var te = this.elements;
  5166. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5167. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5168. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5169. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5170. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5171. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5172. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5173. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5174. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5175. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5176. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5177. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5178. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5179. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5180. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5181. return this;
  5182. },
  5183. multiplyScalar: function ( s ) {
  5184. var te = this.elements;
  5185. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5186. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5187. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5188. return this;
  5189. },
  5190. determinant: function () {
  5191. var te = this.elements;
  5192. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5193. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5194. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5195. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5196. },
  5197. getInverse: function ( matrix, throwOnDegenerate ) {
  5198. if ( matrix && matrix.isMatrix4 ) {
  5199. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5200. }
  5201. var me = matrix.elements,
  5202. te = this.elements,
  5203. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5204. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5205. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5206. t11 = n33 * n22 - n32 * n23,
  5207. t12 = n32 * n13 - n33 * n12,
  5208. t13 = n23 * n12 - n22 * n13,
  5209. det = n11 * t11 + n21 * t12 + n31 * t13;
  5210. if ( det === 0 ) {
  5211. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5212. if ( throwOnDegenerate === true ) {
  5213. throw new Error( msg );
  5214. } else {
  5215. console.warn( msg );
  5216. }
  5217. return this.identity();
  5218. }
  5219. var detInv = 1 / det;
  5220. te[ 0 ] = t11 * detInv;
  5221. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5222. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5223. te[ 3 ] = t12 * detInv;
  5224. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5225. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5226. te[ 6 ] = t13 * detInv;
  5227. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5228. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5229. return this;
  5230. },
  5231. transpose: function () {
  5232. var tmp, m = this.elements;
  5233. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5234. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5235. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5236. return this;
  5237. },
  5238. getNormalMatrix: function ( matrix4 ) {
  5239. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5240. },
  5241. transposeIntoArray: function ( r ) {
  5242. var m = this.elements;
  5243. r[ 0 ] = m[ 0 ];
  5244. r[ 1 ] = m[ 3 ];
  5245. r[ 2 ] = m[ 6 ];
  5246. r[ 3 ] = m[ 1 ];
  5247. r[ 4 ] = m[ 4 ];
  5248. r[ 5 ] = m[ 7 ];
  5249. r[ 6 ] = m[ 2 ];
  5250. r[ 7 ] = m[ 5 ];
  5251. r[ 8 ] = m[ 8 ];
  5252. return this;
  5253. },
  5254. equals: function ( matrix ) {
  5255. var te = this.elements;
  5256. var me = matrix.elements;
  5257. for ( var i = 0; i < 9; i ++ ) {
  5258. if ( te[ i ] !== me[ i ] ) return false;
  5259. }
  5260. return true;
  5261. },
  5262. fromArray: function ( array, offset ) {
  5263. if ( offset === undefined ) offset = 0;
  5264. for ( var i = 0; i < 9; i ++ ) {
  5265. this.elements[ i ] = array[ i + offset ];
  5266. }
  5267. return this;
  5268. },
  5269. toArray: function ( array, offset ) {
  5270. if ( array === undefined ) array = [];
  5271. if ( offset === undefined ) offset = 0;
  5272. var te = this.elements;
  5273. array[ offset ] = te[ 0 ];
  5274. array[ offset + 1 ] = te[ 1 ];
  5275. array[ offset + 2 ] = te[ 2 ];
  5276. array[ offset + 3 ] = te[ 3 ];
  5277. array[ offset + 4 ] = te[ 4 ];
  5278. array[ offset + 5 ] = te[ 5 ];
  5279. array[ offset + 6 ] = te[ 6 ];
  5280. array[ offset + 7 ] = te[ 7 ];
  5281. array[ offset + 8 ] = te[ 8 ];
  5282. return array;
  5283. }
  5284. } );
  5285. /**
  5286. * @author bhouston / http://clara.io
  5287. */
  5288. function Plane( normal, constant ) {
  5289. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5290. this.constant = ( constant !== undefined ) ? constant : 0;
  5291. }
  5292. Object.assign( Plane.prototype, {
  5293. set: function ( normal, constant ) {
  5294. this.normal.copy( normal );
  5295. this.constant = constant;
  5296. return this;
  5297. },
  5298. setComponents: function ( x, y, z, w ) {
  5299. this.normal.set( x, y, z );
  5300. this.constant = w;
  5301. return this;
  5302. },
  5303. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5304. this.normal.copy( normal );
  5305. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5306. return this;
  5307. },
  5308. setFromCoplanarPoints: function () {
  5309. var v1 = new Vector3();
  5310. var v2 = new Vector3();
  5311. return function setFromCoplanarPoints( a, b, c ) {
  5312. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5313. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5314. this.setFromNormalAndCoplanarPoint( normal, a );
  5315. return this;
  5316. };
  5317. }(),
  5318. clone: function () {
  5319. return new this.constructor().copy( this );
  5320. },
  5321. copy: function ( plane ) {
  5322. this.normal.copy( plane.normal );
  5323. this.constant = plane.constant;
  5324. return this;
  5325. },
  5326. normalize: function () {
  5327. // Note: will lead to a divide by zero if the plane is invalid.
  5328. var inverseNormalLength = 1.0 / this.normal.length();
  5329. this.normal.multiplyScalar( inverseNormalLength );
  5330. this.constant *= inverseNormalLength;
  5331. return this;
  5332. },
  5333. negate: function () {
  5334. this.constant *= - 1;
  5335. this.normal.negate();
  5336. return this;
  5337. },
  5338. distanceToPoint: function ( point ) {
  5339. return this.normal.dot( point ) + this.constant;
  5340. },
  5341. distanceToSphere: function ( sphere ) {
  5342. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5343. },
  5344. projectPoint: function ( point, optionalTarget ) {
  5345. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5346. },
  5347. orthoPoint: function ( point, optionalTarget ) {
  5348. var perpendicularMagnitude = this.distanceToPoint( point );
  5349. var result = optionalTarget || new Vector3();
  5350. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5351. },
  5352. intersectLine: function () {
  5353. var v1 = new Vector3();
  5354. return function intersectLine( line, optionalTarget ) {
  5355. var result = optionalTarget || new Vector3();
  5356. var direction = line.delta( v1 );
  5357. var denominator = this.normal.dot( direction );
  5358. if ( denominator === 0 ) {
  5359. // line is coplanar, return origin
  5360. if ( this.distanceToPoint( line.start ) === 0 ) {
  5361. return result.copy( line.start );
  5362. }
  5363. // Unsure if this is the correct method to handle this case.
  5364. return undefined;
  5365. }
  5366. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5367. if ( t < 0 || t > 1 ) {
  5368. return undefined;
  5369. }
  5370. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5371. };
  5372. }(),
  5373. intersectsLine: function ( line ) {
  5374. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5375. var startSign = this.distanceToPoint( line.start );
  5376. var endSign = this.distanceToPoint( line.end );
  5377. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5378. },
  5379. intersectsBox: function ( box ) {
  5380. return box.intersectsPlane( this );
  5381. },
  5382. intersectsSphere: function ( sphere ) {
  5383. return sphere.intersectsPlane( this );
  5384. },
  5385. coplanarPoint: function ( optionalTarget ) {
  5386. var result = optionalTarget || new Vector3();
  5387. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5388. },
  5389. applyMatrix4: function () {
  5390. var v1 = new Vector3();
  5391. var m1 = new Matrix3();
  5392. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5393. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5394. // transform normal based on theory here:
  5395. // http://www.songho.ca/opengl/gl_normaltransform.html
  5396. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5397. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5398. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5399. this.constant = - referencePoint.dot( normal );
  5400. return this;
  5401. };
  5402. }(),
  5403. translate: function ( offset ) {
  5404. this.constant = this.constant - offset.dot( this.normal );
  5405. return this;
  5406. },
  5407. equals: function ( plane ) {
  5408. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5409. }
  5410. } );
  5411. /**
  5412. * @author mrdoob / http://mrdoob.com/
  5413. * @author alteredq / http://alteredqualia.com/
  5414. * @author bhouston / http://clara.io
  5415. */
  5416. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5417. this.planes = [
  5418. ( p0 !== undefined ) ? p0 : new Plane(),
  5419. ( p1 !== undefined ) ? p1 : new Plane(),
  5420. ( p2 !== undefined ) ? p2 : new Plane(),
  5421. ( p3 !== undefined ) ? p3 : new Plane(),
  5422. ( p4 !== undefined ) ? p4 : new Plane(),
  5423. ( p5 !== undefined ) ? p5 : new Plane()
  5424. ];
  5425. }
  5426. Object.assign( Frustum.prototype, {
  5427. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5428. var planes = this.planes;
  5429. planes[ 0 ].copy( p0 );
  5430. planes[ 1 ].copy( p1 );
  5431. planes[ 2 ].copy( p2 );
  5432. planes[ 3 ].copy( p3 );
  5433. planes[ 4 ].copy( p4 );
  5434. planes[ 5 ].copy( p5 );
  5435. return this;
  5436. },
  5437. clone: function () {
  5438. return new this.constructor().copy( this );
  5439. },
  5440. copy: function ( frustum ) {
  5441. var planes = this.planes;
  5442. for ( var i = 0; i < 6; i ++ ) {
  5443. planes[ i ].copy( frustum.planes[ i ] );
  5444. }
  5445. return this;
  5446. },
  5447. setFromMatrix: function ( m ) {
  5448. var planes = this.planes;
  5449. var me = m.elements;
  5450. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5451. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5452. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5453. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5454. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5455. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5456. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5457. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5458. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5459. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5460. return this;
  5461. },
  5462. intersectsObject: function () {
  5463. var sphere = new Sphere();
  5464. return function intersectsObject( object ) {
  5465. var geometry = object.geometry;
  5466. if ( geometry.boundingSphere === null )
  5467. geometry.computeBoundingSphere();
  5468. sphere.copy( geometry.boundingSphere )
  5469. .applyMatrix4( object.matrixWorld );
  5470. return this.intersectsSphere( sphere );
  5471. };
  5472. }(),
  5473. intersectsSprite: function () {
  5474. var sphere = new Sphere();
  5475. return function intersectsSprite( sprite ) {
  5476. sphere.center.set( 0, 0, 0 );
  5477. sphere.radius = 0.7071067811865476;
  5478. sphere.applyMatrix4( sprite.matrixWorld );
  5479. return this.intersectsSphere( sphere );
  5480. };
  5481. }(),
  5482. intersectsSphere: function ( sphere ) {
  5483. var planes = this.planes;
  5484. var center = sphere.center;
  5485. var negRadius = - sphere.radius;
  5486. for ( var i = 0; i < 6; i ++ ) {
  5487. var distance = planes[ i ].distanceToPoint( center );
  5488. if ( distance < negRadius ) {
  5489. return false;
  5490. }
  5491. }
  5492. return true;
  5493. },
  5494. intersectsBox: function () {
  5495. var p1 = new Vector3(),
  5496. p2 = new Vector3();
  5497. return function intersectsBox( box ) {
  5498. var planes = this.planes;
  5499. for ( var i = 0; i < 6; i ++ ) {
  5500. var plane = planes[ i ];
  5501. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5502. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5503. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5504. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5505. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5506. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5507. var d1 = plane.distanceToPoint( p1 );
  5508. var d2 = plane.distanceToPoint( p2 );
  5509. // if both outside plane, no intersection
  5510. if ( d1 < 0 && d2 < 0 ) {
  5511. return false;
  5512. }
  5513. }
  5514. return true;
  5515. };
  5516. }(),
  5517. containsPoint: function ( point ) {
  5518. var planes = this.planes;
  5519. for ( var i = 0; i < 6; i ++ ) {
  5520. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5521. return false;
  5522. }
  5523. }
  5524. return true;
  5525. }
  5526. } );
  5527. /**
  5528. * @author alteredq / http://alteredqualia.com/
  5529. * @author mrdoob / http://mrdoob.com/
  5530. */
  5531. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5532. var _gl = _renderer.context,
  5533. _state = _renderer.state,
  5534. _frustum = new Frustum(),
  5535. _projScreenMatrix = new Matrix4(),
  5536. _lightShadows = _lights.shadows,
  5537. _shadowMapSize = new Vector2(),
  5538. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5539. _lookTarget = new Vector3(),
  5540. _lightPositionWorld = new Vector3(),
  5541. _MorphingFlag = 1,
  5542. _SkinningFlag = 2,
  5543. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5544. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5545. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5546. _materialCache = {};
  5547. var cubeDirections = [
  5548. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5549. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5550. ];
  5551. var cubeUps = [
  5552. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5553. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5554. ];
  5555. var cube2DViewPorts = [
  5556. new Vector4(), new Vector4(), new Vector4(),
  5557. new Vector4(), new Vector4(), new Vector4()
  5558. ];
  5559. // init
  5560. var depthMaterialTemplate = new MeshDepthMaterial();
  5561. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5562. depthMaterialTemplate.clipping = true;
  5563. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5564. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  5565. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5566. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5567. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5568. var depthMaterial = depthMaterialTemplate.clone();
  5569. depthMaterial.morphTargets = useMorphing;
  5570. depthMaterial.skinning = useSkinning;
  5571. _depthMaterials[ i ] = depthMaterial;
  5572. var distanceMaterial = new ShaderMaterial( {
  5573. defines: {
  5574. 'USE_SHADOWMAP': ''
  5575. },
  5576. uniforms: distanceUniforms,
  5577. vertexShader: distanceShader.vertexShader,
  5578. fragmentShader: distanceShader.fragmentShader,
  5579. morphTargets: useMorphing,
  5580. skinning: useSkinning,
  5581. clipping: true
  5582. } );
  5583. _distanceMaterials[ i ] = distanceMaterial;
  5584. }
  5585. //
  5586. var scope = this;
  5587. this.enabled = false;
  5588. this.autoUpdate = true;
  5589. this.needsUpdate = false;
  5590. this.type = PCFShadowMap;
  5591. this.renderReverseSided = true;
  5592. this.renderSingleSided = true;
  5593. this.render = function ( scene, camera ) {
  5594. if ( scope.enabled === false ) return;
  5595. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5596. if ( _lightShadows.length === 0 ) return;
  5597. // Set GL state for depth map.
  5598. _state.disable( _gl.BLEND );
  5599. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5600. _state.buffers.depth.setTest( true );
  5601. _state.setScissorTest( false );
  5602. // render depth map
  5603. var faceCount;
  5604. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5605. var light = _lightShadows[ i ];
  5606. var shadow = light.shadow;
  5607. var isPointLight = light && light.isPointLight;
  5608. if ( shadow === undefined ) {
  5609. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5610. continue;
  5611. }
  5612. var shadowCamera = shadow.camera;
  5613. _shadowMapSize.copy( shadow.mapSize );
  5614. _shadowMapSize.min( _maxShadowMapSize );
  5615. if ( isPointLight ) {
  5616. var vpWidth = _shadowMapSize.x;
  5617. var vpHeight = _shadowMapSize.y;
  5618. // These viewports map a cube-map onto a 2D texture with the
  5619. // following orientation:
  5620. //
  5621. // xzXZ
  5622. // y Y
  5623. //
  5624. // X - Positive x direction
  5625. // x - Negative x direction
  5626. // Y - Positive y direction
  5627. // y - Negative y direction
  5628. // Z - Positive z direction
  5629. // z - Negative z direction
  5630. // positive X
  5631. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5632. // negative X
  5633. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5634. // positive Z
  5635. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5636. // negative Z
  5637. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5638. // positive Y
  5639. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5640. // negative Y
  5641. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5642. _shadowMapSize.x *= 4.0;
  5643. _shadowMapSize.y *= 2.0;
  5644. }
  5645. if ( shadow.map === null ) {
  5646. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5647. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5648. shadow.map.texture.name = light.name + ".shadowMap";
  5649. shadowCamera.updateProjectionMatrix();
  5650. }
  5651. if ( shadow.isSpotLightShadow ) {
  5652. shadow.update( light );
  5653. }
  5654. var shadowMap = shadow.map;
  5655. var shadowMatrix = shadow.matrix;
  5656. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5657. shadowCamera.position.copy( _lightPositionWorld );
  5658. if ( isPointLight ) {
  5659. faceCount = 6;
  5660. // for point lights we set the shadow matrix to be a translation-only matrix
  5661. // equal to inverse of the light's position
  5662. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5663. } else {
  5664. faceCount = 1;
  5665. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5666. shadowCamera.lookAt( _lookTarget );
  5667. shadowCamera.updateMatrixWorld();
  5668. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5669. // compute shadow matrix
  5670. shadowMatrix.set(
  5671. 0.5, 0.0, 0.0, 0.5,
  5672. 0.0, 0.5, 0.0, 0.5,
  5673. 0.0, 0.0, 0.5, 0.5,
  5674. 0.0, 0.0, 0.0, 1.0
  5675. );
  5676. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5677. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5678. }
  5679. _renderer.setRenderTarget( shadowMap );
  5680. _renderer.clear();
  5681. // render shadow map for each cube face (if omni-directional) or
  5682. // run a single pass if not
  5683. for ( var face = 0; face < faceCount; face ++ ) {
  5684. if ( isPointLight ) {
  5685. _lookTarget.copy( shadowCamera.position );
  5686. _lookTarget.add( cubeDirections[ face ] );
  5687. shadowCamera.up.copy( cubeUps[ face ] );
  5688. shadowCamera.lookAt( _lookTarget );
  5689. shadowCamera.updateMatrixWorld();
  5690. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5691. var vpDimensions = cube2DViewPorts[ face ];
  5692. _state.viewport( vpDimensions );
  5693. }
  5694. // update camera matrices and frustum
  5695. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5696. _frustum.setFromMatrix( _projScreenMatrix );
  5697. // set object matrices & frustum culling
  5698. renderObject( scene, camera, shadowCamera, isPointLight );
  5699. }
  5700. }
  5701. // Restore GL state.
  5702. var clearColor = _renderer.getClearColor();
  5703. var clearAlpha = _renderer.getClearAlpha();
  5704. _renderer.setClearColor( clearColor, clearAlpha );
  5705. scope.needsUpdate = false;
  5706. };
  5707. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5708. var geometry = object.geometry;
  5709. var result = null;
  5710. var materialVariants = _depthMaterials;
  5711. var customMaterial = object.customDepthMaterial;
  5712. if ( isPointLight ) {
  5713. materialVariants = _distanceMaterials;
  5714. customMaterial = object.customDistanceMaterial;
  5715. }
  5716. if ( ! customMaterial ) {
  5717. var useMorphing = false;
  5718. if ( material.morphTargets ) {
  5719. if ( geometry && geometry.isBufferGeometry ) {
  5720. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5721. } else if ( geometry && geometry.isGeometry ) {
  5722. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5723. }
  5724. }
  5725. if ( object.isSkinnedMesh && material.skinning === false ) {
  5726. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5727. }
  5728. var useSkinning = object.isSkinnedMesh && material.skinning;
  5729. var variantIndex = 0;
  5730. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5731. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5732. result = materialVariants[ variantIndex ];
  5733. } else {
  5734. result = customMaterial;
  5735. }
  5736. if ( _renderer.localClippingEnabled &&
  5737. material.clipShadows === true &&
  5738. material.clippingPlanes.length !== 0 ) {
  5739. // in this case we need a unique material instance reflecting the
  5740. // appropriate state
  5741. var keyA = result.uuid, keyB = material.uuid;
  5742. var materialsForVariant = _materialCache[ keyA ];
  5743. if ( materialsForVariant === undefined ) {
  5744. materialsForVariant = {};
  5745. _materialCache[ keyA ] = materialsForVariant;
  5746. }
  5747. var cachedMaterial = materialsForVariant[ keyB ];
  5748. if ( cachedMaterial === undefined ) {
  5749. cachedMaterial = result.clone();
  5750. materialsForVariant[ keyB ] = cachedMaterial;
  5751. }
  5752. result = cachedMaterial;
  5753. }
  5754. result.visible = material.visible;
  5755. result.wireframe = material.wireframe;
  5756. var side = material.side;
  5757. if ( scope.renderSingleSided && side == DoubleSide ) {
  5758. side = FrontSide;
  5759. }
  5760. if ( scope.renderReverseSided ) {
  5761. if ( side === FrontSide ) side = BackSide;
  5762. else if ( side === BackSide ) side = FrontSide;
  5763. }
  5764. result.side = side;
  5765. result.clipShadows = material.clipShadows;
  5766. result.clippingPlanes = material.clippingPlanes;
  5767. result.wireframeLinewidth = material.wireframeLinewidth;
  5768. result.linewidth = material.linewidth;
  5769. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5770. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5771. }
  5772. return result;
  5773. }
  5774. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5775. if ( object.visible === false ) return;
  5776. var visible = object.layers.test( camera.layers );
  5777. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5778. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5779. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5780. var geometry = _objects.update( object );
  5781. var material = object.material;
  5782. if ( Array.isArray( material ) ) {
  5783. var groups = geometry.groups;
  5784. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5785. var group = groups[ k ];
  5786. var groupMaterial = material[ group.materialIndex ];
  5787. if ( groupMaterial && groupMaterial.visible ) {
  5788. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5789. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5790. }
  5791. }
  5792. } else if ( material.visible ) {
  5793. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5794. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5795. }
  5796. }
  5797. }
  5798. var children = object.children;
  5799. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5800. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5801. }
  5802. }
  5803. }
  5804. /**
  5805. * @author bhouston / http://clara.io
  5806. */
  5807. function Ray( origin, direction ) {
  5808. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5809. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5810. }
  5811. Object.assign( Ray.prototype, {
  5812. set: function ( origin, direction ) {
  5813. this.origin.copy( origin );
  5814. this.direction.copy( direction );
  5815. return this;
  5816. },
  5817. clone: function () {
  5818. return new this.constructor().copy( this );
  5819. },
  5820. copy: function ( ray ) {
  5821. this.origin.copy( ray.origin );
  5822. this.direction.copy( ray.direction );
  5823. return this;
  5824. },
  5825. at: function ( t, optionalTarget ) {
  5826. var result = optionalTarget || new Vector3();
  5827. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5828. },
  5829. lookAt: function ( v ) {
  5830. this.direction.copy( v ).sub( this.origin ).normalize();
  5831. return this;
  5832. },
  5833. recast: function () {
  5834. var v1 = new Vector3();
  5835. return function recast( t ) {
  5836. this.origin.copy( this.at( t, v1 ) );
  5837. return this;
  5838. };
  5839. }(),
  5840. closestPointToPoint: function ( point, optionalTarget ) {
  5841. var result = optionalTarget || new Vector3();
  5842. result.subVectors( point, this.origin );
  5843. var directionDistance = result.dot( this.direction );
  5844. if ( directionDistance < 0 ) {
  5845. return result.copy( this.origin );
  5846. }
  5847. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5848. },
  5849. distanceToPoint: function ( point ) {
  5850. return Math.sqrt( this.distanceSqToPoint( point ) );
  5851. },
  5852. distanceSqToPoint: function () {
  5853. var v1 = new Vector3();
  5854. return function distanceSqToPoint( point ) {
  5855. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5856. // point behind the ray
  5857. if ( directionDistance < 0 ) {
  5858. return this.origin.distanceToSquared( point );
  5859. }
  5860. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5861. return v1.distanceToSquared( point );
  5862. };
  5863. }(),
  5864. distanceSqToSegment: function () {
  5865. var segCenter = new Vector3();
  5866. var segDir = new Vector3();
  5867. var diff = new Vector3();
  5868. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5869. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5870. // It returns the min distance between the ray and the segment
  5871. // defined by v0 and v1
  5872. // It can also set two optional targets :
  5873. // - The closest point on the ray
  5874. // - The closest point on the segment
  5875. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5876. segDir.copy( v1 ).sub( v0 ).normalize();
  5877. diff.copy( this.origin ).sub( segCenter );
  5878. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5879. var a01 = - this.direction.dot( segDir );
  5880. var b0 = diff.dot( this.direction );
  5881. var b1 = - diff.dot( segDir );
  5882. var c = diff.lengthSq();
  5883. var det = Math.abs( 1 - a01 * a01 );
  5884. var s0, s1, sqrDist, extDet;
  5885. if ( det > 0 ) {
  5886. // The ray and segment are not parallel.
  5887. s0 = a01 * b1 - b0;
  5888. s1 = a01 * b0 - b1;
  5889. extDet = segExtent * det;
  5890. if ( s0 >= 0 ) {
  5891. if ( s1 >= - extDet ) {
  5892. if ( s1 <= extDet ) {
  5893. // region 0
  5894. // Minimum at interior points of ray and segment.
  5895. var invDet = 1 / det;
  5896. s0 *= invDet;
  5897. s1 *= invDet;
  5898. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5899. } else {
  5900. // region 1
  5901. s1 = segExtent;
  5902. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5903. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5904. }
  5905. } else {
  5906. // region 5
  5907. s1 = - segExtent;
  5908. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5909. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5910. }
  5911. } else {
  5912. if ( s1 <= - extDet ) {
  5913. // region 4
  5914. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5915. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5916. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5917. } else if ( s1 <= extDet ) {
  5918. // region 3
  5919. s0 = 0;
  5920. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5921. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5922. } else {
  5923. // region 2
  5924. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5925. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5926. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5927. }
  5928. }
  5929. } else {
  5930. // Ray and segment are parallel.
  5931. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  5932. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5933. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5934. }
  5935. if ( optionalPointOnRay ) {
  5936. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  5937. }
  5938. if ( optionalPointOnSegment ) {
  5939. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  5940. }
  5941. return sqrDist;
  5942. };
  5943. }(),
  5944. intersectSphere: function () {
  5945. var v1 = new Vector3();
  5946. return function intersectSphere( sphere, optionalTarget ) {
  5947. v1.subVectors( sphere.center, this.origin );
  5948. var tca = v1.dot( this.direction );
  5949. var d2 = v1.dot( v1 ) - tca * tca;
  5950. var radius2 = sphere.radius * sphere.radius;
  5951. if ( d2 > radius2 ) return null;
  5952. var thc = Math.sqrt( radius2 - d2 );
  5953. // t0 = first intersect point - entrance on front of sphere
  5954. var t0 = tca - thc;
  5955. // t1 = second intersect point - exit point on back of sphere
  5956. var t1 = tca + thc;
  5957. // test to see if both t0 and t1 are behind the ray - if so, return null
  5958. if ( t0 < 0 && t1 < 0 ) return null;
  5959. // test to see if t0 is behind the ray:
  5960. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5961. // in order to always return an intersect point that is in front of the ray.
  5962. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  5963. // else t0 is in front of the ray, so return the first collision point scaled by t0
  5964. return this.at( t0, optionalTarget );
  5965. };
  5966. }(),
  5967. intersectsSphere: function ( sphere ) {
  5968. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  5969. },
  5970. distanceToPlane: function ( plane ) {
  5971. var denominator = plane.normal.dot( this.direction );
  5972. if ( denominator === 0 ) {
  5973. // line is coplanar, return origin
  5974. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  5975. return 0;
  5976. }
  5977. // Null is preferable to undefined since undefined means.... it is undefined
  5978. return null;
  5979. }
  5980. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  5981. // Return if the ray never intersects the plane
  5982. return t >= 0 ? t : null;
  5983. },
  5984. intersectPlane: function ( plane, optionalTarget ) {
  5985. var t = this.distanceToPlane( plane );
  5986. if ( t === null ) {
  5987. return null;
  5988. }
  5989. return this.at( t, optionalTarget );
  5990. },
  5991. intersectsPlane: function ( plane ) {
  5992. // check if the ray lies on the plane first
  5993. var distToPoint = plane.distanceToPoint( this.origin );
  5994. if ( distToPoint === 0 ) {
  5995. return true;
  5996. }
  5997. var denominator = plane.normal.dot( this.direction );
  5998. if ( denominator * distToPoint < 0 ) {
  5999. return true;
  6000. }
  6001. // ray origin is behind the plane (and is pointing behind it)
  6002. return false;
  6003. },
  6004. intersectBox: function ( box, optionalTarget ) {
  6005. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6006. var invdirx = 1 / this.direction.x,
  6007. invdiry = 1 / this.direction.y,
  6008. invdirz = 1 / this.direction.z;
  6009. var origin = this.origin;
  6010. if ( invdirx >= 0 ) {
  6011. tmin = ( box.min.x - origin.x ) * invdirx;
  6012. tmax = ( box.max.x - origin.x ) * invdirx;
  6013. } else {
  6014. tmin = ( box.max.x - origin.x ) * invdirx;
  6015. tmax = ( box.min.x - origin.x ) * invdirx;
  6016. }
  6017. if ( invdiry >= 0 ) {
  6018. tymin = ( box.min.y - origin.y ) * invdiry;
  6019. tymax = ( box.max.y - origin.y ) * invdiry;
  6020. } else {
  6021. tymin = ( box.max.y - origin.y ) * invdiry;
  6022. tymax = ( box.min.y - origin.y ) * invdiry;
  6023. }
  6024. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6025. // These lines also handle the case where tmin or tmax is NaN
  6026. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6027. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6028. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6029. if ( invdirz >= 0 ) {
  6030. tzmin = ( box.min.z - origin.z ) * invdirz;
  6031. tzmax = ( box.max.z - origin.z ) * invdirz;
  6032. } else {
  6033. tzmin = ( box.max.z - origin.z ) * invdirz;
  6034. tzmax = ( box.min.z - origin.z ) * invdirz;
  6035. }
  6036. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6037. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6038. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6039. //return point closest to the ray (positive side)
  6040. if ( tmax < 0 ) return null;
  6041. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6042. },
  6043. intersectsBox: ( function () {
  6044. var v = new Vector3();
  6045. return function intersectsBox( box ) {
  6046. return this.intersectBox( box, v ) !== null;
  6047. };
  6048. } )(),
  6049. intersectTriangle: function () {
  6050. // Compute the offset origin, edges, and normal.
  6051. var diff = new Vector3();
  6052. var edge1 = new Vector3();
  6053. var edge2 = new Vector3();
  6054. var normal = new Vector3();
  6055. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6056. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6057. edge1.subVectors( b, a );
  6058. edge2.subVectors( c, a );
  6059. normal.crossVectors( edge1, edge2 );
  6060. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6061. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6062. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6063. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6064. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6065. var DdN = this.direction.dot( normal );
  6066. var sign;
  6067. if ( DdN > 0 ) {
  6068. if ( backfaceCulling ) return null;
  6069. sign = 1;
  6070. } else if ( DdN < 0 ) {
  6071. sign = - 1;
  6072. DdN = - DdN;
  6073. } else {
  6074. return null;
  6075. }
  6076. diff.subVectors( this.origin, a );
  6077. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6078. // b1 < 0, no intersection
  6079. if ( DdQxE2 < 0 ) {
  6080. return null;
  6081. }
  6082. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6083. // b2 < 0, no intersection
  6084. if ( DdE1xQ < 0 ) {
  6085. return null;
  6086. }
  6087. // b1+b2 > 1, no intersection
  6088. if ( DdQxE2 + DdE1xQ > DdN ) {
  6089. return null;
  6090. }
  6091. // Line intersects triangle, check if ray does.
  6092. var QdN = - sign * diff.dot( normal );
  6093. // t < 0, no intersection
  6094. if ( QdN < 0 ) {
  6095. return null;
  6096. }
  6097. // Ray intersects triangle.
  6098. return this.at( QdN / DdN, optionalTarget );
  6099. };
  6100. }(),
  6101. applyMatrix4: function ( matrix4 ) {
  6102. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6103. this.origin.applyMatrix4( matrix4 );
  6104. this.direction.sub( this.origin );
  6105. this.direction.normalize();
  6106. return this;
  6107. },
  6108. equals: function ( ray ) {
  6109. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6110. }
  6111. } );
  6112. /**
  6113. * @author mrdoob / http://mrdoob.com/
  6114. * @author WestLangley / http://github.com/WestLangley
  6115. * @author bhouston / http://clara.io
  6116. */
  6117. function Euler( x, y, z, order ) {
  6118. this._x = x || 0;
  6119. this._y = y || 0;
  6120. this._z = z || 0;
  6121. this._order = order || Euler.DefaultOrder;
  6122. }
  6123. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6124. Euler.DefaultOrder = 'XYZ';
  6125. Object.defineProperties( Euler.prototype, {
  6126. x: {
  6127. get: function () {
  6128. return this._x;
  6129. },
  6130. set: function ( value ) {
  6131. this._x = value;
  6132. this.onChangeCallback();
  6133. }
  6134. },
  6135. y: {
  6136. get: function () {
  6137. return this._y;
  6138. },
  6139. set: function ( value ) {
  6140. this._y = value;
  6141. this.onChangeCallback();
  6142. }
  6143. },
  6144. z: {
  6145. get: function () {
  6146. return this._z;
  6147. },
  6148. set: function ( value ) {
  6149. this._z = value;
  6150. this.onChangeCallback();
  6151. }
  6152. },
  6153. order: {
  6154. get: function () {
  6155. return this._order;
  6156. },
  6157. set: function ( value ) {
  6158. this._order = value;
  6159. this.onChangeCallback();
  6160. }
  6161. }
  6162. } );
  6163. Object.assign( Euler.prototype, {
  6164. isEuler: true,
  6165. set: function ( x, y, z, order ) {
  6166. this._x = x;
  6167. this._y = y;
  6168. this._z = z;
  6169. this._order = order || this._order;
  6170. this.onChangeCallback();
  6171. return this;
  6172. },
  6173. clone: function () {
  6174. return new this.constructor( this._x, this._y, this._z, this._order );
  6175. },
  6176. copy: function ( euler ) {
  6177. this._x = euler._x;
  6178. this._y = euler._y;
  6179. this._z = euler._z;
  6180. this._order = euler._order;
  6181. this.onChangeCallback();
  6182. return this;
  6183. },
  6184. setFromRotationMatrix: function ( m, order, update ) {
  6185. var clamp = _Math.clamp;
  6186. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6187. var te = m.elements;
  6188. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6189. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6190. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6191. order = order || this._order;
  6192. if ( order === 'XYZ' ) {
  6193. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6194. if ( Math.abs( m13 ) < 0.99999 ) {
  6195. this._x = Math.atan2( - m23, m33 );
  6196. this._z = Math.atan2( - m12, m11 );
  6197. } else {
  6198. this._x = Math.atan2( m32, m22 );
  6199. this._z = 0;
  6200. }
  6201. } else if ( order === 'YXZ' ) {
  6202. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6203. if ( Math.abs( m23 ) < 0.99999 ) {
  6204. this._y = Math.atan2( m13, m33 );
  6205. this._z = Math.atan2( m21, m22 );
  6206. } else {
  6207. this._y = Math.atan2( - m31, m11 );
  6208. this._z = 0;
  6209. }
  6210. } else if ( order === 'ZXY' ) {
  6211. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6212. if ( Math.abs( m32 ) < 0.99999 ) {
  6213. this._y = Math.atan2( - m31, m33 );
  6214. this._z = Math.atan2( - m12, m22 );
  6215. } else {
  6216. this._y = 0;
  6217. this._z = Math.atan2( m21, m11 );
  6218. }
  6219. } else if ( order === 'ZYX' ) {
  6220. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6221. if ( Math.abs( m31 ) < 0.99999 ) {
  6222. this._x = Math.atan2( m32, m33 );
  6223. this._z = Math.atan2( m21, m11 );
  6224. } else {
  6225. this._x = 0;
  6226. this._z = Math.atan2( - m12, m22 );
  6227. }
  6228. } else if ( order === 'YZX' ) {
  6229. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6230. if ( Math.abs( m21 ) < 0.99999 ) {
  6231. this._x = Math.atan2( - m23, m22 );
  6232. this._y = Math.atan2( - m31, m11 );
  6233. } else {
  6234. this._x = 0;
  6235. this._y = Math.atan2( m13, m33 );
  6236. }
  6237. } else if ( order === 'XZY' ) {
  6238. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6239. if ( Math.abs( m12 ) < 0.99999 ) {
  6240. this._x = Math.atan2( m32, m22 );
  6241. this._y = Math.atan2( m13, m11 );
  6242. } else {
  6243. this._x = Math.atan2( - m23, m33 );
  6244. this._y = 0;
  6245. }
  6246. } else {
  6247. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6248. }
  6249. this._order = order;
  6250. if ( update !== false ) this.onChangeCallback();
  6251. return this;
  6252. },
  6253. setFromQuaternion: function () {
  6254. var matrix = new Matrix4();
  6255. return function setFromQuaternion( q, order, update ) {
  6256. matrix.makeRotationFromQuaternion( q );
  6257. return this.setFromRotationMatrix( matrix, order, update );
  6258. };
  6259. }(),
  6260. setFromVector3: function ( v, order ) {
  6261. return this.set( v.x, v.y, v.z, order || this._order );
  6262. },
  6263. reorder: function () {
  6264. // WARNING: this discards revolution information -bhouston
  6265. var q = new Quaternion();
  6266. return function reorder( newOrder ) {
  6267. q.setFromEuler( this );
  6268. return this.setFromQuaternion( q, newOrder );
  6269. };
  6270. }(),
  6271. equals: function ( euler ) {
  6272. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6273. },
  6274. fromArray: function ( array ) {
  6275. this._x = array[ 0 ];
  6276. this._y = array[ 1 ];
  6277. this._z = array[ 2 ];
  6278. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6279. this.onChangeCallback();
  6280. return this;
  6281. },
  6282. toArray: function ( array, offset ) {
  6283. if ( array === undefined ) array = [];
  6284. if ( offset === undefined ) offset = 0;
  6285. array[ offset ] = this._x;
  6286. array[ offset + 1 ] = this._y;
  6287. array[ offset + 2 ] = this._z;
  6288. array[ offset + 3 ] = this._order;
  6289. return array;
  6290. },
  6291. toVector3: function ( optionalResult ) {
  6292. if ( optionalResult ) {
  6293. return optionalResult.set( this._x, this._y, this._z );
  6294. } else {
  6295. return new Vector3( this._x, this._y, this._z );
  6296. }
  6297. },
  6298. onChange: function ( callback ) {
  6299. this.onChangeCallback = callback;
  6300. return this;
  6301. },
  6302. onChangeCallback: function () {}
  6303. } );
  6304. /**
  6305. * @author mrdoob / http://mrdoob.com/
  6306. */
  6307. function Layers() {
  6308. this.mask = 1 | 0;
  6309. }
  6310. Object.assign( Layers.prototype, {
  6311. set: function ( channel ) {
  6312. this.mask = 1 << channel | 0;
  6313. },
  6314. enable: function ( channel ) {
  6315. this.mask |= 1 << channel | 0;
  6316. },
  6317. toggle: function ( channel ) {
  6318. this.mask ^= 1 << channel | 0;
  6319. },
  6320. disable: function ( channel ) {
  6321. this.mask &= ~ ( 1 << channel | 0 );
  6322. },
  6323. test: function ( layers ) {
  6324. return ( this.mask & layers.mask ) !== 0;
  6325. }
  6326. } );
  6327. /**
  6328. * @author mrdoob / http://mrdoob.com/
  6329. * @author mikael emtinger / http://gomo.se/
  6330. * @author alteredq / http://alteredqualia.com/
  6331. * @author WestLangley / http://github.com/WestLangley
  6332. * @author elephantatwork / www.elephantatwork.ch
  6333. */
  6334. var object3DId = 0;
  6335. function Object3D() {
  6336. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6337. this.uuid = _Math.generateUUID();
  6338. this.name = '';
  6339. this.type = 'Object3D';
  6340. this.parent = null;
  6341. this.children = [];
  6342. this.up = Object3D.DefaultUp.clone();
  6343. var position = new Vector3();
  6344. var rotation = new Euler();
  6345. var quaternion = new Quaternion();
  6346. var scale = new Vector3( 1, 1, 1 );
  6347. function onRotationChange() {
  6348. quaternion.setFromEuler( rotation, false );
  6349. }
  6350. function onQuaternionChange() {
  6351. rotation.setFromQuaternion( quaternion, undefined, false );
  6352. }
  6353. rotation.onChange( onRotationChange );
  6354. quaternion.onChange( onQuaternionChange );
  6355. Object.defineProperties( this, {
  6356. position: {
  6357. enumerable: true,
  6358. value: position
  6359. },
  6360. rotation: {
  6361. enumerable: true,
  6362. value: rotation
  6363. },
  6364. quaternion: {
  6365. enumerable: true,
  6366. value: quaternion
  6367. },
  6368. scale: {
  6369. enumerable: true,
  6370. value: scale
  6371. },
  6372. modelViewMatrix: {
  6373. value: new Matrix4()
  6374. },
  6375. normalMatrix: {
  6376. value: new Matrix3()
  6377. }
  6378. } );
  6379. this.matrix = new Matrix4();
  6380. this.matrixWorld = new Matrix4();
  6381. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6382. this.matrixWorldNeedsUpdate = false;
  6383. this.layers = new Layers();
  6384. this.visible = true;
  6385. this.castShadow = false;
  6386. this.receiveShadow = false;
  6387. this.frustumCulled = true;
  6388. this.renderOrder = 0;
  6389. this.userData = {};
  6390. }
  6391. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6392. Object3D.DefaultMatrixAutoUpdate = true;
  6393. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6394. isObject3D: true,
  6395. onBeforeRender: function () {},
  6396. onAfterRender: function () {},
  6397. applyMatrix: function ( matrix ) {
  6398. this.matrix.multiplyMatrices( matrix, this.matrix );
  6399. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6400. },
  6401. applyQuaternion: function ( q ) {
  6402. this.quaternion.premultiply( q );
  6403. return this;
  6404. },
  6405. setRotationFromAxisAngle: function ( axis, angle ) {
  6406. // assumes axis is normalized
  6407. this.quaternion.setFromAxisAngle( axis, angle );
  6408. },
  6409. setRotationFromEuler: function ( euler ) {
  6410. this.quaternion.setFromEuler( euler, true );
  6411. },
  6412. setRotationFromMatrix: function ( m ) {
  6413. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6414. this.quaternion.setFromRotationMatrix( m );
  6415. },
  6416. setRotationFromQuaternion: function ( q ) {
  6417. // assumes q is normalized
  6418. this.quaternion.copy( q );
  6419. },
  6420. rotateOnAxis: function () {
  6421. // rotate object on axis in object space
  6422. // axis is assumed to be normalized
  6423. var q1 = new Quaternion();
  6424. return function rotateOnAxis( axis, angle ) {
  6425. q1.setFromAxisAngle( axis, angle );
  6426. this.quaternion.multiply( q1 );
  6427. return this;
  6428. };
  6429. }(),
  6430. rotateX: function () {
  6431. var v1 = new Vector3( 1, 0, 0 );
  6432. return function rotateX( angle ) {
  6433. return this.rotateOnAxis( v1, angle );
  6434. };
  6435. }(),
  6436. rotateY: function () {
  6437. var v1 = new Vector3( 0, 1, 0 );
  6438. return function rotateY( angle ) {
  6439. return this.rotateOnAxis( v1, angle );
  6440. };
  6441. }(),
  6442. rotateZ: function () {
  6443. var v1 = new Vector3( 0, 0, 1 );
  6444. return function rotateZ( angle ) {
  6445. return this.rotateOnAxis( v1, angle );
  6446. };
  6447. }(),
  6448. translateOnAxis: function () {
  6449. // translate object by distance along axis in object space
  6450. // axis is assumed to be normalized
  6451. var v1 = new Vector3();
  6452. return function translateOnAxis( axis, distance ) {
  6453. v1.copy( axis ).applyQuaternion( this.quaternion );
  6454. this.position.add( v1.multiplyScalar( distance ) );
  6455. return this;
  6456. };
  6457. }(),
  6458. translateX: function () {
  6459. var v1 = new Vector3( 1, 0, 0 );
  6460. return function translateX( distance ) {
  6461. return this.translateOnAxis( v1, distance );
  6462. };
  6463. }(),
  6464. translateY: function () {
  6465. var v1 = new Vector3( 0, 1, 0 );
  6466. return function translateY( distance ) {
  6467. return this.translateOnAxis( v1, distance );
  6468. };
  6469. }(),
  6470. translateZ: function () {
  6471. var v1 = new Vector3( 0, 0, 1 );
  6472. return function translateZ( distance ) {
  6473. return this.translateOnAxis( v1, distance );
  6474. };
  6475. }(),
  6476. localToWorld: function ( vector ) {
  6477. return vector.applyMatrix4( this.matrixWorld );
  6478. },
  6479. worldToLocal: function () {
  6480. var m1 = new Matrix4();
  6481. return function worldToLocal( vector ) {
  6482. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6483. };
  6484. }(),
  6485. lookAt: function () {
  6486. // This method does not support objects with rotated and/or translated parent(s)
  6487. var m1 = new Matrix4();
  6488. return function lookAt( vector ) {
  6489. if ( this.isCamera ) {
  6490. m1.lookAt( this.position, vector, this.up );
  6491. } else {
  6492. m1.lookAt( vector, this.position, this.up );
  6493. }
  6494. this.quaternion.setFromRotationMatrix( m1 );
  6495. };
  6496. }(),
  6497. add: function ( object ) {
  6498. if ( arguments.length > 1 ) {
  6499. for ( var i = 0; i < arguments.length; i ++ ) {
  6500. this.add( arguments[ i ] );
  6501. }
  6502. return this;
  6503. }
  6504. if ( object === this ) {
  6505. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6506. return this;
  6507. }
  6508. if ( ( object && object.isObject3D ) ) {
  6509. if ( object.parent !== null ) {
  6510. object.parent.remove( object );
  6511. }
  6512. object.parent = this;
  6513. object.dispatchEvent( { type: 'added' } );
  6514. this.children.push( object );
  6515. } else {
  6516. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6517. }
  6518. return this;
  6519. },
  6520. remove: function ( object ) {
  6521. if ( arguments.length > 1 ) {
  6522. for ( var i = 0; i < arguments.length; i ++ ) {
  6523. this.remove( arguments[ i ] );
  6524. }
  6525. }
  6526. var index = this.children.indexOf( object );
  6527. if ( index !== - 1 ) {
  6528. object.parent = null;
  6529. object.dispatchEvent( { type: 'removed' } );
  6530. this.children.splice( index, 1 );
  6531. }
  6532. },
  6533. getObjectById: function ( id ) {
  6534. return this.getObjectByProperty( 'id', id );
  6535. },
  6536. getObjectByName: function ( name ) {
  6537. return this.getObjectByProperty( 'name', name );
  6538. },
  6539. getObjectByProperty: function ( name, value ) {
  6540. if ( this[ name ] === value ) return this;
  6541. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6542. var child = this.children[ i ];
  6543. var object = child.getObjectByProperty( name, value );
  6544. if ( object !== undefined ) {
  6545. return object;
  6546. }
  6547. }
  6548. return undefined;
  6549. },
  6550. getWorldPosition: function ( optionalTarget ) {
  6551. var result = optionalTarget || new Vector3();
  6552. this.updateMatrixWorld( true );
  6553. return result.setFromMatrixPosition( this.matrixWorld );
  6554. },
  6555. getWorldQuaternion: function () {
  6556. var position = new Vector3();
  6557. var scale = new Vector3();
  6558. return function getWorldQuaternion( optionalTarget ) {
  6559. var result = optionalTarget || new Quaternion();
  6560. this.updateMatrixWorld( true );
  6561. this.matrixWorld.decompose( position, result, scale );
  6562. return result;
  6563. };
  6564. }(),
  6565. getWorldRotation: function () {
  6566. var quaternion = new Quaternion();
  6567. return function getWorldRotation( optionalTarget ) {
  6568. var result = optionalTarget || new Euler();
  6569. this.getWorldQuaternion( quaternion );
  6570. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6571. };
  6572. }(),
  6573. getWorldScale: function () {
  6574. var position = new Vector3();
  6575. var quaternion = new Quaternion();
  6576. return function getWorldScale( optionalTarget ) {
  6577. var result = optionalTarget || new Vector3();
  6578. this.updateMatrixWorld( true );
  6579. this.matrixWorld.decompose( position, quaternion, result );
  6580. return result;
  6581. };
  6582. }(),
  6583. getWorldDirection: function () {
  6584. var quaternion = new Quaternion();
  6585. return function getWorldDirection( optionalTarget ) {
  6586. var result = optionalTarget || new Vector3();
  6587. this.getWorldQuaternion( quaternion );
  6588. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6589. };
  6590. }(),
  6591. raycast: function () {},
  6592. traverse: function ( callback ) {
  6593. callback( this );
  6594. var children = this.children;
  6595. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6596. children[ i ].traverse( callback );
  6597. }
  6598. },
  6599. traverseVisible: function ( callback ) {
  6600. if ( this.visible === false ) return;
  6601. callback( this );
  6602. var children = this.children;
  6603. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6604. children[ i ].traverseVisible( callback );
  6605. }
  6606. },
  6607. traverseAncestors: function ( callback ) {
  6608. var parent = this.parent;
  6609. if ( parent !== null ) {
  6610. callback( parent );
  6611. parent.traverseAncestors( callback );
  6612. }
  6613. },
  6614. updateMatrix: function () {
  6615. this.matrix.compose( this.position, this.quaternion, this.scale );
  6616. this.matrixWorldNeedsUpdate = true;
  6617. },
  6618. updateMatrixWorld: function ( force ) {
  6619. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6620. if ( this.matrixWorldNeedsUpdate || force ) {
  6621. if ( this.parent === null ) {
  6622. this.matrixWorld.copy( this.matrix );
  6623. } else {
  6624. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6625. }
  6626. this.matrixWorldNeedsUpdate = false;
  6627. force = true;
  6628. }
  6629. // update children
  6630. var children = this.children;
  6631. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6632. children[ i ].updateMatrixWorld( force );
  6633. }
  6634. },
  6635. toJSON: function ( meta ) {
  6636. // meta is '' when called from JSON.stringify
  6637. var isRootObject = ( meta === undefined || meta === '' );
  6638. var output = {};
  6639. // meta is a hash used to collect geometries, materials.
  6640. // not providing it implies that this is the root object
  6641. // being serialized.
  6642. if ( isRootObject ) {
  6643. // initialize meta obj
  6644. meta = {
  6645. geometries: {},
  6646. materials: {},
  6647. textures: {},
  6648. images: {}
  6649. };
  6650. output.metadata = {
  6651. version: 4.5,
  6652. type: 'Object',
  6653. generator: 'Object3D.toJSON'
  6654. };
  6655. }
  6656. // standard Object3D serialization
  6657. var object = {};
  6658. object.uuid = this.uuid;
  6659. object.type = this.type;
  6660. if ( this.name !== '' ) object.name = this.name;
  6661. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6662. if ( this.castShadow === true ) object.castShadow = true;
  6663. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6664. if ( this.visible === false ) object.visible = false;
  6665. object.matrix = this.matrix.toArray();
  6666. //
  6667. function serialize( library, element ) {
  6668. if ( library[ element.uuid ] === undefined ) {
  6669. library[ element.uuid ] = element.toJSON( meta );
  6670. }
  6671. return element.uuid;
  6672. }
  6673. if ( this.geometry !== undefined ) {
  6674. object.geometry = serialize( meta.geometries, this.geometry );
  6675. }
  6676. if ( this.material !== undefined ) {
  6677. if ( Array.isArray( this.material ) ) {
  6678. var uuids = [];
  6679. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6680. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6681. }
  6682. object.material = uuids;
  6683. } else {
  6684. object.material = serialize( meta.materials, this.material );
  6685. }
  6686. }
  6687. //
  6688. if ( this.children.length > 0 ) {
  6689. object.children = [];
  6690. for ( var i = 0; i < this.children.length; i ++ ) {
  6691. object.children.push( this.children[ i ].toJSON( meta ).object );
  6692. }
  6693. }
  6694. if ( isRootObject ) {
  6695. var geometries = extractFromCache( meta.geometries );
  6696. var materials = extractFromCache( meta.materials );
  6697. var textures = extractFromCache( meta.textures );
  6698. var images = extractFromCache( meta.images );
  6699. if ( geometries.length > 0 ) output.geometries = geometries;
  6700. if ( materials.length > 0 ) output.materials = materials;
  6701. if ( textures.length > 0 ) output.textures = textures;
  6702. if ( images.length > 0 ) output.images = images;
  6703. }
  6704. output.object = object;
  6705. return output;
  6706. // extract data from the cache hash
  6707. // remove metadata on each item
  6708. // and return as array
  6709. function extractFromCache( cache ) {
  6710. var values = [];
  6711. for ( var key in cache ) {
  6712. var data = cache[ key ];
  6713. delete data.metadata;
  6714. values.push( data );
  6715. }
  6716. return values;
  6717. }
  6718. },
  6719. clone: function ( recursive ) {
  6720. return new this.constructor().copy( this, recursive );
  6721. },
  6722. copy: function ( source, recursive ) {
  6723. if ( recursive === undefined ) recursive = true;
  6724. this.name = source.name;
  6725. this.up.copy( source.up );
  6726. this.position.copy( source.position );
  6727. this.quaternion.copy( source.quaternion );
  6728. this.scale.copy( source.scale );
  6729. this.matrix.copy( source.matrix );
  6730. this.matrixWorld.copy( source.matrixWorld );
  6731. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6732. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6733. this.layers.mask = source.layers.mask;
  6734. this.visible = source.visible;
  6735. this.castShadow = source.castShadow;
  6736. this.receiveShadow = source.receiveShadow;
  6737. this.frustumCulled = source.frustumCulled;
  6738. this.renderOrder = source.renderOrder;
  6739. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6740. if ( recursive === true ) {
  6741. for ( var i = 0; i < source.children.length; i ++ ) {
  6742. var child = source.children[ i ];
  6743. this.add( child.clone() );
  6744. }
  6745. }
  6746. return this;
  6747. }
  6748. } );
  6749. /**
  6750. * @author bhouston / http://clara.io
  6751. */
  6752. function Line3( start, end ) {
  6753. this.start = ( start !== undefined ) ? start : new Vector3();
  6754. this.end = ( end !== undefined ) ? end : new Vector3();
  6755. }
  6756. Object.assign( Line3.prototype, {
  6757. set: function ( start, end ) {
  6758. this.start.copy( start );
  6759. this.end.copy( end );
  6760. return this;
  6761. },
  6762. clone: function () {
  6763. return new this.constructor().copy( this );
  6764. },
  6765. copy: function ( line ) {
  6766. this.start.copy( line.start );
  6767. this.end.copy( line.end );
  6768. return this;
  6769. },
  6770. getCenter: function ( optionalTarget ) {
  6771. var result = optionalTarget || new Vector3();
  6772. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6773. },
  6774. delta: function ( optionalTarget ) {
  6775. var result = optionalTarget || new Vector3();
  6776. return result.subVectors( this.end, this.start );
  6777. },
  6778. distanceSq: function () {
  6779. return this.start.distanceToSquared( this.end );
  6780. },
  6781. distance: function () {
  6782. return this.start.distanceTo( this.end );
  6783. },
  6784. at: function ( t, optionalTarget ) {
  6785. var result = optionalTarget || new Vector3();
  6786. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6787. },
  6788. closestPointToPointParameter: function () {
  6789. var startP = new Vector3();
  6790. var startEnd = new Vector3();
  6791. return function closestPointToPointParameter( point, clampToLine ) {
  6792. startP.subVectors( point, this.start );
  6793. startEnd.subVectors( this.end, this.start );
  6794. var startEnd2 = startEnd.dot( startEnd );
  6795. var startEnd_startP = startEnd.dot( startP );
  6796. var t = startEnd_startP / startEnd2;
  6797. if ( clampToLine ) {
  6798. t = _Math.clamp( t, 0, 1 );
  6799. }
  6800. return t;
  6801. };
  6802. }(),
  6803. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6804. var t = this.closestPointToPointParameter( point, clampToLine );
  6805. var result = optionalTarget || new Vector3();
  6806. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6807. },
  6808. applyMatrix4: function ( matrix ) {
  6809. this.start.applyMatrix4( matrix );
  6810. this.end.applyMatrix4( matrix );
  6811. return this;
  6812. },
  6813. equals: function ( line ) {
  6814. return line.start.equals( this.start ) && line.end.equals( this.end );
  6815. }
  6816. } );
  6817. /**
  6818. * @author bhouston / http://clara.io
  6819. * @author mrdoob / http://mrdoob.com/
  6820. */
  6821. function Triangle( a, b, c ) {
  6822. this.a = ( a !== undefined ) ? a : new Vector3();
  6823. this.b = ( b !== undefined ) ? b : new Vector3();
  6824. this.c = ( c !== undefined ) ? c : new Vector3();
  6825. }
  6826. Object.assign( Triangle, {
  6827. normal: function () {
  6828. var v0 = new Vector3();
  6829. return function normal( a, b, c, optionalTarget ) {
  6830. var result = optionalTarget || new Vector3();
  6831. result.subVectors( c, b );
  6832. v0.subVectors( a, b );
  6833. result.cross( v0 );
  6834. var resultLengthSq = result.lengthSq();
  6835. if ( resultLengthSq > 0 ) {
  6836. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6837. }
  6838. return result.set( 0, 0, 0 );
  6839. };
  6840. }(),
  6841. // static/instance method to calculate barycentric coordinates
  6842. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6843. barycoordFromPoint: function () {
  6844. var v0 = new Vector3();
  6845. var v1 = new Vector3();
  6846. var v2 = new Vector3();
  6847. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6848. v0.subVectors( c, a );
  6849. v1.subVectors( b, a );
  6850. v2.subVectors( point, a );
  6851. var dot00 = v0.dot( v0 );
  6852. var dot01 = v0.dot( v1 );
  6853. var dot02 = v0.dot( v2 );
  6854. var dot11 = v1.dot( v1 );
  6855. var dot12 = v1.dot( v2 );
  6856. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6857. var result = optionalTarget || new Vector3();
  6858. // collinear or singular triangle
  6859. if ( denom === 0 ) {
  6860. // arbitrary location outside of triangle?
  6861. // not sure if this is the best idea, maybe should be returning undefined
  6862. return result.set( - 2, - 1, - 1 );
  6863. }
  6864. var invDenom = 1 / denom;
  6865. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6866. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6867. // barycentric coordinates must always sum to 1
  6868. return result.set( 1 - u - v, v, u );
  6869. };
  6870. }(),
  6871. containsPoint: function () {
  6872. var v1 = new Vector3();
  6873. return function containsPoint( point, a, b, c ) {
  6874. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6875. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6876. };
  6877. }()
  6878. } );
  6879. Object.assign( Triangle.prototype, {
  6880. set: function ( a, b, c ) {
  6881. this.a.copy( a );
  6882. this.b.copy( b );
  6883. this.c.copy( c );
  6884. return this;
  6885. },
  6886. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6887. this.a.copy( points[ i0 ] );
  6888. this.b.copy( points[ i1 ] );
  6889. this.c.copy( points[ i2 ] );
  6890. return this;
  6891. },
  6892. clone: function () {
  6893. return new this.constructor().copy( this );
  6894. },
  6895. copy: function ( triangle ) {
  6896. this.a.copy( triangle.a );
  6897. this.b.copy( triangle.b );
  6898. this.c.copy( triangle.c );
  6899. return this;
  6900. },
  6901. area: function () {
  6902. var v0 = new Vector3();
  6903. var v1 = new Vector3();
  6904. return function area() {
  6905. v0.subVectors( this.c, this.b );
  6906. v1.subVectors( this.a, this.b );
  6907. return v0.cross( v1 ).length() * 0.5;
  6908. };
  6909. }(),
  6910. midpoint: function ( optionalTarget ) {
  6911. var result = optionalTarget || new Vector3();
  6912. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6913. },
  6914. normal: function ( optionalTarget ) {
  6915. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6916. },
  6917. plane: function ( optionalTarget ) {
  6918. var result = optionalTarget || new Plane();
  6919. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6920. },
  6921. barycoordFromPoint: function ( point, optionalTarget ) {
  6922. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6923. },
  6924. containsPoint: function ( point ) {
  6925. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6926. },
  6927. closestPointToPoint: function () {
  6928. var plane = new Plane();
  6929. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  6930. var projectedPoint = new Vector3();
  6931. var closestPoint = new Vector3();
  6932. return function closestPointToPoint( point, optionalTarget ) {
  6933. var result = optionalTarget || new Vector3();
  6934. var minDistance = Infinity;
  6935. // project the point onto the plane of the triangle
  6936. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6937. plane.projectPoint( point, projectedPoint );
  6938. // check if the projection lies within the triangle
  6939. if( this.containsPoint( projectedPoint ) === true ) {
  6940. // if so, this is the closest point
  6941. result.copy( projectedPoint );
  6942. } else {
  6943. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6944. edgeList[ 0 ].set( this.a, this.b );
  6945. edgeList[ 1 ].set( this.b, this.c );
  6946. edgeList[ 2 ].set( this.c, this.a );
  6947. for( var i = 0; i < edgeList.length; i ++ ) {
  6948. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  6949. var distance = projectedPoint.distanceToSquared( closestPoint );
  6950. if( distance < minDistance ) {
  6951. minDistance = distance;
  6952. result.copy( closestPoint );
  6953. }
  6954. }
  6955. }
  6956. return result;
  6957. };
  6958. }(),
  6959. equals: function ( triangle ) {
  6960. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6961. }
  6962. } );
  6963. /**
  6964. * @author mrdoob / http://mrdoob.com/
  6965. * @author alteredq / http://alteredqualia.com/
  6966. */
  6967. function Face3( a, b, c, normal, color, materialIndex ) {
  6968. this.a = a;
  6969. this.b = b;
  6970. this.c = c;
  6971. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6972. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6973. this.color = ( color && color.isColor ) ? color : new Color();
  6974. this.vertexColors = Array.isArray( color ) ? color : [];
  6975. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6976. }
  6977. Object.assign( Face3.prototype, {
  6978. clone: function () {
  6979. return new this.constructor().copy( this );
  6980. },
  6981. copy: function ( source ) {
  6982. this.a = source.a;
  6983. this.b = source.b;
  6984. this.c = source.c;
  6985. this.normal.copy( source.normal );
  6986. this.color.copy( source.color );
  6987. this.materialIndex = source.materialIndex;
  6988. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6989. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6990. }
  6991. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6992. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6993. }
  6994. return this;
  6995. }
  6996. } );
  6997. /**
  6998. * @author mrdoob / http://mrdoob.com/
  6999. * @author alteredq / http://alteredqualia.com/
  7000. *
  7001. * parameters = {
  7002. * color: <hex>,
  7003. * opacity: <float>,
  7004. * map: new THREE.Texture( <Image> ),
  7005. *
  7006. * lightMap: new THREE.Texture( <Image> ),
  7007. * lightMapIntensity: <float>
  7008. *
  7009. * aoMap: new THREE.Texture( <Image> ),
  7010. * aoMapIntensity: <float>
  7011. *
  7012. * specularMap: new THREE.Texture( <Image> ),
  7013. *
  7014. * alphaMap: new THREE.Texture( <Image> ),
  7015. *
  7016. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7017. * combine: THREE.Multiply,
  7018. * reflectivity: <float>,
  7019. * refractionRatio: <float>,
  7020. *
  7021. * shading: THREE.SmoothShading,
  7022. * depthTest: <bool>,
  7023. * depthWrite: <bool>,
  7024. *
  7025. * wireframe: <boolean>,
  7026. * wireframeLinewidth: <float>,
  7027. *
  7028. * skinning: <bool>,
  7029. * morphTargets: <bool>
  7030. * }
  7031. */
  7032. function MeshBasicMaterial( parameters ) {
  7033. Material.call( this );
  7034. this.type = 'MeshBasicMaterial';
  7035. this.color = new Color( 0xffffff ); // emissive
  7036. this.map = null;
  7037. this.lightMap = null;
  7038. this.lightMapIntensity = 1.0;
  7039. this.aoMap = null;
  7040. this.aoMapIntensity = 1.0;
  7041. this.specularMap = null;
  7042. this.alphaMap = null;
  7043. this.envMap = null;
  7044. this.combine = MultiplyOperation;
  7045. this.reflectivity = 1;
  7046. this.refractionRatio = 0.98;
  7047. this.wireframe = false;
  7048. this.wireframeLinewidth = 1;
  7049. this.wireframeLinecap = 'round';
  7050. this.wireframeLinejoin = 'round';
  7051. this.skinning = false;
  7052. this.morphTargets = false;
  7053. this.lights = false;
  7054. this.setValues( parameters );
  7055. }
  7056. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7057. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7058. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7059. MeshBasicMaterial.prototype.copy = function ( source ) {
  7060. Material.prototype.copy.call( this, source );
  7061. this.color.copy( source.color );
  7062. this.map = source.map;
  7063. this.lightMap = source.lightMap;
  7064. this.lightMapIntensity = source.lightMapIntensity;
  7065. this.aoMap = source.aoMap;
  7066. this.aoMapIntensity = source.aoMapIntensity;
  7067. this.specularMap = source.specularMap;
  7068. this.alphaMap = source.alphaMap;
  7069. this.envMap = source.envMap;
  7070. this.combine = source.combine;
  7071. this.reflectivity = source.reflectivity;
  7072. this.refractionRatio = source.refractionRatio;
  7073. this.wireframe = source.wireframe;
  7074. this.wireframeLinewidth = source.wireframeLinewidth;
  7075. this.wireframeLinecap = source.wireframeLinecap;
  7076. this.wireframeLinejoin = source.wireframeLinejoin;
  7077. this.skinning = source.skinning;
  7078. this.morphTargets = source.morphTargets;
  7079. return this;
  7080. };
  7081. /**
  7082. * @author mrdoob / http://mrdoob.com/
  7083. */
  7084. function BufferAttribute( array, itemSize, normalized ) {
  7085. if ( Array.isArray( array ) ) {
  7086. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7087. }
  7088. this.uuid = _Math.generateUUID();
  7089. this.array = array;
  7090. this.itemSize = itemSize;
  7091. this.count = array !== undefined ? array.length / itemSize : 0;
  7092. this.normalized = normalized === true;
  7093. this.dynamic = false;
  7094. this.updateRange = { offset: 0, count: - 1 };
  7095. this.onUploadCallback = function () {};
  7096. this.version = 0;
  7097. }
  7098. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7099. set: function ( value ) {
  7100. if ( value === true ) this.version ++;
  7101. }
  7102. } );
  7103. Object.assign( BufferAttribute.prototype, {
  7104. isBufferAttribute: true,
  7105. setArray: function ( array ) {
  7106. if ( Array.isArray( array ) ) {
  7107. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7108. }
  7109. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7110. this.array = array;
  7111. },
  7112. setDynamic: function ( value ) {
  7113. this.dynamic = value;
  7114. return this;
  7115. },
  7116. copy: function ( source ) {
  7117. this.array = new source.array.constructor( source.array );
  7118. this.itemSize = source.itemSize;
  7119. this.count = source.count;
  7120. this.normalized = source.normalized;
  7121. this.dynamic = source.dynamic;
  7122. return this;
  7123. },
  7124. copyAt: function ( index1, attribute, index2 ) {
  7125. index1 *= this.itemSize;
  7126. index2 *= attribute.itemSize;
  7127. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7128. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7129. }
  7130. return this;
  7131. },
  7132. copyArray: function ( array ) {
  7133. this.array.set( array );
  7134. return this;
  7135. },
  7136. copyColorsArray: function ( colors ) {
  7137. var array = this.array, offset = 0;
  7138. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7139. var color = colors[ i ];
  7140. if ( color === undefined ) {
  7141. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7142. color = new Color();
  7143. }
  7144. array[ offset ++ ] = color.r;
  7145. array[ offset ++ ] = color.g;
  7146. array[ offset ++ ] = color.b;
  7147. }
  7148. return this;
  7149. },
  7150. copyIndicesArray: function ( indices ) {
  7151. var array = this.array, offset = 0;
  7152. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7153. var index = indices[ i ];
  7154. array[ offset ++ ] = index.a;
  7155. array[ offset ++ ] = index.b;
  7156. array[ offset ++ ] = index.c;
  7157. }
  7158. return this;
  7159. },
  7160. copyVector2sArray: function ( vectors ) {
  7161. var array = this.array, offset = 0;
  7162. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7163. var vector = vectors[ i ];
  7164. if ( vector === undefined ) {
  7165. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7166. vector = new Vector2();
  7167. }
  7168. array[ offset ++ ] = vector.x;
  7169. array[ offset ++ ] = vector.y;
  7170. }
  7171. return this;
  7172. },
  7173. copyVector3sArray: function ( vectors ) {
  7174. var array = this.array, offset = 0;
  7175. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7176. var vector = vectors[ i ];
  7177. if ( vector === undefined ) {
  7178. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7179. vector = new Vector3();
  7180. }
  7181. array[ offset ++ ] = vector.x;
  7182. array[ offset ++ ] = vector.y;
  7183. array[ offset ++ ] = vector.z;
  7184. }
  7185. return this;
  7186. },
  7187. copyVector4sArray: function ( vectors ) {
  7188. var array = this.array, offset = 0;
  7189. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7190. var vector = vectors[ i ];
  7191. if ( vector === undefined ) {
  7192. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7193. vector = new Vector4();
  7194. }
  7195. array[ offset ++ ] = vector.x;
  7196. array[ offset ++ ] = vector.y;
  7197. array[ offset ++ ] = vector.z;
  7198. array[ offset ++ ] = vector.w;
  7199. }
  7200. return this;
  7201. },
  7202. set: function ( value, offset ) {
  7203. if ( offset === undefined ) offset = 0;
  7204. this.array.set( value, offset );
  7205. return this;
  7206. },
  7207. getX: function ( index ) {
  7208. return this.array[ index * this.itemSize ];
  7209. },
  7210. setX: function ( index, x ) {
  7211. this.array[ index * this.itemSize ] = x;
  7212. return this;
  7213. },
  7214. getY: function ( index ) {
  7215. return this.array[ index * this.itemSize + 1 ];
  7216. },
  7217. setY: function ( index, y ) {
  7218. this.array[ index * this.itemSize + 1 ] = y;
  7219. return this;
  7220. },
  7221. getZ: function ( index ) {
  7222. return this.array[ index * this.itemSize + 2 ];
  7223. },
  7224. setZ: function ( index, z ) {
  7225. this.array[ index * this.itemSize + 2 ] = z;
  7226. return this;
  7227. },
  7228. getW: function ( index ) {
  7229. return this.array[ index * this.itemSize + 3 ];
  7230. },
  7231. setW: function ( index, w ) {
  7232. this.array[ index * this.itemSize + 3 ] = w;
  7233. return this;
  7234. },
  7235. setXY: function ( index, x, y ) {
  7236. index *= this.itemSize;
  7237. this.array[ index + 0 ] = x;
  7238. this.array[ index + 1 ] = y;
  7239. return this;
  7240. },
  7241. setXYZ: function ( index, x, y, z ) {
  7242. index *= this.itemSize;
  7243. this.array[ index + 0 ] = x;
  7244. this.array[ index + 1 ] = y;
  7245. this.array[ index + 2 ] = z;
  7246. return this;
  7247. },
  7248. setXYZW: function ( index, x, y, z, w ) {
  7249. index *= this.itemSize;
  7250. this.array[ index + 0 ] = x;
  7251. this.array[ index + 1 ] = y;
  7252. this.array[ index + 2 ] = z;
  7253. this.array[ index + 3 ] = w;
  7254. return this;
  7255. },
  7256. onUpload: function ( callback ) {
  7257. this.onUploadCallback = callback;
  7258. return this;
  7259. },
  7260. clone: function () {
  7261. return new this.constructor( this.array, this.itemSize ).copy( this );
  7262. }
  7263. } );
  7264. //
  7265. function Int8BufferAttribute( array, itemSize ) {
  7266. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7267. }
  7268. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7269. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7270. function Uint8BufferAttribute( array, itemSize ) {
  7271. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7272. }
  7273. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7274. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7275. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7276. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7277. }
  7278. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7279. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7280. function Int16BufferAttribute( array, itemSize ) {
  7281. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7282. }
  7283. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7284. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7285. function Uint16BufferAttribute( array, itemSize ) {
  7286. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7287. }
  7288. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7289. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7290. function Int32BufferAttribute( array, itemSize ) {
  7291. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7292. }
  7293. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7294. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7295. function Uint32BufferAttribute( array, itemSize ) {
  7296. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7297. }
  7298. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7299. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7300. function Float32BufferAttribute( array, itemSize ) {
  7301. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7302. }
  7303. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7304. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7305. function Float64BufferAttribute( array, itemSize ) {
  7306. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7307. }
  7308. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7309. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7310. /**
  7311. * @author mrdoob / http://mrdoob.com/
  7312. */
  7313. function DirectGeometry() {
  7314. this.indices = [];
  7315. this.vertices = [];
  7316. this.normals = [];
  7317. this.colors = [];
  7318. this.uvs = [];
  7319. this.uvs2 = [];
  7320. this.groups = [];
  7321. this.morphTargets = {};
  7322. this.skinWeights = [];
  7323. this.skinIndices = [];
  7324. // this.lineDistances = [];
  7325. this.boundingBox = null;
  7326. this.boundingSphere = null;
  7327. // update flags
  7328. this.verticesNeedUpdate = false;
  7329. this.normalsNeedUpdate = false;
  7330. this.colorsNeedUpdate = false;
  7331. this.uvsNeedUpdate = false;
  7332. this.groupsNeedUpdate = false;
  7333. }
  7334. Object.assign( DirectGeometry.prototype, {
  7335. computeGroups: function ( geometry ) {
  7336. var group;
  7337. var groups = [];
  7338. var materialIndex = undefined;
  7339. var faces = geometry.faces;
  7340. for ( var i = 0; i < faces.length; i ++ ) {
  7341. var face = faces[ i ];
  7342. // materials
  7343. if ( face.materialIndex !== materialIndex ) {
  7344. materialIndex = face.materialIndex;
  7345. if ( group !== undefined ) {
  7346. group.count = ( i * 3 ) - group.start;
  7347. groups.push( group );
  7348. }
  7349. group = {
  7350. start: i * 3,
  7351. materialIndex: materialIndex
  7352. };
  7353. }
  7354. }
  7355. if ( group !== undefined ) {
  7356. group.count = ( i * 3 ) - group.start;
  7357. groups.push( group );
  7358. }
  7359. this.groups = groups;
  7360. },
  7361. fromGeometry: function ( geometry ) {
  7362. var faces = geometry.faces;
  7363. var vertices = geometry.vertices;
  7364. var faceVertexUvs = geometry.faceVertexUvs;
  7365. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7366. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7367. // morphs
  7368. var morphTargets = geometry.morphTargets;
  7369. var morphTargetsLength = morphTargets.length;
  7370. var morphTargetsPosition;
  7371. if ( morphTargetsLength > 0 ) {
  7372. morphTargetsPosition = [];
  7373. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7374. morphTargetsPosition[ i ] = [];
  7375. }
  7376. this.morphTargets.position = morphTargetsPosition;
  7377. }
  7378. var morphNormals = geometry.morphNormals;
  7379. var morphNormalsLength = morphNormals.length;
  7380. var morphTargetsNormal;
  7381. if ( morphNormalsLength > 0 ) {
  7382. morphTargetsNormal = [];
  7383. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7384. morphTargetsNormal[ i ] = [];
  7385. }
  7386. this.morphTargets.normal = morphTargetsNormal;
  7387. }
  7388. // skins
  7389. var skinIndices = geometry.skinIndices;
  7390. var skinWeights = geometry.skinWeights;
  7391. var hasSkinIndices = skinIndices.length === vertices.length;
  7392. var hasSkinWeights = skinWeights.length === vertices.length;
  7393. //
  7394. for ( var i = 0; i < faces.length; i ++ ) {
  7395. var face = faces[ i ];
  7396. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7397. var vertexNormals = face.vertexNormals;
  7398. if ( vertexNormals.length === 3 ) {
  7399. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7400. } else {
  7401. var normal = face.normal;
  7402. this.normals.push( normal, normal, normal );
  7403. }
  7404. var vertexColors = face.vertexColors;
  7405. if ( vertexColors.length === 3 ) {
  7406. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7407. } else {
  7408. var color = face.color;
  7409. this.colors.push( color, color, color );
  7410. }
  7411. if ( hasFaceVertexUv === true ) {
  7412. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7413. if ( vertexUvs !== undefined ) {
  7414. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7415. } else {
  7416. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7417. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7418. }
  7419. }
  7420. if ( hasFaceVertexUv2 === true ) {
  7421. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7422. if ( vertexUvs !== undefined ) {
  7423. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7424. } else {
  7425. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7426. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7427. }
  7428. }
  7429. // morphs
  7430. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7431. var morphTarget = morphTargets[ j ].vertices;
  7432. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7433. }
  7434. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7435. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7436. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7437. }
  7438. // skins
  7439. if ( hasSkinIndices ) {
  7440. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7441. }
  7442. if ( hasSkinWeights ) {
  7443. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7444. }
  7445. }
  7446. this.computeGroups( geometry );
  7447. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7448. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7449. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7450. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7451. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7452. return this;
  7453. }
  7454. } );
  7455. function arrayMax( array ) {
  7456. if ( array.length === 0 ) return - Infinity;
  7457. var max = array[ 0 ];
  7458. for ( var i = 1, l = array.length; i < l; ++ i ) {
  7459. if ( array[ i ] > max ) max = array[ i ];
  7460. }
  7461. return max;
  7462. }
  7463. /**
  7464. * @author mrdoob / http://mrdoob.com/
  7465. * @author kile / http://kile.stravaganza.org/
  7466. * @author alteredq / http://alteredqualia.com/
  7467. * @author mikael emtinger / http://gomo.se/
  7468. * @author zz85 / http://www.lab4games.net/zz85/blog
  7469. * @author bhouston / http://clara.io
  7470. */
  7471. var count = 0;
  7472. function GeometryIdCount() { return count++; }
  7473. function Geometry() {
  7474. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7475. this.uuid = _Math.generateUUID();
  7476. this.name = '';
  7477. this.type = 'Geometry';
  7478. this.vertices = [];
  7479. this.colors = [];
  7480. this.faces = [];
  7481. this.faceVertexUvs = [[]];
  7482. this.morphTargets = [];
  7483. this.morphNormals = [];
  7484. this.skinWeights = [];
  7485. this.skinIndices = [];
  7486. this.lineDistances = [];
  7487. this.boundingBox = null;
  7488. this.boundingSphere = null;
  7489. // update flags
  7490. this.elementsNeedUpdate = false;
  7491. this.verticesNeedUpdate = false;
  7492. this.uvsNeedUpdate = false;
  7493. this.normalsNeedUpdate = false;
  7494. this.colorsNeedUpdate = false;
  7495. this.lineDistancesNeedUpdate = false;
  7496. this.groupsNeedUpdate = false;
  7497. }
  7498. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7499. isGeometry: true,
  7500. applyMatrix: function ( matrix ) {
  7501. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7502. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7503. var vertex = this.vertices[ i ];
  7504. vertex.applyMatrix4( matrix );
  7505. }
  7506. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7507. var face = this.faces[ i ];
  7508. face.normal.applyMatrix3( normalMatrix ).normalize();
  7509. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7510. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7511. }
  7512. }
  7513. if ( this.boundingBox !== null ) {
  7514. this.computeBoundingBox();
  7515. }
  7516. if ( this.boundingSphere !== null ) {
  7517. this.computeBoundingSphere();
  7518. }
  7519. this.verticesNeedUpdate = true;
  7520. this.normalsNeedUpdate = true;
  7521. return this;
  7522. },
  7523. rotateX: function () {
  7524. // rotate geometry around world x-axis
  7525. var m1 = new Matrix4();
  7526. return function rotateX( angle ) {
  7527. m1.makeRotationX( angle );
  7528. this.applyMatrix( m1 );
  7529. return this;
  7530. };
  7531. }(),
  7532. rotateY: function () {
  7533. // rotate geometry around world y-axis
  7534. var m1 = new Matrix4();
  7535. return function rotateY( angle ) {
  7536. m1.makeRotationY( angle );
  7537. this.applyMatrix( m1 );
  7538. return this;
  7539. };
  7540. }(),
  7541. rotateZ: function () {
  7542. // rotate geometry around world z-axis
  7543. var m1 = new Matrix4();
  7544. return function rotateZ( angle ) {
  7545. m1.makeRotationZ( angle );
  7546. this.applyMatrix( m1 );
  7547. return this;
  7548. };
  7549. }(),
  7550. translate: function () {
  7551. // translate geometry
  7552. var m1 = new Matrix4();
  7553. return function translate( x, y, z ) {
  7554. m1.makeTranslation( x, y, z );
  7555. this.applyMatrix( m1 );
  7556. return this;
  7557. };
  7558. }(),
  7559. scale: function () {
  7560. // scale geometry
  7561. var m1 = new Matrix4();
  7562. return function scale( x, y, z ) {
  7563. m1.makeScale( x, y, z );
  7564. this.applyMatrix( m1 );
  7565. return this;
  7566. };
  7567. }(),
  7568. lookAt: function () {
  7569. var obj = new Object3D();
  7570. return function lookAt( vector ) {
  7571. obj.lookAt( vector );
  7572. obj.updateMatrix();
  7573. this.applyMatrix( obj.matrix );
  7574. };
  7575. }(),
  7576. fromBufferGeometry: function ( geometry ) {
  7577. var scope = this;
  7578. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7579. var attributes = geometry.attributes;
  7580. var positions = attributes.position.array;
  7581. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7582. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7583. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7584. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7585. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7586. var tempNormals = [];
  7587. var tempUVs = [];
  7588. var tempUVs2 = [];
  7589. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7590. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7591. if ( normals !== undefined ) {
  7592. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7593. }
  7594. if ( colors !== undefined ) {
  7595. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7596. }
  7597. if ( uvs !== undefined ) {
  7598. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7599. }
  7600. if ( uvs2 !== undefined ) {
  7601. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7602. }
  7603. }
  7604. function addFace( a, b, c, materialIndex ) {
  7605. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7606. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7607. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7608. scope.faces.push( face );
  7609. if ( uvs !== undefined ) {
  7610. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7611. }
  7612. if ( uvs2 !== undefined ) {
  7613. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7614. }
  7615. }
  7616. var groups = geometry.groups;
  7617. if ( groups.length > 0 ) {
  7618. for ( var i = 0; i < groups.length; i ++ ) {
  7619. var group = groups[ i ];
  7620. var start = group.start;
  7621. var count = group.count;
  7622. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7623. if ( indices !== undefined ) {
  7624. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7625. } else {
  7626. addFace( j, j + 1, j + 2, group.materialIndex );
  7627. }
  7628. }
  7629. }
  7630. } else {
  7631. if ( indices !== undefined ) {
  7632. for ( var i = 0; i < indices.length; i += 3 ) {
  7633. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7634. }
  7635. } else {
  7636. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7637. addFace( i, i + 1, i + 2 );
  7638. }
  7639. }
  7640. }
  7641. this.computeFaceNormals();
  7642. if ( geometry.boundingBox !== null ) {
  7643. this.boundingBox = geometry.boundingBox.clone();
  7644. }
  7645. if ( geometry.boundingSphere !== null ) {
  7646. this.boundingSphere = geometry.boundingSphere.clone();
  7647. }
  7648. return this;
  7649. },
  7650. center: function () {
  7651. this.computeBoundingBox();
  7652. var offset = this.boundingBox.getCenter().negate();
  7653. this.translate( offset.x, offset.y, offset.z );
  7654. return offset;
  7655. },
  7656. normalize: function () {
  7657. this.computeBoundingSphere();
  7658. var center = this.boundingSphere.center;
  7659. var radius = this.boundingSphere.radius;
  7660. var s = radius === 0 ? 1 : 1.0 / radius;
  7661. var matrix = new Matrix4();
  7662. matrix.set(
  7663. s, 0, 0, - s * center.x,
  7664. 0, s, 0, - s * center.y,
  7665. 0, 0, s, - s * center.z,
  7666. 0, 0, 0, 1
  7667. );
  7668. this.applyMatrix( matrix );
  7669. return this;
  7670. },
  7671. computeFaceNormals: function () {
  7672. var cb = new Vector3(), ab = new Vector3();
  7673. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7674. var face = this.faces[ f ];
  7675. var vA = this.vertices[ face.a ];
  7676. var vB = this.vertices[ face.b ];
  7677. var vC = this.vertices[ face.c ];
  7678. cb.subVectors( vC, vB );
  7679. ab.subVectors( vA, vB );
  7680. cb.cross( ab );
  7681. cb.normalize();
  7682. face.normal.copy( cb );
  7683. }
  7684. },
  7685. computeVertexNormals: function ( areaWeighted ) {
  7686. if ( areaWeighted === undefined ) areaWeighted = true;
  7687. var v, vl, f, fl, face, vertices;
  7688. vertices = new Array( this.vertices.length );
  7689. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7690. vertices[ v ] = new Vector3();
  7691. }
  7692. if ( areaWeighted ) {
  7693. // vertex normals weighted by triangle areas
  7694. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7695. var vA, vB, vC;
  7696. var cb = new Vector3(), ab = new Vector3();
  7697. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7698. face = this.faces[ f ];
  7699. vA = this.vertices[ face.a ];
  7700. vB = this.vertices[ face.b ];
  7701. vC = this.vertices[ face.c ];
  7702. cb.subVectors( vC, vB );
  7703. ab.subVectors( vA, vB );
  7704. cb.cross( ab );
  7705. vertices[ face.a ].add( cb );
  7706. vertices[ face.b ].add( cb );
  7707. vertices[ face.c ].add( cb );
  7708. }
  7709. } else {
  7710. this.computeFaceNormals();
  7711. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7712. face = this.faces[ f ];
  7713. vertices[ face.a ].add( face.normal );
  7714. vertices[ face.b ].add( face.normal );
  7715. vertices[ face.c ].add( face.normal );
  7716. }
  7717. }
  7718. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7719. vertices[ v ].normalize();
  7720. }
  7721. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7722. face = this.faces[ f ];
  7723. var vertexNormals = face.vertexNormals;
  7724. if ( vertexNormals.length === 3 ) {
  7725. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7726. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7727. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7728. } else {
  7729. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7730. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7731. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7732. }
  7733. }
  7734. if ( this.faces.length > 0 ) {
  7735. this.normalsNeedUpdate = true;
  7736. }
  7737. },
  7738. computeFlatVertexNormals: function () {
  7739. var f, fl, face;
  7740. this.computeFaceNormals();
  7741. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7742. face = this.faces[ f ];
  7743. var vertexNormals = face.vertexNormals;
  7744. if ( vertexNormals.length === 3 ) {
  7745. vertexNormals[ 0 ].copy( face.normal );
  7746. vertexNormals[ 1 ].copy( face.normal );
  7747. vertexNormals[ 2 ].copy( face.normal );
  7748. } else {
  7749. vertexNormals[ 0 ] = face.normal.clone();
  7750. vertexNormals[ 1 ] = face.normal.clone();
  7751. vertexNormals[ 2 ] = face.normal.clone();
  7752. }
  7753. }
  7754. if ( this.faces.length > 0 ) {
  7755. this.normalsNeedUpdate = true;
  7756. }
  7757. },
  7758. computeMorphNormals: function () {
  7759. var i, il, f, fl, face;
  7760. // save original normals
  7761. // - create temp variables on first access
  7762. // otherwise just copy (for faster repeated calls)
  7763. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7764. face = this.faces[ f ];
  7765. if ( ! face.__originalFaceNormal ) {
  7766. face.__originalFaceNormal = face.normal.clone();
  7767. } else {
  7768. face.__originalFaceNormal.copy( face.normal );
  7769. }
  7770. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7771. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7772. if ( ! face.__originalVertexNormals[ i ] ) {
  7773. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7774. } else {
  7775. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7776. }
  7777. }
  7778. }
  7779. // use temp geometry to compute face and vertex normals for each morph
  7780. var tmpGeo = new Geometry();
  7781. tmpGeo.faces = this.faces;
  7782. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7783. // create on first access
  7784. if ( ! this.morphNormals[ i ] ) {
  7785. this.morphNormals[ i ] = {};
  7786. this.morphNormals[ i ].faceNormals = [];
  7787. this.morphNormals[ i ].vertexNormals = [];
  7788. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7789. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7790. var faceNormal, vertexNormals;
  7791. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7792. faceNormal = new Vector3();
  7793. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7794. dstNormalsFace.push( faceNormal );
  7795. dstNormalsVertex.push( vertexNormals );
  7796. }
  7797. }
  7798. var morphNormals = this.morphNormals[ i ];
  7799. // set vertices to morph target
  7800. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7801. // compute morph normals
  7802. tmpGeo.computeFaceNormals();
  7803. tmpGeo.computeVertexNormals();
  7804. // store morph normals
  7805. var faceNormal, vertexNormals;
  7806. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7807. face = this.faces[ f ];
  7808. faceNormal = morphNormals.faceNormals[ f ];
  7809. vertexNormals = morphNormals.vertexNormals[ f ];
  7810. faceNormal.copy( face.normal );
  7811. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7812. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7813. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7814. }
  7815. }
  7816. // restore original normals
  7817. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7818. face = this.faces[ f ];
  7819. face.normal = face.__originalFaceNormal;
  7820. face.vertexNormals = face.__originalVertexNormals;
  7821. }
  7822. },
  7823. computeLineDistances: function () {
  7824. var d = 0;
  7825. var vertices = this.vertices;
  7826. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7827. if ( i > 0 ) {
  7828. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7829. }
  7830. this.lineDistances[ i ] = d;
  7831. }
  7832. },
  7833. computeBoundingBox: function () {
  7834. if ( this.boundingBox === null ) {
  7835. this.boundingBox = new Box3();
  7836. }
  7837. this.boundingBox.setFromPoints( this.vertices );
  7838. },
  7839. computeBoundingSphere: function () {
  7840. if ( this.boundingSphere === null ) {
  7841. this.boundingSphere = new Sphere();
  7842. }
  7843. this.boundingSphere.setFromPoints( this.vertices );
  7844. },
  7845. merge: function ( geometry, matrix, materialIndexOffset ) {
  7846. if ( ( geometry && geometry.isGeometry ) === false ) {
  7847. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7848. return;
  7849. }
  7850. var normalMatrix,
  7851. vertexOffset = this.vertices.length,
  7852. vertices1 = this.vertices,
  7853. vertices2 = geometry.vertices,
  7854. faces1 = this.faces,
  7855. faces2 = geometry.faces,
  7856. uvs1 = this.faceVertexUvs[ 0 ],
  7857. uvs2 = geometry.faceVertexUvs[ 0 ],
  7858. colors1 = this.colors,
  7859. colors2 = geometry.colors;
  7860. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7861. if ( matrix !== undefined ) {
  7862. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7863. }
  7864. // vertices
  7865. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7866. var vertex = vertices2[ i ];
  7867. var vertexCopy = vertex.clone();
  7868. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7869. vertices1.push( vertexCopy );
  7870. }
  7871. // colors
  7872. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7873. colors1.push( colors2[ i ].clone() );
  7874. }
  7875. // faces
  7876. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7877. var face = faces2[ i ], faceCopy, normal, color,
  7878. faceVertexNormals = face.vertexNormals,
  7879. faceVertexColors = face.vertexColors;
  7880. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7881. faceCopy.normal.copy( face.normal );
  7882. if ( normalMatrix !== undefined ) {
  7883. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7884. }
  7885. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7886. normal = faceVertexNormals[ j ].clone();
  7887. if ( normalMatrix !== undefined ) {
  7888. normal.applyMatrix3( normalMatrix ).normalize();
  7889. }
  7890. faceCopy.vertexNormals.push( normal );
  7891. }
  7892. faceCopy.color.copy( face.color );
  7893. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7894. color = faceVertexColors[ j ];
  7895. faceCopy.vertexColors.push( color.clone() );
  7896. }
  7897. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7898. faces1.push( faceCopy );
  7899. }
  7900. // uvs
  7901. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7902. var uv = uvs2[ i ], uvCopy = [];
  7903. if ( uv === undefined ) {
  7904. continue;
  7905. }
  7906. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7907. uvCopy.push( uv[ j ].clone() );
  7908. }
  7909. uvs1.push( uvCopy );
  7910. }
  7911. },
  7912. mergeMesh: function ( mesh ) {
  7913. if ( ( mesh && mesh.isMesh ) === false ) {
  7914. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7915. return;
  7916. }
  7917. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7918. this.merge( mesh.geometry, mesh.matrix );
  7919. },
  7920. /*
  7921. * Checks for duplicate vertices with hashmap.
  7922. * Duplicated vertices are removed
  7923. * and faces' vertices are updated.
  7924. */
  7925. mergeVertices: function () {
  7926. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7927. var unique = [], changes = [];
  7928. var v, key;
  7929. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7930. var precision = Math.pow( 10, precisionPoints );
  7931. var i, il, face;
  7932. var indices, j, jl;
  7933. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7934. v = this.vertices[ i ];
  7935. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7936. if ( verticesMap[ key ] === undefined ) {
  7937. verticesMap[ key ] = i;
  7938. unique.push( this.vertices[ i ] );
  7939. changes[ i ] = unique.length - 1;
  7940. } else {
  7941. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7942. changes[ i ] = changes[ verticesMap[ key ] ];
  7943. }
  7944. }
  7945. // if faces are completely degenerate after merging vertices, we
  7946. // have to remove them from the geometry.
  7947. var faceIndicesToRemove = [];
  7948. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7949. face = this.faces[ i ];
  7950. face.a = changes[ face.a ];
  7951. face.b = changes[ face.b ];
  7952. face.c = changes[ face.c ];
  7953. indices = [ face.a, face.b, face.c ];
  7954. // if any duplicate vertices are found in a Face3
  7955. // we have to remove the face as nothing can be saved
  7956. for ( var n = 0; n < 3; n ++ ) {
  7957. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7958. faceIndicesToRemove.push( i );
  7959. break;
  7960. }
  7961. }
  7962. }
  7963. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7964. var idx = faceIndicesToRemove[ i ];
  7965. this.faces.splice( idx, 1 );
  7966. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7967. this.faceVertexUvs[ j ].splice( idx, 1 );
  7968. }
  7969. }
  7970. // Use unique set of vertices
  7971. var diff = this.vertices.length - unique.length;
  7972. this.vertices = unique;
  7973. return diff;
  7974. },
  7975. sortFacesByMaterialIndex: function () {
  7976. var faces = this.faces;
  7977. var length = faces.length;
  7978. // tag faces
  7979. for ( var i = 0; i < length; i ++ ) {
  7980. faces[ i ]._id = i;
  7981. }
  7982. // sort faces
  7983. function materialIndexSort( a, b ) {
  7984. return a.materialIndex - b.materialIndex;
  7985. }
  7986. faces.sort( materialIndexSort );
  7987. // sort uvs
  7988. var uvs1 = this.faceVertexUvs[ 0 ];
  7989. var uvs2 = this.faceVertexUvs[ 1 ];
  7990. var newUvs1, newUvs2;
  7991. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7992. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7993. for ( var i = 0; i < length; i ++ ) {
  7994. var id = faces[ i ]._id;
  7995. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7996. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7997. }
  7998. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7999. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8000. },
  8001. toJSON: function () {
  8002. var data = {
  8003. metadata: {
  8004. version: 4.5,
  8005. type: 'Geometry',
  8006. generator: 'Geometry.toJSON'
  8007. }
  8008. };
  8009. // standard Geometry serialization
  8010. data.uuid = this.uuid;
  8011. data.type = this.type;
  8012. if ( this.name !== '' ) data.name = this.name;
  8013. if ( this.parameters !== undefined ) {
  8014. var parameters = this.parameters;
  8015. for ( var key in parameters ) {
  8016. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8017. }
  8018. return data;
  8019. }
  8020. var vertices = [];
  8021. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8022. var vertex = this.vertices[ i ];
  8023. vertices.push( vertex.x, vertex.y, vertex.z );
  8024. }
  8025. var faces = [];
  8026. var normals = [];
  8027. var normalsHash = {};
  8028. var colors = [];
  8029. var colorsHash = {};
  8030. var uvs = [];
  8031. var uvsHash = {};
  8032. for ( var i = 0; i < this.faces.length; i ++ ) {
  8033. var face = this.faces[ i ];
  8034. var hasMaterial = true;
  8035. var hasFaceUv = false; // deprecated
  8036. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8037. var hasFaceNormal = face.normal.length() > 0;
  8038. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8039. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8040. var hasFaceVertexColor = face.vertexColors.length > 0;
  8041. var faceType = 0;
  8042. faceType = setBit( faceType, 0, 0 ); // isQuad
  8043. faceType = setBit( faceType, 1, hasMaterial );
  8044. faceType = setBit( faceType, 2, hasFaceUv );
  8045. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8046. faceType = setBit( faceType, 4, hasFaceNormal );
  8047. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8048. faceType = setBit( faceType, 6, hasFaceColor );
  8049. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8050. faces.push( faceType );
  8051. faces.push( face.a, face.b, face.c );
  8052. faces.push( face.materialIndex );
  8053. if ( hasFaceVertexUv ) {
  8054. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8055. faces.push(
  8056. getUvIndex( faceVertexUvs[ 0 ] ),
  8057. getUvIndex( faceVertexUvs[ 1 ] ),
  8058. getUvIndex( faceVertexUvs[ 2 ] )
  8059. );
  8060. }
  8061. if ( hasFaceNormal ) {
  8062. faces.push( getNormalIndex( face.normal ) );
  8063. }
  8064. if ( hasFaceVertexNormal ) {
  8065. var vertexNormals = face.vertexNormals;
  8066. faces.push(
  8067. getNormalIndex( vertexNormals[ 0 ] ),
  8068. getNormalIndex( vertexNormals[ 1 ] ),
  8069. getNormalIndex( vertexNormals[ 2 ] )
  8070. );
  8071. }
  8072. if ( hasFaceColor ) {
  8073. faces.push( getColorIndex( face.color ) );
  8074. }
  8075. if ( hasFaceVertexColor ) {
  8076. var vertexColors = face.vertexColors;
  8077. faces.push(
  8078. getColorIndex( vertexColors[ 0 ] ),
  8079. getColorIndex( vertexColors[ 1 ] ),
  8080. getColorIndex( vertexColors[ 2 ] )
  8081. );
  8082. }
  8083. }
  8084. function setBit( value, position, enabled ) {
  8085. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8086. }
  8087. function getNormalIndex( normal ) {
  8088. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8089. if ( normalsHash[ hash ] !== undefined ) {
  8090. return normalsHash[ hash ];
  8091. }
  8092. normalsHash[ hash ] = normals.length / 3;
  8093. normals.push( normal.x, normal.y, normal.z );
  8094. return normalsHash[ hash ];
  8095. }
  8096. function getColorIndex( color ) {
  8097. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8098. if ( colorsHash[ hash ] !== undefined ) {
  8099. return colorsHash[ hash ];
  8100. }
  8101. colorsHash[ hash ] = colors.length;
  8102. colors.push( color.getHex() );
  8103. return colorsHash[ hash ];
  8104. }
  8105. function getUvIndex( uv ) {
  8106. var hash = uv.x.toString() + uv.y.toString();
  8107. if ( uvsHash[ hash ] !== undefined ) {
  8108. return uvsHash[ hash ];
  8109. }
  8110. uvsHash[ hash ] = uvs.length / 2;
  8111. uvs.push( uv.x, uv.y );
  8112. return uvsHash[ hash ];
  8113. }
  8114. data.data = {};
  8115. data.data.vertices = vertices;
  8116. data.data.normals = normals;
  8117. if ( colors.length > 0 ) data.data.colors = colors;
  8118. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8119. data.data.faces = faces;
  8120. return data;
  8121. },
  8122. clone: function () {
  8123. /*
  8124. // Handle primitives
  8125. var parameters = this.parameters;
  8126. if ( parameters !== undefined ) {
  8127. var values = [];
  8128. for ( var key in parameters ) {
  8129. values.push( parameters[ key ] );
  8130. }
  8131. var geometry = Object.create( this.constructor.prototype );
  8132. this.constructor.apply( geometry, values );
  8133. return geometry;
  8134. }
  8135. return new this.constructor().copy( this );
  8136. */
  8137. return new Geometry().copy( this );
  8138. },
  8139. copy: function ( source ) {
  8140. var i, il, j, jl, k, kl;
  8141. // reset
  8142. this.vertices = [];
  8143. this.colors = [];
  8144. this.faces = [];
  8145. this.faceVertexUvs = [[]];
  8146. this.morphTargets = [];
  8147. this.morphNormals = [];
  8148. this.skinWeights = [];
  8149. this.skinIndices = [];
  8150. this.lineDistances = [];
  8151. this.boundingBox = null;
  8152. this.boundingSphere = null;
  8153. // name
  8154. this.name = source.name;
  8155. // vertices
  8156. var vertices = source.vertices;
  8157. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  8158. this.vertices.push( vertices[ i ].clone() );
  8159. }
  8160. // colors
  8161. var colors = source.colors;
  8162. for ( i = 0, il = colors.length; i < il; i ++ ) {
  8163. this.colors.push( colors[ i ].clone() );
  8164. }
  8165. // faces
  8166. var faces = source.faces;
  8167. for ( i = 0, il = faces.length; i < il; i ++ ) {
  8168. this.faces.push( faces[ i ].clone() );
  8169. }
  8170. // face vertex uvs
  8171. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8172. var faceVertexUvs = source.faceVertexUvs[ i ];
  8173. if ( this.faceVertexUvs[ i ] === undefined ) {
  8174. this.faceVertexUvs[ i ] = [];
  8175. }
  8176. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8177. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8178. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  8179. var uv = uvs[ k ];
  8180. uvsCopy.push( uv.clone() );
  8181. }
  8182. this.faceVertexUvs[ i ].push( uvsCopy );
  8183. }
  8184. }
  8185. // morph targets
  8186. var morphTargets = source.morphTargets;
  8187. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  8188. var morphTarget = {};
  8189. morphTarget.name = morphTargets[ i ].name;
  8190. // vertices
  8191. if ( morphTargets[ i ].vertices !== undefined ) {
  8192. morphTarget.vertices = [];
  8193. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  8194. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  8195. }
  8196. }
  8197. // normals
  8198. if ( morphTargets[ i ].normals !== undefined ) {
  8199. morphTarget.normals = [];
  8200. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  8201. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  8202. }
  8203. }
  8204. this.morphTargets.push( morphTarget );
  8205. }
  8206. // morph normals
  8207. var morphNormals = source.morphNormals;
  8208. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  8209. var morphNormal = {};
  8210. // vertex normals
  8211. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  8212. morphNormal.vertexNormals = [];
  8213. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  8214. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  8215. var destVertexNormal = {};
  8216. destVertexNormal.a = srcVertexNormal.a.clone();
  8217. destVertexNormal.b = srcVertexNormal.b.clone();
  8218. destVertexNormal.c = srcVertexNormal.c.clone();
  8219. morphNormal.vertexNormals.push( destVertexNormal );
  8220. }
  8221. }
  8222. // face normals
  8223. if ( morphNormals[ i ].faceNormals !== undefined ) {
  8224. morphNormal.faceNormals = [];
  8225. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  8226. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  8227. }
  8228. }
  8229. this.morphNormals.push( morphNormal );
  8230. }
  8231. // skin weights
  8232. var skinWeights = source.skinWeights;
  8233. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  8234. this.skinWeights.push( skinWeights[ i ].clone() );
  8235. }
  8236. // skin indices
  8237. var skinIndices = source.skinIndices;
  8238. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  8239. this.skinIndices.push( skinIndices[ i ].clone() );
  8240. }
  8241. // line distances
  8242. var lineDistances = source.lineDistances;
  8243. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  8244. this.lineDistances.push( lineDistances[ i ] );
  8245. }
  8246. // bounding box
  8247. var boundingBox = source.boundingBox;
  8248. if ( boundingBox !== null ) {
  8249. this.boundingBox = boundingBox.clone();
  8250. }
  8251. // bounding sphere
  8252. var boundingSphere = source.boundingSphere;
  8253. if ( boundingSphere !== null ) {
  8254. this.boundingSphere = boundingSphere.clone();
  8255. }
  8256. // update flags
  8257. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8258. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8259. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8260. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8261. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8262. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8263. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8264. return this;
  8265. },
  8266. dispose: function () {
  8267. this.dispatchEvent( { type: 'dispose' } );
  8268. }
  8269. } );
  8270. /**
  8271. * @author alteredq / http://alteredqualia.com/
  8272. * @author mrdoob / http://mrdoob.com/
  8273. */
  8274. function BufferGeometry() {
  8275. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8276. this.uuid = _Math.generateUUID();
  8277. this.name = '';
  8278. this.type = 'BufferGeometry';
  8279. this.index = null;
  8280. this.attributes = {};
  8281. this.morphAttributes = {};
  8282. this.groups = [];
  8283. this.boundingBox = null;
  8284. this.boundingSphere = null;
  8285. this.drawRange = { start: 0, count: Infinity };
  8286. }
  8287. BufferGeometry.MaxIndex = 65535;
  8288. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8289. isBufferGeometry: true,
  8290. getIndex: function () {
  8291. return this.index;
  8292. },
  8293. setIndex: function ( index ) {
  8294. if ( Array.isArray( index ) ) {
  8295. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8296. } else {
  8297. this.index = index;
  8298. }
  8299. },
  8300. addAttribute: function ( name, attribute ) {
  8301. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8302. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8303. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8304. return;
  8305. }
  8306. if ( name === 'index' ) {
  8307. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8308. this.setIndex( attribute );
  8309. return;
  8310. }
  8311. this.attributes[ name ] = attribute;
  8312. return this;
  8313. },
  8314. getAttribute: function ( name ) {
  8315. return this.attributes[ name ];
  8316. },
  8317. removeAttribute: function ( name ) {
  8318. delete this.attributes[ name ];
  8319. return this;
  8320. },
  8321. addGroup: function ( start, count, materialIndex ) {
  8322. this.groups.push( {
  8323. start: start,
  8324. count: count,
  8325. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8326. } );
  8327. },
  8328. clearGroups: function () {
  8329. this.groups = [];
  8330. },
  8331. setDrawRange: function ( start, count ) {
  8332. this.drawRange.start = start;
  8333. this.drawRange.count = count;
  8334. },
  8335. applyMatrix: function ( matrix ) {
  8336. var position = this.attributes.position;
  8337. if ( position !== undefined ) {
  8338. matrix.applyToBufferAttribute( position );
  8339. position.needsUpdate = true;
  8340. }
  8341. var normal = this.attributes.normal;
  8342. if ( normal !== undefined ) {
  8343. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8344. normalMatrix.applyToBufferAttribute( normal );
  8345. normal.needsUpdate = true;
  8346. }
  8347. if ( this.boundingBox !== null ) {
  8348. this.computeBoundingBox();
  8349. }
  8350. if ( this.boundingSphere !== null ) {
  8351. this.computeBoundingSphere();
  8352. }
  8353. return this;
  8354. },
  8355. rotateX: function () {
  8356. // rotate geometry around world x-axis
  8357. var m1 = new Matrix4();
  8358. return function rotateX( angle ) {
  8359. m1.makeRotationX( angle );
  8360. this.applyMatrix( m1 );
  8361. return this;
  8362. };
  8363. }(),
  8364. rotateY: function () {
  8365. // rotate geometry around world y-axis
  8366. var m1 = new Matrix4();
  8367. return function rotateY( angle ) {
  8368. m1.makeRotationY( angle );
  8369. this.applyMatrix( m1 );
  8370. return this;
  8371. };
  8372. }(),
  8373. rotateZ: function () {
  8374. // rotate geometry around world z-axis
  8375. var m1 = new Matrix4();
  8376. return function rotateZ( angle ) {
  8377. m1.makeRotationZ( angle );
  8378. this.applyMatrix( m1 );
  8379. return this;
  8380. };
  8381. }(),
  8382. translate: function () {
  8383. // translate geometry
  8384. var m1 = new Matrix4();
  8385. return function translate( x, y, z ) {
  8386. m1.makeTranslation( x, y, z );
  8387. this.applyMatrix( m1 );
  8388. return this;
  8389. };
  8390. }(),
  8391. scale: function () {
  8392. // scale geometry
  8393. var m1 = new Matrix4();
  8394. return function scale( x, y, z ) {
  8395. m1.makeScale( x, y, z );
  8396. this.applyMatrix( m1 );
  8397. return this;
  8398. };
  8399. }(),
  8400. lookAt: function () {
  8401. var obj = new Object3D();
  8402. return function lookAt( vector ) {
  8403. obj.lookAt( vector );
  8404. obj.updateMatrix();
  8405. this.applyMatrix( obj.matrix );
  8406. };
  8407. }(),
  8408. center: function () {
  8409. this.computeBoundingBox();
  8410. var offset = this.boundingBox.getCenter().negate();
  8411. this.translate( offset.x, offset.y, offset.z );
  8412. return offset;
  8413. },
  8414. setFromObject: function ( object ) {
  8415. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8416. var geometry = object.geometry;
  8417. if ( object.isPoints || object.isLine ) {
  8418. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8419. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8420. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8421. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8422. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8423. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8424. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8425. }
  8426. if ( geometry.boundingSphere !== null ) {
  8427. this.boundingSphere = geometry.boundingSphere.clone();
  8428. }
  8429. if ( geometry.boundingBox !== null ) {
  8430. this.boundingBox = geometry.boundingBox.clone();
  8431. }
  8432. } else if ( object.isMesh ) {
  8433. if ( geometry && geometry.isGeometry ) {
  8434. this.fromGeometry( geometry );
  8435. }
  8436. }
  8437. return this;
  8438. },
  8439. updateFromObject: function ( object ) {
  8440. var geometry = object.geometry;
  8441. if ( object.isMesh ) {
  8442. var direct = geometry.__directGeometry;
  8443. if ( geometry.elementsNeedUpdate === true ) {
  8444. direct = undefined;
  8445. geometry.elementsNeedUpdate = false;
  8446. }
  8447. if ( direct === undefined ) {
  8448. return this.fromGeometry( geometry );
  8449. }
  8450. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8451. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8452. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8453. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8454. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8455. geometry.verticesNeedUpdate = false;
  8456. geometry.normalsNeedUpdate = false;
  8457. geometry.colorsNeedUpdate = false;
  8458. geometry.uvsNeedUpdate = false;
  8459. geometry.groupsNeedUpdate = false;
  8460. geometry = direct;
  8461. }
  8462. var attribute;
  8463. if ( geometry.verticesNeedUpdate === true ) {
  8464. attribute = this.attributes.position;
  8465. if ( attribute !== undefined ) {
  8466. attribute.copyVector3sArray( geometry.vertices );
  8467. attribute.needsUpdate = true;
  8468. }
  8469. geometry.verticesNeedUpdate = false;
  8470. }
  8471. if ( geometry.normalsNeedUpdate === true ) {
  8472. attribute = this.attributes.normal;
  8473. if ( attribute !== undefined ) {
  8474. attribute.copyVector3sArray( geometry.normals );
  8475. attribute.needsUpdate = true;
  8476. }
  8477. geometry.normalsNeedUpdate = false;
  8478. }
  8479. if ( geometry.colorsNeedUpdate === true ) {
  8480. attribute = this.attributes.color;
  8481. if ( attribute !== undefined ) {
  8482. attribute.copyColorsArray( geometry.colors );
  8483. attribute.needsUpdate = true;
  8484. }
  8485. geometry.colorsNeedUpdate = false;
  8486. }
  8487. if ( geometry.uvsNeedUpdate ) {
  8488. attribute = this.attributes.uv;
  8489. if ( attribute !== undefined ) {
  8490. attribute.copyVector2sArray( geometry.uvs );
  8491. attribute.needsUpdate = true;
  8492. }
  8493. geometry.uvsNeedUpdate = false;
  8494. }
  8495. if ( geometry.lineDistancesNeedUpdate ) {
  8496. attribute = this.attributes.lineDistance;
  8497. if ( attribute !== undefined ) {
  8498. attribute.copyArray( geometry.lineDistances );
  8499. attribute.needsUpdate = true;
  8500. }
  8501. geometry.lineDistancesNeedUpdate = false;
  8502. }
  8503. if ( geometry.groupsNeedUpdate ) {
  8504. geometry.computeGroups( object.geometry );
  8505. this.groups = geometry.groups;
  8506. geometry.groupsNeedUpdate = false;
  8507. }
  8508. return this;
  8509. },
  8510. fromGeometry: function ( geometry ) {
  8511. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8512. return this.fromDirectGeometry( geometry.__directGeometry );
  8513. },
  8514. fromDirectGeometry: function ( geometry ) {
  8515. var positions = new Float32Array( geometry.vertices.length * 3 );
  8516. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8517. if ( geometry.normals.length > 0 ) {
  8518. var normals = new Float32Array( geometry.normals.length * 3 );
  8519. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8520. }
  8521. if ( geometry.colors.length > 0 ) {
  8522. var colors = new Float32Array( geometry.colors.length * 3 );
  8523. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8524. }
  8525. if ( geometry.uvs.length > 0 ) {
  8526. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8527. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8528. }
  8529. if ( geometry.uvs2.length > 0 ) {
  8530. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8531. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8532. }
  8533. if ( geometry.indices.length > 0 ) {
  8534. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8535. var indices = new TypeArray( geometry.indices.length * 3 );
  8536. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8537. }
  8538. // groups
  8539. this.groups = geometry.groups;
  8540. // morphs
  8541. for ( var name in geometry.morphTargets ) {
  8542. var array = [];
  8543. var morphTargets = geometry.morphTargets[ name ];
  8544. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8545. var morphTarget = morphTargets[ i ];
  8546. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8547. array.push( attribute.copyVector3sArray( morphTarget ) );
  8548. }
  8549. this.morphAttributes[ name ] = array;
  8550. }
  8551. // skinning
  8552. if ( geometry.skinIndices.length > 0 ) {
  8553. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8554. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8555. }
  8556. if ( geometry.skinWeights.length > 0 ) {
  8557. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8558. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8559. }
  8560. //
  8561. if ( geometry.boundingSphere !== null ) {
  8562. this.boundingSphere = geometry.boundingSphere.clone();
  8563. }
  8564. if ( geometry.boundingBox !== null ) {
  8565. this.boundingBox = geometry.boundingBox.clone();
  8566. }
  8567. return this;
  8568. },
  8569. computeBoundingBox: function () {
  8570. if ( this.boundingBox === null ) {
  8571. this.boundingBox = new Box3();
  8572. }
  8573. var position = this.attributes.position;
  8574. if ( position !== undefined ) {
  8575. this.boundingBox.setFromBufferAttribute( position );
  8576. } else {
  8577. this.boundingBox.makeEmpty();
  8578. }
  8579. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8580. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8581. }
  8582. },
  8583. computeBoundingSphere: function () {
  8584. var box = new Box3();
  8585. var vector = new Vector3();
  8586. return function computeBoundingSphere() {
  8587. if ( this.boundingSphere === null ) {
  8588. this.boundingSphere = new Sphere();
  8589. }
  8590. var position = this.attributes.position;
  8591. if ( position ) {
  8592. var center = this.boundingSphere.center;
  8593. box.setFromBufferAttribute( position );
  8594. box.getCenter( center );
  8595. // hoping to find a boundingSphere with a radius smaller than the
  8596. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8597. var maxRadiusSq = 0;
  8598. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8599. vector.x = position.getX( i );
  8600. vector.y = position.getY( i );
  8601. vector.z = position.getZ( i );
  8602. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8603. }
  8604. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8605. if ( isNaN( this.boundingSphere.radius ) ) {
  8606. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8607. }
  8608. }
  8609. };
  8610. }(),
  8611. computeFaceNormals: function () {
  8612. // backwards compatibility
  8613. },
  8614. computeVertexNormals: function () {
  8615. var index = this.index;
  8616. var attributes = this.attributes;
  8617. var groups = this.groups;
  8618. if ( attributes.position ) {
  8619. var positions = attributes.position.array;
  8620. if ( attributes.normal === undefined ) {
  8621. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8622. } else {
  8623. // reset existing normals to zero
  8624. var array = attributes.normal.array;
  8625. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8626. array[ i ] = 0;
  8627. }
  8628. }
  8629. var normals = attributes.normal.array;
  8630. var vA, vB, vC;
  8631. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8632. var cb = new Vector3(), ab = new Vector3();
  8633. // indexed elements
  8634. if ( index ) {
  8635. var indices = index.array;
  8636. if ( groups.length === 0 ) {
  8637. this.addGroup( 0, indices.length );
  8638. }
  8639. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8640. var group = groups[ j ];
  8641. var start = group.start;
  8642. var count = group.count;
  8643. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8644. vA = indices[ i + 0 ] * 3;
  8645. vB = indices[ i + 1 ] * 3;
  8646. vC = indices[ i + 2 ] * 3;
  8647. pA.fromArray( positions, vA );
  8648. pB.fromArray( positions, vB );
  8649. pC.fromArray( positions, vC );
  8650. cb.subVectors( pC, pB );
  8651. ab.subVectors( pA, pB );
  8652. cb.cross( ab );
  8653. normals[ vA ] += cb.x;
  8654. normals[ vA + 1 ] += cb.y;
  8655. normals[ vA + 2 ] += cb.z;
  8656. normals[ vB ] += cb.x;
  8657. normals[ vB + 1 ] += cb.y;
  8658. normals[ vB + 2 ] += cb.z;
  8659. normals[ vC ] += cb.x;
  8660. normals[ vC + 1 ] += cb.y;
  8661. normals[ vC + 2 ] += cb.z;
  8662. }
  8663. }
  8664. } else {
  8665. // non-indexed elements (unconnected triangle soup)
  8666. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8667. pA.fromArray( positions, i );
  8668. pB.fromArray( positions, i + 3 );
  8669. pC.fromArray( positions, i + 6 );
  8670. cb.subVectors( pC, pB );
  8671. ab.subVectors( pA, pB );
  8672. cb.cross( ab );
  8673. normals[ i ] = cb.x;
  8674. normals[ i + 1 ] = cb.y;
  8675. normals[ i + 2 ] = cb.z;
  8676. normals[ i + 3 ] = cb.x;
  8677. normals[ i + 4 ] = cb.y;
  8678. normals[ i + 5 ] = cb.z;
  8679. normals[ i + 6 ] = cb.x;
  8680. normals[ i + 7 ] = cb.y;
  8681. normals[ i + 8 ] = cb.z;
  8682. }
  8683. }
  8684. this.normalizeNormals();
  8685. attributes.normal.needsUpdate = true;
  8686. }
  8687. },
  8688. merge: function ( geometry, offset ) {
  8689. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8690. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8691. return;
  8692. }
  8693. if ( offset === undefined ) offset = 0;
  8694. var attributes = this.attributes;
  8695. for ( var key in attributes ) {
  8696. if ( geometry.attributes[ key ] === undefined ) continue;
  8697. var attribute1 = attributes[ key ];
  8698. var attributeArray1 = attribute1.array;
  8699. var attribute2 = geometry.attributes[ key ];
  8700. var attributeArray2 = attribute2.array;
  8701. var attributeSize = attribute2.itemSize;
  8702. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8703. attributeArray1[ j ] = attributeArray2[ i ];
  8704. }
  8705. }
  8706. return this;
  8707. },
  8708. normalizeNormals: function () {
  8709. var normals = this.attributes.normal;
  8710. var x, y, z, n;
  8711. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8712. x = normals.getX( i );
  8713. y = normals.getY( i );
  8714. z = normals.getZ( i );
  8715. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8716. normals.setXYZ( i, x * n, y * n, z * n );
  8717. }
  8718. },
  8719. toNonIndexed: function () {
  8720. if ( this.index === null ) {
  8721. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8722. return this;
  8723. }
  8724. var geometry2 = new BufferGeometry();
  8725. var indices = this.index.array;
  8726. var attributes = this.attributes;
  8727. for ( var name in attributes ) {
  8728. var attribute = attributes[ name ];
  8729. var array = attribute.array;
  8730. var itemSize = attribute.itemSize;
  8731. var array2 = new array.constructor( indices.length * itemSize );
  8732. var index = 0, index2 = 0;
  8733. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8734. index = indices[ i ] * itemSize;
  8735. for ( var j = 0; j < itemSize; j ++ ) {
  8736. array2[ index2 ++ ] = array[ index ++ ];
  8737. }
  8738. }
  8739. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8740. }
  8741. return geometry2;
  8742. },
  8743. toJSON: function () {
  8744. var data = {
  8745. metadata: {
  8746. version: 4.5,
  8747. type: 'BufferGeometry',
  8748. generator: 'BufferGeometry.toJSON'
  8749. }
  8750. };
  8751. // standard BufferGeometry serialization
  8752. data.uuid = this.uuid;
  8753. data.type = this.type;
  8754. if ( this.name !== '' ) data.name = this.name;
  8755. if ( this.parameters !== undefined ) {
  8756. var parameters = this.parameters;
  8757. for ( var key in parameters ) {
  8758. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8759. }
  8760. return data;
  8761. }
  8762. data.data = { attributes: {} };
  8763. var index = this.index;
  8764. if ( index !== null ) {
  8765. var array = Array.prototype.slice.call( index.array );
  8766. data.data.index = {
  8767. type: index.array.constructor.name,
  8768. array: array
  8769. };
  8770. }
  8771. var attributes = this.attributes;
  8772. for ( var key in attributes ) {
  8773. var attribute = attributes[ key ];
  8774. var array = Array.prototype.slice.call( attribute.array );
  8775. data.data.attributes[ key ] = {
  8776. itemSize: attribute.itemSize,
  8777. type: attribute.array.constructor.name,
  8778. array: array,
  8779. normalized: attribute.normalized
  8780. };
  8781. }
  8782. var groups = this.groups;
  8783. if ( groups.length > 0 ) {
  8784. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8785. }
  8786. var boundingSphere = this.boundingSphere;
  8787. if ( boundingSphere !== null ) {
  8788. data.data.boundingSphere = {
  8789. center: boundingSphere.center.toArray(),
  8790. radius: boundingSphere.radius
  8791. };
  8792. }
  8793. return data;
  8794. },
  8795. clone: function () {
  8796. /*
  8797. // Handle primitives
  8798. var parameters = this.parameters;
  8799. if ( parameters !== undefined ) {
  8800. var values = [];
  8801. for ( var key in parameters ) {
  8802. values.push( parameters[ key ] );
  8803. }
  8804. var geometry = Object.create( this.constructor.prototype );
  8805. this.constructor.apply( geometry, values );
  8806. return geometry;
  8807. }
  8808. return new this.constructor().copy( this );
  8809. */
  8810. return new BufferGeometry().copy( this );
  8811. },
  8812. copy: function ( source ) {
  8813. var name, i, l;
  8814. // reset
  8815. this.index = null;
  8816. this.attributes = {};
  8817. this.morphAttributes = {};
  8818. this.groups = [];
  8819. this.boundingBox = null;
  8820. this.boundingSphere = null;
  8821. // name
  8822. this.name = source.name;
  8823. // index
  8824. var index = source.index;
  8825. if ( index !== null ) {
  8826. this.setIndex( index.clone() );
  8827. }
  8828. // attributes
  8829. var attributes = source.attributes;
  8830. for ( name in attributes ) {
  8831. var attribute = attributes[ name ];
  8832. this.addAttribute( name, attribute.clone() );
  8833. }
  8834. // morph attributes
  8835. var morphAttributes = source.morphAttributes;
  8836. for ( name in morphAttributes ) {
  8837. var array = [];
  8838. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8839. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8840. array.push( morphAttribute[ i ].clone() );
  8841. }
  8842. this.morphAttributes[ name ] = array;
  8843. }
  8844. // groups
  8845. var groups = source.groups;
  8846. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8847. var group = groups[ i ];
  8848. this.addGroup( group.start, group.count, group.materialIndex );
  8849. }
  8850. // bounding box
  8851. var boundingBox = source.boundingBox;
  8852. if ( boundingBox !== null ) {
  8853. this.boundingBox = boundingBox.clone();
  8854. }
  8855. // bounding sphere
  8856. var boundingSphere = source.boundingSphere;
  8857. if ( boundingSphere !== null ) {
  8858. this.boundingSphere = boundingSphere.clone();
  8859. }
  8860. // draw range
  8861. this.drawRange.start = source.drawRange.start;
  8862. this.drawRange.count = source.drawRange.count;
  8863. return this;
  8864. },
  8865. dispose: function () {
  8866. this.dispatchEvent( { type: 'dispose' } );
  8867. }
  8868. } );
  8869. /**
  8870. * @author mrdoob / http://mrdoob.com/
  8871. * @author alteredq / http://alteredqualia.com/
  8872. * @author mikael emtinger / http://gomo.se/
  8873. * @author jonobr1 / http://jonobr1.com/
  8874. */
  8875. function Mesh( geometry, material ) {
  8876. Object3D.call( this );
  8877. this.type = 'Mesh';
  8878. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8879. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8880. this.drawMode = TrianglesDrawMode;
  8881. this.updateMorphTargets();
  8882. }
  8883. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8884. constructor: Mesh,
  8885. isMesh: true,
  8886. setDrawMode: function ( value ) {
  8887. this.drawMode = value;
  8888. },
  8889. copy: function ( source ) {
  8890. Object3D.prototype.copy.call( this, source );
  8891. this.drawMode = source.drawMode;
  8892. return this;
  8893. },
  8894. updateMorphTargets: function () {
  8895. var morphTargets = this.geometry.morphTargets;
  8896. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8897. this.morphTargetInfluences = [];
  8898. this.morphTargetDictionary = {};
  8899. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8900. this.morphTargetInfluences.push( 0 );
  8901. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8902. }
  8903. }
  8904. },
  8905. raycast: ( function () {
  8906. var inverseMatrix = new Matrix4();
  8907. var ray = new Ray();
  8908. var sphere = new Sphere();
  8909. var vA = new Vector3();
  8910. var vB = new Vector3();
  8911. var vC = new Vector3();
  8912. var tempA = new Vector3();
  8913. var tempB = new Vector3();
  8914. var tempC = new Vector3();
  8915. var uvA = new Vector2();
  8916. var uvB = new Vector2();
  8917. var uvC = new Vector2();
  8918. var barycoord = new Vector3();
  8919. var intersectionPoint = new Vector3();
  8920. var intersectionPointWorld = new Vector3();
  8921. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8922. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8923. uv1.multiplyScalar( barycoord.x );
  8924. uv2.multiplyScalar( barycoord.y );
  8925. uv3.multiplyScalar( barycoord.z );
  8926. uv1.add( uv2 ).add( uv3 );
  8927. return uv1.clone();
  8928. }
  8929. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8930. var intersect;
  8931. var material = object.material;
  8932. if ( material.side === BackSide ) {
  8933. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8934. } else {
  8935. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8936. }
  8937. if ( intersect === null ) return null;
  8938. intersectionPointWorld.copy( point );
  8939. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8940. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8941. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8942. return {
  8943. distance: distance,
  8944. point: intersectionPointWorld.clone(),
  8945. object: object
  8946. };
  8947. }
  8948. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  8949. vA.fromBufferAttribute( position, a );
  8950. vB.fromBufferAttribute( position, b );
  8951. vC.fromBufferAttribute( position, c );
  8952. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8953. if ( intersection ) {
  8954. if ( uv ) {
  8955. uvA.fromBufferAttribute( uv, a );
  8956. uvB.fromBufferAttribute( uv, b );
  8957. uvC.fromBufferAttribute( uv, c );
  8958. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8959. }
  8960. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8961. intersection.faceIndex = a;
  8962. }
  8963. return intersection;
  8964. }
  8965. return function raycast( raycaster, intersects ) {
  8966. var geometry = this.geometry;
  8967. var material = this.material;
  8968. var matrixWorld = this.matrixWorld;
  8969. if ( material === undefined ) return;
  8970. // Checking boundingSphere distance to ray
  8971. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8972. sphere.copy( geometry.boundingSphere );
  8973. sphere.applyMatrix4( matrixWorld );
  8974. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8975. //
  8976. inverseMatrix.getInverse( matrixWorld );
  8977. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8978. // Check boundingBox before continuing
  8979. if ( geometry.boundingBox !== null ) {
  8980. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8981. }
  8982. var intersection;
  8983. if ( geometry.isBufferGeometry ) {
  8984. var a, b, c;
  8985. var index = geometry.index;
  8986. var position = geometry.attributes.position;
  8987. var uv = geometry.attributes.uv;
  8988. var i, l;
  8989. if ( index !== null ) {
  8990. // indexed buffer geometry
  8991. for ( i = 0, l = index.count; i < l; i += 3 ) {
  8992. a = index.getX( i );
  8993. b = index.getX( i + 1 );
  8994. c = index.getX( i + 2 );
  8995. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  8996. if ( intersection ) {
  8997. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8998. intersects.push( intersection );
  8999. }
  9000. }
  9001. } else {
  9002. // non-indexed buffer geometry
  9003. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9004. a = i;
  9005. b = i + 1;
  9006. c = i + 2;
  9007. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9008. if ( intersection ) {
  9009. intersection.index = a; // triangle number in positions buffer semantics
  9010. intersects.push( intersection );
  9011. }
  9012. }
  9013. }
  9014. } else if ( geometry.isGeometry ) {
  9015. var fvA, fvB, fvC;
  9016. var isMultiMaterial = Array.isArray( material );
  9017. var vertices = geometry.vertices;
  9018. var faces = geometry.faces;
  9019. var uvs;
  9020. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9021. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9022. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9023. var face = faces[ f ];
  9024. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9025. if ( faceMaterial === undefined ) continue;
  9026. fvA = vertices[ face.a ];
  9027. fvB = vertices[ face.b ];
  9028. fvC = vertices[ face.c ];
  9029. if ( faceMaterial.morphTargets === true ) {
  9030. var morphTargets = geometry.morphTargets;
  9031. var morphInfluences = this.morphTargetInfluences;
  9032. vA.set( 0, 0, 0 );
  9033. vB.set( 0, 0, 0 );
  9034. vC.set( 0, 0, 0 );
  9035. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9036. var influence = morphInfluences[ t ];
  9037. if ( influence === 0 ) continue;
  9038. var targets = morphTargets[ t ].vertices;
  9039. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9040. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9041. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9042. }
  9043. vA.add( fvA );
  9044. vB.add( fvB );
  9045. vC.add( fvC );
  9046. fvA = vA;
  9047. fvB = vB;
  9048. fvC = vC;
  9049. }
  9050. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9051. if ( intersection ) {
  9052. if ( uvs && uvs[ f ] ) {
  9053. var uvs_f = uvs[ f ];
  9054. uvA.copy( uvs_f[ 0 ] );
  9055. uvB.copy( uvs_f[ 1 ] );
  9056. uvC.copy( uvs_f[ 2 ] );
  9057. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9058. }
  9059. intersection.face = face;
  9060. intersection.faceIndex = f;
  9061. intersects.push( intersection );
  9062. }
  9063. }
  9064. }
  9065. };
  9066. }() ),
  9067. clone: function () {
  9068. return new this.constructor( this.geometry, this.material ).copy( this );
  9069. }
  9070. } );
  9071. /**
  9072. * @author mrdoob / http://mrdoob.com/
  9073. * @author Mugen87 / https://github.com/Mugen87
  9074. */
  9075. // BoxGeometry
  9076. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9077. Geometry.call( this );
  9078. this.type = 'BoxGeometry';
  9079. this.parameters = {
  9080. width: width,
  9081. height: height,
  9082. depth: depth,
  9083. widthSegments: widthSegments,
  9084. heightSegments: heightSegments,
  9085. depthSegments: depthSegments
  9086. };
  9087. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  9088. this.mergeVertices();
  9089. }
  9090. BoxGeometry.prototype = Object.create( Geometry.prototype );
  9091. BoxGeometry.prototype.constructor = BoxGeometry;
  9092. // BoxBufferGeometry
  9093. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9094. BufferGeometry.call( this );
  9095. this.type = 'BoxBufferGeometry';
  9096. this.parameters = {
  9097. width: width,
  9098. height: height,
  9099. depth: depth,
  9100. widthSegments: widthSegments,
  9101. heightSegments: heightSegments,
  9102. depthSegments: depthSegments
  9103. };
  9104. var scope = this;
  9105. // segments
  9106. widthSegments = Math.floor( widthSegments ) || 1;
  9107. heightSegments = Math.floor( heightSegments ) || 1;
  9108. depthSegments = Math.floor( depthSegments ) || 1;
  9109. // buffers
  9110. var indices = [];
  9111. var vertices = [];
  9112. var normals = [];
  9113. var uvs = [];
  9114. // helper variables
  9115. var numberOfVertices = 0;
  9116. var groupStart = 0;
  9117. // build each side of the box geometry
  9118. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  9119. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9120. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9121. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9122. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9123. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9124. // build geometry
  9125. this.setIndex( indices );
  9126. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  9127. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  9128. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  9129. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9130. var segmentWidth = width / gridX;
  9131. var segmentHeight = height / gridY;
  9132. var widthHalf = width / 2;
  9133. var heightHalf = height / 2;
  9134. var depthHalf = depth / 2;
  9135. var gridX1 = gridX + 1;
  9136. var gridY1 = gridY + 1;
  9137. var vertexCounter = 0;
  9138. var groupCount = 0;
  9139. var ix, iy;
  9140. var vector = new Vector3();
  9141. // generate vertices, normals and uvs
  9142. for ( iy = 0; iy < gridY1; iy ++ ) {
  9143. var y = iy * segmentHeight - heightHalf;
  9144. for ( ix = 0; ix < gridX1; ix ++ ) {
  9145. var x = ix * segmentWidth - widthHalf;
  9146. // set values to correct vector component
  9147. vector[ u ] = x * udir;
  9148. vector[ v ] = y * vdir;
  9149. vector[ w ] = depthHalf;
  9150. // now apply vector to vertex buffer
  9151. vertices.push( vector.x, vector.y, vector.z );
  9152. // set values to correct vector component
  9153. vector[ u ] = 0;
  9154. vector[ v ] = 0;
  9155. vector[ w ] = depth > 0 ? 1 : - 1;
  9156. // now apply vector to normal buffer
  9157. normals.push( vector.x, vector.y, vector.z );
  9158. // uvs
  9159. uvs.push( ix / gridX );
  9160. uvs.push( 1 - ( iy / gridY ) );
  9161. // counters
  9162. vertexCounter += 1;
  9163. }
  9164. }
  9165. // indices
  9166. // 1. you need three indices to draw a single face
  9167. // 2. a single segment consists of two faces
  9168. // 3. so we need to generate six (2*3) indices per segment
  9169. for ( iy = 0; iy < gridY; iy ++ ) {
  9170. for ( ix = 0; ix < gridX; ix ++ ) {
  9171. var a = numberOfVertices + ix + gridX1 * iy;
  9172. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9173. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9174. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9175. // faces
  9176. indices.push( a, b, d );
  9177. indices.push( b, c, d );
  9178. // increase counter
  9179. groupCount += 6;
  9180. }
  9181. }
  9182. // add a group to the geometry. this will ensure multi material support
  9183. scope.addGroup( groupStart, groupCount, materialIndex );
  9184. // calculate new start value for groups
  9185. groupStart += groupCount;
  9186. // update total number of vertices
  9187. numberOfVertices += vertexCounter;
  9188. }
  9189. }
  9190. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9191. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9192. /**
  9193. * @author mrdoob / http://mrdoob.com/
  9194. * @author Mugen87 / https://github.com/Mugen87
  9195. */
  9196. // PlaneGeometry
  9197. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  9198. Geometry.call( this );
  9199. this.type = 'PlaneGeometry';
  9200. this.parameters = {
  9201. width: width,
  9202. height: height,
  9203. widthSegments: widthSegments,
  9204. heightSegments: heightSegments
  9205. };
  9206. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  9207. this.mergeVertices();
  9208. }
  9209. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  9210. PlaneGeometry.prototype.constructor = PlaneGeometry;
  9211. // PlaneBufferGeometry
  9212. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9213. BufferGeometry.call( this );
  9214. this.type = 'PlaneBufferGeometry';
  9215. this.parameters = {
  9216. width: width,
  9217. height: height,
  9218. widthSegments: widthSegments,
  9219. heightSegments: heightSegments
  9220. };
  9221. var width_half = width / 2;
  9222. var height_half = height / 2;
  9223. var gridX = Math.floor( widthSegments ) || 1;
  9224. var gridY = Math.floor( heightSegments ) || 1;
  9225. var gridX1 = gridX + 1;
  9226. var gridY1 = gridY + 1;
  9227. var segment_width = width / gridX;
  9228. var segment_height = height / gridY;
  9229. var ix, iy;
  9230. // buffers
  9231. var indices = [];
  9232. var vertices = [];
  9233. var normals = [];
  9234. var uvs = [];
  9235. // generate vertices, normals and uvs
  9236. for ( iy = 0; iy < gridY1; iy ++ ) {
  9237. var y = iy * segment_height - height_half;
  9238. for ( ix = 0; ix < gridX1; ix ++ ) {
  9239. var x = ix * segment_width - width_half;
  9240. vertices.push( x, - y, 0 );
  9241. normals.push( 0, 0, 1 );
  9242. uvs.push( ix / gridX );
  9243. uvs.push( 1 - ( iy / gridY ) );
  9244. }
  9245. }
  9246. // indices
  9247. for ( iy = 0; iy < gridY; iy ++ ) {
  9248. for ( ix = 0; ix < gridX; ix ++ ) {
  9249. var a = ix + gridX1 * iy;
  9250. var b = ix + gridX1 * ( iy + 1 );
  9251. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9252. var d = ( ix + 1 ) + gridX1 * iy;
  9253. // faces
  9254. indices.push( a, b, d );
  9255. indices.push( b, c, d );
  9256. }
  9257. }
  9258. // build geometry
  9259. this.setIndex( indices );
  9260. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  9261. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  9262. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  9263. }
  9264. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9265. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9266. /**
  9267. * @author mrdoob / http://mrdoob.com/
  9268. * @author mikael emtinger / http://gomo.se/
  9269. * @author WestLangley / http://github.com/WestLangley
  9270. */
  9271. function Camera() {
  9272. Object3D.call( this );
  9273. this.type = 'Camera';
  9274. this.matrixWorldInverse = new Matrix4();
  9275. this.projectionMatrix = new Matrix4();
  9276. }
  9277. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9278. constructor: Camera,
  9279. isCamera: true,
  9280. copy: function ( source ) {
  9281. Object3D.prototype.copy.call( this, source );
  9282. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9283. this.projectionMatrix.copy( source.projectionMatrix );
  9284. return this;
  9285. },
  9286. getWorldDirection: function () {
  9287. var quaternion = new Quaternion();
  9288. return function getWorldDirection( optionalTarget ) {
  9289. var result = optionalTarget || new Vector3();
  9290. this.getWorldQuaternion( quaternion );
  9291. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9292. };
  9293. }(),
  9294. clone: function () {
  9295. return new this.constructor().copy( this );
  9296. }
  9297. } );
  9298. /**
  9299. * @author mrdoob / http://mrdoob.com/
  9300. * @author greggman / http://games.greggman.com/
  9301. * @author zz85 / http://www.lab4games.net/zz85/blog
  9302. * @author tschw
  9303. */
  9304. function PerspectiveCamera( fov, aspect, near, far ) {
  9305. Camera.call( this );
  9306. this.type = 'PerspectiveCamera';
  9307. this.fov = fov !== undefined ? fov : 50;
  9308. this.zoom = 1;
  9309. this.near = near !== undefined ? near : 0.1;
  9310. this.far = far !== undefined ? far : 2000;
  9311. this.focus = 10;
  9312. this.aspect = aspect !== undefined ? aspect : 1;
  9313. this.view = null;
  9314. this.filmGauge = 35; // width of the film (default in millimeters)
  9315. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9316. this.updateProjectionMatrix();
  9317. }
  9318. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9319. constructor: PerspectiveCamera,
  9320. isPerspectiveCamera: true,
  9321. copy: function ( source ) {
  9322. Camera.prototype.copy.call( this, source );
  9323. this.fov = source.fov;
  9324. this.zoom = source.zoom;
  9325. this.near = source.near;
  9326. this.far = source.far;
  9327. this.focus = source.focus;
  9328. this.aspect = source.aspect;
  9329. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9330. this.filmGauge = source.filmGauge;
  9331. this.filmOffset = source.filmOffset;
  9332. return this;
  9333. },
  9334. /**
  9335. * Sets the FOV by focal length in respect to the current .filmGauge.
  9336. *
  9337. * The default film gauge is 35, so that the focal length can be specified for
  9338. * a 35mm (full frame) camera.
  9339. *
  9340. * Values for focal length and film gauge must have the same unit.
  9341. */
  9342. setFocalLength: function ( focalLength ) {
  9343. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9344. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9345. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9346. this.updateProjectionMatrix();
  9347. },
  9348. /**
  9349. * Calculates the focal length from the current .fov and .filmGauge.
  9350. */
  9351. getFocalLength: function () {
  9352. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9353. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9354. },
  9355. getEffectiveFOV: function () {
  9356. return _Math.RAD2DEG * 2 * Math.atan(
  9357. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9358. },
  9359. getFilmWidth: function () {
  9360. // film not completely covered in portrait format (aspect < 1)
  9361. return this.filmGauge * Math.min( this.aspect, 1 );
  9362. },
  9363. getFilmHeight: function () {
  9364. // film not completely covered in landscape format (aspect > 1)
  9365. return this.filmGauge / Math.max( this.aspect, 1 );
  9366. },
  9367. /**
  9368. * Sets an offset in a larger frustum. This is useful for multi-window or
  9369. * multi-monitor/multi-machine setups.
  9370. *
  9371. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9372. * the monitors are in grid like this
  9373. *
  9374. * +---+---+---+
  9375. * | A | B | C |
  9376. * +---+---+---+
  9377. * | D | E | F |
  9378. * +---+---+---+
  9379. *
  9380. * then for each monitor you would call it like this
  9381. *
  9382. * var w = 1920;
  9383. * var h = 1080;
  9384. * var fullWidth = w * 3;
  9385. * var fullHeight = h * 2;
  9386. *
  9387. * --A--
  9388. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9389. * --B--
  9390. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9391. * --C--
  9392. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9393. * --D--
  9394. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9395. * --E--
  9396. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9397. * --F--
  9398. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9399. *
  9400. * Note there is no reason monitors have to be the same size or in a grid.
  9401. */
  9402. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9403. this.aspect = fullWidth / fullHeight;
  9404. this.view = {
  9405. fullWidth: fullWidth,
  9406. fullHeight: fullHeight,
  9407. offsetX: x,
  9408. offsetY: y,
  9409. width: width,
  9410. height: height
  9411. };
  9412. this.updateProjectionMatrix();
  9413. },
  9414. clearViewOffset: function () {
  9415. this.view = null;
  9416. this.updateProjectionMatrix();
  9417. },
  9418. updateProjectionMatrix: function () {
  9419. var near = this.near,
  9420. top = near * Math.tan(
  9421. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9422. height = 2 * top,
  9423. width = this.aspect * height,
  9424. left = - 0.5 * width,
  9425. view = this.view;
  9426. if ( view !== null ) {
  9427. var fullWidth = view.fullWidth,
  9428. fullHeight = view.fullHeight;
  9429. left += view.offsetX * width / fullWidth;
  9430. top -= view.offsetY * height / fullHeight;
  9431. width *= view.width / fullWidth;
  9432. height *= view.height / fullHeight;
  9433. }
  9434. var skew = this.filmOffset;
  9435. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9436. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  9437. },
  9438. toJSON: function ( meta ) {
  9439. var data = Object3D.prototype.toJSON.call( this, meta );
  9440. data.object.fov = this.fov;
  9441. data.object.zoom = this.zoom;
  9442. data.object.near = this.near;
  9443. data.object.far = this.far;
  9444. data.object.focus = this.focus;
  9445. data.object.aspect = this.aspect;
  9446. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9447. data.object.filmGauge = this.filmGauge;
  9448. data.object.filmOffset = this.filmOffset;
  9449. return data;
  9450. }
  9451. } );
  9452. /**
  9453. * @author alteredq / http://alteredqualia.com/
  9454. * @author arose / http://github.com/arose
  9455. */
  9456. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9457. Camera.call( this );
  9458. this.type = 'OrthographicCamera';
  9459. this.zoom = 1;
  9460. this.view = null;
  9461. this.left = left;
  9462. this.right = right;
  9463. this.top = top;
  9464. this.bottom = bottom;
  9465. this.near = ( near !== undefined ) ? near : 0.1;
  9466. this.far = ( far !== undefined ) ? far : 2000;
  9467. this.updateProjectionMatrix();
  9468. }
  9469. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9470. constructor: OrthographicCamera,
  9471. isOrthographicCamera: true,
  9472. copy: function ( source ) {
  9473. Camera.prototype.copy.call( this, source );
  9474. this.left = source.left;
  9475. this.right = source.right;
  9476. this.top = source.top;
  9477. this.bottom = source.bottom;
  9478. this.near = source.near;
  9479. this.far = source.far;
  9480. this.zoom = source.zoom;
  9481. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9482. return this;
  9483. },
  9484. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9485. this.view = {
  9486. fullWidth: fullWidth,
  9487. fullHeight: fullHeight,
  9488. offsetX: x,
  9489. offsetY: y,
  9490. width: width,
  9491. height: height
  9492. };
  9493. this.updateProjectionMatrix();
  9494. },
  9495. clearViewOffset: function() {
  9496. this.view = null;
  9497. this.updateProjectionMatrix();
  9498. },
  9499. updateProjectionMatrix: function () {
  9500. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9501. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9502. var cx = ( this.right + this.left ) / 2;
  9503. var cy = ( this.top + this.bottom ) / 2;
  9504. var left = cx - dx;
  9505. var right = cx + dx;
  9506. var top = cy + dy;
  9507. var bottom = cy - dy;
  9508. if ( this.view !== null ) {
  9509. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9510. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9511. var scaleW = ( this.right - this.left ) / this.view.width;
  9512. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9513. left += scaleW * ( this.view.offsetX / zoomW );
  9514. right = left + scaleW * ( this.view.width / zoomW );
  9515. top -= scaleH * ( this.view.offsetY / zoomH );
  9516. bottom = top - scaleH * ( this.view.height / zoomH );
  9517. }
  9518. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9519. },
  9520. toJSON: function ( meta ) {
  9521. var data = Object3D.prototype.toJSON.call( this, meta );
  9522. data.object.zoom = this.zoom;
  9523. data.object.left = this.left;
  9524. data.object.right = this.right;
  9525. data.object.top = this.top;
  9526. data.object.bottom = this.bottom;
  9527. data.object.near = this.near;
  9528. data.object.far = this.far;
  9529. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9530. return data;
  9531. }
  9532. } );
  9533. /**
  9534. * @author mrdoob / http://mrdoob.com/
  9535. */
  9536. function WebGLAttributes( gl ) {
  9537. var buffers = {};
  9538. function createBuffer( attribute, bufferType ) {
  9539. var array = attribute.array;
  9540. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  9541. var buffer = gl.createBuffer();
  9542. gl.bindBuffer( bufferType, buffer );
  9543. gl.bufferData( bufferType, array, usage );
  9544. attribute.onUploadCallback();
  9545. var type = gl.FLOAT;
  9546. if ( array instanceof Float32Array ) {
  9547. type = gl.FLOAT;
  9548. } else if ( array instanceof Float64Array ) {
  9549. console.warn( "Unsupported data buffer format: Float64Array" );
  9550. } else if ( array instanceof Uint16Array ) {
  9551. type = gl.UNSIGNED_SHORT;
  9552. } else if ( array instanceof Int16Array ) {
  9553. type = gl.SHORT;
  9554. } else if ( array instanceof Uint32Array ) {
  9555. type = gl.UNSIGNED_INT;
  9556. } else if ( array instanceof Int32Array ) {
  9557. type = gl.INT;
  9558. } else if ( array instanceof Int8Array ) {
  9559. type = gl.BYTE;
  9560. } else if ( array instanceof Uint8Array ) {
  9561. type = gl.UNSIGNED_BYTE;
  9562. }
  9563. return {
  9564. buffer: buffer,
  9565. type: type,
  9566. bytesPerElement: array.BYTES_PER_ELEMENT,
  9567. version: attribute.version
  9568. };
  9569. }
  9570. function updateBuffer( buffer, attribute, bufferType ) {
  9571. var array = attribute.array;
  9572. var updateRange = attribute.updateRange;
  9573. gl.bindBuffer( bufferType, buffer );
  9574. if ( attribute.dynamic === false ) {
  9575. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  9576. } else if ( updateRange.count === - 1 ) {
  9577. // Not using update ranges
  9578. gl.bufferSubData( bufferType, 0, array );
  9579. } else if ( updateRange.count === 0 ) {
  9580. 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.' );
  9581. } else {
  9582. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  9583. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  9584. updateRange.count = 0; // reset range
  9585. }
  9586. }
  9587. //
  9588. function get( attribute ) {
  9589. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9590. return buffers[ attribute.uuid ];
  9591. }
  9592. function remove( attribute ) {
  9593. var data = buffers[ attribute.uuid ];
  9594. if ( data ) {
  9595. gl.deleteBuffer( data.buffer );
  9596. delete buffers[ attribute.uuid ];
  9597. }
  9598. }
  9599. function update( attribute, bufferType ) {
  9600. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9601. var data = buffers[ attribute.uuid ];
  9602. if ( data === undefined ) {
  9603. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  9604. } else if ( data.version < attribute.version ) {
  9605. updateBuffer( data.buffer, attribute, bufferType );
  9606. data.version = attribute.version;
  9607. }
  9608. }
  9609. return {
  9610. get: get,
  9611. remove: remove,
  9612. update: update
  9613. };
  9614. }
  9615. /**
  9616. * @author mrdoob / http://mrdoob.com/
  9617. */
  9618. function painterSortStable( a, b ) {
  9619. if ( a.renderOrder !== b.renderOrder ) {
  9620. return a.renderOrder - b.renderOrder;
  9621. } else if ( a.program && b.program && a.program !== b.program ) {
  9622. return a.program.id - b.program.id;
  9623. } else if ( a.material.id !== b.material.id ) {
  9624. return a.material.id - b.material.id;
  9625. } else if ( a.z !== b.z ) {
  9626. return a.z - b.z;
  9627. } else {
  9628. return a.id - b.id;
  9629. }
  9630. }
  9631. function reversePainterSortStable( a, b ) {
  9632. if ( a.renderOrder !== b.renderOrder ) {
  9633. return a.renderOrder - b.renderOrder;
  9634. } if ( a.z !== b.z ) {
  9635. return b.z - a.z;
  9636. } else {
  9637. return a.id - b.id;
  9638. }
  9639. }
  9640. function WebGLRenderList() {
  9641. var opaque = [];
  9642. var opaqueLastIndex = - 1;
  9643. var transparent = [];
  9644. var transparentLastIndex = - 1;
  9645. function init() {
  9646. opaqueLastIndex = - 1;
  9647. transparentLastIndex = - 1;
  9648. }
  9649. function push( object, geometry, material, z, group ) {
  9650. var array, index;
  9651. // allocate the next position in the appropriate array
  9652. if ( material.transparent ) {
  9653. array = transparent;
  9654. index = ++ transparentLastIndex;
  9655. } else {
  9656. array = opaque;
  9657. index = ++ opaqueLastIndex;
  9658. }
  9659. // recycle existing render item or grow the array
  9660. var renderItem = array[ index ];
  9661. if ( renderItem ) {
  9662. renderItem.id = object.id;
  9663. renderItem.object = object;
  9664. renderItem.geometry = geometry;
  9665. renderItem.material = material;
  9666. renderItem.program = material.program;
  9667. renderItem.renderOrder = object.renderOrder;
  9668. renderItem.z = z;
  9669. renderItem.group = group;
  9670. } else {
  9671. renderItem = {
  9672. id: object.id,
  9673. object: object,
  9674. geometry: geometry,
  9675. material: material,
  9676. program: material.program,
  9677. renderOrder: object.renderOrder,
  9678. z: z,
  9679. group: group
  9680. };
  9681. // assert( index === array.length );
  9682. array.push( renderItem );
  9683. }
  9684. }
  9685. function finish() {
  9686. opaque.length = opaqueLastIndex + 1;
  9687. transparent.length = transparentLastIndex + 1;
  9688. }
  9689. function sort() {
  9690. opaque.sort( painterSortStable );
  9691. transparent.sort( reversePainterSortStable );
  9692. }
  9693. return {
  9694. opaque: opaque,
  9695. transparent: transparent,
  9696. init: init,
  9697. push: push,
  9698. finish: finish,
  9699. sort: sort
  9700. };
  9701. }
  9702. function WebGLRenderLists() {
  9703. var lists = {};
  9704. function get( scene, camera ) {
  9705. var hash = scene.id + ',' + camera.id;
  9706. var list = lists[ hash ];
  9707. if ( list === undefined ) {
  9708. // console.log( 'THREE.WebGLRenderLists:', hash );
  9709. list = new WebGLRenderList();
  9710. lists[ hash ] = list;
  9711. }
  9712. return list;
  9713. }
  9714. function dispose() {
  9715. lists = {};
  9716. }
  9717. return {
  9718. get: get,
  9719. dispose: dispose
  9720. };
  9721. }
  9722. /**
  9723. * @author mrdoob / http://mrdoob.com/
  9724. */
  9725. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9726. var mode;
  9727. function setMode( value ) {
  9728. mode = value;
  9729. }
  9730. var type, size;
  9731. function setIndex( index ) {
  9732. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9733. type = gl.UNSIGNED_INT;
  9734. size = 4;
  9735. } else if ( index.array instanceof Uint16Array ) {
  9736. type = gl.UNSIGNED_SHORT;
  9737. size = 2;
  9738. } else {
  9739. type = gl.UNSIGNED_BYTE;
  9740. size = 1;
  9741. }
  9742. }
  9743. function render( start, count ) {
  9744. gl.drawElements( mode, count, type, start * size );
  9745. infoRender.calls ++;
  9746. infoRender.vertices += count;
  9747. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9748. }
  9749. function renderInstances( geometry, start, count ) {
  9750. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9751. if ( extension === null ) {
  9752. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9753. return;
  9754. }
  9755. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9756. infoRender.calls ++;
  9757. infoRender.vertices += count * geometry.maxInstancedCount;
  9758. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9759. }
  9760. //
  9761. this.setMode = setMode;
  9762. this.setIndex = setIndex;
  9763. this.render = render;
  9764. this.renderInstances = renderInstances;
  9765. }
  9766. /**
  9767. * @author mrdoob / http://mrdoob.com/
  9768. */
  9769. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9770. var mode;
  9771. function setMode( value ) {
  9772. mode = value;
  9773. }
  9774. function render( start, count ) {
  9775. gl.drawArrays( mode, start, count );
  9776. infoRender.calls ++;
  9777. infoRender.vertices += count;
  9778. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9779. }
  9780. function renderInstances( geometry, start, count ) {
  9781. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9782. if ( extension === null ) {
  9783. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9784. return;
  9785. }
  9786. var position = geometry.attributes.position;
  9787. if ( position.isInterleavedBufferAttribute ) {
  9788. count = position.data.count;
  9789. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9790. } else {
  9791. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  9792. }
  9793. infoRender.calls ++;
  9794. infoRender.vertices += count * geometry.maxInstancedCount;
  9795. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9796. }
  9797. //
  9798. this.setMode = setMode;
  9799. this.render = render;
  9800. this.renderInstances = renderInstances;
  9801. }
  9802. /**
  9803. * @author mrdoob / http://mrdoob.com/
  9804. */
  9805. function WebGLGeometries( gl, attributes, infoMemory ) {
  9806. var geometries = {};
  9807. var wireframeAttributes = {};
  9808. function onGeometryDispose( event ) {
  9809. var geometry = event.target;
  9810. var buffergeometry = geometries[ geometry.id ];
  9811. if ( buffergeometry.index !== null ) {
  9812. attributes.remove( buffergeometry.index );
  9813. }
  9814. for ( var name in buffergeometry.attributes ) {
  9815. attributes.remove( buffergeometry.attributes[ name ] );
  9816. }
  9817. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9818. delete geometries[ geometry.id ];
  9819. // TODO Remove duplicate code
  9820. var attribute = wireframeAttributes[ geometry.id ];
  9821. if ( attribute ) {
  9822. attributes.remove( attribute );
  9823. delete wireframeAttributes[ geometry.id ];
  9824. }
  9825. attribute = wireframeAttributes[ buffergeometry.id ];
  9826. if ( attribute ) {
  9827. attributes.remove( attribute );
  9828. delete wireframeAttributes[ buffergeometry.id ];
  9829. }
  9830. //
  9831. infoMemory.geometries --;
  9832. }
  9833. function get( object, geometry ) {
  9834. var buffergeometry = geometries[ geometry.id ];
  9835. if ( buffergeometry ) return buffergeometry;
  9836. geometry.addEventListener( 'dispose', onGeometryDispose );
  9837. if ( geometry.isBufferGeometry ) {
  9838. buffergeometry = geometry;
  9839. } else if ( geometry.isGeometry ) {
  9840. if ( geometry._bufferGeometry === undefined ) {
  9841. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9842. }
  9843. buffergeometry = geometry._bufferGeometry;
  9844. }
  9845. geometries[ geometry.id ] = buffergeometry;
  9846. infoMemory.geometries ++;
  9847. return buffergeometry;
  9848. }
  9849. function update( geometry ) {
  9850. var index = geometry.index;
  9851. var geometryAttributes = geometry.attributes;
  9852. if ( index !== null ) {
  9853. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9854. }
  9855. for ( var name in geometryAttributes ) {
  9856. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9857. }
  9858. // morph targets
  9859. var morphAttributes = geometry.morphAttributes;
  9860. for ( var name in morphAttributes ) {
  9861. var array = morphAttributes[ name ];
  9862. for ( var i = 0, l = array.length; i < l; i ++ ) {
  9863. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9864. }
  9865. }
  9866. }
  9867. function getWireframeAttribute( geometry ) {
  9868. var attribute = wireframeAttributes[ geometry.id ];
  9869. if ( attribute ) return attribute;
  9870. var indices = [];
  9871. var geometryIndex = geometry.index;
  9872. var geometryAttributes = geometry.attributes;
  9873. // console.time( 'wireframe' );
  9874. if ( geometryIndex !== null ) {
  9875. var array = geometryIndex.array;
  9876. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9877. var a = array[ i + 0 ];
  9878. var b = array[ i + 1 ];
  9879. var c = array[ i + 2 ];
  9880. indices.push( a, b, b, c, c, a );
  9881. }
  9882. } else {
  9883. var array = geometryAttributes.position.array;
  9884. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9885. var a = i + 0;
  9886. var b = i + 1;
  9887. var c = i + 2;
  9888. indices.push( a, b, b, c, c, a );
  9889. }
  9890. }
  9891. // console.timeEnd( 'wireframe' );
  9892. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9893. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  9894. wireframeAttributes[ geometry.id ] = attribute;
  9895. return attribute;
  9896. }
  9897. return {
  9898. get: get,
  9899. update: update,
  9900. getWireframeAttribute: getWireframeAttribute
  9901. };
  9902. }
  9903. /**
  9904. * @author mrdoob / http://mrdoob.com/
  9905. */
  9906. function WebGLLights() {
  9907. var lights = {};
  9908. return {
  9909. get: function ( light ) {
  9910. if ( lights[ light.id ] !== undefined ) {
  9911. return lights[ light.id ];
  9912. }
  9913. var uniforms;
  9914. switch ( light.type ) {
  9915. case 'DirectionalLight':
  9916. uniforms = {
  9917. direction: new Vector3(),
  9918. color: new Color(),
  9919. shadow: false,
  9920. shadowBias: 0,
  9921. shadowRadius: 1,
  9922. shadowMapSize: new Vector2()
  9923. };
  9924. break;
  9925. case 'SpotLight':
  9926. uniforms = {
  9927. position: new Vector3(),
  9928. direction: new Vector3(),
  9929. color: new Color(),
  9930. distance: 0,
  9931. coneCos: 0,
  9932. penumbraCos: 0,
  9933. decay: 0,
  9934. shadow: false,
  9935. shadowBias: 0,
  9936. shadowRadius: 1,
  9937. shadowMapSize: new Vector2()
  9938. };
  9939. break;
  9940. case 'PointLight':
  9941. uniforms = {
  9942. position: new Vector3(),
  9943. color: new Color(),
  9944. distance: 0,
  9945. decay: 0,
  9946. shadow: false,
  9947. shadowBias: 0,
  9948. shadowRadius: 1,
  9949. shadowMapSize: new Vector2()
  9950. };
  9951. break;
  9952. case 'HemisphereLight':
  9953. uniforms = {
  9954. direction: new Vector3(),
  9955. skyColor: new Color(),
  9956. groundColor: new Color()
  9957. };
  9958. break;
  9959. case 'RectAreaLight':
  9960. uniforms = {
  9961. color: new Color(),
  9962. position: new Vector3(),
  9963. halfWidth: new Vector3(),
  9964. halfHeight: new Vector3()
  9965. // TODO (abelnation): set RectAreaLight shadow uniforms
  9966. };
  9967. break;
  9968. }
  9969. lights[ light.id ] = uniforms;
  9970. return uniforms;
  9971. }
  9972. };
  9973. }
  9974. /**
  9975. * @author mrdoob / http://mrdoob.com/
  9976. */
  9977. function WebGLObjects( gl, geometries, infoRender ) {
  9978. var updateList = {};
  9979. function update( object ) {
  9980. var frame = infoRender.frame;
  9981. var geometry = object.geometry;
  9982. var buffergeometry = geometries.get( object, geometry );
  9983. // Update once per frame
  9984. if ( updateList[ buffergeometry.id ] !== frame ) {
  9985. if ( geometry.isGeometry ) {
  9986. buffergeometry.updateFromObject( object );
  9987. }
  9988. geometries.update( buffergeometry );
  9989. updateList[ buffergeometry.id ] = frame;
  9990. }
  9991. return buffergeometry;
  9992. }
  9993. function clear() {
  9994. updateList = {};
  9995. }
  9996. return {
  9997. update: update,
  9998. clear: clear
  9999. };
  10000. }
  10001. /**
  10002. * @author mrdoob / http://mrdoob.com/
  10003. */
  10004. function addLineNumbers( string ) {
  10005. var lines = string.split( '\n' );
  10006. for ( var i = 0; i < lines.length; i ++ ) {
  10007. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10008. }
  10009. return lines.join( '\n' );
  10010. }
  10011. function WebGLShader( gl, type, string ) {
  10012. var shader = gl.createShader( type );
  10013. gl.shaderSource( shader, string );
  10014. gl.compileShader( shader );
  10015. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10016. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10017. }
  10018. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10019. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10020. }
  10021. // --enable-privileged-webgl-extension
  10022. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10023. return shader;
  10024. }
  10025. /**
  10026. * @author mrdoob / http://mrdoob.com/
  10027. */
  10028. var programIdCount = 0;
  10029. function getEncodingComponents( encoding ) {
  10030. switch ( encoding ) {
  10031. case LinearEncoding:
  10032. return [ 'Linear','( value )' ];
  10033. case sRGBEncoding:
  10034. return [ 'sRGB','( value )' ];
  10035. case RGBEEncoding:
  10036. return [ 'RGBE','( value )' ];
  10037. case RGBM7Encoding:
  10038. return [ 'RGBM','( value, 7.0 )' ];
  10039. case RGBM16Encoding:
  10040. return [ 'RGBM','( value, 16.0 )' ];
  10041. case RGBDEncoding:
  10042. return [ 'RGBD','( value, 256.0 )' ];
  10043. case GammaEncoding:
  10044. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10045. default:
  10046. throw new Error( 'unsupported encoding: ' + encoding );
  10047. }
  10048. }
  10049. function getTexelDecodingFunction( functionName, encoding ) {
  10050. var components = getEncodingComponents( encoding );
  10051. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10052. }
  10053. function getTexelEncodingFunction( functionName, encoding ) {
  10054. var components = getEncodingComponents( encoding );
  10055. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10056. }
  10057. function getToneMappingFunction( functionName, toneMapping ) {
  10058. var toneMappingName;
  10059. switch ( toneMapping ) {
  10060. case LinearToneMapping:
  10061. toneMappingName = "Linear";
  10062. break;
  10063. case ReinhardToneMapping:
  10064. toneMappingName = "Reinhard";
  10065. break;
  10066. case Uncharted2ToneMapping:
  10067. toneMappingName = "Uncharted2";
  10068. break;
  10069. case CineonToneMapping:
  10070. toneMappingName = "OptimizedCineon";
  10071. break;
  10072. default:
  10073. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10074. }
  10075. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10076. }
  10077. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10078. extensions = extensions || {};
  10079. var chunks = [
  10080. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10081. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10082. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10083. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10084. ];
  10085. return chunks.filter( filterEmptyLine ).join( '\n' );
  10086. }
  10087. function generateDefines( defines ) {
  10088. var chunks = [];
  10089. for ( var name in defines ) {
  10090. var value = defines[ name ];
  10091. if ( value === false ) continue;
  10092. chunks.push( '#define ' + name + ' ' + value );
  10093. }
  10094. return chunks.join( '\n' );
  10095. }
  10096. function fetchAttributeLocations( gl, program, identifiers ) {
  10097. var attributes = {};
  10098. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10099. for ( var i = 0; i < n; i ++ ) {
  10100. var info = gl.getActiveAttrib( program, i );
  10101. var name = info.name;
  10102. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10103. attributes[ name ] = gl.getAttribLocation( program, name );
  10104. }
  10105. return attributes;
  10106. }
  10107. function filterEmptyLine( string ) {
  10108. return string !== '';
  10109. }
  10110. function replaceLightNums( string, parameters ) {
  10111. return string
  10112. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10113. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10114. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10115. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10116. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10117. }
  10118. function parseIncludes( string ) {
  10119. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10120. function replace( match, include ) {
  10121. var replace = ShaderChunk[ include ];
  10122. if ( replace === undefined ) {
  10123. throw new Error( 'Can not resolve #include <' + include + '>' );
  10124. }
  10125. return parseIncludes( replace );
  10126. }
  10127. return string.replace( pattern, replace );
  10128. }
  10129. function unrollLoops( string ) {
  10130. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10131. function replace( match, start, end, snippet ) {
  10132. var unroll = '';
  10133. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10134. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10135. }
  10136. return unroll;
  10137. }
  10138. return string.replace( pattern, replace );
  10139. }
  10140. function WebGLProgram( renderer, code, material, parameters ) {
  10141. var gl = renderer.context;
  10142. var extensions = material.extensions;
  10143. var defines = material.defines;
  10144. var vertexShader = material.__webglShader.vertexShader;
  10145. var fragmentShader = material.__webglShader.fragmentShader;
  10146. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10147. if ( parameters.shadowMapType === PCFShadowMap ) {
  10148. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10149. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10150. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10151. }
  10152. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10153. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10154. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10155. if ( parameters.envMap ) {
  10156. switch ( material.envMap.mapping ) {
  10157. case CubeReflectionMapping:
  10158. case CubeRefractionMapping:
  10159. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10160. break;
  10161. case CubeUVReflectionMapping:
  10162. case CubeUVRefractionMapping:
  10163. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10164. break;
  10165. case EquirectangularReflectionMapping:
  10166. case EquirectangularRefractionMapping:
  10167. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10168. break;
  10169. case SphericalReflectionMapping:
  10170. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10171. break;
  10172. }
  10173. switch ( material.envMap.mapping ) {
  10174. case CubeRefractionMapping:
  10175. case EquirectangularRefractionMapping:
  10176. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10177. break;
  10178. }
  10179. switch ( material.combine ) {
  10180. case MultiplyOperation:
  10181. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10182. break;
  10183. case MixOperation:
  10184. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10185. break;
  10186. case AddOperation:
  10187. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10188. break;
  10189. }
  10190. }
  10191. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10192. // console.log( 'building new program ' );
  10193. //
  10194. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  10195. var customDefines = generateDefines( defines );
  10196. //
  10197. var program = gl.createProgram();
  10198. var prefixVertex, prefixFragment;
  10199. if ( material.isRawShaderMaterial ) {
  10200. prefixVertex = [
  10201. customDefines,
  10202. '\n'
  10203. ].filter( filterEmptyLine ).join( '\n' );
  10204. prefixFragment = [
  10205. customExtensions,
  10206. customDefines,
  10207. '\n'
  10208. ].filter( filterEmptyLine ).join( '\n' );
  10209. } else {
  10210. prefixVertex = [
  10211. 'precision ' + parameters.precision + ' float;',
  10212. 'precision ' + parameters.precision + ' int;',
  10213. '#define SHADER_NAME ' + material.__webglShader.name,
  10214. customDefines,
  10215. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10216. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10217. '#define MAX_BONES ' + parameters.maxBones,
  10218. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10219. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10220. parameters.map ? '#define USE_MAP' : '',
  10221. parameters.envMap ? '#define USE_ENVMAP' : '',
  10222. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10223. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10224. parameters.aoMap ? '#define USE_AOMAP' : '',
  10225. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10226. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10227. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10228. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10229. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10230. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10231. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10232. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10233. parameters.vertexColors ? '#define USE_COLOR' : '',
  10234. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10235. parameters.skinning ? '#define USE_SKINNING' : '',
  10236. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10237. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10238. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10239. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10240. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10241. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10242. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10243. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10244. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10245. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10246. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10247. 'uniform mat4 modelMatrix;',
  10248. 'uniform mat4 modelViewMatrix;',
  10249. 'uniform mat4 projectionMatrix;',
  10250. 'uniform mat4 viewMatrix;',
  10251. 'uniform mat3 normalMatrix;',
  10252. 'uniform vec3 cameraPosition;',
  10253. 'attribute vec3 position;',
  10254. 'attribute vec3 normal;',
  10255. 'attribute vec2 uv;',
  10256. '#ifdef USE_COLOR',
  10257. ' attribute vec3 color;',
  10258. '#endif',
  10259. '#ifdef USE_MORPHTARGETS',
  10260. ' attribute vec3 morphTarget0;',
  10261. ' attribute vec3 morphTarget1;',
  10262. ' attribute vec3 morphTarget2;',
  10263. ' attribute vec3 morphTarget3;',
  10264. ' #ifdef USE_MORPHNORMALS',
  10265. ' attribute vec3 morphNormal0;',
  10266. ' attribute vec3 morphNormal1;',
  10267. ' attribute vec3 morphNormal2;',
  10268. ' attribute vec3 morphNormal3;',
  10269. ' #else',
  10270. ' attribute vec3 morphTarget4;',
  10271. ' attribute vec3 morphTarget5;',
  10272. ' attribute vec3 morphTarget6;',
  10273. ' attribute vec3 morphTarget7;',
  10274. ' #endif',
  10275. '#endif',
  10276. '#ifdef USE_SKINNING',
  10277. ' attribute vec4 skinIndex;',
  10278. ' attribute vec4 skinWeight;',
  10279. '#endif',
  10280. '\n'
  10281. ].filter( filterEmptyLine ).join( '\n' );
  10282. prefixFragment = [
  10283. customExtensions,
  10284. 'precision ' + parameters.precision + ' float;',
  10285. 'precision ' + parameters.precision + ' int;',
  10286. '#define SHADER_NAME ' + material.__webglShader.name,
  10287. customDefines,
  10288. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10289. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10290. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10291. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10292. parameters.map ? '#define USE_MAP' : '',
  10293. parameters.envMap ? '#define USE_ENVMAP' : '',
  10294. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10295. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10296. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10297. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10298. parameters.aoMap ? '#define USE_AOMAP' : '',
  10299. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10300. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10301. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10302. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10303. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10304. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10305. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10306. parameters.vertexColors ? '#define USE_COLOR' : '',
  10307. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10308. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10309. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10310. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10311. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10312. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10313. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10314. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10315. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10316. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10317. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10318. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10319. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10320. 'uniform mat4 viewMatrix;',
  10321. 'uniform vec3 cameraPosition;',
  10322. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10323. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10324. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10325. parameters.dithering ? '#define DITHERING' : '',
  10326. ( 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
  10327. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10328. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10329. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10330. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10331. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10332. '\n'
  10333. ].filter( filterEmptyLine ).join( '\n' );
  10334. }
  10335. vertexShader = parseIncludes( vertexShader, parameters );
  10336. vertexShader = replaceLightNums( vertexShader, parameters );
  10337. fragmentShader = parseIncludes( fragmentShader, parameters );
  10338. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10339. if ( ! material.isShaderMaterial ) {
  10340. vertexShader = unrollLoops( vertexShader );
  10341. fragmentShader = unrollLoops( fragmentShader );
  10342. }
  10343. var vertexGlsl = prefixVertex + vertexShader;
  10344. var fragmentGlsl = prefixFragment + fragmentShader;
  10345. // console.log( '*VERTEX*', vertexGlsl );
  10346. // console.log( '*FRAGMENT*', fragmentGlsl );
  10347. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10348. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10349. gl.attachShader( program, glVertexShader );
  10350. gl.attachShader( program, glFragmentShader );
  10351. // Force a particular attribute to index 0.
  10352. if ( material.index0AttributeName !== undefined ) {
  10353. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10354. } else if ( parameters.morphTargets === true ) {
  10355. // programs with morphTargets displace position out of attribute 0
  10356. gl.bindAttribLocation( program, 0, 'position' );
  10357. }
  10358. gl.linkProgram( program );
  10359. var programLog = gl.getProgramInfoLog( program );
  10360. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10361. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10362. var runnable = true;
  10363. var haveDiagnostics = true;
  10364. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10365. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10366. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10367. runnable = false;
  10368. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10369. } else if ( programLog !== '' ) {
  10370. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10371. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10372. haveDiagnostics = false;
  10373. }
  10374. if ( haveDiagnostics ) {
  10375. this.diagnostics = {
  10376. runnable: runnable,
  10377. material: material,
  10378. programLog: programLog,
  10379. vertexShader: {
  10380. log: vertexLog,
  10381. prefix: prefixVertex
  10382. },
  10383. fragmentShader: {
  10384. log: fragmentLog,
  10385. prefix: prefixFragment
  10386. }
  10387. };
  10388. }
  10389. // clean up
  10390. gl.deleteShader( glVertexShader );
  10391. gl.deleteShader( glFragmentShader );
  10392. // set up caching for uniform locations
  10393. var cachedUniforms;
  10394. this.getUniforms = function() {
  10395. if ( cachedUniforms === undefined ) {
  10396. cachedUniforms =
  10397. new WebGLUniforms( gl, program, renderer );
  10398. }
  10399. return cachedUniforms;
  10400. };
  10401. // set up caching for attribute locations
  10402. var cachedAttributes;
  10403. this.getAttributes = function() {
  10404. if ( cachedAttributes === undefined ) {
  10405. cachedAttributes = fetchAttributeLocations( gl, program );
  10406. }
  10407. return cachedAttributes;
  10408. };
  10409. // free resource
  10410. this.destroy = function() {
  10411. gl.deleteProgram( program );
  10412. this.program = undefined;
  10413. };
  10414. // DEPRECATED
  10415. Object.defineProperties( this, {
  10416. uniforms: {
  10417. get: function() {
  10418. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10419. return this.getUniforms();
  10420. }
  10421. },
  10422. attributes: {
  10423. get: function() {
  10424. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10425. return this.getAttributes();
  10426. }
  10427. }
  10428. } );
  10429. //
  10430. this.id = programIdCount ++;
  10431. this.code = code;
  10432. this.usedTimes = 1;
  10433. this.program = program;
  10434. this.vertexShader = glVertexShader;
  10435. this.fragmentShader = glFragmentShader;
  10436. return this;
  10437. }
  10438. /**
  10439. * @author mrdoob / http://mrdoob.com/
  10440. */
  10441. function WebGLPrograms( renderer, capabilities ) {
  10442. var programs = [];
  10443. var shaderIDs = {
  10444. MeshDepthMaterial: 'depth',
  10445. MeshNormalMaterial: 'normal',
  10446. MeshBasicMaterial: 'basic',
  10447. MeshLambertMaterial: 'lambert',
  10448. MeshPhongMaterial: 'phong',
  10449. MeshToonMaterial: 'phong',
  10450. MeshStandardMaterial: 'physical',
  10451. MeshPhysicalMaterial: 'physical',
  10452. LineBasicMaterial: 'basic',
  10453. LineDashedMaterial: 'dashed',
  10454. PointsMaterial: 'points'
  10455. };
  10456. var parameterNames = [
  10457. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10458. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10459. "roughnessMap", "metalnessMap", "gradientMap",
  10460. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10461. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10462. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10463. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10464. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10465. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10466. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10467. ];
  10468. function allocateBones( object ) {
  10469. var skeleton = object.skeleton;
  10470. var bones = skeleton.bones;
  10471. if ( capabilities.floatVertexTextures ) {
  10472. return 1024;
  10473. } else {
  10474. // default for when object is not specified
  10475. // ( for example when prebuilding shader to be used with multiple objects )
  10476. //
  10477. // - leave some extra space for other uniforms
  10478. // - limit here is ANGLE's 254 max uniform vectors
  10479. // (up to 54 should be safe)
  10480. var nVertexUniforms = capabilities.maxVertexUniforms;
  10481. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10482. var maxBones = Math.min( nVertexMatrices, bones.length );
  10483. if ( maxBones < bones.length ) {
  10484. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10485. return 0;
  10486. }
  10487. return maxBones;
  10488. }
  10489. }
  10490. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10491. var encoding;
  10492. if ( ! map ) {
  10493. encoding = LinearEncoding;
  10494. } else if ( map.isTexture ) {
  10495. encoding = map.encoding;
  10496. } else if ( map.isWebGLRenderTarget ) {
  10497. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10498. encoding = map.texture.encoding;
  10499. }
  10500. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10501. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10502. encoding = GammaEncoding;
  10503. }
  10504. return encoding;
  10505. }
  10506. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10507. var shaderID = shaderIDs[ material.type ];
  10508. // heuristics to create shader parameters according to lights in the scene
  10509. // (not to blow over maxLights budget)
  10510. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10511. var precision = renderer.getPrecision();
  10512. if ( material.precision !== null ) {
  10513. precision = capabilities.getMaxPrecision( material.precision );
  10514. if ( precision !== material.precision ) {
  10515. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10516. }
  10517. }
  10518. var currentRenderTarget = renderer.getRenderTarget();
  10519. var parameters = {
  10520. shaderID: shaderID,
  10521. precision: precision,
  10522. supportsVertexTextures: capabilities.vertexTextures,
  10523. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10524. map: !! material.map,
  10525. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10526. envMap: !! material.envMap,
  10527. envMapMode: material.envMap && material.envMap.mapping,
  10528. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10529. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10530. lightMap: !! material.lightMap,
  10531. aoMap: !! material.aoMap,
  10532. emissiveMap: !! material.emissiveMap,
  10533. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10534. bumpMap: !! material.bumpMap,
  10535. normalMap: !! material.normalMap,
  10536. displacementMap: !! material.displacementMap,
  10537. roughnessMap: !! material.roughnessMap,
  10538. metalnessMap: !! material.metalnessMap,
  10539. specularMap: !! material.specularMap,
  10540. alphaMap: !! material.alphaMap,
  10541. gradientMap: !! material.gradientMap,
  10542. combine: material.combine,
  10543. vertexColors: material.vertexColors,
  10544. fog: !! fog,
  10545. useFog: material.fog,
  10546. fogExp: ( fog && fog.isFogExp2 ),
  10547. flatShading: material.shading === FlatShading,
  10548. sizeAttenuation: material.sizeAttenuation,
  10549. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10550. skinning: material.skinning && maxBones > 0,
  10551. maxBones: maxBones,
  10552. useVertexTexture: capabilities.floatVertexTextures,
  10553. morphTargets: material.morphTargets,
  10554. morphNormals: material.morphNormals,
  10555. maxMorphTargets: renderer.maxMorphTargets,
  10556. maxMorphNormals: renderer.maxMorphNormals,
  10557. numDirLights: lights.directional.length,
  10558. numPointLights: lights.point.length,
  10559. numSpotLights: lights.spot.length,
  10560. numRectAreaLights: lights.rectArea.length,
  10561. numHemiLights: lights.hemi.length,
  10562. numClippingPlanes: nClipPlanes,
  10563. numClipIntersection: nClipIntersection,
  10564. dithering: material.dithering,
  10565. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10566. shadowMapType: renderer.shadowMap.type,
  10567. toneMapping: renderer.toneMapping,
  10568. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10569. premultipliedAlpha: material.premultipliedAlpha,
  10570. alphaTest: material.alphaTest,
  10571. doubleSided: material.side === DoubleSide,
  10572. flipSided: material.side === BackSide,
  10573. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10574. };
  10575. return parameters;
  10576. };
  10577. this.getProgramCode = function ( material, parameters ) {
  10578. var array = [];
  10579. if ( parameters.shaderID ) {
  10580. array.push( parameters.shaderID );
  10581. } else {
  10582. array.push( material.fragmentShader );
  10583. array.push( material.vertexShader );
  10584. }
  10585. if ( material.defines !== undefined ) {
  10586. for ( var name in material.defines ) {
  10587. array.push( name );
  10588. array.push( material.defines[ name ] );
  10589. }
  10590. }
  10591. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10592. array.push( parameters[ parameterNames[ i ] ] );
  10593. }
  10594. return array.join();
  10595. };
  10596. this.acquireProgram = function ( material, parameters, code ) {
  10597. var program;
  10598. // Check if code has been already compiled
  10599. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10600. var programInfo = programs[ p ];
  10601. if ( programInfo.code === code ) {
  10602. program = programInfo;
  10603. ++ program.usedTimes;
  10604. break;
  10605. }
  10606. }
  10607. if ( program === undefined ) {
  10608. program = new WebGLProgram( renderer, code, material, parameters );
  10609. programs.push( program );
  10610. }
  10611. return program;
  10612. };
  10613. this.releaseProgram = function ( program ) {
  10614. if ( -- program.usedTimes === 0 ) {
  10615. // Remove from unordered set
  10616. var i = programs.indexOf( program );
  10617. programs[ i ] = programs[ programs.length - 1 ];
  10618. programs.pop();
  10619. // Free WebGL resources
  10620. program.destroy();
  10621. }
  10622. };
  10623. // Exposed for resource monitoring & error feedback via renderer.info:
  10624. this.programs = programs;
  10625. }
  10626. /**
  10627. * @author mrdoob / http://mrdoob.com/
  10628. */
  10629. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) {
  10630. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10631. //
  10632. function clampToMaxSize( image, maxSize ) {
  10633. if ( image.width > maxSize || image.height > maxSize ) {
  10634. // Warning: Scaling through the canvas will only work with images that use
  10635. // premultiplied alpha.
  10636. var scale = maxSize / Math.max( image.width, image.height );
  10637. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10638. canvas.width = Math.floor( image.width * scale );
  10639. canvas.height = Math.floor( image.height * scale );
  10640. var context = canvas.getContext( '2d' );
  10641. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10642. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10643. return canvas;
  10644. }
  10645. return image;
  10646. }
  10647. function isPowerOfTwo( image ) {
  10648. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10649. }
  10650. function makePowerOfTwo( image ) {
  10651. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10652. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10653. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10654. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10655. var context = canvas.getContext( '2d' );
  10656. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10657. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10658. return canvas;
  10659. }
  10660. return image;
  10661. }
  10662. function textureNeedsPowerOfTwo( texture ) {
  10663. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10664. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10665. }
  10666. // Fallback filters for non-power-of-2 textures
  10667. function filterFallback( f ) {
  10668. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10669. return _gl.NEAREST;
  10670. }
  10671. return _gl.LINEAR;
  10672. }
  10673. //
  10674. function onTextureDispose( event ) {
  10675. var texture = event.target;
  10676. texture.removeEventListener( 'dispose', onTextureDispose );
  10677. deallocateTexture( texture );
  10678. infoMemory.textures --;
  10679. }
  10680. function onRenderTargetDispose( event ) {
  10681. var renderTarget = event.target;
  10682. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10683. deallocateRenderTarget( renderTarget );
  10684. infoMemory.textures --;
  10685. }
  10686. //
  10687. function deallocateTexture( texture ) {
  10688. var textureProperties = properties.get( texture );
  10689. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10690. // cube texture
  10691. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10692. } else {
  10693. // 2D texture
  10694. if ( textureProperties.__webglInit === undefined ) return;
  10695. _gl.deleteTexture( textureProperties.__webglTexture );
  10696. }
  10697. // remove all webgl properties
  10698. properties.remove( texture );
  10699. }
  10700. function deallocateRenderTarget( renderTarget ) {
  10701. var renderTargetProperties = properties.get( renderTarget );
  10702. var textureProperties = properties.get( renderTarget.texture );
  10703. if ( ! renderTarget ) return;
  10704. if ( textureProperties.__webglTexture !== undefined ) {
  10705. _gl.deleteTexture( textureProperties.__webglTexture );
  10706. }
  10707. if ( renderTarget.depthTexture ) {
  10708. renderTarget.depthTexture.dispose();
  10709. }
  10710. if ( renderTarget.isWebGLRenderTargetCube ) {
  10711. for ( var i = 0; i < 6; i ++ ) {
  10712. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10713. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10714. }
  10715. } else {
  10716. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10717. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10718. }
  10719. properties.remove( renderTarget.texture );
  10720. properties.remove( renderTarget );
  10721. }
  10722. //
  10723. function setTexture2D( texture, slot ) {
  10724. var textureProperties = properties.get( texture );
  10725. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10726. var image = texture.image;
  10727. if ( image === undefined ) {
  10728. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10729. } else if ( image.complete === false ) {
  10730. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10731. } else {
  10732. uploadTexture( textureProperties, texture, slot );
  10733. return;
  10734. }
  10735. }
  10736. state.activeTexture( _gl.TEXTURE0 + slot );
  10737. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10738. }
  10739. function setTextureCube( texture, slot ) {
  10740. var textureProperties = properties.get( texture );
  10741. if ( texture.image.length === 6 ) {
  10742. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10743. if ( ! textureProperties.__image__webglTextureCube ) {
  10744. texture.addEventListener( 'dispose', onTextureDispose );
  10745. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10746. infoMemory.textures ++;
  10747. }
  10748. state.activeTexture( _gl.TEXTURE0 + slot );
  10749. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10750. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10751. var isCompressed = ( texture && texture.isCompressedTexture );
  10752. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  10753. var cubeImage = [];
  10754. for ( var i = 0; i < 6; i ++ ) {
  10755. if ( ! isCompressed && ! isDataTexture ) {
  10756. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10757. } else {
  10758. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10759. }
  10760. }
  10761. var image = cubeImage[ 0 ],
  10762. isPowerOfTwoImage = isPowerOfTwo( image ),
  10763. glFormat = paramThreeToGL( texture.format ),
  10764. glType = paramThreeToGL( texture.type );
  10765. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10766. for ( var i = 0; i < 6; i ++ ) {
  10767. if ( ! isCompressed ) {
  10768. if ( isDataTexture ) {
  10769. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10770. } else {
  10771. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10772. }
  10773. } else {
  10774. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10775. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10776. mipmap = mipmaps[ j ];
  10777. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10778. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10779. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10780. } else {
  10781. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10782. }
  10783. } else {
  10784. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10785. }
  10786. }
  10787. }
  10788. }
  10789. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10790. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10791. }
  10792. textureProperties.__version = texture.version;
  10793. if ( texture.onUpdate ) texture.onUpdate( texture );
  10794. } else {
  10795. state.activeTexture( _gl.TEXTURE0 + slot );
  10796. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10797. }
  10798. }
  10799. }
  10800. function setTextureCubeDynamic( texture, slot ) {
  10801. state.activeTexture( _gl.TEXTURE0 + slot );
  10802. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10803. }
  10804. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10805. var extension;
  10806. if ( isPowerOfTwoImage ) {
  10807. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10808. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10809. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10810. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10811. } else {
  10812. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10813. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10814. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10815. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10816. }
  10817. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10818. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10819. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10820. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10821. }
  10822. }
  10823. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10824. if ( extension ) {
  10825. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10826. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10827. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10828. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10829. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10830. }
  10831. }
  10832. }
  10833. function uploadTexture( textureProperties, texture, slot ) {
  10834. if ( textureProperties.__webglInit === undefined ) {
  10835. textureProperties.__webglInit = true;
  10836. texture.addEventListener( 'dispose', onTextureDispose );
  10837. textureProperties.__webglTexture = _gl.createTexture();
  10838. infoMemory.textures ++;
  10839. }
  10840. state.activeTexture( _gl.TEXTURE0 + slot );
  10841. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10842. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10843. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10844. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10845. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10846. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10847. image = makePowerOfTwo( image );
  10848. }
  10849. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10850. glFormat = paramThreeToGL( texture.format ),
  10851. glType = paramThreeToGL( texture.type );
  10852. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10853. var mipmap, mipmaps = texture.mipmaps;
  10854. if ( texture.isDepthTexture ) {
  10855. // populate depth texture with dummy data
  10856. var internalFormat = _gl.DEPTH_COMPONENT;
  10857. if ( texture.type === FloatType ) {
  10858. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10859. internalFormat = _gl.DEPTH_COMPONENT32F;
  10860. } else if ( _isWebGL2 ) {
  10861. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10862. internalFormat = _gl.DEPTH_COMPONENT16;
  10863. }
  10864. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10865. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10866. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10867. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10868. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10869. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10870. texture.type = UnsignedShortType;
  10871. glType = paramThreeToGL( texture.type );
  10872. }
  10873. }
  10874. // Depth stencil textures need the DEPTH_STENCIL internal format
  10875. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10876. if ( texture.format === DepthStencilFormat ) {
  10877. internalFormat = _gl.DEPTH_STENCIL;
  10878. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10879. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10880. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10881. if ( texture.type !== UnsignedInt248Type ) {
  10882. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10883. texture.type = UnsignedInt248Type;
  10884. glType = paramThreeToGL( texture.type );
  10885. }
  10886. }
  10887. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10888. } else if ( texture.isDataTexture ) {
  10889. // use manually created mipmaps if available
  10890. // if there are no manual mipmaps
  10891. // set 0 level mipmap and then use GL to generate other mipmap levels
  10892. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10893. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10894. mipmap = mipmaps[ i ];
  10895. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10896. }
  10897. texture.generateMipmaps = false;
  10898. } else {
  10899. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10900. }
  10901. } else if ( texture.isCompressedTexture ) {
  10902. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10903. mipmap = mipmaps[ i ];
  10904. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10905. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10906. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10907. } else {
  10908. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10909. }
  10910. } else {
  10911. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10912. }
  10913. }
  10914. } else {
  10915. // regular Texture (image, video, canvas)
  10916. // use manually created mipmaps if available
  10917. // if there are no manual mipmaps
  10918. // set 0 level mipmap and then use GL to generate other mipmap levels
  10919. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10920. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10921. mipmap = mipmaps[ i ];
  10922. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10923. }
  10924. texture.generateMipmaps = false;
  10925. } else {
  10926. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10927. }
  10928. }
  10929. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10930. textureProperties.__version = texture.version;
  10931. if ( texture.onUpdate ) texture.onUpdate( texture );
  10932. }
  10933. // Render targets
  10934. // Setup storage for target texture and bind it to correct framebuffer
  10935. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10936. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10937. var glType = paramThreeToGL( renderTarget.texture.type );
  10938. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10939. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10940. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10941. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10942. }
  10943. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10944. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10945. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10946. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10947. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10948. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10949. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10950. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10951. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10952. } else {
  10953. // FIXME: We don't support !depth !stencil
  10954. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10955. }
  10956. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10957. }
  10958. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10959. function setupDepthTexture( framebuffer, renderTarget ) {
  10960. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10961. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10962. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10963. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10964. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10965. }
  10966. // upload an empty depth texture with framebuffer size
  10967. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10968. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10969. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10970. renderTarget.depthTexture.image.width = renderTarget.width;
  10971. renderTarget.depthTexture.image.height = renderTarget.height;
  10972. renderTarget.depthTexture.needsUpdate = true;
  10973. }
  10974. setTexture2D( renderTarget.depthTexture, 0 );
  10975. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10976. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10977. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10978. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10979. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10980. } else {
  10981. throw new Error('Unknown depthTexture format')
  10982. }
  10983. }
  10984. // Setup GL resources for a non-texture depth buffer
  10985. function setupDepthRenderbuffer( renderTarget ) {
  10986. var renderTargetProperties = properties.get( renderTarget );
  10987. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10988. if ( renderTarget.depthTexture ) {
  10989. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10990. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10991. } else {
  10992. if ( isCube ) {
  10993. renderTargetProperties.__webglDepthbuffer = [];
  10994. for ( var i = 0; i < 6; i ++ ) {
  10995. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10996. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10997. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10998. }
  10999. } else {
  11000. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11001. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11002. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11003. }
  11004. }
  11005. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11006. }
  11007. // Set up GL resources for the render target
  11008. function setupRenderTarget( renderTarget ) {
  11009. var renderTargetProperties = properties.get( renderTarget );
  11010. var textureProperties = properties.get( renderTarget.texture );
  11011. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11012. textureProperties.__webglTexture = _gl.createTexture();
  11013. infoMemory.textures ++;
  11014. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11015. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11016. // Setup framebuffer
  11017. if ( isCube ) {
  11018. renderTargetProperties.__webglFramebuffer = [];
  11019. for ( var i = 0; i < 6; i ++ ) {
  11020. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11021. }
  11022. } else {
  11023. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11024. }
  11025. // Setup color buffer
  11026. if ( isCube ) {
  11027. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11028. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11029. for ( var i = 0; i < 6; i ++ ) {
  11030. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11031. }
  11032. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11033. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11034. } else {
  11035. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11036. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11037. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11038. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11039. state.bindTexture( _gl.TEXTURE_2D, null );
  11040. }
  11041. // Setup depth and stencil buffers
  11042. if ( renderTarget.depthBuffer ) {
  11043. setupDepthRenderbuffer( renderTarget );
  11044. }
  11045. }
  11046. function updateRenderTargetMipmap( renderTarget ) {
  11047. var texture = renderTarget.texture;
  11048. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  11049. texture.minFilter !== NearestFilter &&
  11050. texture.minFilter !== LinearFilter ) {
  11051. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11052. var webglTexture = properties.get( texture ).__webglTexture;
  11053. state.bindTexture( target, webglTexture );
  11054. _gl.generateMipmap( target );
  11055. state.bindTexture( target, null );
  11056. }
  11057. }
  11058. this.setTexture2D = setTexture2D;
  11059. this.setTextureCube = setTextureCube;
  11060. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11061. this.setupRenderTarget = setupRenderTarget;
  11062. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11063. }
  11064. /**
  11065. * @author fordacious / fordacious.github.io
  11066. */
  11067. function WebGLProperties() {
  11068. var properties = {};
  11069. function get( object ) {
  11070. var uuid = object.uuid;
  11071. var map = properties[ uuid ];
  11072. if ( map === undefined ) {
  11073. map = {};
  11074. properties[ uuid ] = map;
  11075. }
  11076. return map;
  11077. }
  11078. function remove( object ) {
  11079. delete properties[ object.uuid ];
  11080. }
  11081. function clear() {
  11082. properties = {};
  11083. }
  11084. return {
  11085. get: get,
  11086. remove: remove,
  11087. clear: clear
  11088. };
  11089. }
  11090. /**
  11091. * @author mrdoob / http://mrdoob.com/
  11092. */
  11093. function WebGLState( gl, extensions, paramThreeToGL ) {
  11094. function ColorBuffer() {
  11095. var locked = false;
  11096. var color = new Vector4();
  11097. var currentColorMask = null;
  11098. var currentColorClear = new Vector4();
  11099. return {
  11100. setMask: function ( colorMask ) {
  11101. if ( currentColorMask !== colorMask && ! locked ) {
  11102. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11103. currentColorMask = colorMask;
  11104. }
  11105. },
  11106. setLocked: function ( lock ) {
  11107. locked = lock;
  11108. },
  11109. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11110. if ( premultipliedAlpha === true ) {
  11111. r *= a; g *= a; b *= a;
  11112. }
  11113. color.set( r, g, b, a );
  11114. if ( currentColorClear.equals( color ) === false ) {
  11115. gl.clearColor( r, g, b, a );
  11116. currentColorClear.copy( color );
  11117. }
  11118. },
  11119. reset: function () {
  11120. locked = false;
  11121. currentColorMask = null;
  11122. currentColorClear.set( 0, 0, 0, 1 );
  11123. }
  11124. };
  11125. }
  11126. function DepthBuffer() {
  11127. var locked = false;
  11128. var currentDepthMask = null;
  11129. var currentDepthFunc = null;
  11130. var currentDepthClear = null;
  11131. return {
  11132. setTest: function ( depthTest ) {
  11133. if ( depthTest ) {
  11134. enable( gl.DEPTH_TEST );
  11135. } else {
  11136. disable( gl.DEPTH_TEST );
  11137. }
  11138. },
  11139. setMask: function ( depthMask ) {
  11140. if ( currentDepthMask !== depthMask && ! locked ) {
  11141. gl.depthMask( depthMask );
  11142. currentDepthMask = depthMask;
  11143. }
  11144. },
  11145. setFunc: function ( depthFunc ) {
  11146. if ( currentDepthFunc !== depthFunc ) {
  11147. if ( depthFunc ) {
  11148. switch ( depthFunc ) {
  11149. case NeverDepth:
  11150. gl.depthFunc( gl.NEVER );
  11151. break;
  11152. case AlwaysDepth:
  11153. gl.depthFunc( gl.ALWAYS );
  11154. break;
  11155. case LessDepth:
  11156. gl.depthFunc( gl.LESS );
  11157. break;
  11158. case LessEqualDepth:
  11159. gl.depthFunc( gl.LEQUAL );
  11160. break;
  11161. case EqualDepth:
  11162. gl.depthFunc( gl.EQUAL );
  11163. break;
  11164. case GreaterEqualDepth:
  11165. gl.depthFunc( gl.GEQUAL );
  11166. break;
  11167. case GreaterDepth:
  11168. gl.depthFunc( gl.GREATER );
  11169. break;
  11170. case NotEqualDepth:
  11171. gl.depthFunc( gl.NOTEQUAL );
  11172. break;
  11173. default:
  11174. gl.depthFunc( gl.LEQUAL );
  11175. }
  11176. } else {
  11177. gl.depthFunc( gl.LEQUAL );
  11178. }
  11179. currentDepthFunc = depthFunc;
  11180. }
  11181. },
  11182. setLocked: function ( lock ) {
  11183. locked = lock;
  11184. },
  11185. setClear: function ( depth ) {
  11186. if ( currentDepthClear !== depth ) {
  11187. gl.clearDepth( depth );
  11188. currentDepthClear = depth;
  11189. }
  11190. },
  11191. reset: function () {
  11192. locked = false;
  11193. currentDepthMask = null;
  11194. currentDepthFunc = null;
  11195. currentDepthClear = null;
  11196. }
  11197. };
  11198. }
  11199. function StencilBuffer() {
  11200. var locked = false;
  11201. var currentStencilMask = null;
  11202. var currentStencilFunc = null;
  11203. var currentStencilRef = null;
  11204. var currentStencilFuncMask = null;
  11205. var currentStencilFail = null;
  11206. var currentStencilZFail = null;
  11207. var currentStencilZPass = null;
  11208. var currentStencilClear = null;
  11209. return {
  11210. setTest: function ( stencilTest ) {
  11211. if ( stencilTest ) {
  11212. enable( gl.STENCIL_TEST );
  11213. } else {
  11214. disable( gl.STENCIL_TEST );
  11215. }
  11216. },
  11217. setMask: function ( stencilMask ) {
  11218. if ( currentStencilMask !== stencilMask && ! locked ) {
  11219. gl.stencilMask( stencilMask );
  11220. currentStencilMask = stencilMask;
  11221. }
  11222. },
  11223. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11224. if ( currentStencilFunc !== stencilFunc ||
  11225. currentStencilRef !== stencilRef ||
  11226. currentStencilFuncMask !== stencilMask ) {
  11227. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11228. currentStencilFunc = stencilFunc;
  11229. currentStencilRef = stencilRef;
  11230. currentStencilFuncMask = stencilMask;
  11231. }
  11232. },
  11233. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11234. if ( currentStencilFail !== stencilFail ||
  11235. currentStencilZFail !== stencilZFail ||
  11236. currentStencilZPass !== stencilZPass ) {
  11237. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11238. currentStencilFail = stencilFail;
  11239. currentStencilZFail = stencilZFail;
  11240. currentStencilZPass = stencilZPass;
  11241. }
  11242. },
  11243. setLocked: function ( lock ) {
  11244. locked = lock;
  11245. },
  11246. setClear: function ( stencil ) {
  11247. if ( currentStencilClear !== stencil ) {
  11248. gl.clearStencil( stencil );
  11249. currentStencilClear = stencil;
  11250. }
  11251. },
  11252. reset: function () {
  11253. locked = false;
  11254. currentStencilMask = null;
  11255. currentStencilFunc = null;
  11256. currentStencilRef = null;
  11257. currentStencilFuncMask = null;
  11258. currentStencilFail = null;
  11259. currentStencilZFail = null;
  11260. currentStencilZPass = null;
  11261. currentStencilClear = null;
  11262. }
  11263. };
  11264. }
  11265. //
  11266. var colorBuffer = new ColorBuffer();
  11267. var depthBuffer = new DepthBuffer();
  11268. var stencilBuffer = new StencilBuffer();
  11269. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11270. var newAttributes = new Uint8Array( maxVertexAttributes );
  11271. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11272. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11273. var capabilities = {};
  11274. var compressedTextureFormats = null;
  11275. var currentBlending = null;
  11276. var currentBlendEquation = null;
  11277. var currentBlendSrc = null;
  11278. var currentBlendDst = null;
  11279. var currentBlendEquationAlpha = null;
  11280. var currentBlendSrcAlpha = null;
  11281. var currentBlendDstAlpha = null;
  11282. var currentPremultipledAlpha = false;
  11283. var currentFlipSided = null;
  11284. var currentCullFace = null;
  11285. var currentLineWidth = null;
  11286. var currentPolygonOffsetFactor = null;
  11287. var currentPolygonOffsetUnits = null;
  11288. var currentScissorTest = null;
  11289. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11290. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11291. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11292. var currentTextureSlot = null;
  11293. var currentBoundTextures = {};
  11294. var currentScissor = new Vector4();
  11295. var currentViewport = new Vector4();
  11296. function createTexture( type, target, count ) {
  11297. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11298. var texture = gl.createTexture();
  11299. gl.bindTexture( type, texture );
  11300. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11301. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11302. for ( var i = 0; i < count; i ++ ) {
  11303. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11304. }
  11305. return texture;
  11306. }
  11307. var emptyTextures = {};
  11308. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11309. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11310. //
  11311. function init() {
  11312. colorBuffer.setClear( 0, 0, 0, 1 );
  11313. depthBuffer.setClear( 1 );
  11314. stencilBuffer.setClear( 0 );
  11315. enable( gl.DEPTH_TEST );
  11316. depthBuffer.setFunc( LessEqualDepth );
  11317. setFlipSided( false );
  11318. setCullFace( CullFaceBack );
  11319. enable( gl.CULL_FACE );
  11320. enable( gl.BLEND );
  11321. setBlending( NormalBlending );
  11322. }
  11323. function initAttributes() {
  11324. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11325. newAttributes[ i ] = 0;
  11326. }
  11327. }
  11328. function enableAttribute( attribute ) {
  11329. newAttributes[ attribute ] = 1;
  11330. if ( enabledAttributes[ attribute ] === 0 ) {
  11331. gl.enableVertexAttribArray( attribute );
  11332. enabledAttributes[ attribute ] = 1;
  11333. }
  11334. if ( attributeDivisors[ attribute ] !== 0 ) {
  11335. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11336. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11337. attributeDivisors[ attribute ] = 0;
  11338. }
  11339. }
  11340. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11341. newAttributes[ attribute ] = 1;
  11342. if ( enabledAttributes[ attribute ] === 0 ) {
  11343. gl.enableVertexAttribArray( attribute );
  11344. enabledAttributes[ attribute ] = 1;
  11345. }
  11346. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11347. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11348. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11349. attributeDivisors[ attribute ] = meshPerAttribute;
  11350. }
  11351. }
  11352. function disableUnusedAttributes() {
  11353. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11354. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11355. gl.disableVertexAttribArray( i );
  11356. enabledAttributes[ i ] = 0;
  11357. }
  11358. }
  11359. }
  11360. function enable( id ) {
  11361. if ( capabilities[ id ] !== true ) {
  11362. gl.enable( id );
  11363. capabilities[ id ] = true;
  11364. }
  11365. }
  11366. function disable( id ) {
  11367. if ( capabilities[ id ] !== false ) {
  11368. gl.disable( id );
  11369. capabilities[ id ] = false;
  11370. }
  11371. }
  11372. function getCompressedTextureFormats() {
  11373. if ( compressedTextureFormats === null ) {
  11374. compressedTextureFormats = [];
  11375. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11376. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11377. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11378. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11379. for ( var i = 0; i < formats.length; i ++ ) {
  11380. compressedTextureFormats.push( formats[ i ] );
  11381. }
  11382. }
  11383. }
  11384. return compressedTextureFormats;
  11385. }
  11386. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11387. if ( blending !== NoBlending ) {
  11388. enable( gl.BLEND );
  11389. } else {
  11390. disable( gl.BLEND );
  11391. }
  11392. if ( ( blending !== CustomBlending ) && ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) ) {
  11393. if ( blending === AdditiveBlending ) {
  11394. if ( premultipliedAlpha ) {
  11395. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11396. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11397. } else {
  11398. gl.blendEquation( gl.FUNC_ADD );
  11399. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11400. }
  11401. } else if ( blending === SubtractiveBlending ) {
  11402. if ( premultipliedAlpha ) {
  11403. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11404. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11405. } else {
  11406. gl.blendEquation( gl.FUNC_ADD );
  11407. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11408. }
  11409. } else if ( blending === MultiplyBlending ) {
  11410. if ( premultipliedAlpha ) {
  11411. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11412. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11413. } else {
  11414. gl.blendEquation( gl.FUNC_ADD );
  11415. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11416. }
  11417. } else {
  11418. if ( premultipliedAlpha ) {
  11419. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11420. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11421. } else {
  11422. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11423. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11424. }
  11425. }
  11426. currentBlending = blending;
  11427. currentPremultipledAlpha = premultipliedAlpha;
  11428. }
  11429. if ( blending === CustomBlending ) {
  11430. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11431. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11432. blendDstAlpha = blendDstAlpha || blendDst;
  11433. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11434. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11435. currentBlendEquation = blendEquation;
  11436. currentBlendEquationAlpha = blendEquationAlpha;
  11437. }
  11438. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11439. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11440. currentBlendSrc = blendSrc;
  11441. currentBlendDst = blendDst;
  11442. currentBlendSrcAlpha = blendSrcAlpha;
  11443. currentBlendDstAlpha = blendDstAlpha;
  11444. }
  11445. } else {
  11446. currentBlendEquation = null;
  11447. currentBlendSrc = null;
  11448. currentBlendDst = null;
  11449. currentBlendEquationAlpha = null;
  11450. currentBlendSrcAlpha = null;
  11451. currentBlendDstAlpha = null;
  11452. }
  11453. }
  11454. function setMaterial( material ) {
  11455. material.side === DoubleSide
  11456. ? disable( gl.CULL_FACE )
  11457. : enable( gl.CULL_FACE );
  11458. setFlipSided( material.side === BackSide );
  11459. material.transparent === true
  11460. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11461. : setBlending( NoBlending );
  11462. depthBuffer.setFunc( material.depthFunc );
  11463. depthBuffer.setTest( material.depthTest );
  11464. depthBuffer.setMask( material.depthWrite );
  11465. colorBuffer.setMask( material.colorWrite );
  11466. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11467. }
  11468. //
  11469. function setFlipSided( flipSided ) {
  11470. if ( currentFlipSided !== flipSided ) {
  11471. if ( flipSided ) {
  11472. gl.frontFace( gl.CW );
  11473. } else {
  11474. gl.frontFace( gl.CCW );
  11475. }
  11476. currentFlipSided = flipSided;
  11477. }
  11478. }
  11479. function setCullFace( cullFace ) {
  11480. if ( cullFace !== CullFaceNone ) {
  11481. enable( gl.CULL_FACE );
  11482. if ( cullFace !== currentCullFace ) {
  11483. if ( cullFace === CullFaceBack ) {
  11484. gl.cullFace( gl.BACK );
  11485. } else if ( cullFace === CullFaceFront ) {
  11486. gl.cullFace( gl.FRONT );
  11487. } else {
  11488. gl.cullFace( gl.FRONT_AND_BACK );
  11489. }
  11490. }
  11491. } else {
  11492. disable( gl.CULL_FACE );
  11493. }
  11494. currentCullFace = cullFace;
  11495. }
  11496. function setLineWidth( width ) {
  11497. if ( width !== currentLineWidth ) {
  11498. if ( lineWidthAvailable ) gl.lineWidth( width );
  11499. currentLineWidth = width;
  11500. }
  11501. }
  11502. function setPolygonOffset( polygonOffset, factor, units ) {
  11503. if ( polygonOffset ) {
  11504. enable( gl.POLYGON_OFFSET_FILL );
  11505. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11506. gl.polygonOffset( factor, units );
  11507. currentPolygonOffsetFactor = factor;
  11508. currentPolygonOffsetUnits = units;
  11509. }
  11510. } else {
  11511. disable( gl.POLYGON_OFFSET_FILL );
  11512. }
  11513. }
  11514. function getScissorTest() {
  11515. return currentScissorTest;
  11516. }
  11517. function setScissorTest( scissorTest ) {
  11518. currentScissorTest = scissorTest;
  11519. if ( scissorTest ) {
  11520. enable( gl.SCISSOR_TEST );
  11521. } else {
  11522. disable( gl.SCISSOR_TEST );
  11523. }
  11524. }
  11525. // texture
  11526. function activeTexture( webglSlot ) {
  11527. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11528. if ( currentTextureSlot !== webglSlot ) {
  11529. gl.activeTexture( webglSlot );
  11530. currentTextureSlot = webglSlot;
  11531. }
  11532. }
  11533. function bindTexture( webglType, webglTexture ) {
  11534. if ( currentTextureSlot === null ) {
  11535. activeTexture();
  11536. }
  11537. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11538. if ( boundTexture === undefined ) {
  11539. boundTexture = { type: undefined, texture: undefined };
  11540. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11541. }
  11542. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11543. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11544. boundTexture.type = webglType;
  11545. boundTexture.texture = webglTexture;
  11546. }
  11547. }
  11548. function compressedTexImage2D() {
  11549. try {
  11550. gl.compressedTexImage2D.apply( gl, arguments );
  11551. } catch ( error ) {
  11552. console.error( error );
  11553. }
  11554. }
  11555. function texImage2D() {
  11556. try {
  11557. gl.texImage2D.apply( gl, arguments );
  11558. } catch ( error ) {
  11559. console.error( error );
  11560. }
  11561. }
  11562. //
  11563. function scissor( scissor ) {
  11564. if ( currentScissor.equals( scissor ) === false ) {
  11565. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11566. currentScissor.copy( scissor );
  11567. }
  11568. }
  11569. function viewport( viewport ) {
  11570. if ( currentViewport.equals( viewport ) === false ) {
  11571. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11572. currentViewport.copy( viewport );
  11573. }
  11574. }
  11575. //
  11576. function reset() {
  11577. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11578. if ( enabledAttributes[ i ] === 1 ) {
  11579. gl.disableVertexAttribArray( i );
  11580. enabledAttributes[ i ] = 0;
  11581. }
  11582. }
  11583. capabilities = {};
  11584. compressedTextureFormats = null;
  11585. currentTextureSlot = null;
  11586. currentBoundTextures = {};
  11587. currentBlending = null;
  11588. currentFlipSided = null;
  11589. currentCullFace = null;
  11590. colorBuffer.reset();
  11591. depthBuffer.reset();
  11592. stencilBuffer.reset();
  11593. }
  11594. return {
  11595. buffers: {
  11596. color: colorBuffer,
  11597. depth: depthBuffer,
  11598. stencil: stencilBuffer
  11599. },
  11600. init: init,
  11601. initAttributes: initAttributes,
  11602. enableAttribute: enableAttribute,
  11603. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11604. disableUnusedAttributes: disableUnusedAttributes,
  11605. enable: enable,
  11606. disable: disable,
  11607. getCompressedTextureFormats: getCompressedTextureFormats,
  11608. setBlending: setBlending,
  11609. setMaterial: setMaterial,
  11610. setFlipSided: setFlipSided,
  11611. setCullFace: setCullFace,
  11612. setLineWidth: setLineWidth,
  11613. setPolygonOffset: setPolygonOffset,
  11614. getScissorTest: getScissorTest,
  11615. setScissorTest: setScissorTest,
  11616. activeTexture: activeTexture,
  11617. bindTexture: bindTexture,
  11618. compressedTexImage2D: compressedTexImage2D,
  11619. texImage2D: texImage2D,
  11620. scissor: scissor,
  11621. viewport: viewport,
  11622. reset: reset
  11623. };
  11624. }
  11625. /**
  11626. * @author mrdoob / http://mrdoob.com/
  11627. */
  11628. function WebGLCapabilities( gl, extensions, parameters ) {
  11629. var maxAnisotropy;
  11630. function getMaxAnisotropy() {
  11631. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11632. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11633. if ( extension !== null ) {
  11634. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11635. } else {
  11636. maxAnisotropy = 0;
  11637. }
  11638. return maxAnisotropy;
  11639. }
  11640. function getMaxPrecision( precision ) {
  11641. if ( precision === 'highp' ) {
  11642. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11643. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11644. return 'highp';
  11645. }
  11646. precision = 'mediump';
  11647. }
  11648. if ( precision === 'mediump' ) {
  11649. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11650. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11651. return 'mediump';
  11652. }
  11653. }
  11654. return 'lowp';
  11655. }
  11656. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11657. var maxPrecision = getMaxPrecision( precision );
  11658. if ( maxPrecision !== precision ) {
  11659. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11660. precision = maxPrecision;
  11661. }
  11662. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11663. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11664. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11665. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11666. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11667. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11668. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11669. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11670. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11671. var vertexTextures = maxVertexTextures > 0;
  11672. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11673. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11674. return {
  11675. getMaxAnisotropy: getMaxAnisotropy,
  11676. getMaxPrecision: getMaxPrecision,
  11677. precision: precision,
  11678. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11679. maxTextures: maxTextures,
  11680. maxVertexTextures: maxVertexTextures,
  11681. maxTextureSize: maxTextureSize,
  11682. maxCubemapSize: maxCubemapSize,
  11683. maxAttributes: maxAttributes,
  11684. maxVertexUniforms: maxVertexUniforms,
  11685. maxVaryings: maxVaryings,
  11686. maxFragmentUniforms: maxFragmentUniforms,
  11687. vertexTextures: vertexTextures,
  11688. floatFragmentTextures: floatFragmentTextures,
  11689. floatVertexTextures: floatVertexTextures
  11690. };
  11691. }
  11692. /**
  11693. * @author mrdoob / http://mrdoob.com/
  11694. */
  11695. function WebGLExtensions( gl ) {
  11696. var extensions = {};
  11697. return {
  11698. get: function ( name ) {
  11699. if ( extensions[ name ] !== undefined ) {
  11700. return extensions[ name ];
  11701. }
  11702. var extension;
  11703. switch ( name ) {
  11704. case 'WEBGL_depth_texture':
  11705. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11706. break;
  11707. case 'EXT_texture_filter_anisotropic':
  11708. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11709. break;
  11710. case 'WEBGL_compressed_texture_s3tc':
  11711. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11712. break;
  11713. case 'WEBGL_compressed_texture_pvrtc':
  11714. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11715. break;
  11716. case 'WEBGL_compressed_texture_etc1':
  11717. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11718. break;
  11719. default:
  11720. extension = gl.getExtension( name );
  11721. }
  11722. if ( extension === null ) {
  11723. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11724. }
  11725. extensions[ name ] = extension;
  11726. return extension;
  11727. }
  11728. };
  11729. }
  11730. /**
  11731. * @author tschw
  11732. */
  11733. function WebGLClipping() {
  11734. var scope = this,
  11735. globalState = null,
  11736. numGlobalPlanes = 0,
  11737. localClippingEnabled = false,
  11738. renderingShadows = false,
  11739. plane = new Plane(),
  11740. viewNormalMatrix = new Matrix3(),
  11741. uniform = { value: null, needsUpdate: false };
  11742. this.uniform = uniform;
  11743. this.numPlanes = 0;
  11744. this.numIntersection = 0;
  11745. this.init = function( planes, enableLocalClipping, camera ) {
  11746. var enabled =
  11747. planes.length !== 0 ||
  11748. enableLocalClipping ||
  11749. // enable state of previous frame - the clipping code has to
  11750. // run another frame in order to reset the state:
  11751. numGlobalPlanes !== 0 ||
  11752. localClippingEnabled;
  11753. localClippingEnabled = enableLocalClipping;
  11754. globalState = projectPlanes( planes, camera, 0 );
  11755. numGlobalPlanes = planes.length;
  11756. return enabled;
  11757. };
  11758. this.beginShadows = function() {
  11759. renderingShadows = true;
  11760. projectPlanes( null );
  11761. };
  11762. this.endShadows = function() {
  11763. renderingShadows = false;
  11764. resetGlobalState();
  11765. };
  11766. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11767. if ( ! localClippingEnabled ||
  11768. planes === null || planes.length === 0 ||
  11769. renderingShadows && ! clipShadows ) {
  11770. // there's no local clipping
  11771. if ( renderingShadows ) {
  11772. // there's no global clipping
  11773. projectPlanes( null );
  11774. } else {
  11775. resetGlobalState();
  11776. }
  11777. } else {
  11778. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11779. lGlobal = nGlobal * 4,
  11780. dstArray = cache.clippingState || null;
  11781. uniform.value = dstArray; // ensure unique state
  11782. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11783. for ( var i = 0; i !== lGlobal; ++ i ) {
  11784. dstArray[ i ] = globalState[ i ];
  11785. }
  11786. cache.clippingState = dstArray;
  11787. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11788. this.numPlanes += nGlobal;
  11789. }
  11790. };
  11791. function resetGlobalState() {
  11792. if ( uniform.value !== globalState ) {
  11793. uniform.value = globalState;
  11794. uniform.needsUpdate = numGlobalPlanes > 0;
  11795. }
  11796. scope.numPlanes = numGlobalPlanes;
  11797. scope.numIntersection = 0;
  11798. }
  11799. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11800. var nPlanes = planes !== null ? planes.length : 0,
  11801. dstArray = null;
  11802. if ( nPlanes !== 0 ) {
  11803. dstArray = uniform.value;
  11804. if ( skipTransform !== true || dstArray === null ) {
  11805. var flatSize = dstOffset + nPlanes * 4,
  11806. viewMatrix = camera.matrixWorldInverse;
  11807. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11808. if ( dstArray === null || dstArray.length < flatSize ) {
  11809. dstArray = new Float32Array( flatSize );
  11810. }
  11811. for ( var i = 0, i4 = dstOffset;
  11812. i !== nPlanes; ++ i, i4 += 4 ) {
  11813. plane.copy( planes[ i ] ).
  11814. applyMatrix4( viewMatrix, viewNormalMatrix );
  11815. plane.normal.toArray( dstArray, i4 );
  11816. dstArray[ i4 + 3 ] = plane.constant;
  11817. }
  11818. }
  11819. uniform.value = dstArray;
  11820. uniform.needsUpdate = true;
  11821. }
  11822. scope.numPlanes = nPlanes;
  11823. return dstArray;
  11824. }
  11825. }
  11826. // import { Sphere } from '../math/Sphere';
  11827. /**
  11828. * @author supereggbert / http://www.paulbrunt.co.uk/
  11829. * @author mrdoob / http://mrdoob.com/
  11830. * @author alteredq / http://alteredqualia.com/
  11831. * @author szimek / https://github.com/szimek/
  11832. * @author tschw
  11833. */
  11834. function WebGLRenderer( parameters ) {
  11835. console.log( 'THREE.WebGLRenderer', REVISION );
  11836. parameters = parameters || {};
  11837. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11838. _context = parameters.context !== undefined ? parameters.context : null,
  11839. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11840. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11841. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11842. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11843. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11844. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11845. var lights = [];
  11846. var currentRenderList = null;
  11847. var morphInfluences = new Float32Array( 8 );
  11848. var sprites = [];
  11849. var lensFlares = [];
  11850. // public properties
  11851. this.domElement = _canvas;
  11852. this.context = null;
  11853. // clearing
  11854. this.autoClear = true;
  11855. this.autoClearColor = true;
  11856. this.autoClearDepth = true;
  11857. this.autoClearStencil = true;
  11858. // scene graph
  11859. this.sortObjects = true;
  11860. // user-defined clipping
  11861. this.clippingPlanes = [];
  11862. this.localClippingEnabled = false;
  11863. // physically based shading
  11864. this.gammaFactor = 2.0; // for backwards compatibility
  11865. this.gammaInput = false;
  11866. this.gammaOutput = false;
  11867. // physical lights
  11868. this.physicallyCorrectLights = false;
  11869. // tone mapping
  11870. this.toneMapping = LinearToneMapping;
  11871. this.toneMappingExposure = 1.0;
  11872. this.toneMappingWhitePoint = 1.0;
  11873. // morphs
  11874. this.maxMorphTargets = 8;
  11875. this.maxMorphNormals = 4;
  11876. // internal properties
  11877. var _this = this,
  11878. // internal state cache
  11879. _currentProgram = null,
  11880. _currentRenderTarget = null,
  11881. _currentFramebuffer = null,
  11882. _currentMaterialId = - 1,
  11883. _currentGeometryProgram = '',
  11884. _currentCamera = null,
  11885. _currentScissor = new Vector4(),
  11886. _currentScissorTest = null,
  11887. _currentViewport = new Vector4(),
  11888. //
  11889. _usedTextureUnits = 0,
  11890. //
  11891. _clearColor = new Color( 0x000000 ),
  11892. _clearAlpha = 0,
  11893. _width = _canvas.width,
  11894. _height = _canvas.height,
  11895. _pixelRatio = 1,
  11896. _scissor = new Vector4( 0, 0, _width, _height ),
  11897. _scissorTest = false,
  11898. _viewport = new Vector4( 0, 0, _width, _height ),
  11899. // frustum
  11900. _frustum = new Frustum(),
  11901. // clipping
  11902. _clipping = new WebGLClipping(),
  11903. _clippingEnabled = false,
  11904. _localClippingEnabled = false,
  11905. // camera matrices cache
  11906. _projScreenMatrix = new Matrix4(),
  11907. _vector3 = new Vector3(),
  11908. _matrix4 = new Matrix4(),
  11909. _matrix42 = new Matrix4(),
  11910. // light arrays cache
  11911. _lights = {
  11912. hash: '',
  11913. ambient: [ 0, 0, 0 ],
  11914. directional: [],
  11915. directionalShadowMap: [],
  11916. directionalShadowMatrix: [],
  11917. spot: [],
  11918. spotShadowMap: [],
  11919. spotShadowMatrix: [],
  11920. rectArea: [],
  11921. point: [],
  11922. pointShadowMap: [],
  11923. pointShadowMatrix: [],
  11924. hemi: [],
  11925. shadows: []
  11926. },
  11927. // info
  11928. _infoMemory = {
  11929. geometries: 0,
  11930. textures: 0
  11931. },
  11932. _infoRender = {
  11933. frame: 0,
  11934. calls: 0,
  11935. vertices: 0,
  11936. faces: 0,
  11937. points: 0
  11938. };
  11939. this.info = {
  11940. render: _infoRender,
  11941. memory: _infoMemory,
  11942. programs: null
  11943. };
  11944. // initialize
  11945. var _gl;
  11946. try {
  11947. var contextAttributes = {
  11948. alpha: _alpha,
  11949. depth: _depth,
  11950. stencil: _stencil,
  11951. antialias: _antialias,
  11952. premultipliedAlpha: _premultipliedAlpha,
  11953. preserveDrawingBuffer: _preserveDrawingBuffer
  11954. };
  11955. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  11956. if ( _gl === null ) {
  11957. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11958. throw 'Error creating WebGL context with your selected attributes.';
  11959. } else {
  11960. throw 'Error creating WebGL context.';
  11961. }
  11962. }
  11963. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11964. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11965. _gl.getShaderPrecisionFormat = function () {
  11966. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11967. };
  11968. }
  11969. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11970. } catch ( error ) {
  11971. console.error( 'THREE.WebGLRenderer: ' + error );
  11972. }
  11973. var extensions = new WebGLExtensions( _gl );
  11974. extensions.get( 'WEBGL_depth_texture' );
  11975. extensions.get( 'OES_texture_float' );
  11976. extensions.get( 'OES_texture_float_linear' );
  11977. extensions.get( 'OES_texture_half_float' );
  11978. extensions.get( 'OES_texture_half_float_linear' );
  11979. extensions.get( 'OES_standard_derivatives' );
  11980. extensions.get( 'ANGLE_instanced_arrays' );
  11981. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11982. BufferGeometry.MaxIndex = 4294967296;
  11983. }
  11984. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11985. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11986. var properties = new WebGLProperties();
  11987. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory );
  11988. var attributes = new WebGLAttributes( _gl );
  11989. var geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  11990. var objects = new WebGLObjects( _gl, geometries, _infoRender );
  11991. var programCache = new WebGLPrograms( this, capabilities );
  11992. var lightCache = new WebGLLights();
  11993. var renderLists = new WebGLRenderLists();
  11994. this.info.programs = programCache.programs;
  11995. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11996. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11997. //
  11998. var backgroundPlaneCamera, backgroundPlaneMesh;
  11999. var backgroundBoxCamera, backgroundBoxMesh;
  12000. //
  12001. function getTargetPixelRatio() {
  12002. return _currentRenderTarget === null ? _pixelRatio : 1;
  12003. }
  12004. function setDefaultGLState() {
  12005. state.init();
  12006. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12007. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12008. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12009. }
  12010. function resetGLState() {
  12011. _currentProgram = null;
  12012. _currentCamera = null;
  12013. _currentGeometryProgram = '';
  12014. _currentMaterialId = - 1;
  12015. state.reset();
  12016. }
  12017. setDefaultGLState();
  12018. this.context = _gl;
  12019. this.capabilities = capabilities;
  12020. this.extensions = extensions;
  12021. this.properties = properties;
  12022. this.state = state;
  12023. // shadow map
  12024. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  12025. this.shadowMap = shadowMap;
  12026. // Plugins
  12027. var spritePlugin = new SpritePlugin( this, sprites );
  12028. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  12029. // API
  12030. this.getContext = function () {
  12031. return _gl;
  12032. };
  12033. this.getContextAttributes = function () {
  12034. return _gl.getContextAttributes();
  12035. };
  12036. this.forceContextLoss = function () {
  12037. var extension = extensions.get( 'WEBGL_lose_context' );
  12038. if ( extension ) extension.loseContext();
  12039. };
  12040. this.getMaxAnisotropy = function () {
  12041. return capabilities.getMaxAnisotropy();
  12042. };
  12043. this.getPrecision = function () {
  12044. return capabilities.precision;
  12045. };
  12046. this.getPixelRatio = function () {
  12047. return _pixelRatio;
  12048. };
  12049. this.setPixelRatio = function ( value ) {
  12050. if ( value === undefined ) return;
  12051. _pixelRatio = value;
  12052. this.setSize( _viewport.z, _viewport.w, false );
  12053. };
  12054. this.getSize = function () {
  12055. return {
  12056. width: _width,
  12057. height: _height
  12058. };
  12059. };
  12060. this.setSize = function ( width, height, updateStyle ) {
  12061. _width = width;
  12062. _height = height;
  12063. _canvas.width = width * _pixelRatio;
  12064. _canvas.height = height * _pixelRatio;
  12065. if ( updateStyle !== false ) {
  12066. _canvas.style.width = width + 'px';
  12067. _canvas.style.height = height + 'px';
  12068. }
  12069. this.setViewport( 0, 0, width, height );
  12070. };
  12071. this.setViewport = function ( x, y, width, height ) {
  12072. state.viewport( _viewport.set( x, y, width, height ) );
  12073. };
  12074. this.setScissor = function ( x, y, width, height ) {
  12075. state.scissor( _scissor.set( x, y, width, height ) );
  12076. };
  12077. this.setScissorTest = function ( boolean ) {
  12078. state.setScissorTest( _scissorTest = boolean );
  12079. };
  12080. // Clearing
  12081. this.getClearColor = function () {
  12082. return _clearColor;
  12083. };
  12084. this.setClearColor = function ( color, alpha ) {
  12085. _clearColor.set( color );
  12086. _clearAlpha = alpha !== undefined ? alpha : 1;
  12087. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12088. };
  12089. this.getClearAlpha = function () {
  12090. return _clearAlpha;
  12091. };
  12092. this.setClearAlpha = function ( alpha ) {
  12093. _clearAlpha = alpha;
  12094. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12095. };
  12096. this.clear = function ( color, depth, stencil ) {
  12097. var bits = 0;
  12098. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12099. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12100. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12101. _gl.clear( bits );
  12102. };
  12103. this.clearColor = function () {
  12104. this.clear( true, false, false );
  12105. };
  12106. this.clearDepth = function () {
  12107. this.clear( false, true, false );
  12108. };
  12109. this.clearStencil = function () {
  12110. this.clear( false, false, true );
  12111. };
  12112. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12113. this.setRenderTarget( renderTarget );
  12114. this.clear( color, depth, stencil );
  12115. };
  12116. // Reset
  12117. this.resetGLState = resetGLState;
  12118. this.dispose = function () {
  12119. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12120. renderLists.dispose();
  12121. };
  12122. // Events
  12123. function onContextLost( event ) {
  12124. event.preventDefault();
  12125. resetGLState();
  12126. setDefaultGLState();
  12127. properties.clear();
  12128. objects.clear();
  12129. }
  12130. function onMaterialDispose( event ) {
  12131. var material = event.target;
  12132. material.removeEventListener( 'dispose', onMaterialDispose );
  12133. deallocateMaterial( material );
  12134. }
  12135. // Buffer deallocation
  12136. function deallocateMaterial( material ) {
  12137. releaseMaterialProgramReference( material );
  12138. properties.remove( material );
  12139. }
  12140. function releaseMaterialProgramReference( material ) {
  12141. var programInfo = properties.get( material ).program;
  12142. material.program = undefined;
  12143. if ( programInfo !== undefined ) {
  12144. programCache.releaseProgram( programInfo );
  12145. }
  12146. }
  12147. // Buffer rendering
  12148. function renderObjectImmediate( object, program, material ) {
  12149. object.render( function ( object ) {
  12150. _this.renderBufferImmediate( object, program, material );
  12151. } );
  12152. }
  12153. this.renderBufferImmediate = function ( object, program, material ) {
  12154. state.initAttributes();
  12155. var buffers = properties.get( object );
  12156. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12157. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12158. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12159. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12160. var programAttributes = program.getAttributes();
  12161. if ( object.hasPositions ) {
  12162. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12163. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12164. state.enableAttribute( programAttributes.position );
  12165. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12166. }
  12167. if ( object.hasNormals ) {
  12168. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12169. if ( ! material.isMeshPhongMaterial &&
  12170. ! material.isMeshStandardMaterial &&
  12171. ! material.isMeshNormalMaterial &&
  12172. material.shading === FlatShading ) {
  12173. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12174. var array = object.normalArray;
  12175. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12176. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12177. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12178. array[ i + 0 ] = nx;
  12179. array[ i + 1 ] = ny;
  12180. array[ i + 2 ] = nz;
  12181. array[ i + 3 ] = nx;
  12182. array[ i + 4 ] = ny;
  12183. array[ i + 5 ] = nz;
  12184. array[ i + 6 ] = nx;
  12185. array[ i + 7 ] = ny;
  12186. array[ i + 8 ] = nz;
  12187. }
  12188. }
  12189. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12190. state.enableAttribute( programAttributes.normal );
  12191. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12192. }
  12193. if ( object.hasUvs && material.map ) {
  12194. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12195. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12196. state.enableAttribute( programAttributes.uv );
  12197. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12198. }
  12199. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12200. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12201. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12202. state.enableAttribute( programAttributes.color );
  12203. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12204. }
  12205. state.disableUnusedAttributes();
  12206. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12207. object.count = 0;
  12208. };
  12209. function absNumericalSort( a, b ) {
  12210. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12211. }
  12212. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12213. state.setMaterial( material );
  12214. var program = setProgram( camera, fog, material, object );
  12215. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12216. var updateBuffers = false;
  12217. if ( geometryProgram !== _currentGeometryProgram ) {
  12218. _currentGeometryProgram = geometryProgram;
  12219. updateBuffers = true;
  12220. }
  12221. // morph targets
  12222. var morphTargetInfluences = object.morphTargetInfluences;
  12223. if ( morphTargetInfluences !== undefined ) {
  12224. // TODO Remove allocations
  12225. var activeInfluences = [];
  12226. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12227. var influence = morphTargetInfluences[ i ];
  12228. activeInfluences.push( [ influence, i ] );
  12229. }
  12230. activeInfluences.sort( absNumericalSort );
  12231. if ( activeInfluences.length > 8 ) {
  12232. activeInfluences.length = 8;
  12233. }
  12234. var morphAttributes = geometry.morphAttributes;
  12235. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12236. var influence = activeInfluences[ i ];
  12237. morphInfluences[ i ] = influence[ 0 ];
  12238. if ( influence[ 0 ] !== 0 ) {
  12239. var index = influence[ 1 ];
  12240. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12241. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12242. } else {
  12243. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12244. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12245. }
  12246. }
  12247. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12248. morphInfluences[ i ] = 0.0;
  12249. }
  12250. program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences );
  12251. updateBuffers = true;
  12252. }
  12253. //
  12254. var index = geometry.index;
  12255. var position = geometry.attributes.position;
  12256. var rangeFactor = 1;
  12257. if ( material.wireframe === true ) {
  12258. index = geometries.getWireframeAttribute( geometry );
  12259. rangeFactor = 2;
  12260. }
  12261. var renderer = bufferRenderer;
  12262. if ( index !== null ) {
  12263. renderer = indexedBufferRenderer;
  12264. renderer.setIndex( index );
  12265. }
  12266. if ( updateBuffers ) {
  12267. setupVertexAttributes( material, program, geometry );
  12268. if ( index !== null ) {
  12269. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  12270. }
  12271. }
  12272. //
  12273. var dataCount = 0;
  12274. if ( index !== null ) {
  12275. dataCount = index.count;
  12276. } else if ( position !== undefined ) {
  12277. dataCount = position.count;
  12278. }
  12279. var rangeStart = geometry.drawRange.start * rangeFactor;
  12280. var rangeCount = geometry.drawRange.count * rangeFactor;
  12281. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12282. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12283. var drawStart = Math.max( rangeStart, groupStart );
  12284. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12285. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12286. if ( drawCount === 0 ) return;
  12287. //
  12288. if ( object.isMesh ) {
  12289. if ( material.wireframe === true ) {
  12290. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12291. renderer.setMode( _gl.LINES );
  12292. } else {
  12293. switch ( object.drawMode ) {
  12294. case TrianglesDrawMode:
  12295. renderer.setMode( _gl.TRIANGLES );
  12296. break;
  12297. case TriangleStripDrawMode:
  12298. renderer.setMode( _gl.TRIANGLE_STRIP );
  12299. break;
  12300. case TriangleFanDrawMode:
  12301. renderer.setMode( _gl.TRIANGLE_FAN );
  12302. break;
  12303. }
  12304. }
  12305. } else if ( object.isLine ) {
  12306. var lineWidth = material.linewidth;
  12307. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12308. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12309. if ( object.isLineSegments ) {
  12310. renderer.setMode( _gl.LINES );
  12311. } else if ( object.isLineLoop ) {
  12312. renderer.setMode( _gl.LINE_LOOP );
  12313. } else {
  12314. renderer.setMode( _gl.LINE_STRIP );
  12315. }
  12316. } else if ( object.isPoints ) {
  12317. renderer.setMode( _gl.POINTS );
  12318. }
  12319. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12320. if ( geometry.maxInstancedCount > 0 ) {
  12321. renderer.renderInstances( geometry, drawStart, drawCount );
  12322. }
  12323. } else {
  12324. renderer.render( drawStart, drawCount );
  12325. }
  12326. };
  12327. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12328. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12329. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12330. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12331. return;
  12332. }
  12333. }
  12334. if ( startIndex === undefined ) startIndex = 0;
  12335. state.initAttributes();
  12336. var geometryAttributes = geometry.attributes;
  12337. var programAttributes = program.getAttributes();
  12338. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12339. for ( var name in programAttributes ) {
  12340. var programAttribute = programAttributes[ name ];
  12341. if ( programAttribute >= 0 ) {
  12342. var geometryAttribute = geometryAttributes[ name ];
  12343. if ( geometryAttribute !== undefined ) {
  12344. var normalized = geometryAttribute.normalized;
  12345. var size = geometryAttribute.itemSize;
  12346. var attributeProperties = attributes.get( geometryAttribute );
  12347. var buffer = attributeProperties.buffer;
  12348. var type = attributeProperties.type;
  12349. var bytesPerElement = attributeProperties.bytesPerElement;
  12350. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12351. var data = geometryAttribute.data;
  12352. var stride = data.stride;
  12353. var offset = geometryAttribute.offset;
  12354. if ( data && data.isInstancedInterleavedBuffer ) {
  12355. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12356. if ( geometry.maxInstancedCount === undefined ) {
  12357. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12358. }
  12359. } else {
  12360. state.enableAttribute( programAttribute );
  12361. }
  12362. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12363. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12364. } else {
  12365. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12366. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12367. if ( geometry.maxInstancedCount === undefined ) {
  12368. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12369. }
  12370. } else {
  12371. state.enableAttribute( programAttribute );
  12372. }
  12373. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12374. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12375. }
  12376. } else if ( materialDefaultAttributeValues !== undefined ) {
  12377. var value = materialDefaultAttributeValues[ name ];
  12378. if ( value !== undefined ) {
  12379. switch ( value.length ) {
  12380. case 2:
  12381. _gl.vertexAttrib2fv( programAttribute, value );
  12382. break;
  12383. case 3:
  12384. _gl.vertexAttrib3fv( programAttribute, value );
  12385. break;
  12386. case 4:
  12387. _gl.vertexAttrib4fv( programAttribute, value );
  12388. break;
  12389. default:
  12390. _gl.vertexAttrib1fv( programAttribute, value );
  12391. }
  12392. }
  12393. }
  12394. }
  12395. }
  12396. state.disableUnusedAttributes();
  12397. }
  12398. // Compile
  12399. this.compile = function ( scene, camera ) {
  12400. lights = [];
  12401. scene.traverse( function ( object ) {
  12402. if ( object.isLight ) {
  12403. lights.push( object );
  12404. }
  12405. } );
  12406. setupLights( lights, camera );
  12407. scene.traverse( function ( object ) {
  12408. if ( object.material ) {
  12409. if ( Array.isArray( object.material ) ) {
  12410. for ( var i = 0; i < object.material.length; i ++ ) {
  12411. initMaterial( object.material[ i ], scene.fog, object );
  12412. }
  12413. } else {
  12414. initMaterial( object.material, scene.fog, object );
  12415. }
  12416. }
  12417. } );
  12418. };
  12419. // Rendering
  12420. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12421. if ( camera !== undefined && camera.isCamera !== true ) {
  12422. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12423. return;
  12424. }
  12425. // reset caching for this frame
  12426. _currentGeometryProgram = '';
  12427. _currentMaterialId = - 1;
  12428. _currentCamera = null;
  12429. // update scene graph
  12430. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12431. // update camera matrices and frustum
  12432. camera.onBeforeRender( _this );
  12433. if ( camera.parent === null ) camera.updateMatrixWorld();
  12434. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12435. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12436. _frustum.setFromMatrix( _projScreenMatrix );
  12437. lights.length = 0;
  12438. sprites.length = 0;
  12439. lensFlares.length = 0;
  12440. _localClippingEnabled = this.localClippingEnabled;
  12441. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12442. currentRenderList = renderLists.get( scene, camera );
  12443. currentRenderList.init();
  12444. projectObject( scene, camera, _this.sortObjects );
  12445. currentRenderList.finish();
  12446. if ( _this.sortObjects === true ) {
  12447. currentRenderList.sort();
  12448. }
  12449. //
  12450. if ( _clippingEnabled ) _clipping.beginShadows();
  12451. setupShadows( lights );
  12452. shadowMap.render( scene, camera );
  12453. setupLights( lights, camera );
  12454. if ( _clippingEnabled ) _clipping.endShadows();
  12455. //
  12456. _infoRender.frame ++;
  12457. _infoRender.calls = 0;
  12458. _infoRender.vertices = 0;
  12459. _infoRender.faces = 0;
  12460. _infoRender.points = 0;
  12461. if ( renderTarget === undefined ) {
  12462. renderTarget = null;
  12463. }
  12464. this.setRenderTarget( renderTarget );
  12465. //
  12466. var background = scene.background;
  12467. if ( background === null ) {
  12468. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12469. } else if ( background && background.isColor ) {
  12470. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12471. forceClear = true;
  12472. }
  12473. if ( this.autoClear || forceClear ) {
  12474. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12475. }
  12476. if ( background && background.isCubeTexture ) {
  12477. if ( backgroundBoxCamera === undefined ) {
  12478. backgroundBoxCamera = new PerspectiveCamera();
  12479. backgroundBoxMesh = new Mesh(
  12480. new BoxBufferGeometry( 5, 5, 5 ),
  12481. new ShaderMaterial( {
  12482. uniforms: ShaderLib.cube.uniforms,
  12483. vertexShader: ShaderLib.cube.vertexShader,
  12484. fragmentShader: ShaderLib.cube.fragmentShader,
  12485. side: BackSide,
  12486. depthTest: false,
  12487. depthWrite: false,
  12488. fog: false
  12489. } )
  12490. );
  12491. }
  12492. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  12493. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  12494. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  12495. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12496. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12497. objects.update( backgroundBoxMesh );
  12498. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12499. } else if ( background && background.isTexture ) {
  12500. if ( backgroundPlaneCamera === undefined ) {
  12501. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12502. backgroundPlaneMesh = new Mesh(
  12503. new PlaneBufferGeometry( 2, 2 ),
  12504. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  12505. );
  12506. }
  12507. backgroundPlaneMesh.material.map = background;
  12508. objects.update( backgroundPlaneMesh );
  12509. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12510. }
  12511. //
  12512. var opaqueObjects = currentRenderList.opaque;
  12513. var transparentObjects = currentRenderList.transparent;
  12514. if ( scene.overrideMaterial ) {
  12515. var overrideMaterial = scene.overrideMaterial;
  12516. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12517. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12518. } else {
  12519. // opaque pass (front-to-back order)
  12520. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  12521. // transparent pass (back-to-front order)
  12522. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  12523. }
  12524. // custom render plugins (post pass)
  12525. spritePlugin.render( scene, camera );
  12526. lensFlarePlugin.render( scene, camera, _currentViewport );
  12527. // Generate mipmap if we're using any kind of mipmap filtering
  12528. if ( renderTarget ) {
  12529. textures.updateRenderTargetMipmap( renderTarget );
  12530. }
  12531. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12532. state.buffers.depth.setTest( true );
  12533. state.buffers.depth.setMask( true );
  12534. state.buffers.color.setMask( true );
  12535. if ( camera.isArrayCamera && camera.enabled ) {
  12536. _this.setScissorTest( false );
  12537. }
  12538. camera.onAfterRender( _this );
  12539. // _gl.finish();
  12540. };
  12541. /*
  12542. // TODO Duplicated code (Frustum)
  12543. var _sphere = new Sphere();
  12544. function isObjectViewable( object ) {
  12545. var geometry = object.geometry;
  12546. if ( geometry.boundingSphere === null )
  12547. geometry.computeBoundingSphere();
  12548. _sphere.copy( geometry.boundingSphere ).
  12549. applyMatrix4( object.matrixWorld );
  12550. return isSphereViewable( _sphere );
  12551. }
  12552. function isSpriteViewable( sprite ) {
  12553. _sphere.center.set( 0, 0, 0 );
  12554. _sphere.radius = 0.7071067811865476;
  12555. _sphere.applyMatrix4( sprite.matrixWorld );
  12556. return isSphereViewable( _sphere );
  12557. }
  12558. function isSphereViewable( sphere ) {
  12559. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12560. var numPlanes = _clipping.numPlanes;
  12561. if ( numPlanes === 0 ) return true;
  12562. var planes = _this.clippingPlanes,
  12563. center = sphere.center,
  12564. negRad = - sphere.radius,
  12565. i = 0;
  12566. do {
  12567. // out when deeper than radius in the negative halfspace
  12568. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12569. } while ( ++ i !== numPlanes );
  12570. return true;
  12571. }
  12572. */
  12573. function projectObject( object, camera, sortObjects ) {
  12574. if ( ! object.visible ) return;
  12575. var visible = object.layers.test( camera.layers );
  12576. if ( visible ) {
  12577. if ( object.isLight ) {
  12578. lights.push( object );
  12579. } else if ( object.isSprite ) {
  12580. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  12581. sprites.push( object );
  12582. }
  12583. } else if ( object.isLensFlare ) {
  12584. lensFlares.push( object );
  12585. } else if ( object.isImmediateRenderObject ) {
  12586. if ( sortObjects ) {
  12587. _vector3.setFromMatrixPosition( object.matrixWorld )
  12588. .applyMatrix4( _projScreenMatrix );
  12589. }
  12590. currentRenderList.push( object, null, object.material, _vector3.z, null );
  12591. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12592. if ( object.isSkinnedMesh ) {
  12593. object.skeleton.update();
  12594. }
  12595. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  12596. if ( sortObjects ) {
  12597. _vector3.setFromMatrixPosition( object.matrixWorld )
  12598. .applyMatrix4( _projScreenMatrix );
  12599. }
  12600. var geometry = objects.update( object );
  12601. var material = object.material;
  12602. if ( Array.isArray( material ) ) {
  12603. var groups = geometry.groups;
  12604. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12605. var group = groups[ i ];
  12606. var groupMaterial = material[ group.materialIndex ];
  12607. if ( groupMaterial && groupMaterial.visible ) {
  12608. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  12609. }
  12610. }
  12611. } else if ( material.visible ) {
  12612. currentRenderList.push( object, geometry, material, _vector3.z, null );
  12613. }
  12614. }
  12615. }
  12616. }
  12617. var children = object.children;
  12618. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12619. projectObject( children[ i ], camera, sortObjects );
  12620. }
  12621. }
  12622. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12623. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12624. var renderItem = renderList[ i ];
  12625. var object = renderItem.object;
  12626. var geometry = renderItem.geometry;
  12627. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12628. var group = renderItem.group;
  12629. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12630. if ( camera.isArrayCamera && camera.enabled ) {
  12631. var cameras = camera.cameras;
  12632. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  12633. var camera2 = cameras[ j ];
  12634. var bounds = camera2.bounds;
  12635. _this.setViewport(
  12636. bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
  12637. bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
  12638. );
  12639. _this.setScissor(
  12640. bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
  12641. bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
  12642. );
  12643. _this.setScissorTest( true );
  12644. renderObject( object, scene, camera2, geometry, material, group );
  12645. }
  12646. } else {
  12647. renderObject( object, scene, camera, geometry, material, group );
  12648. }
  12649. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12650. }
  12651. }
  12652. function renderObject( object, scene, camera, geometry, material, group ) {
  12653. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12654. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12655. if ( object.isImmediateRenderObject ) {
  12656. state.setMaterial( material );
  12657. var program = setProgram( camera, scene.fog, material, object );
  12658. _currentGeometryProgram = '';
  12659. renderObjectImmediate( object, program, material );
  12660. } else {
  12661. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12662. }
  12663. }
  12664. function initMaterial( material, fog, object ) {
  12665. var materialProperties = properties.get( material );
  12666. var parameters = programCache.getParameters(
  12667. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12668. var code = programCache.getProgramCode( material, parameters );
  12669. var program = materialProperties.program;
  12670. var programChange = true;
  12671. if ( program === undefined ) {
  12672. // new material
  12673. material.addEventListener( 'dispose', onMaterialDispose );
  12674. } else if ( program.code !== code ) {
  12675. // changed glsl or parameters
  12676. releaseMaterialProgramReference( material );
  12677. } else if ( parameters.shaderID !== undefined ) {
  12678. // same glsl and uniform list
  12679. return;
  12680. } else {
  12681. // only rebuild uniform list
  12682. programChange = false;
  12683. }
  12684. if ( programChange ) {
  12685. if ( parameters.shaderID ) {
  12686. var shader = ShaderLib[ parameters.shaderID ];
  12687. materialProperties.__webglShader = {
  12688. name: material.type,
  12689. uniforms: UniformsUtils.clone( shader.uniforms ),
  12690. vertexShader: shader.vertexShader,
  12691. fragmentShader: shader.fragmentShader
  12692. };
  12693. } else {
  12694. materialProperties.__webglShader = {
  12695. name: material.type,
  12696. uniforms: material.uniforms,
  12697. vertexShader: material.vertexShader,
  12698. fragmentShader: material.fragmentShader
  12699. };
  12700. }
  12701. material.__webglShader = materialProperties.__webglShader;
  12702. program = programCache.acquireProgram( material, parameters, code );
  12703. materialProperties.program = program;
  12704. material.program = program;
  12705. }
  12706. var programAttributes = program.getAttributes();
  12707. if ( material.morphTargets ) {
  12708. material.numSupportedMorphTargets = 0;
  12709. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12710. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  12711. material.numSupportedMorphTargets ++;
  12712. }
  12713. }
  12714. }
  12715. if ( material.morphNormals ) {
  12716. material.numSupportedMorphNormals = 0;
  12717. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12718. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  12719. material.numSupportedMorphNormals ++;
  12720. }
  12721. }
  12722. }
  12723. var uniforms = materialProperties.__webglShader.uniforms;
  12724. if ( ! material.isShaderMaterial &&
  12725. ! material.isRawShaderMaterial ||
  12726. material.clipping === true ) {
  12727. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12728. materialProperties.numIntersection = _clipping.numIntersection;
  12729. uniforms.clippingPlanes = _clipping.uniform;
  12730. }
  12731. materialProperties.fog = fog;
  12732. // store the light setup it was created for
  12733. materialProperties.lightsHash = _lights.hash;
  12734. if ( material.lights ) {
  12735. // wire up the material to this renderer's lighting state
  12736. uniforms.ambientLightColor.value = _lights.ambient;
  12737. uniforms.directionalLights.value = _lights.directional;
  12738. uniforms.spotLights.value = _lights.spot;
  12739. uniforms.rectAreaLights.value = _lights.rectArea;
  12740. uniforms.pointLights.value = _lights.point;
  12741. uniforms.hemisphereLights.value = _lights.hemi;
  12742. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12743. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12744. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12745. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12746. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12747. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12748. // TODO (abelnation): add area lights shadow info to uniforms
  12749. }
  12750. var progUniforms = materialProperties.program.getUniforms(),
  12751. uniformsList =
  12752. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12753. materialProperties.uniformsList = uniformsList;
  12754. }
  12755. function setProgram( camera, fog, material, object ) {
  12756. _usedTextureUnits = 0;
  12757. var materialProperties = properties.get( material );
  12758. if ( _clippingEnabled ) {
  12759. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12760. var useCache =
  12761. camera === _currentCamera &&
  12762. material.id === _currentMaterialId;
  12763. // we might want to call this function with some ClippingGroup
  12764. // object instead of the material, once it becomes feasible
  12765. // (#8465, #8379)
  12766. _clipping.setState(
  12767. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12768. camera, materialProperties, useCache );
  12769. }
  12770. }
  12771. if ( material.needsUpdate === false ) {
  12772. if ( materialProperties.program === undefined ) {
  12773. material.needsUpdate = true;
  12774. } else if ( material.fog && materialProperties.fog !== fog ) {
  12775. material.needsUpdate = true;
  12776. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12777. material.needsUpdate = true;
  12778. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12779. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12780. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12781. material.needsUpdate = true;
  12782. }
  12783. }
  12784. if ( material.needsUpdate ) {
  12785. initMaterial( material, fog, object );
  12786. material.needsUpdate = false;
  12787. }
  12788. var refreshProgram = false;
  12789. var refreshMaterial = false;
  12790. var refreshLights = false;
  12791. var program = materialProperties.program,
  12792. p_uniforms = program.getUniforms(),
  12793. m_uniforms = materialProperties.__webglShader.uniforms;
  12794. if ( program.id !== _currentProgram ) {
  12795. _gl.useProgram( program.program );
  12796. _currentProgram = program.id;
  12797. refreshProgram = true;
  12798. refreshMaterial = true;
  12799. refreshLights = true;
  12800. }
  12801. if ( material.id !== _currentMaterialId ) {
  12802. _currentMaterialId = material.id;
  12803. refreshMaterial = true;
  12804. }
  12805. if ( refreshProgram || camera !== _currentCamera ) {
  12806. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  12807. if ( capabilities.logarithmicDepthBuffer ) {
  12808. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12809. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12810. }
  12811. if ( camera !== _currentCamera ) {
  12812. _currentCamera = camera;
  12813. // lighting uniforms depend on the camera so enforce an update
  12814. // now, in case this material supports lights - or later, when
  12815. // the next material that does gets activated:
  12816. refreshMaterial = true; // set to true on material change
  12817. refreshLights = true; // remains set until update done
  12818. }
  12819. // load material specific uniforms
  12820. // (shader material also gets them for the sake of genericity)
  12821. if ( material.isShaderMaterial ||
  12822. material.isMeshPhongMaterial ||
  12823. material.isMeshStandardMaterial ||
  12824. material.envMap ) {
  12825. var uCamPos = p_uniforms.map.cameraPosition;
  12826. if ( uCamPos !== undefined ) {
  12827. uCamPos.setValue( _gl,
  12828. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12829. }
  12830. }
  12831. if ( material.isMeshPhongMaterial ||
  12832. material.isMeshLambertMaterial ||
  12833. material.isMeshBasicMaterial ||
  12834. material.isMeshStandardMaterial ||
  12835. material.isShaderMaterial ||
  12836. material.skinning ) {
  12837. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12838. }
  12839. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  12840. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  12841. }
  12842. // skinning uniforms must be set even if material didn't change
  12843. // auto-setting of texture unit for bone texture must go before other textures
  12844. // not sure why, but otherwise weird things happen
  12845. if ( material.skinning ) {
  12846. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12847. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12848. var skeleton = object.skeleton;
  12849. if ( skeleton ) {
  12850. var bones = skeleton.bones;
  12851. if ( capabilities.floatVertexTextures ) {
  12852. if ( skeleton.boneTexture === undefined ) {
  12853. // layout (1 matrix = 4 pixels)
  12854. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  12855. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  12856. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  12857. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  12858. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  12859. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  12860. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  12861. size = Math.max( size, 4 );
  12862. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  12863. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  12864. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  12865. skeleton.boneMatrices = boneMatrices;
  12866. skeleton.boneTexture = boneTexture;
  12867. skeleton.boneTextureSize = size;
  12868. }
  12869. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  12870. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  12871. } else {
  12872. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12873. }
  12874. }
  12875. }
  12876. if ( refreshMaterial ) {
  12877. if ( material.lights ) {
  12878. // the current material requires lighting info
  12879. // note: all lighting uniforms are always set correctly
  12880. // they simply reference the renderer's state for their
  12881. // values
  12882. //
  12883. // use the current material's .needsUpdate flags to set
  12884. // the GL state when required
  12885. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12886. }
  12887. // refresh uniforms common to several materials
  12888. if ( fog && material.fog ) {
  12889. refreshUniformsFog( m_uniforms, fog );
  12890. }
  12891. if ( material.isMeshBasicMaterial ||
  12892. material.isMeshLambertMaterial ||
  12893. material.isMeshPhongMaterial ||
  12894. material.isMeshStandardMaterial ||
  12895. material.isMeshNormalMaterial ||
  12896. material.isMeshDepthMaterial ) {
  12897. refreshUniformsCommon( m_uniforms, material );
  12898. }
  12899. // refresh single material specific uniforms
  12900. if ( material.isLineBasicMaterial ) {
  12901. refreshUniformsLine( m_uniforms, material );
  12902. } else if ( material.isLineDashedMaterial ) {
  12903. refreshUniformsLine( m_uniforms, material );
  12904. refreshUniformsDash( m_uniforms, material );
  12905. } else if ( material.isPointsMaterial ) {
  12906. refreshUniformsPoints( m_uniforms, material );
  12907. } else if ( material.isMeshLambertMaterial ) {
  12908. refreshUniformsLambert( m_uniforms, material );
  12909. } else if ( material.isMeshToonMaterial ) {
  12910. refreshUniformsToon( m_uniforms, material );
  12911. } else if ( material.isMeshPhongMaterial ) {
  12912. refreshUniformsPhong( m_uniforms, material );
  12913. } else if ( material.isMeshPhysicalMaterial ) {
  12914. refreshUniformsPhysical( m_uniforms, material );
  12915. } else if ( material.isMeshStandardMaterial ) {
  12916. refreshUniformsStandard( m_uniforms, material );
  12917. } else if ( material.isMeshDepthMaterial ) {
  12918. if ( material.displacementMap ) {
  12919. m_uniforms.displacementMap.value = material.displacementMap;
  12920. m_uniforms.displacementScale.value = material.displacementScale;
  12921. m_uniforms.displacementBias.value = material.displacementBias;
  12922. }
  12923. } else if ( material.isMeshNormalMaterial ) {
  12924. refreshUniformsNormal( m_uniforms, material );
  12925. }
  12926. // RectAreaLight Texture
  12927. // TODO (mrdoob): Find a nicer implementation
  12928. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  12929. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  12930. WebGLUniforms.upload(
  12931. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12932. }
  12933. // common matrices
  12934. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  12935. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  12936. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12937. return program;
  12938. }
  12939. // Uniforms (refresh uniforms objects)
  12940. function refreshUniformsCommon( uniforms, material ) {
  12941. uniforms.opacity.value = material.opacity;
  12942. uniforms.diffuse.value = material.color;
  12943. if ( material.emissive ) {
  12944. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12945. }
  12946. uniforms.map.value = material.map;
  12947. uniforms.specularMap.value = material.specularMap;
  12948. uniforms.alphaMap.value = material.alphaMap;
  12949. if ( material.lightMap ) {
  12950. uniforms.lightMap.value = material.lightMap;
  12951. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12952. }
  12953. if ( material.aoMap ) {
  12954. uniforms.aoMap.value = material.aoMap;
  12955. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12956. }
  12957. // uv repeat and offset setting priorities
  12958. // 1. color map
  12959. // 2. specular map
  12960. // 3. normal map
  12961. // 4. bump map
  12962. // 5. alpha map
  12963. // 6. emissive map
  12964. var uvScaleMap;
  12965. if ( material.map ) {
  12966. uvScaleMap = material.map;
  12967. } else if ( material.specularMap ) {
  12968. uvScaleMap = material.specularMap;
  12969. } else if ( material.displacementMap ) {
  12970. uvScaleMap = material.displacementMap;
  12971. } else if ( material.normalMap ) {
  12972. uvScaleMap = material.normalMap;
  12973. } else if ( material.bumpMap ) {
  12974. uvScaleMap = material.bumpMap;
  12975. } else if ( material.roughnessMap ) {
  12976. uvScaleMap = material.roughnessMap;
  12977. } else if ( material.metalnessMap ) {
  12978. uvScaleMap = material.metalnessMap;
  12979. } else if ( material.alphaMap ) {
  12980. uvScaleMap = material.alphaMap;
  12981. } else if ( material.emissiveMap ) {
  12982. uvScaleMap = material.emissiveMap;
  12983. }
  12984. if ( uvScaleMap !== undefined ) {
  12985. // backwards compatibility
  12986. if ( uvScaleMap.isWebGLRenderTarget ) {
  12987. uvScaleMap = uvScaleMap.texture;
  12988. }
  12989. var offset = uvScaleMap.offset;
  12990. var repeat = uvScaleMap.repeat;
  12991. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12992. }
  12993. uniforms.envMap.value = material.envMap;
  12994. // don't flip CubeTexture envMaps, flip everything else:
  12995. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12996. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12997. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12998. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12999. uniforms.reflectivity.value = material.reflectivity;
  13000. uniforms.refractionRatio.value = material.refractionRatio;
  13001. }
  13002. function refreshUniformsLine( uniforms, material ) {
  13003. uniforms.diffuse.value = material.color;
  13004. uniforms.opacity.value = material.opacity;
  13005. }
  13006. function refreshUniformsDash( uniforms, material ) {
  13007. uniforms.dashSize.value = material.dashSize;
  13008. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13009. uniforms.scale.value = material.scale;
  13010. }
  13011. function refreshUniformsPoints( uniforms, material ) {
  13012. uniforms.diffuse.value = material.color;
  13013. uniforms.opacity.value = material.opacity;
  13014. uniforms.size.value = material.size * _pixelRatio;
  13015. uniforms.scale.value = _height * 0.5;
  13016. uniforms.map.value = material.map;
  13017. if ( material.map !== null ) {
  13018. var offset = material.map.offset;
  13019. var repeat = material.map.repeat;
  13020. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13021. }
  13022. }
  13023. function refreshUniformsFog( uniforms, fog ) {
  13024. uniforms.fogColor.value = fog.color;
  13025. if ( fog.isFog ) {
  13026. uniforms.fogNear.value = fog.near;
  13027. uniforms.fogFar.value = fog.far;
  13028. } else if ( fog.isFogExp2 ) {
  13029. uniforms.fogDensity.value = fog.density;
  13030. }
  13031. }
  13032. function refreshUniformsLambert( uniforms, material ) {
  13033. if ( material.emissiveMap ) {
  13034. uniforms.emissiveMap.value = material.emissiveMap;
  13035. }
  13036. }
  13037. function refreshUniformsPhong( uniforms, material ) {
  13038. uniforms.specular.value = material.specular;
  13039. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13040. if ( material.emissiveMap ) {
  13041. uniforms.emissiveMap.value = material.emissiveMap;
  13042. }
  13043. if ( material.bumpMap ) {
  13044. uniforms.bumpMap.value = material.bumpMap;
  13045. uniforms.bumpScale.value = material.bumpScale;
  13046. }
  13047. if ( material.normalMap ) {
  13048. uniforms.normalMap.value = material.normalMap;
  13049. uniforms.normalScale.value.copy( material.normalScale );
  13050. }
  13051. if ( material.displacementMap ) {
  13052. uniforms.displacementMap.value = material.displacementMap;
  13053. uniforms.displacementScale.value = material.displacementScale;
  13054. uniforms.displacementBias.value = material.displacementBias;
  13055. }
  13056. }
  13057. function refreshUniformsToon( uniforms, material ) {
  13058. refreshUniformsPhong( uniforms, material );
  13059. if ( material.gradientMap ) {
  13060. uniforms.gradientMap.value = material.gradientMap;
  13061. }
  13062. }
  13063. function refreshUniformsStandard( uniforms, material ) {
  13064. uniforms.roughness.value = material.roughness;
  13065. uniforms.metalness.value = material.metalness;
  13066. if ( material.roughnessMap ) {
  13067. uniforms.roughnessMap.value = material.roughnessMap;
  13068. }
  13069. if ( material.metalnessMap ) {
  13070. uniforms.metalnessMap.value = material.metalnessMap;
  13071. }
  13072. if ( material.emissiveMap ) {
  13073. uniforms.emissiveMap.value = material.emissiveMap;
  13074. }
  13075. if ( material.bumpMap ) {
  13076. uniforms.bumpMap.value = material.bumpMap;
  13077. uniforms.bumpScale.value = material.bumpScale;
  13078. }
  13079. if ( material.normalMap ) {
  13080. uniforms.normalMap.value = material.normalMap;
  13081. uniforms.normalScale.value.copy( material.normalScale );
  13082. }
  13083. if ( material.displacementMap ) {
  13084. uniforms.displacementMap.value = material.displacementMap;
  13085. uniforms.displacementScale.value = material.displacementScale;
  13086. uniforms.displacementBias.value = material.displacementBias;
  13087. }
  13088. if ( material.envMap ) {
  13089. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13090. uniforms.envMapIntensity.value = material.envMapIntensity;
  13091. }
  13092. }
  13093. function refreshUniformsPhysical( uniforms, material ) {
  13094. uniforms.clearCoat.value = material.clearCoat;
  13095. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13096. refreshUniformsStandard( uniforms, material );
  13097. }
  13098. function refreshUniformsNormal( uniforms, material ) {
  13099. if ( material.bumpMap ) {
  13100. uniforms.bumpMap.value = material.bumpMap;
  13101. uniforms.bumpScale.value = material.bumpScale;
  13102. }
  13103. if ( material.normalMap ) {
  13104. uniforms.normalMap.value = material.normalMap;
  13105. uniforms.normalScale.value.copy( material.normalScale );
  13106. }
  13107. if ( material.displacementMap ) {
  13108. uniforms.displacementMap.value = material.displacementMap;
  13109. uniforms.displacementScale.value = material.displacementScale;
  13110. uniforms.displacementBias.value = material.displacementBias;
  13111. }
  13112. }
  13113. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13114. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13115. uniforms.ambientLightColor.needsUpdate = value;
  13116. uniforms.directionalLights.needsUpdate = value;
  13117. uniforms.pointLights.needsUpdate = value;
  13118. uniforms.spotLights.needsUpdate = value;
  13119. uniforms.rectAreaLights.needsUpdate = value;
  13120. uniforms.hemisphereLights.needsUpdate = value;
  13121. }
  13122. // Lighting
  13123. function setupShadows( lights ) {
  13124. var lightShadowsLength = 0;
  13125. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  13126. var light = lights[ i ];
  13127. if ( light.castShadow ) {
  13128. _lights.shadows[ lightShadowsLength ] = light;
  13129. lightShadowsLength ++;
  13130. }
  13131. }
  13132. _lights.shadows.length = lightShadowsLength;
  13133. }
  13134. function setupLights( lights, camera ) {
  13135. var l, ll, light, shadow,
  13136. r = 0, g = 0, b = 0,
  13137. color,
  13138. intensity,
  13139. distance,
  13140. shadowMap,
  13141. viewMatrix = camera.matrixWorldInverse,
  13142. directionalLength = 0,
  13143. pointLength = 0,
  13144. spotLength = 0,
  13145. rectAreaLength = 0,
  13146. hemiLength = 0;
  13147. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13148. light = lights[ l ];
  13149. color = light.color;
  13150. intensity = light.intensity;
  13151. distance = light.distance;
  13152. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13153. if ( light.isAmbientLight ) {
  13154. r += color.r * intensity;
  13155. g += color.g * intensity;
  13156. b += color.b * intensity;
  13157. } else if ( light.isDirectionalLight ) {
  13158. var uniforms = lightCache.get( light );
  13159. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13160. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13161. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13162. uniforms.direction.sub( _vector3 );
  13163. uniforms.direction.transformDirection( viewMatrix );
  13164. uniforms.shadow = light.castShadow;
  13165. if ( light.castShadow ) {
  13166. shadow = light.shadow;
  13167. uniforms.shadowBias = shadow.bias;
  13168. uniforms.shadowRadius = shadow.radius;
  13169. uniforms.shadowMapSize = shadow.mapSize;
  13170. }
  13171. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  13172. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13173. _lights.directional[ directionalLength ] = uniforms;
  13174. directionalLength ++;
  13175. } else if ( light.isSpotLight ) {
  13176. var uniforms = lightCache.get( light );
  13177. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13178. uniforms.position.applyMatrix4( viewMatrix );
  13179. uniforms.color.copy( color ).multiplyScalar( intensity );
  13180. uniforms.distance = distance;
  13181. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13182. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13183. uniforms.direction.sub( _vector3 );
  13184. uniforms.direction.transformDirection( viewMatrix );
  13185. uniforms.coneCos = Math.cos( light.angle );
  13186. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13187. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13188. uniforms.shadow = light.castShadow;
  13189. if ( light.castShadow ) {
  13190. shadow = light.shadow;
  13191. uniforms.shadowBias = shadow.bias;
  13192. uniforms.shadowRadius = shadow.radius;
  13193. uniforms.shadowMapSize = shadow.mapSize;
  13194. }
  13195. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13196. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13197. _lights.spot[ spotLength ] = uniforms;
  13198. spotLength ++;
  13199. } else if ( light.isRectAreaLight ) {
  13200. var uniforms = lightCache.get( light );
  13201. // (a) intensity controls irradiance of entire light
  13202. uniforms.color
  13203. .copy( color )
  13204. .multiplyScalar( intensity / ( light.width * light.height ) );
  13205. // (b) intensity controls the radiance per light area
  13206. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13207. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13208. uniforms.position.applyMatrix4( viewMatrix );
  13209. // extract local rotation of light to derive width/height half vectors
  13210. _matrix42.identity();
  13211. _matrix4.copy( light.matrixWorld );
  13212. _matrix4.premultiply( viewMatrix );
  13213. _matrix42.extractRotation( _matrix4 );
  13214. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13215. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13216. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13217. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13218. // TODO (abelnation): RectAreaLight distance?
  13219. // uniforms.distance = distance;
  13220. _lights.rectArea[ rectAreaLength ] = uniforms;
  13221. rectAreaLength ++;
  13222. } else if ( light.isPointLight ) {
  13223. var uniforms = lightCache.get( light );
  13224. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13225. uniforms.position.applyMatrix4( viewMatrix );
  13226. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13227. uniforms.distance = light.distance;
  13228. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13229. uniforms.shadow = light.castShadow;
  13230. if ( light.castShadow ) {
  13231. shadow = light.shadow;
  13232. uniforms.shadowBias = shadow.bias;
  13233. uniforms.shadowRadius = shadow.radius;
  13234. uniforms.shadowMapSize = shadow.mapSize;
  13235. }
  13236. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13237. _lights.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13238. _lights.point[ pointLength ] = uniforms;
  13239. pointLength ++;
  13240. } else if ( light.isHemisphereLight ) {
  13241. var uniforms = lightCache.get( light );
  13242. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13243. uniforms.direction.transformDirection( viewMatrix );
  13244. uniforms.direction.normalize();
  13245. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13246. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13247. _lights.hemi[ hemiLength ] = uniforms;
  13248. hemiLength ++;
  13249. }
  13250. }
  13251. _lights.ambient[ 0 ] = r;
  13252. _lights.ambient[ 1 ] = g;
  13253. _lights.ambient[ 2 ] = b;
  13254. _lights.directional.length = directionalLength;
  13255. _lights.spot.length = spotLength;
  13256. _lights.rectArea.length = rectAreaLength;
  13257. _lights.point.length = pointLength;
  13258. _lights.hemi.length = hemiLength;
  13259. // TODO (sam-g-steel) why aren't we using join
  13260. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13261. }
  13262. // GL state setting
  13263. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13264. state.setCullFace( cullFace );
  13265. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13266. };
  13267. // Textures
  13268. function allocTextureUnit() {
  13269. var textureUnit = _usedTextureUnits;
  13270. if ( textureUnit >= capabilities.maxTextures ) {
  13271. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13272. }
  13273. _usedTextureUnits += 1;
  13274. return textureUnit;
  13275. }
  13276. this.allocTextureUnit = allocTextureUnit;
  13277. // this.setTexture2D = setTexture2D;
  13278. this.setTexture2D = ( function () {
  13279. var warned = false;
  13280. // backwards compatibility: peel texture.texture
  13281. return function setTexture2D( texture, slot ) {
  13282. if ( texture && texture.isWebGLRenderTarget ) {
  13283. if ( ! warned ) {
  13284. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13285. warned = true;
  13286. }
  13287. texture = texture.texture;
  13288. }
  13289. textures.setTexture2D( texture, slot );
  13290. };
  13291. }() );
  13292. this.setTexture = ( function () {
  13293. var warned = false;
  13294. return function setTexture( texture, slot ) {
  13295. if ( ! warned ) {
  13296. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13297. warned = true;
  13298. }
  13299. textures.setTexture2D( texture, slot );
  13300. };
  13301. }() );
  13302. this.setTextureCube = ( function () {
  13303. var warned = false;
  13304. return function setTextureCube( texture, slot ) {
  13305. // backwards compatibility: peel texture.texture
  13306. if ( texture && texture.isWebGLRenderTargetCube ) {
  13307. if ( ! warned ) {
  13308. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13309. warned = true;
  13310. }
  13311. texture = texture.texture;
  13312. }
  13313. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13314. // TODO: unify these code paths
  13315. if ( ( texture && texture.isCubeTexture ) ||
  13316. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13317. // CompressedTexture can have Array in image :/
  13318. // this function alone should take care of cube textures
  13319. textures.setTextureCube( texture, slot );
  13320. } else {
  13321. // assumed: texture property of THREE.WebGLRenderTargetCube
  13322. textures.setTextureCubeDynamic( texture, slot );
  13323. }
  13324. };
  13325. }() );
  13326. this.getRenderTarget = function () {
  13327. return _currentRenderTarget;
  13328. };
  13329. this.setRenderTarget = function ( renderTarget ) {
  13330. _currentRenderTarget = renderTarget;
  13331. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13332. textures.setupRenderTarget( renderTarget );
  13333. }
  13334. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13335. var framebuffer;
  13336. if ( renderTarget ) {
  13337. var renderTargetProperties = properties.get( renderTarget );
  13338. if ( isCube ) {
  13339. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13340. } else {
  13341. framebuffer = renderTargetProperties.__webglFramebuffer;
  13342. }
  13343. _currentScissor.copy( renderTarget.scissor );
  13344. _currentScissorTest = renderTarget.scissorTest;
  13345. _currentViewport.copy( renderTarget.viewport );
  13346. } else {
  13347. framebuffer = null;
  13348. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13349. _currentScissorTest = _scissorTest;
  13350. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13351. }
  13352. if ( _currentFramebuffer !== framebuffer ) {
  13353. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13354. _currentFramebuffer = framebuffer;
  13355. }
  13356. state.scissor( _currentScissor );
  13357. state.setScissorTest( _currentScissorTest );
  13358. state.viewport( _currentViewport );
  13359. if ( isCube ) {
  13360. var textureProperties = properties.get( renderTarget.texture );
  13361. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13362. }
  13363. };
  13364. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13365. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13366. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13367. return;
  13368. }
  13369. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13370. if ( framebuffer ) {
  13371. var restore = false;
  13372. if ( framebuffer !== _currentFramebuffer ) {
  13373. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13374. restore = true;
  13375. }
  13376. try {
  13377. var texture = renderTarget.texture;
  13378. var textureFormat = texture.format;
  13379. var textureType = texture.type;
  13380. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13381. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13382. return;
  13383. }
  13384. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13385. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13386. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13387. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13388. return;
  13389. }
  13390. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13391. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13392. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13393. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13394. }
  13395. } else {
  13396. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13397. }
  13398. } finally {
  13399. if ( restore ) {
  13400. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13401. }
  13402. }
  13403. }
  13404. };
  13405. // Map three.js constants to WebGL constants
  13406. function paramThreeToGL( p ) {
  13407. var extension;
  13408. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13409. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13410. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13411. if ( p === NearestFilter ) return _gl.NEAREST;
  13412. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13413. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13414. if ( p === LinearFilter ) return _gl.LINEAR;
  13415. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13416. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13417. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13418. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13419. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13420. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13421. if ( p === ByteType ) return _gl.BYTE;
  13422. if ( p === ShortType ) return _gl.SHORT;
  13423. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13424. if ( p === IntType ) return _gl.INT;
  13425. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13426. if ( p === FloatType ) return _gl.FLOAT;
  13427. if ( p === HalfFloatType ) {
  13428. extension = extensions.get( 'OES_texture_half_float' );
  13429. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13430. }
  13431. if ( p === AlphaFormat ) return _gl.ALPHA;
  13432. if ( p === RGBFormat ) return _gl.RGB;
  13433. if ( p === RGBAFormat ) return _gl.RGBA;
  13434. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13435. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13436. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13437. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13438. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13439. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13440. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13441. if ( p === ZeroFactor ) return _gl.ZERO;
  13442. if ( p === OneFactor ) return _gl.ONE;
  13443. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13444. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13445. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13446. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13447. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13448. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13449. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13450. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13451. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13452. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13453. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13454. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13455. if ( extension !== null ) {
  13456. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13457. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13458. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13459. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13460. }
  13461. }
  13462. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13463. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13464. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13465. if ( extension !== null ) {
  13466. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13467. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13468. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13469. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13470. }
  13471. }
  13472. if ( p === RGB_ETC1_Format ) {
  13473. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13474. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13475. }
  13476. if ( p === MinEquation || p === MaxEquation ) {
  13477. extension = extensions.get( 'EXT_blend_minmax' );
  13478. if ( extension !== null ) {
  13479. if ( p === MinEquation ) return extension.MIN_EXT;
  13480. if ( p === MaxEquation ) return extension.MAX_EXT;
  13481. }
  13482. }
  13483. if ( p === UnsignedInt248Type ) {
  13484. extension = extensions.get( 'WEBGL_depth_texture' );
  13485. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13486. }
  13487. return 0;
  13488. }
  13489. }
  13490. /**
  13491. * @author mrdoob / http://mrdoob.com/
  13492. * @author alteredq / http://alteredqualia.com/
  13493. */
  13494. function FogExp2 ( color, density ) {
  13495. this.name = '';
  13496. this.color = new Color( color );
  13497. this.density = ( density !== undefined ) ? density : 0.00025;
  13498. }
  13499. FogExp2.prototype.isFogExp2 = true;
  13500. FogExp2.prototype.clone = function () {
  13501. return new FogExp2( this.color.getHex(), this.density );
  13502. };
  13503. FogExp2.prototype.toJSON = function ( meta ) {
  13504. return {
  13505. type: 'FogExp2',
  13506. color: this.color.getHex(),
  13507. density: this.density
  13508. };
  13509. };
  13510. /**
  13511. * @author mrdoob / http://mrdoob.com/
  13512. * @author alteredq / http://alteredqualia.com/
  13513. */
  13514. function Fog ( color, near, far ) {
  13515. this.name = '';
  13516. this.color = new Color( color );
  13517. this.near = ( near !== undefined ) ? near : 1;
  13518. this.far = ( far !== undefined ) ? far : 1000;
  13519. }
  13520. Fog.prototype.isFog = true;
  13521. Fog.prototype.clone = function () {
  13522. return new Fog( this.color.getHex(), this.near, this.far );
  13523. };
  13524. Fog.prototype.toJSON = function ( meta ) {
  13525. return {
  13526. type: 'Fog',
  13527. color: this.color.getHex(),
  13528. near: this.near,
  13529. far: this.far
  13530. };
  13531. };
  13532. /**
  13533. * @author mrdoob / http://mrdoob.com/
  13534. */
  13535. function Scene () {
  13536. Object3D.call( this );
  13537. this.type = 'Scene';
  13538. this.background = null;
  13539. this.fog = null;
  13540. this.overrideMaterial = null;
  13541. this.autoUpdate = true; // checked by the renderer
  13542. }
  13543. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13544. constructor: Scene,
  13545. copy: function ( source, recursive ) {
  13546. Object3D.prototype.copy.call( this, source, recursive );
  13547. if ( source.background !== null ) this.background = source.background.clone();
  13548. if ( source.fog !== null ) this.fog = source.fog.clone();
  13549. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13550. this.autoUpdate = source.autoUpdate;
  13551. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13552. return this;
  13553. },
  13554. toJSON: function ( meta ) {
  13555. var data = Object3D.prototype.toJSON.call( this, meta );
  13556. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13557. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13558. return data;
  13559. }
  13560. } );
  13561. /**
  13562. * @author mikael emtinger / http://gomo.se/
  13563. * @author alteredq / http://alteredqualia.com/
  13564. */
  13565. function LensFlare( texture, size, distance, blending, color ) {
  13566. Object3D.call( this );
  13567. this.lensFlares = [];
  13568. this.positionScreen = new Vector3();
  13569. this.customUpdateCallback = undefined;
  13570. if ( texture !== undefined ) {
  13571. this.add( texture, size, distance, blending, color );
  13572. }
  13573. }
  13574. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13575. constructor: LensFlare,
  13576. isLensFlare: true,
  13577. copy: function ( source ) {
  13578. Object3D.prototype.copy.call( this, source );
  13579. this.positionScreen.copy( source.positionScreen );
  13580. this.customUpdateCallback = source.customUpdateCallback;
  13581. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13582. this.lensFlares.push( source.lensFlares[ i ] );
  13583. }
  13584. return this;
  13585. },
  13586. add: function ( texture, size, distance, blending, color, opacity ) {
  13587. if ( size === undefined ) size = - 1;
  13588. if ( distance === undefined ) distance = 0;
  13589. if ( opacity === undefined ) opacity = 1;
  13590. if ( color === undefined ) color = new Color( 0xffffff );
  13591. if ( blending === undefined ) blending = NormalBlending;
  13592. distance = Math.min( distance, Math.max( 0, distance ) );
  13593. this.lensFlares.push( {
  13594. texture: texture, // THREE.Texture
  13595. size: size, // size in pixels (-1 = use texture.width)
  13596. distance: distance, // distance (0-1) from light source (0=at light source)
  13597. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13598. scale: 1, // scale
  13599. rotation: 0, // rotation
  13600. opacity: opacity, // opacity
  13601. color: color, // color
  13602. blending: blending // blending
  13603. } );
  13604. },
  13605. /*
  13606. * Update lens flares update positions on all flares based on the screen position
  13607. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13608. */
  13609. updateLensFlares: function () {
  13610. var f, fl = this.lensFlares.length;
  13611. var flare;
  13612. var vecX = - this.positionScreen.x * 2;
  13613. var vecY = - this.positionScreen.y * 2;
  13614. for ( f = 0; f < fl; f ++ ) {
  13615. flare = this.lensFlares[ f ];
  13616. flare.x = this.positionScreen.x + vecX * flare.distance;
  13617. flare.y = this.positionScreen.y + vecY * flare.distance;
  13618. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13619. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13620. }
  13621. }
  13622. } );
  13623. /**
  13624. * @author alteredq / http://alteredqualia.com/
  13625. *
  13626. * parameters = {
  13627. * color: <hex>,
  13628. * opacity: <float>,
  13629. * map: new THREE.Texture( <Image> ),
  13630. *
  13631. * uvOffset: new THREE.Vector2(),
  13632. * uvScale: new THREE.Vector2()
  13633. * }
  13634. */
  13635. function SpriteMaterial( parameters ) {
  13636. Material.call( this );
  13637. this.type = 'SpriteMaterial';
  13638. this.color = new Color( 0xffffff );
  13639. this.map = null;
  13640. this.rotation = 0;
  13641. this.fog = false;
  13642. this.lights = false;
  13643. this.setValues( parameters );
  13644. }
  13645. SpriteMaterial.prototype = Object.create( Material.prototype );
  13646. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13647. SpriteMaterial.prototype.isSpriteMaterial = true;
  13648. SpriteMaterial.prototype.copy = function ( source ) {
  13649. Material.prototype.copy.call( this, source );
  13650. this.color.copy( source.color );
  13651. this.map = source.map;
  13652. this.rotation = source.rotation;
  13653. return this;
  13654. };
  13655. /**
  13656. * @author mikael emtinger / http://gomo.se/
  13657. * @author alteredq / http://alteredqualia.com/
  13658. */
  13659. function Sprite( material ) {
  13660. Object3D.call( this );
  13661. this.type = 'Sprite';
  13662. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13663. }
  13664. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13665. constructor: Sprite,
  13666. isSprite: true,
  13667. raycast: ( function () {
  13668. var intersectPoint = new Vector3();
  13669. var worldPosition = new Vector3();
  13670. var worldScale = new Vector3();
  13671. return function raycast( raycaster, intersects ) {
  13672. worldPosition.setFromMatrixPosition( this.matrixWorld );
  13673. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  13674. worldScale.setFromMatrixScale( this.matrixWorld );
  13675. var guessSizeSq = worldScale.x * worldScale.y / 4;
  13676. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  13677. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13678. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13679. intersects.push( {
  13680. distance: distance,
  13681. point: intersectPoint.clone(),
  13682. face: null,
  13683. object: this
  13684. } );
  13685. };
  13686. }() ),
  13687. clone: function () {
  13688. return new this.constructor( this.material ).copy( this );
  13689. }
  13690. } );
  13691. /**
  13692. * @author mikael emtinger / http://gomo.se/
  13693. * @author alteredq / http://alteredqualia.com/
  13694. * @author mrdoob / http://mrdoob.com/
  13695. */
  13696. function LOD() {
  13697. Object3D.call( this );
  13698. this.type = 'LOD';
  13699. Object.defineProperties( this, {
  13700. levels: {
  13701. enumerable: true,
  13702. value: []
  13703. }
  13704. } );
  13705. }
  13706. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13707. constructor: LOD,
  13708. copy: function ( source ) {
  13709. Object3D.prototype.copy.call( this, source, false );
  13710. var levels = source.levels;
  13711. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13712. var level = levels[ i ];
  13713. this.addLevel( level.object.clone(), level.distance );
  13714. }
  13715. return this;
  13716. },
  13717. addLevel: function ( object, distance ) {
  13718. if ( distance === undefined ) distance = 0;
  13719. distance = Math.abs( distance );
  13720. var levels = this.levels;
  13721. for ( var l = 0; l < levels.length; l ++ ) {
  13722. if ( distance < levels[ l ].distance ) {
  13723. break;
  13724. }
  13725. }
  13726. levels.splice( l, 0, { distance: distance, object: object } );
  13727. this.add( object );
  13728. },
  13729. getObjectForDistance: function ( distance ) {
  13730. var levels = this.levels;
  13731. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13732. if ( distance < levels[ i ].distance ) {
  13733. break;
  13734. }
  13735. }
  13736. return levels[ i - 1 ].object;
  13737. },
  13738. raycast: ( function () {
  13739. var matrixPosition = new Vector3();
  13740. return function raycast( raycaster, intersects ) {
  13741. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13742. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13743. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13744. };
  13745. }() ),
  13746. update: function () {
  13747. var v1 = new Vector3();
  13748. var v2 = new Vector3();
  13749. return function update( camera ) {
  13750. var levels = this.levels;
  13751. if ( levels.length > 1 ) {
  13752. v1.setFromMatrixPosition( camera.matrixWorld );
  13753. v2.setFromMatrixPosition( this.matrixWorld );
  13754. var distance = v1.distanceTo( v2 );
  13755. levels[ 0 ].object.visible = true;
  13756. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13757. if ( distance >= levels[ i ].distance ) {
  13758. levels[ i - 1 ].object.visible = false;
  13759. levels[ i ].object.visible = true;
  13760. } else {
  13761. break;
  13762. }
  13763. }
  13764. for ( ; i < l; i ++ ) {
  13765. levels[ i ].object.visible = false;
  13766. }
  13767. }
  13768. };
  13769. }(),
  13770. toJSON: function ( meta ) {
  13771. var data = Object3D.prototype.toJSON.call( this, meta );
  13772. data.object.levels = [];
  13773. var levels = this.levels;
  13774. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13775. var level = levels[ i ];
  13776. data.object.levels.push( {
  13777. object: level.object.uuid,
  13778. distance: level.distance
  13779. } );
  13780. }
  13781. return data;
  13782. }
  13783. } );
  13784. /**
  13785. * @author mikael emtinger / http://gomo.se/
  13786. * @author alteredq / http://alteredqualia.com/
  13787. * @author michael guerrero / http://realitymeltdown.com
  13788. * @author ikerr / http://verold.com
  13789. */
  13790. function Skeleton( bones, boneInverses ) {
  13791. // copy the bone array
  13792. bones = bones || [];
  13793. this.bones = bones.slice( 0 );
  13794. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  13795. // use the supplied bone inverses or calculate the inverses
  13796. if ( boneInverses === undefined ) {
  13797. this.calculateInverses();
  13798. } else {
  13799. if ( this.bones.length === boneInverses.length ) {
  13800. this.boneInverses = boneInverses.slice( 0 );
  13801. } else {
  13802. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  13803. this.boneInverses = [];
  13804. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  13805. this.boneInverses.push( new Matrix4() );
  13806. }
  13807. }
  13808. }
  13809. }
  13810. Object.assign( Skeleton.prototype, {
  13811. calculateInverses: function () {
  13812. this.boneInverses = [];
  13813. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  13814. var inverse = new Matrix4();
  13815. if ( this.bones[ i ] ) {
  13816. inverse.getInverse( this.bones[ i ].matrixWorld );
  13817. }
  13818. this.boneInverses.push( inverse );
  13819. }
  13820. },
  13821. pose: function () {
  13822. var bone, i, il;
  13823. // recover the bind-time world matrices
  13824. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  13825. bone = this.bones[ i ];
  13826. if ( bone ) {
  13827. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  13828. }
  13829. }
  13830. // compute the local matrices, positions, rotations and scales
  13831. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  13832. bone = this.bones[ i ];
  13833. if ( bone ) {
  13834. if ( bone.parent && bone.parent.isBone ) {
  13835. bone.matrix.getInverse( bone.parent.matrixWorld );
  13836. bone.matrix.multiply( bone.matrixWorld );
  13837. } else {
  13838. bone.matrix.copy( bone.matrixWorld );
  13839. }
  13840. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13841. }
  13842. }
  13843. },
  13844. update: ( function () {
  13845. var offsetMatrix = new Matrix4();
  13846. var identityMatrix = new Matrix4();
  13847. return function update() {
  13848. var bones = this.bones;
  13849. var boneInverses = this.boneInverses;
  13850. var boneMatrices = this.boneMatrices;
  13851. var boneTexture = this.boneTexture;
  13852. // flatten bone matrices to array
  13853. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  13854. // compute the offset between the current and the original transform
  13855. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  13856. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  13857. offsetMatrix.toArray( boneMatrices, i * 16 );
  13858. }
  13859. if ( boneTexture !== undefined ) {
  13860. boneTexture.needsUpdate = true;
  13861. }
  13862. };
  13863. } )(),
  13864. clone: function () {
  13865. return new Skeleton( this.bones, this.boneInverses );
  13866. }
  13867. } );
  13868. /**
  13869. * @author mikael emtinger / http://gomo.se/
  13870. * @author alteredq / http://alteredqualia.com/
  13871. * @author ikerr / http://verold.com
  13872. */
  13873. function Bone() {
  13874. Object3D.call( this );
  13875. this.type = 'Bone';
  13876. }
  13877. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13878. constructor: Bone,
  13879. isBone: true
  13880. } );
  13881. /**
  13882. * @author mikael emtinger / http://gomo.se/
  13883. * @author alteredq / http://alteredqualia.com/
  13884. * @author ikerr / http://verold.com
  13885. */
  13886. function SkinnedMesh( geometry, material ) {
  13887. Mesh.call( this, geometry, material );
  13888. this.type = 'SkinnedMesh';
  13889. this.bindMode = 'attached';
  13890. this.bindMatrix = new Matrix4();
  13891. this.bindMatrixInverse = new Matrix4();
  13892. var bones = this.initBones();
  13893. var skeleton = new Skeleton( bones );
  13894. this.bind( skeleton, this.matrixWorld );
  13895. this.normalizeSkinWeights();
  13896. }
  13897. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13898. constructor: SkinnedMesh,
  13899. isSkinnedMesh: true,
  13900. initBones: function () {
  13901. var bones = [], bone, gbone;
  13902. var i, il;
  13903. if ( this.geometry && this.geometry.bones !== undefined ) {
  13904. // first, create array of 'Bone' objects from geometry data
  13905. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  13906. gbone = this.geometry.bones[ i ];
  13907. // create new 'Bone' object
  13908. bone = new Bone();
  13909. bones.push( bone );
  13910. // apply values
  13911. bone.name = gbone.name;
  13912. bone.position.fromArray( gbone.pos );
  13913. bone.quaternion.fromArray( gbone.rotq );
  13914. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13915. }
  13916. // second, create bone hierarchy
  13917. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  13918. gbone = this.geometry.bones[ i ];
  13919. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  13920. // subsequent bones in the hierarchy
  13921. bones[ gbone.parent ].add( bones[ i ] );
  13922. } else {
  13923. // topmost bone, immediate child of the skinned mesh
  13924. this.add( bones[ i ] );
  13925. }
  13926. }
  13927. }
  13928. // now the bones are part of the scene graph and children of the skinned mesh.
  13929. // let's update the corresponding matrices
  13930. this.updateMatrixWorld( true );
  13931. return bones;
  13932. },
  13933. bind: function ( skeleton, bindMatrix ) {
  13934. this.skeleton = skeleton;
  13935. if ( bindMatrix === undefined ) {
  13936. this.updateMatrixWorld( true );
  13937. this.skeleton.calculateInverses();
  13938. bindMatrix = this.matrixWorld;
  13939. }
  13940. this.bindMatrix.copy( bindMatrix );
  13941. this.bindMatrixInverse.getInverse( bindMatrix );
  13942. },
  13943. pose: function () {
  13944. this.skeleton.pose();
  13945. },
  13946. normalizeSkinWeights: function () {
  13947. var scale, i;
  13948. if ( this.geometry && this.geometry.isGeometry ) {
  13949. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13950. var sw = this.geometry.skinWeights[ i ];
  13951. scale = 1.0 / sw.lengthManhattan();
  13952. if ( scale !== Infinity ) {
  13953. sw.multiplyScalar( scale );
  13954. } else {
  13955. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13956. }
  13957. }
  13958. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13959. var vec = new Vector4();
  13960. var skinWeight = this.geometry.attributes.skinWeight;
  13961. for ( i = 0; i < skinWeight.count; i ++ ) {
  13962. vec.x = skinWeight.getX( i );
  13963. vec.y = skinWeight.getY( i );
  13964. vec.z = skinWeight.getZ( i );
  13965. vec.w = skinWeight.getW( i );
  13966. scale = 1.0 / vec.lengthManhattan();
  13967. if ( scale !== Infinity ) {
  13968. vec.multiplyScalar( scale );
  13969. } else {
  13970. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13971. }
  13972. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13973. }
  13974. }
  13975. },
  13976. updateMatrixWorld: function ( force ) {
  13977. Mesh.prototype.updateMatrixWorld.call( this, force );
  13978. if ( this.bindMode === 'attached' ) {
  13979. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13980. } else if ( this.bindMode === 'detached' ) {
  13981. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13982. } else {
  13983. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  13984. }
  13985. },
  13986. clone: function () {
  13987. return new this.constructor( this.geometry, this.material ).copy( this );
  13988. }
  13989. } );
  13990. /**
  13991. * @author mrdoob / http://mrdoob.com/
  13992. * @author alteredq / http://alteredqualia.com/
  13993. *
  13994. * parameters = {
  13995. * color: <hex>,
  13996. * opacity: <float>,
  13997. *
  13998. * linewidth: <float>,
  13999. * linecap: "round",
  14000. * linejoin: "round"
  14001. * }
  14002. */
  14003. function LineBasicMaterial( parameters ) {
  14004. Material.call( this );
  14005. this.type = 'LineBasicMaterial';
  14006. this.color = new Color( 0xffffff );
  14007. this.linewidth = 1;
  14008. this.linecap = 'round';
  14009. this.linejoin = 'round';
  14010. this.lights = false;
  14011. this.setValues( parameters );
  14012. }
  14013. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14014. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14015. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14016. LineBasicMaterial.prototype.copy = function ( source ) {
  14017. Material.prototype.copy.call( this, source );
  14018. this.color.copy( source.color );
  14019. this.linewidth = source.linewidth;
  14020. this.linecap = source.linecap;
  14021. this.linejoin = source.linejoin;
  14022. return this;
  14023. };
  14024. /**
  14025. * @author mrdoob / http://mrdoob.com/
  14026. */
  14027. function Line( geometry, material, mode ) {
  14028. if ( mode === 1 ) {
  14029. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14030. return new LineSegments( geometry, material );
  14031. }
  14032. Object3D.call( this );
  14033. this.type = 'Line';
  14034. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14035. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14036. }
  14037. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14038. constructor: Line,
  14039. isLine: true,
  14040. raycast: ( function () {
  14041. var inverseMatrix = new Matrix4();
  14042. var ray = new Ray();
  14043. var sphere = new Sphere();
  14044. return function raycast( raycaster, intersects ) {
  14045. var precision = raycaster.linePrecision;
  14046. var precisionSq = precision * precision;
  14047. var geometry = this.geometry;
  14048. var matrixWorld = this.matrixWorld;
  14049. // Checking boundingSphere distance to ray
  14050. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14051. sphere.copy( geometry.boundingSphere );
  14052. sphere.applyMatrix4( matrixWorld );
  14053. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14054. //
  14055. inverseMatrix.getInverse( matrixWorld );
  14056. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14057. var vStart = new Vector3();
  14058. var vEnd = new Vector3();
  14059. var interSegment = new Vector3();
  14060. var interRay = new Vector3();
  14061. var step = (this && this.isLineSegments) ? 2 : 1;
  14062. if ( geometry.isBufferGeometry ) {
  14063. var index = geometry.index;
  14064. var attributes = geometry.attributes;
  14065. var positions = attributes.position.array;
  14066. if ( index !== null ) {
  14067. var indices = index.array;
  14068. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14069. var a = indices[ i ];
  14070. var b = indices[ i + 1 ];
  14071. vStart.fromArray( positions, a * 3 );
  14072. vEnd.fromArray( positions, b * 3 );
  14073. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14074. if ( distSq > precisionSq ) continue;
  14075. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14076. var distance = raycaster.ray.origin.distanceTo( interRay );
  14077. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14078. intersects.push( {
  14079. distance: distance,
  14080. // What do we want? intersection point on the ray or on the segment??
  14081. // point: raycaster.ray.at( distance ),
  14082. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14083. index: i,
  14084. face: null,
  14085. faceIndex: null,
  14086. object: this
  14087. } );
  14088. }
  14089. } else {
  14090. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14091. vStart.fromArray( positions, 3 * i );
  14092. vEnd.fromArray( positions, 3 * i + 3 );
  14093. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14094. if ( distSq > precisionSq ) continue;
  14095. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14096. var distance = raycaster.ray.origin.distanceTo( interRay );
  14097. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14098. intersects.push( {
  14099. distance: distance,
  14100. // What do we want? intersection point on the ray or on the segment??
  14101. // point: raycaster.ray.at( distance ),
  14102. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14103. index: i,
  14104. face: null,
  14105. faceIndex: null,
  14106. object: this
  14107. } );
  14108. }
  14109. }
  14110. } else if ( geometry.isGeometry ) {
  14111. var vertices = geometry.vertices;
  14112. var nbVertices = vertices.length;
  14113. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14114. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14115. if ( distSq > precisionSq ) continue;
  14116. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14117. var distance = raycaster.ray.origin.distanceTo( interRay );
  14118. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14119. intersects.push( {
  14120. distance: distance,
  14121. // What do we want? intersection point on the ray or on the segment??
  14122. // point: raycaster.ray.at( distance ),
  14123. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14124. index: i,
  14125. face: null,
  14126. faceIndex: null,
  14127. object: this
  14128. } );
  14129. }
  14130. }
  14131. };
  14132. }() ),
  14133. clone: function () {
  14134. return new this.constructor( this.geometry, this.material ).copy( this );
  14135. }
  14136. } );
  14137. /**
  14138. * @author mrdoob / http://mrdoob.com/
  14139. */
  14140. function LineSegments( geometry, material ) {
  14141. Line.call( this, geometry, material );
  14142. this.type = 'LineSegments';
  14143. }
  14144. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14145. constructor: LineSegments,
  14146. isLineSegments: true
  14147. } );
  14148. /**
  14149. * @author mgreter / http://github.com/mgreter
  14150. */
  14151. function LineLoop( geometry, material ) {
  14152. Line.call( this, geometry, material );
  14153. this.type = 'LineLoop';
  14154. }
  14155. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14156. constructor: LineLoop,
  14157. isLineLoop: true,
  14158. } );
  14159. /**
  14160. * @author mrdoob / http://mrdoob.com/
  14161. * @author alteredq / http://alteredqualia.com/
  14162. *
  14163. * parameters = {
  14164. * color: <hex>,
  14165. * opacity: <float>,
  14166. * map: new THREE.Texture( <Image> ),
  14167. *
  14168. * size: <float>,
  14169. * sizeAttenuation: <bool>
  14170. * }
  14171. */
  14172. function PointsMaterial( parameters ) {
  14173. Material.call( this );
  14174. this.type = 'PointsMaterial';
  14175. this.color = new Color( 0xffffff );
  14176. this.map = null;
  14177. this.size = 1;
  14178. this.sizeAttenuation = true;
  14179. this.lights = false;
  14180. this.setValues( parameters );
  14181. }
  14182. PointsMaterial.prototype = Object.create( Material.prototype );
  14183. PointsMaterial.prototype.constructor = PointsMaterial;
  14184. PointsMaterial.prototype.isPointsMaterial = true;
  14185. PointsMaterial.prototype.copy = function ( source ) {
  14186. Material.prototype.copy.call( this, source );
  14187. this.color.copy( source.color );
  14188. this.map = source.map;
  14189. this.size = source.size;
  14190. this.sizeAttenuation = source.sizeAttenuation;
  14191. return this;
  14192. };
  14193. /**
  14194. * @author alteredq / http://alteredqualia.com/
  14195. */
  14196. function Points( geometry, material ) {
  14197. Object3D.call( this );
  14198. this.type = 'Points';
  14199. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14200. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14201. }
  14202. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14203. constructor: Points,
  14204. isPoints: true,
  14205. raycast: ( function () {
  14206. var inverseMatrix = new Matrix4();
  14207. var ray = new Ray();
  14208. var sphere = new Sphere();
  14209. return function raycast( raycaster, intersects ) {
  14210. var object = this;
  14211. var geometry = this.geometry;
  14212. var matrixWorld = this.matrixWorld;
  14213. var threshold = raycaster.params.Points.threshold;
  14214. // Checking boundingSphere distance to ray
  14215. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14216. sphere.copy( geometry.boundingSphere );
  14217. sphere.applyMatrix4( matrixWorld );
  14218. sphere.radius += threshold;
  14219. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14220. //
  14221. inverseMatrix.getInverse( matrixWorld );
  14222. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14223. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14224. var localThresholdSq = localThreshold * localThreshold;
  14225. var position = new Vector3();
  14226. function testPoint( point, index ) {
  14227. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14228. if ( rayPointDistanceSq < localThresholdSq ) {
  14229. var intersectPoint = ray.closestPointToPoint( point );
  14230. intersectPoint.applyMatrix4( matrixWorld );
  14231. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14232. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14233. intersects.push( {
  14234. distance: distance,
  14235. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14236. point: intersectPoint.clone(),
  14237. index: index,
  14238. face: null,
  14239. object: object
  14240. } );
  14241. }
  14242. }
  14243. if ( geometry.isBufferGeometry ) {
  14244. var index = geometry.index;
  14245. var attributes = geometry.attributes;
  14246. var positions = attributes.position.array;
  14247. if ( index !== null ) {
  14248. var indices = index.array;
  14249. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14250. var a = indices[ i ];
  14251. position.fromArray( positions, a * 3 );
  14252. testPoint( position, a );
  14253. }
  14254. } else {
  14255. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14256. position.fromArray( positions, i * 3 );
  14257. testPoint( position, i );
  14258. }
  14259. }
  14260. } else {
  14261. var vertices = geometry.vertices;
  14262. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14263. testPoint( vertices[ i ], i );
  14264. }
  14265. }
  14266. };
  14267. }() ),
  14268. clone: function () {
  14269. return new this.constructor( this.geometry, this.material ).copy( this );
  14270. }
  14271. } );
  14272. /**
  14273. * @author mrdoob / http://mrdoob.com/
  14274. */
  14275. function Group() {
  14276. Object3D.call( this );
  14277. this.type = 'Group';
  14278. }
  14279. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14280. constructor: Group
  14281. } );
  14282. /**
  14283. * @author mrdoob / http://mrdoob.com/
  14284. */
  14285. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14286. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14287. this.generateMipmaps = false;
  14288. var scope = this;
  14289. function update() {
  14290. requestAnimationFrame( update );
  14291. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14292. scope.needsUpdate = true;
  14293. }
  14294. }
  14295. update();
  14296. }
  14297. VideoTexture.prototype = Object.create( Texture.prototype );
  14298. VideoTexture.prototype.constructor = VideoTexture;
  14299. /**
  14300. * @author alteredq / http://alteredqualia.com/
  14301. */
  14302. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14303. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14304. this.image = { width: width, height: height };
  14305. this.mipmaps = mipmaps;
  14306. // no flipping for cube textures
  14307. // (also flipping doesn't work for compressed textures )
  14308. this.flipY = false;
  14309. // can't generate mipmaps for compressed textures
  14310. // mips must be embedded in DDS files
  14311. this.generateMipmaps = false;
  14312. }
  14313. CompressedTexture.prototype = Object.create( Texture.prototype );
  14314. CompressedTexture.prototype.constructor = CompressedTexture;
  14315. CompressedTexture.prototype.isCompressedTexture = true;
  14316. /**
  14317. * @author mrdoob / http://mrdoob.com/
  14318. */
  14319. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14320. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14321. this.needsUpdate = true;
  14322. }
  14323. CanvasTexture.prototype = Object.create( Texture.prototype );
  14324. CanvasTexture.prototype.constructor = CanvasTexture;
  14325. /**
  14326. * @author Matt DesLauriers / @mattdesl
  14327. * @author atix / arthursilber.de
  14328. */
  14329. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14330. format = format !== undefined ? format : DepthFormat;
  14331. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14332. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14333. }
  14334. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14335. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14336. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14337. this.image = { width: width, height: height };
  14338. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14339. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14340. this.flipY = false;
  14341. this.generateMipmaps = false;
  14342. }
  14343. DepthTexture.prototype = Object.create( Texture.prototype );
  14344. DepthTexture.prototype.constructor = DepthTexture;
  14345. DepthTexture.prototype.isDepthTexture = true;
  14346. /**
  14347. * @author mrdoob / http://mrdoob.com/
  14348. * @author Mugen87 / https://github.com/Mugen87
  14349. */
  14350. function WireframeGeometry( geometry ) {
  14351. BufferGeometry.call( this );
  14352. this.type = 'WireframeGeometry';
  14353. // buffer
  14354. var vertices = [];
  14355. // helper variables
  14356. var i, j, l, o, ol;
  14357. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14358. var key, keys = [ 'a', 'b', 'c' ];
  14359. var vertex;
  14360. // different logic for Geometry and BufferGeometry
  14361. if ( geometry && geometry.isGeometry ) {
  14362. // create a data structure that contains all edges without duplicates
  14363. var faces = geometry.faces;
  14364. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14365. var face = faces[ i ];
  14366. for ( j = 0; j < 3; j ++ ) {
  14367. edge1 = face[ keys[ j ] ];
  14368. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14369. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14370. edge[ 1 ] = Math.max( edge1, edge2 );
  14371. key = edge[ 0 ] + ',' + edge[ 1 ];
  14372. if ( edges[ key ] === undefined ) {
  14373. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14374. }
  14375. }
  14376. }
  14377. // generate vertices
  14378. for ( key in edges ) {
  14379. e = edges[ key ];
  14380. vertex = geometry.vertices[ e.index1 ];
  14381. vertices.push( vertex.x, vertex.y, vertex.z );
  14382. vertex = geometry.vertices[ e.index2 ];
  14383. vertices.push( vertex.x, vertex.y, vertex.z );
  14384. }
  14385. } else if ( geometry && geometry.isBufferGeometry ) {
  14386. var position, indices, groups;
  14387. var group, start, count;
  14388. var index1, index2;
  14389. vertex = new Vector3();
  14390. if ( geometry.index !== null ) {
  14391. // indexed BufferGeometry
  14392. position = geometry.attributes.position;
  14393. indices = geometry.index;
  14394. groups = geometry.groups;
  14395. if ( groups.length === 0 ) {
  14396. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14397. }
  14398. // create a data structure that contains all eges without duplicates
  14399. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14400. group = groups[ o ];
  14401. start = group.start;
  14402. count = group.count;
  14403. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14404. for ( j = 0; j < 3; j ++ ) {
  14405. edge1 = indices.getX( i + j );
  14406. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14407. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14408. edge[ 1 ] = Math.max( edge1, edge2 );
  14409. key = edge[ 0 ] + ',' + edge[ 1 ];
  14410. if ( edges[ key ] === undefined ) {
  14411. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14412. }
  14413. }
  14414. }
  14415. }
  14416. // generate vertices
  14417. for ( key in edges ) {
  14418. e = edges[ key ];
  14419. vertex.fromBufferAttribute( position, e.index1 );
  14420. vertices.push( vertex.x, vertex.y, vertex.z );
  14421. vertex.fromBufferAttribute( position, e.index2 );
  14422. vertices.push( vertex.x, vertex.y, vertex.z );
  14423. }
  14424. } else {
  14425. // non-indexed BufferGeometry
  14426. position = geometry.attributes.position;
  14427. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14428. for ( j = 0; j < 3; j ++ ) {
  14429. // three edges per triangle, an edge is represented as (index1, index2)
  14430. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14431. index1 = 3 * i + j;
  14432. vertex.fromBufferAttribute( position, index1 );
  14433. vertices.push( vertex.x, vertex.y, vertex.z );
  14434. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14435. vertex.fromBufferAttribute( position, index2 );
  14436. vertices.push( vertex.x, vertex.y, vertex.z );
  14437. }
  14438. }
  14439. }
  14440. }
  14441. // build geometry
  14442. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14443. }
  14444. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14445. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14446. /**
  14447. * @author zz85 / https://github.com/zz85
  14448. * @author Mugen87 / https://github.com/Mugen87
  14449. *
  14450. * Parametric Surfaces Geometry
  14451. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14452. */
  14453. // ParametricGeometry
  14454. function ParametricGeometry( func, slices, stacks ) {
  14455. Geometry.call( this );
  14456. this.type = 'ParametricGeometry';
  14457. this.parameters = {
  14458. func: func,
  14459. slices: slices,
  14460. stacks: stacks
  14461. };
  14462. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14463. this.mergeVertices();
  14464. }
  14465. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14466. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14467. // ParametricBufferGeometry
  14468. function ParametricBufferGeometry( func, slices, stacks ) {
  14469. BufferGeometry.call( this );
  14470. this.type = 'ParametricBufferGeometry';
  14471. this.parameters = {
  14472. func: func,
  14473. slices: slices,
  14474. stacks: stacks
  14475. };
  14476. // buffers
  14477. var indices = [];
  14478. var vertices = [];
  14479. var normals = [];
  14480. var uvs = [];
  14481. var EPS = 0.00001;
  14482. var normal = new Vector3();
  14483. var p0 = new Vector3(), p1 = new Vector3();
  14484. var pu = new Vector3(), pv = new Vector3();
  14485. var i, j;
  14486. // generate vertices, normals and uvs
  14487. var sliceCount = slices + 1;
  14488. for ( i = 0; i <= stacks; i ++ ) {
  14489. var v = i / stacks;
  14490. for ( j = 0; j <= slices; j ++ ) {
  14491. var u = j / slices;
  14492. // vertex
  14493. p0 = func( u, v, p0 );
  14494. vertices.push( p0.x, p0.y, p0.z );
  14495. // normal
  14496. // approximate tangent vectors via finite differences
  14497. if ( u - EPS >= 0 ) {
  14498. p1 = func( u - EPS, v, p1 );
  14499. pu.subVectors( p0, p1 );
  14500. } else {
  14501. p1 = func( u + EPS, v, p1 );
  14502. pu.subVectors( p1, p0 );
  14503. }
  14504. if ( v - EPS >= 0 ) {
  14505. p1 = func( u, v - EPS, p1 );
  14506. pv.subVectors( p0, p1 );
  14507. } else {
  14508. p1 = func( u, v + EPS, p1 );
  14509. pv.subVectors( p1, p0 );
  14510. }
  14511. // cross product of tangent vectors returns surface normal
  14512. normal.crossVectors( pu, pv ).normalize();
  14513. normals.push( normal.x, normal.y, normal.z );
  14514. // uv
  14515. uvs.push( u, v );
  14516. }
  14517. }
  14518. // generate indices
  14519. for ( i = 0; i < stacks; i ++ ) {
  14520. for ( j = 0; j < slices; j ++ ) {
  14521. var a = i * sliceCount + j;
  14522. var b = i * sliceCount + j + 1;
  14523. var c = ( i + 1 ) * sliceCount + j + 1;
  14524. var d = ( i + 1 ) * sliceCount + j;
  14525. // faces one and two
  14526. indices.push( a, b, d );
  14527. indices.push( b, c, d );
  14528. }
  14529. }
  14530. // build geometry
  14531. this.setIndex( indices );
  14532. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14533. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14534. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14535. }
  14536. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14537. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14538. /**
  14539. * @author clockworkgeek / https://github.com/clockworkgeek
  14540. * @author timothypratley / https://github.com/timothypratley
  14541. * @author WestLangley / http://github.com/WestLangley
  14542. * @author Mugen87 / https://github.com/Mugen87
  14543. */
  14544. // PolyhedronGeometry
  14545. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14546. Geometry.call( this );
  14547. this.type = 'PolyhedronGeometry';
  14548. this.parameters = {
  14549. vertices: vertices,
  14550. indices: indices,
  14551. radius: radius,
  14552. detail: detail
  14553. };
  14554. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14555. this.mergeVertices();
  14556. }
  14557. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14558. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14559. // PolyhedronBufferGeometry
  14560. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14561. BufferGeometry.call( this );
  14562. this.type = 'PolyhedronBufferGeometry';
  14563. this.parameters = {
  14564. vertices: vertices,
  14565. indices: indices,
  14566. radius: radius,
  14567. detail: detail
  14568. };
  14569. radius = radius || 1;
  14570. detail = detail || 0;
  14571. // default buffer data
  14572. var vertexBuffer = [];
  14573. var uvBuffer = [];
  14574. // the subdivision creates the vertex buffer data
  14575. subdivide( detail );
  14576. // all vertices should lie on a conceptual sphere with a given radius
  14577. appplyRadius( radius );
  14578. // finally, create the uv data
  14579. generateUVs();
  14580. // build non-indexed geometry
  14581. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14582. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14583. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14584. if ( detail === 0 ) {
  14585. this.computeVertexNormals(); // flat normals
  14586. } else {
  14587. this.normalizeNormals(); // smooth normals
  14588. }
  14589. // helper functions
  14590. function subdivide( detail ) {
  14591. var a = new Vector3();
  14592. var b = new Vector3();
  14593. var c = new Vector3();
  14594. // iterate over all faces and apply a subdivison with the given detail value
  14595. for ( var i = 0; i < indices.length; i += 3 ) {
  14596. // get the vertices of the face
  14597. getVertexByIndex( indices[ i + 0 ], a );
  14598. getVertexByIndex( indices[ i + 1 ], b );
  14599. getVertexByIndex( indices[ i + 2 ], c );
  14600. // perform subdivision
  14601. subdivideFace( a, b, c, detail );
  14602. }
  14603. }
  14604. function subdivideFace( a, b, c, detail ) {
  14605. var cols = Math.pow( 2, detail );
  14606. // we use this multidimensional array as a data structure for creating the subdivision
  14607. var v = [];
  14608. var i, j;
  14609. // construct all of the vertices for this subdivision
  14610. for ( i = 0; i <= cols; i ++ ) {
  14611. v[ i ] = [];
  14612. var aj = a.clone().lerp( c, i / cols );
  14613. var bj = b.clone().lerp( c, i / cols );
  14614. var rows = cols - i;
  14615. for ( j = 0; j <= rows; j ++ ) {
  14616. if ( j === 0 && i === cols ) {
  14617. v[ i ][ j ] = aj;
  14618. } else {
  14619. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14620. }
  14621. }
  14622. }
  14623. // construct all of the faces
  14624. for ( i = 0; i < cols; i ++ ) {
  14625. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14626. var k = Math.floor( j / 2 );
  14627. if ( j % 2 === 0 ) {
  14628. pushVertex( v[ i ][ k + 1 ] );
  14629. pushVertex( v[ i + 1 ][ k ] );
  14630. pushVertex( v[ i ][ k ] );
  14631. } else {
  14632. pushVertex( v[ i ][ k + 1 ] );
  14633. pushVertex( v[ i + 1 ][ k + 1 ] );
  14634. pushVertex( v[ i + 1 ][ k ] );
  14635. }
  14636. }
  14637. }
  14638. }
  14639. function appplyRadius( radius ) {
  14640. var vertex = new Vector3();
  14641. // iterate over the entire buffer and apply the radius to each vertex
  14642. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14643. vertex.x = vertexBuffer[ i + 0 ];
  14644. vertex.y = vertexBuffer[ i + 1 ];
  14645. vertex.z = vertexBuffer[ i + 2 ];
  14646. vertex.normalize().multiplyScalar( radius );
  14647. vertexBuffer[ i + 0 ] = vertex.x;
  14648. vertexBuffer[ i + 1 ] = vertex.y;
  14649. vertexBuffer[ i + 2 ] = vertex.z;
  14650. }
  14651. }
  14652. function generateUVs() {
  14653. var vertex = new Vector3();
  14654. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14655. vertex.x = vertexBuffer[ i + 0 ];
  14656. vertex.y = vertexBuffer[ i + 1 ];
  14657. vertex.z = vertexBuffer[ i + 2 ];
  14658. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14659. var v = inclination( vertex ) / Math.PI + 0.5;
  14660. uvBuffer.push( u, 1 - v );
  14661. }
  14662. correctUVs();
  14663. correctSeam();
  14664. }
  14665. function correctSeam() {
  14666. // handle case when face straddles the seam, see #3269
  14667. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14668. // uv data of a single face
  14669. var x0 = uvBuffer[ i + 0 ];
  14670. var x1 = uvBuffer[ i + 2 ];
  14671. var x2 = uvBuffer[ i + 4 ];
  14672. var max = Math.max( x0, x1, x2 );
  14673. var min = Math.min( x0, x1, x2 );
  14674. // 0.9 is somewhat arbitrary
  14675. if ( max > 0.9 && min < 0.1 ) {
  14676. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14677. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14678. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14679. }
  14680. }
  14681. }
  14682. function pushVertex( vertex ) {
  14683. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14684. }
  14685. function getVertexByIndex( index, vertex ) {
  14686. var stride = index * 3;
  14687. vertex.x = vertices[ stride + 0 ];
  14688. vertex.y = vertices[ stride + 1 ];
  14689. vertex.z = vertices[ stride + 2 ];
  14690. }
  14691. function correctUVs() {
  14692. var a = new Vector3();
  14693. var b = new Vector3();
  14694. var c = new Vector3();
  14695. var centroid = new Vector3();
  14696. var uvA = new Vector2();
  14697. var uvB = new Vector2();
  14698. var uvC = new Vector2();
  14699. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14700. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14701. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14702. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14703. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14704. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14705. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14706. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14707. var azi = azimuth( centroid );
  14708. correctUV( uvA, j + 0, a, azi );
  14709. correctUV( uvB, j + 2, b, azi );
  14710. correctUV( uvC, j + 4, c, azi );
  14711. }
  14712. }
  14713. function correctUV( uv, stride, vector, azimuth ) {
  14714. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14715. uvBuffer[ stride ] = uv.x - 1;
  14716. }
  14717. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14718. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14719. }
  14720. }
  14721. // Angle around the Y axis, counter-clockwise when looking from above.
  14722. function azimuth( vector ) {
  14723. return Math.atan2( vector.z, - vector.x );
  14724. }
  14725. // Angle above the XZ plane.
  14726. function inclination( vector ) {
  14727. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14728. }
  14729. }
  14730. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14731. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14732. /**
  14733. * @author timothypratley / https://github.com/timothypratley
  14734. * @author Mugen87 / https://github.com/Mugen87
  14735. */
  14736. // TetrahedronGeometry
  14737. function TetrahedronGeometry( radius, detail ) {
  14738. Geometry.call( this );
  14739. this.type = 'TetrahedronGeometry';
  14740. this.parameters = {
  14741. radius: radius,
  14742. detail: detail
  14743. };
  14744. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14745. this.mergeVertices();
  14746. }
  14747. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14748. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14749. // TetrahedronBufferGeometry
  14750. function TetrahedronBufferGeometry( radius, detail ) {
  14751. var vertices = [
  14752. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14753. ];
  14754. var indices = [
  14755. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14756. ];
  14757. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14758. this.type = 'TetrahedronBufferGeometry';
  14759. this.parameters = {
  14760. radius: radius,
  14761. detail: detail
  14762. };
  14763. }
  14764. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14765. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14766. /**
  14767. * @author timothypratley / https://github.com/timothypratley
  14768. * @author Mugen87 / https://github.com/Mugen87
  14769. */
  14770. // OctahedronGeometry
  14771. function OctahedronGeometry( radius, detail ) {
  14772. Geometry.call( this );
  14773. this.type = 'OctahedronGeometry';
  14774. this.parameters = {
  14775. radius: radius,
  14776. detail: detail
  14777. };
  14778. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14779. this.mergeVertices();
  14780. }
  14781. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14782. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14783. // OctahedronBufferGeometry
  14784. function OctahedronBufferGeometry( radius, detail ) {
  14785. var vertices = [
  14786. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14787. ];
  14788. var indices = [
  14789. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14790. ];
  14791. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14792. this.type = 'OctahedronBufferGeometry';
  14793. this.parameters = {
  14794. radius: radius,
  14795. detail: detail
  14796. };
  14797. }
  14798. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14799. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14800. /**
  14801. * @author timothypratley / https://github.com/timothypratley
  14802. * @author Mugen87 / https://github.com/Mugen87
  14803. */
  14804. // IcosahedronGeometry
  14805. function IcosahedronGeometry( radius, detail ) {
  14806. Geometry.call( this );
  14807. this.type = 'IcosahedronGeometry';
  14808. this.parameters = {
  14809. radius: radius,
  14810. detail: detail
  14811. };
  14812. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14813. this.mergeVertices();
  14814. }
  14815. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14816. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14817. // IcosahedronBufferGeometry
  14818. function IcosahedronBufferGeometry( radius, detail ) {
  14819. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14820. var vertices = [
  14821. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14822. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14823. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14824. ];
  14825. var indices = [
  14826. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14827. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14828. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14829. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14830. ];
  14831. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14832. this.type = 'IcosahedronBufferGeometry';
  14833. this.parameters = {
  14834. radius: radius,
  14835. detail: detail
  14836. };
  14837. }
  14838. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14839. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14840. /**
  14841. * @author Abe Pazos / https://hamoid.com
  14842. * @author Mugen87 / https://github.com/Mugen87
  14843. */
  14844. // DodecahedronGeometry
  14845. function DodecahedronGeometry( radius, detail ) {
  14846. Geometry.call( this );
  14847. this.type = 'DodecahedronGeometry';
  14848. this.parameters = {
  14849. radius: radius,
  14850. detail: detail
  14851. };
  14852. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14853. this.mergeVertices();
  14854. }
  14855. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14856. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14857. // DodecahedronBufferGeometry
  14858. function DodecahedronBufferGeometry( radius, detail ) {
  14859. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14860. var r = 1 / t;
  14861. var vertices = [
  14862. // (±1, ±1, ±1)
  14863. - 1, - 1, - 1, - 1, - 1, 1,
  14864. - 1, 1, - 1, - 1, 1, 1,
  14865. 1, - 1, - 1, 1, - 1, 1,
  14866. 1, 1, - 1, 1, 1, 1,
  14867. // (0, ±1/φ, ±φ)
  14868. 0, - r, - t, 0, - r, t,
  14869. 0, r, - t, 0, r, t,
  14870. // (±1/φ, ±φ, 0)
  14871. - r, - t, 0, - r, t, 0,
  14872. r, - t, 0, r, t, 0,
  14873. // (±φ, 0, ±1/φ)
  14874. - t, 0, - r, t, 0, - r,
  14875. - t, 0, r, t, 0, r
  14876. ];
  14877. var indices = [
  14878. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14879. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14880. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14881. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14882. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14883. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14884. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14885. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14886. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14887. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14888. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14889. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14890. ];
  14891. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14892. this.type = 'DodecahedronBufferGeometry';
  14893. this.parameters = {
  14894. radius: radius,
  14895. detail: detail
  14896. };
  14897. }
  14898. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14899. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14900. /**
  14901. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14902. * @author WestLangley / https://github.com/WestLangley
  14903. * @author zz85 / https://github.com/zz85
  14904. * @author miningold / https://github.com/miningold
  14905. * @author jonobr1 / https://github.com/jonobr1
  14906. * @author Mugen87 / https://github.com/Mugen87
  14907. *
  14908. */
  14909. // TubeGeometry
  14910. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14911. Geometry.call( this );
  14912. this.type = 'TubeGeometry';
  14913. this.parameters = {
  14914. path: path,
  14915. tubularSegments: tubularSegments,
  14916. radius: radius,
  14917. radialSegments: radialSegments,
  14918. closed: closed
  14919. };
  14920. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14921. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14922. // expose internals
  14923. this.tangents = bufferGeometry.tangents;
  14924. this.normals = bufferGeometry.normals;
  14925. this.binormals = bufferGeometry.binormals;
  14926. // create geometry
  14927. this.fromBufferGeometry( bufferGeometry );
  14928. this.mergeVertices();
  14929. }
  14930. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14931. TubeGeometry.prototype.constructor = TubeGeometry;
  14932. // TubeBufferGeometry
  14933. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14934. BufferGeometry.call( this );
  14935. this.type = 'TubeBufferGeometry';
  14936. this.parameters = {
  14937. path: path,
  14938. tubularSegments: tubularSegments,
  14939. radius: radius,
  14940. radialSegments: radialSegments,
  14941. closed: closed
  14942. };
  14943. tubularSegments = tubularSegments || 64;
  14944. radius = radius || 1;
  14945. radialSegments = radialSegments || 8;
  14946. closed = closed || false;
  14947. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14948. // expose internals
  14949. this.tangents = frames.tangents;
  14950. this.normals = frames.normals;
  14951. this.binormals = frames.binormals;
  14952. // helper variables
  14953. var vertex = new Vector3();
  14954. var normal = new Vector3();
  14955. var uv = new Vector2();
  14956. var i, j;
  14957. // buffer
  14958. var vertices = [];
  14959. var normals = [];
  14960. var uvs = [];
  14961. var indices = [];
  14962. // create buffer data
  14963. generateBufferData();
  14964. // build geometry
  14965. this.setIndex( indices );
  14966. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14967. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14968. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14969. // functions
  14970. function generateBufferData() {
  14971. for ( i = 0; i < tubularSegments; i ++ ) {
  14972. generateSegment( i );
  14973. }
  14974. // if the geometry is not closed, generate the last row of vertices and normals
  14975. // at the regular position on the given path
  14976. //
  14977. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  14978. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  14979. // uvs are generated in a separate function.
  14980. // this makes it easy compute correct values for closed geometries
  14981. generateUVs();
  14982. // finally create faces
  14983. generateIndices();
  14984. }
  14985. function generateSegment( i ) {
  14986. // we use getPointAt to sample evenly distributed points from the given path
  14987. var P = path.getPointAt( i / tubularSegments );
  14988. // retrieve corresponding normal and binormal
  14989. var N = frames.normals[ i ];
  14990. var B = frames.binormals[ i ];
  14991. // generate normals and vertices for the current segment
  14992. for ( j = 0; j <= radialSegments; j ++ ) {
  14993. var v = j / radialSegments * Math.PI * 2;
  14994. var sin = Math.sin( v );
  14995. var cos = - Math.cos( v );
  14996. // normal
  14997. normal.x = ( cos * N.x + sin * B.x );
  14998. normal.y = ( cos * N.y + sin * B.y );
  14999. normal.z = ( cos * N.z + sin * B.z );
  15000. normal.normalize();
  15001. normals.push( normal.x, normal.y, normal.z );
  15002. // vertex
  15003. vertex.x = P.x + radius * normal.x;
  15004. vertex.y = P.y + radius * normal.y;
  15005. vertex.z = P.z + radius * normal.z;
  15006. vertices.push( vertex.x, vertex.y, vertex.z );
  15007. }
  15008. }
  15009. function generateIndices() {
  15010. for ( j = 1; j <= tubularSegments; j ++ ) {
  15011. for ( i = 1; i <= radialSegments; i ++ ) {
  15012. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15013. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15014. var c = ( radialSegments + 1 ) * j + i;
  15015. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15016. // faces
  15017. indices.push( a, b, d );
  15018. indices.push( b, c, d );
  15019. }
  15020. }
  15021. }
  15022. function generateUVs() {
  15023. for ( i = 0; i <= tubularSegments; i ++ ) {
  15024. for ( j = 0; j <= radialSegments; j ++ ) {
  15025. uv.x = i / tubularSegments;
  15026. uv.y = j / radialSegments;
  15027. uvs.push( uv.x, uv.y );
  15028. }
  15029. }
  15030. }
  15031. }
  15032. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15033. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15034. /**
  15035. * @author oosmoxiecode
  15036. * @author Mugen87 / https://github.com/Mugen87
  15037. *
  15038. * based on http://www.blackpawn.com/texts/pqtorus/
  15039. */
  15040. // TorusKnotGeometry
  15041. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15042. Geometry.call( this );
  15043. this.type = 'TorusKnotGeometry';
  15044. this.parameters = {
  15045. radius: radius,
  15046. tube: tube,
  15047. tubularSegments: tubularSegments,
  15048. radialSegments: radialSegments,
  15049. p: p,
  15050. q: q
  15051. };
  15052. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15053. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15054. this.mergeVertices();
  15055. }
  15056. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15057. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15058. // TorusKnotBufferGeometry
  15059. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15060. BufferGeometry.call( this );
  15061. this.type = 'TorusKnotBufferGeometry';
  15062. this.parameters = {
  15063. radius: radius,
  15064. tube: tube,
  15065. tubularSegments: tubularSegments,
  15066. radialSegments: radialSegments,
  15067. p: p,
  15068. q: q
  15069. };
  15070. radius = radius || 100;
  15071. tube = tube || 40;
  15072. tubularSegments = Math.floor( tubularSegments ) || 64;
  15073. radialSegments = Math.floor( radialSegments ) || 8;
  15074. p = p || 2;
  15075. q = q || 3;
  15076. // buffers
  15077. var indices = [];
  15078. var vertices = [];
  15079. var normals = [];
  15080. var uvs = [];
  15081. // helper variables
  15082. var i, j;
  15083. var vertex = new Vector3();
  15084. var normal = new Vector3();
  15085. var P1 = new Vector3();
  15086. var P2 = new Vector3();
  15087. var B = new Vector3();
  15088. var T = new Vector3();
  15089. var N = new Vector3();
  15090. // generate vertices, normals and uvs
  15091. for ( i = 0; i <= tubularSegments; ++ i ) {
  15092. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15093. var u = i / tubularSegments * p * Math.PI * 2;
  15094. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15095. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15096. calculatePositionOnCurve( u, p, q, radius, P1 );
  15097. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15098. // calculate orthonormal basis
  15099. T.subVectors( P2, P1 );
  15100. N.addVectors( P2, P1 );
  15101. B.crossVectors( T, N );
  15102. N.crossVectors( B, T );
  15103. // normalize B, N. T can be ignored, we don't use it
  15104. B.normalize();
  15105. N.normalize();
  15106. for ( j = 0; j <= radialSegments; ++ j ) {
  15107. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15108. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15109. var v = j / radialSegments * Math.PI * 2;
  15110. var cx = - tube * Math.cos( v );
  15111. var cy = tube * Math.sin( v );
  15112. // now calculate the final vertex position.
  15113. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15114. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15115. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15116. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15117. vertices.push( vertex.x, vertex.y, vertex.z );
  15118. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15119. normal.subVectors( vertex, P1 ).normalize();
  15120. normals.push( normal.x, normal.y, normal.z );
  15121. // uv
  15122. uvs.push( i / tubularSegments );
  15123. uvs.push( j / radialSegments );
  15124. }
  15125. }
  15126. // generate indices
  15127. for ( j = 1; j <= tubularSegments; j ++ ) {
  15128. for ( i = 1; i <= radialSegments; i ++ ) {
  15129. // indices
  15130. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15131. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15132. var c = ( radialSegments + 1 ) * j + i;
  15133. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15134. // faces
  15135. indices.push( a, b, d );
  15136. indices.push( b, c, d );
  15137. }
  15138. }
  15139. // build geometry
  15140. this.setIndex( indices );
  15141. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15142. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15143. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15144. // this function calculates the current position on the torus curve
  15145. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15146. var cu = Math.cos( u );
  15147. var su = Math.sin( u );
  15148. var quOverP = q / p * u;
  15149. var cs = Math.cos( quOverP );
  15150. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15151. position.y = radius * ( 2 + cs ) * su * 0.5;
  15152. position.z = radius * Math.sin( quOverP ) * 0.5;
  15153. }
  15154. }
  15155. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15156. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15157. /**
  15158. * @author oosmoxiecode
  15159. * @author mrdoob / http://mrdoob.com/
  15160. * @author Mugen87 / https://github.com/Mugen87
  15161. */
  15162. // TorusGeometry
  15163. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15164. Geometry.call( this );
  15165. this.type = 'TorusGeometry';
  15166. this.parameters = {
  15167. radius: radius,
  15168. tube: tube,
  15169. radialSegments: radialSegments,
  15170. tubularSegments: tubularSegments,
  15171. arc: arc
  15172. };
  15173. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15174. this.mergeVertices();
  15175. }
  15176. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15177. TorusGeometry.prototype.constructor = TorusGeometry;
  15178. // TorusBufferGeometry
  15179. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15180. BufferGeometry.call( this );
  15181. this.type = 'TorusBufferGeometry';
  15182. this.parameters = {
  15183. radius: radius,
  15184. tube: tube,
  15185. radialSegments: radialSegments,
  15186. tubularSegments: tubularSegments,
  15187. arc: arc
  15188. };
  15189. radius = radius || 100;
  15190. tube = tube || 40;
  15191. radialSegments = Math.floor( radialSegments ) || 8;
  15192. tubularSegments = Math.floor( tubularSegments ) || 6;
  15193. arc = arc || Math.PI * 2;
  15194. // buffers
  15195. var indices = [];
  15196. var vertices = [];
  15197. var normals = [];
  15198. var uvs = [];
  15199. // helper variables
  15200. var center = new Vector3();
  15201. var vertex = new Vector3();
  15202. var normal = new Vector3();
  15203. var j, i;
  15204. // generate vertices, normals and uvs
  15205. for ( j = 0; j <= radialSegments; j ++ ) {
  15206. for ( i = 0; i <= tubularSegments; i ++ ) {
  15207. var u = i / tubularSegments * arc;
  15208. var v = j / radialSegments * Math.PI * 2;
  15209. // vertex
  15210. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15211. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15212. vertex.z = tube * Math.sin( v );
  15213. vertices.push( vertex.x, vertex.y, vertex.z );
  15214. // normal
  15215. center.x = radius * Math.cos( u );
  15216. center.y = radius * Math.sin( u );
  15217. normal.subVectors( vertex, center ).normalize();
  15218. normals.push( normal.x, normal.y, normal.z );
  15219. // uv
  15220. uvs.push( i / tubularSegments );
  15221. uvs.push( j / radialSegments );
  15222. }
  15223. }
  15224. // generate indices
  15225. for ( j = 1; j <= radialSegments; j ++ ) {
  15226. for ( i = 1; i <= tubularSegments; i ++ ) {
  15227. // indices
  15228. var a = ( tubularSegments + 1 ) * j + i - 1;
  15229. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15230. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15231. var d = ( tubularSegments + 1 ) * j + i;
  15232. // faces
  15233. indices.push( a, b, d );
  15234. indices.push( b, c, d );
  15235. }
  15236. }
  15237. // build geometry
  15238. this.setIndex( indices );
  15239. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15240. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15241. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15242. }
  15243. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15244. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15245. /**
  15246. * @author zz85 / http://www.lab4games.net/zz85/blog
  15247. */
  15248. var ShapeUtils = {
  15249. // calculate area of the contour polygon
  15250. area: function ( contour ) {
  15251. var n = contour.length;
  15252. var a = 0.0;
  15253. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15254. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15255. }
  15256. return a * 0.5;
  15257. },
  15258. triangulate: ( function () {
  15259. /**
  15260. * This code is a quick port of code written in C++ which was submitted to
  15261. * flipcode.com by John W. Ratcliff // July 22, 2000
  15262. * See original code and more information here:
  15263. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15264. *
  15265. * ported to actionscript by Zevan Rosser
  15266. * www.actionsnippet.com
  15267. *
  15268. * ported to javascript by Joshua Koo
  15269. * http://www.lab4games.net/zz85/blog
  15270. *
  15271. */
  15272. function snip( contour, u, v, w, n, verts ) {
  15273. var p;
  15274. var ax, ay, bx, by;
  15275. var cx, cy, px, py;
  15276. ax = contour[ verts[ u ] ].x;
  15277. ay = contour[ verts[ u ] ].y;
  15278. bx = contour[ verts[ v ] ].x;
  15279. by = contour[ verts[ v ] ].y;
  15280. cx = contour[ verts[ w ] ].x;
  15281. cy = contour[ verts[ w ] ].y;
  15282. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15283. var aX, aY, bX, bY, cX, cY;
  15284. var apx, apy, bpx, bpy, cpx, cpy;
  15285. var cCROSSap, bCROSScp, aCROSSbp;
  15286. aX = cx - bx; aY = cy - by;
  15287. bX = ax - cx; bY = ay - cy;
  15288. cX = bx - ax; cY = by - ay;
  15289. for ( p = 0; p < n; p ++ ) {
  15290. px = contour[ verts[ p ] ].x;
  15291. py = contour[ verts[ p ] ].y;
  15292. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15293. ( ( px === bx ) && ( py === by ) ) ||
  15294. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15295. apx = px - ax; apy = py - ay;
  15296. bpx = px - bx; bpy = py - by;
  15297. cpx = px - cx; cpy = py - cy;
  15298. // see if p is inside triangle abc
  15299. aCROSSbp = aX * bpy - aY * bpx;
  15300. cCROSSap = cX * apy - cY * apx;
  15301. bCROSScp = bX * cpy - bY * cpx;
  15302. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15303. }
  15304. return true;
  15305. }
  15306. // takes in an contour array and returns
  15307. return function triangulate( contour, indices ) {
  15308. var n = contour.length;
  15309. if ( n < 3 ) return null;
  15310. var result = [],
  15311. verts = [],
  15312. vertIndices = [];
  15313. /* we want a counter-clockwise polygon in verts */
  15314. var u, v, w;
  15315. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15316. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15317. } else {
  15318. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15319. }
  15320. var nv = n;
  15321. /* remove nv - 2 vertices, creating 1 triangle every time */
  15322. var count = 2 * nv; /* error detection */
  15323. for ( v = nv - 1; nv > 2; ) {
  15324. /* if we loop, it is probably a non-simple polygon */
  15325. if ( ( count -- ) <= 0 ) {
  15326. //** Triangulate: ERROR - probable bad polygon!
  15327. //throw ( "Warning, unable to triangulate polygon!" );
  15328. //return null;
  15329. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15330. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15331. if ( indices ) return vertIndices;
  15332. return result;
  15333. }
  15334. /* three consecutive vertices in current polygon, <u,v,w> */
  15335. u = v; if ( nv <= u ) u = 0; /* previous */
  15336. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15337. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15338. if ( snip( contour, u, v, w, nv, verts ) ) {
  15339. var a, b, c, s, t;
  15340. /* true names of the vertices */
  15341. a = verts[ u ];
  15342. b = verts[ v ];
  15343. c = verts[ w ];
  15344. /* output Triangle */
  15345. result.push( [ contour[ a ],
  15346. contour[ b ],
  15347. contour[ c ] ] );
  15348. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15349. /* remove v from the remaining polygon */
  15350. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15351. verts[ s ] = verts[ t ];
  15352. }
  15353. nv --;
  15354. /* reset error detection counter */
  15355. count = 2 * nv;
  15356. }
  15357. }
  15358. if ( indices ) return vertIndices;
  15359. return result;
  15360. }
  15361. } )(),
  15362. triangulateShape: function ( contour, holes ) {
  15363. function removeDupEndPts(points) {
  15364. var l = points.length;
  15365. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15366. points.pop();
  15367. }
  15368. }
  15369. removeDupEndPts( contour );
  15370. holes.forEach( removeDupEndPts );
  15371. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15372. // inOtherPt needs to be collinear to the inSegment
  15373. if ( inSegPt1.x !== inSegPt2.x ) {
  15374. if ( inSegPt1.x < inSegPt2.x ) {
  15375. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15376. } else {
  15377. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15378. }
  15379. } else {
  15380. if ( inSegPt1.y < inSegPt2.y ) {
  15381. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15382. } else {
  15383. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15384. }
  15385. }
  15386. }
  15387. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15388. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15389. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15390. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15391. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15392. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15393. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15394. if ( Math.abs( limit ) > Number.EPSILON ) {
  15395. // not parallel
  15396. var perpSeg2;
  15397. if ( limit > 0 ) {
  15398. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15399. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15400. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15401. } else {
  15402. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15403. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15404. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15405. }
  15406. // i.e. to reduce rounding errors
  15407. // intersection at endpoint of segment#1?
  15408. if ( perpSeg2 === 0 ) {
  15409. if ( ( inExcludeAdjacentSegs ) &&
  15410. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15411. return [ inSeg1Pt1 ];
  15412. }
  15413. if ( perpSeg2 === limit ) {
  15414. if ( ( inExcludeAdjacentSegs ) &&
  15415. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15416. return [ inSeg1Pt2 ];
  15417. }
  15418. // intersection at endpoint of segment#2?
  15419. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15420. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15421. // return real intersection point
  15422. var factorSeg1 = perpSeg2 / limit;
  15423. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15424. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15425. } else {
  15426. // parallel or collinear
  15427. if ( ( perpSeg1 !== 0 ) ||
  15428. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15429. // they are collinear or degenerate
  15430. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15431. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15432. // both segments are points
  15433. if ( seg1Pt && seg2Pt ) {
  15434. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15435. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15436. return [ inSeg1Pt1 ]; // they are the same point
  15437. }
  15438. // segment#1 is a single point
  15439. if ( seg1Pt ) {
  15440. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15441. return [ inSeg1Pt1 ];
  15442. }
  15443. // segment#2 is a single point
  15444. if ( seg2Pt ) {
  15445. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15446. return [ inSeg2Pt1 ];
  15447. }
  15448. // they are collinear segments, which might overlap
  15449. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15450. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15451. if ( seg1dx !== 0 ) {
  15452. // the segments are NOT on a vertical line
  15453. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15454. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15455. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15456. } else {
  15457. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15458. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15459. }
  15460. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15461. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15462. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15463. } else {
  15464. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15465. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15466. }
  15467. } else {
  15468. // the segments are on a vertical line
  15469. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15470. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15471. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15472. } else {
  15473. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15474. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15475. }
  15476. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15477. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15478. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15479. } else {
  15480. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15481. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15482. }
  15483. }
  15484. if ( seg1minVal <= seg2minVal ) {
  15485. if ( seg1maxVal < seg2minVal ) return [];
  15486. if ( seg1maxVal === seg2minVal ) {
  15487. if ( inExcludeAdjacentSegs ) return [];
  15488. return [ seg2min ];
  15489. }
  15490. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15491. return [ seg2min, seg2max ];
  15492. } else {
  15493. if ( seg1minVal > seg2maxVal ) return [];
  15494. if ( seg1minVal === seg2maxVal ) {
  15495. if ( inExcludeAdjacentSegs ) return [];
  15496. return [ seg1min ];
  15497. }
  15498. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15499. return [ seg1min, seg2max ];
  15500. }
  15501. }
  15502. }
  15503. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15504. // The order of legs is important
  15505. // translation of all points, so that Vertex is at (0,0)
  15506. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15507. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15508. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15509. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15510. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15511. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15512. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15513. // angle != 180 deg.
  15514. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15515. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15516. if ( from2toAngle > 0 ) {
  15517. // main angle < 180 deg.
  15518. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15519. } else {
  15520. // main angle > 180 deg.
  15521. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15522. }
  15523. } else {
  15524. // angle == 180 deg.
  15525. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15526. return ( from2otherAngle > 0 );
  15527. }
  15528. }
  15529. function removeHoles( contour, holes ) {
  15530. var shape = contour.concat(); // work on this shape
  15531. var hole;
  15532. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15533. // Check if hole point lies within angle around shape point
  15534. var lastShapeIdx = shape.length - 1;
  15535. var prevShapeIdx = inShapeIdx - 1;
  15536. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15537. var nextShapeIdx = inShapeIdx + 1;
  15538. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15539. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15540. if ( ! insideAngle ) {
  15541. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15542. return false;
  15543. }
  15544. // Check if shape point lies within angle around hole point
  15545. var lastHoleIdx = hole.length - 1;
  15546. var prevHoleIdx = inHoleIdx - 1;
  15547. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15548. var nextHoleIdx = inHoleIdx + 1;
  15549. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15550. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15551. if ( ! insideAngle ) {
  15552. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15553. return false;
  15554. }
  15555. return true;
  15556. }
  15557. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15558. // checks for intersections with shape edges
  15559. var sIdx, nextIdx, intersection;
  15560. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15561. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15562. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15563. if ( intersection.length > 0 ) return true;
  15564. }
  15565. return false;
  15566. }
  15567. var indepHoles = [];
  15568. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15569. // checks for intersections with hole edges
  15570. var ihIdx, chkHole,
  15571. hIdx, nextIdx, intersection;
  15572. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15573. chkHole = holes[ indepHoles[ ihIdx ]];
  15574. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15575. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15576. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15577. if ( intersection.length > 0 ) return true;
  15578. }
  15579. }
  15580. return false;
  15581. }
  15582. var holeIndex, shapeIndex,
  15583. shapePt, holePt,
  15584. holeIdx, cutKey, failedCuts = [],
  15585. tmpShape1, tmpShape2,
  15586. tmpHole1, tmpHole2;
  15587. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15588. indepHoles.push( h );
  15589. }
  15590. var minShapeIndex = 0;
  15591. var counter = indepHoles.length * 2;
  15592. while ( indepHoles.length > 0 ) {
  15593. counter --;
  15594. if ( counter < 0 ) {
  15595. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15596. break;
  15597. }
  15598. // search for shape-vertex and hole-vertex,
  15599. // which can be connected without intersections
  15600. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15601. shapePt = shape[ shapeIndex ];
  15602. holeIndex = - 1;
  15603. // search for hole which can be reached without intersections
  15604. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15605. holeIdx = indepHoles[ h ];
  15606. // prevent multiple checks
  15607. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15608. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15609. hole = holes[ holeIdx ];
  15610. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15611. holePt = hole[ h2 ];
  15612. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15613. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15614. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15615. holeIndex = h2;
  15616. indepHoles.splice( h, 1 );
  15617. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15618. tmpShape2 = shape.slice( shapeIndex );
  15619. tmpHole1 = hole.slice( holeIndex );
  15620. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15621. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15622. minShapeIndex = shapeIndex;
  15623. // Debug only, to show the selected cuts
  15624. // glob_CutLines.push( [ shapePt, holePt ] );
  15625. break;
  15626. }
  15627. if ( holeIndex >= 0 ) break; // hole-vertex found
  15628. failedCuts[ cutKey ] = true; // remember failure
  15629. }
  15630. if ( holeIndex >= 0 ) break; // hole-vertex found
  15631. }
  15632. }
  15633. return shape; /* shape with no holes */
  15634. }
  15635. var i, il, f, face,
  15636. key, index,
  15637. allPointsMap = {};
  15638. // 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.
  15639. var allpoints = contour.concat();
  15640. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15641. Array.prototype.push.apply( allpoints, holes[ h ] );
  15642. }
  15643. //console.log( "allpoints",allpoints, allpoints.length );
  15644. // prepare all points map
  15645. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15646. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15647. if ( allPointsMap[ key ] !== undefined ) {
  15648. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15649. }
  15650. allPointsMap[ key ] = i;
  15651. }
  15652. // remove holes by cutting paths to holes and adding them to the shape
  15653. var shapeWithoutHoles = removeHoles( contour, holes );
  15654. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15655. //console.log( "triangles",triangles, triangles.length );
  15656. // check all face vertices against all points map
  15657. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15658. face = triangles[ i ];
  15659. for ( f = 0; f < 3; f ++ ) {
  15660. key = face[ f ].x + ":" + face[ f ].y;
  15661. index = allPointsMap[ key ];
  15662. if ( index !== undefined ) {
  15663. face[ f ] = index;
  15664. }
  15665. }
  15666. }
  15667. return triangles.concat();
  15668. },
  15669. isClockWise: function ( pts ) {
  15670. return ShapeUtils.area( pts ) < 0;
  15671. }
  15672. };
  15673. /**
  15674. * @author zz85 / http://www.lab4games.net/zz85/blog
  15675. *
  15676. * Creates extruded geometry from a path shape.
  15677. *
  15678. * parameters = {
  15679. *
  15680. * curveSegments: <int>, // number of points on the curves
  15681. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15682. * amount: <int>, // Depth to extrude the shape
  15683. *
  15684. * bevelEnabled: <bool>, // turn on bevel
  15685. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15686. * bevelSize: <float>, // how far from shape outline is bevel
  15687. * bevelSegments: <int>, // number of bevel layers
  15688. *
  15689. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15690. * frames: <Object> // containing arrays of tangents, normals, binormals
  15691. *
  15692. * UVGenerator: <Object> // object that provides UV generator functions
  15693. *
  15694. * }
  15695. */
  15696. // ExtrudeGeometry
  15697. function ExtrudeGeometry( shapes, options ) {
  15698. Geometry.call( this );
  15699. this.type = 'ExtrudeGeometry';
  15700. this.parameters = {
  15701. shapes: shapes,
  15702. options: options
  15703. };
  15704. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  15705. this.mergeVertices();
  15706. }
  15707. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15708. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15709. // ExtrudeBufferGeometry
  15710. function ExtrudeBufferGeometry( shapes, options ) {
  15711. if ( typeof ( shapes ) === "undefined" ) {
  15712. shapes = [];
  15713. return;
  15714. }
  15715. BufferGeometry.call( this );
  15716. this.type = 'ExtrudeBufferGeometry';
  15717. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15718. this.addShapeList( shapes, options );
  15719. this.computeVertexNormals();
  15720. // can't really use automatic vertex normals
  15721. // as then front and back sides get smoothed too
  15722. // should do separate smoothing just for sides
  15723. //this.computeVertexNormals();
  15724. //console.log( "took", ( Date.now() - startTime ) );
  15725. }
  15726. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15727. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  15728. ExtrudeBufferGeometry.prototype.getArrays = function () {
  15729. var positionAttribute = this.getAttribute( "position" );
  15730. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  15731. var uvAttribute = this.getAttribute( "uv" );
  15732. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  15733. var IndexAttribute = this.index;
  15734. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  15735. return {
  15736. position: verticesArray,
  15737. uv: uvArray,
  15738. index: indicesArray
  15739. };
  15740. };
  15741. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  15742. var sl = shapes.length;
  15743. options.arrays = this.getArrays();
  15744. for ( var s = 0; s < sl; s ++ ) {
  15745. var shape = shapes[ s ];
  15746. this.addShape( shape, options );
  15747. }
  15748. this.setIndex( options.arrays.index );
  15749. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  15750. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  15751. };
  15752. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  15753. var arrays = options.arrays ? options.arrays : this.getArrays();
  15754. var verticesArray = arrays.position;
  15755. var indicesArray = arrays.index;
  15756. var uvArray = arrays.uv;
  15757. var placeholder = [];
  15758. var amount = options.amount !== undefined ? options.amount : 100;
  15759. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15760. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15761. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15762. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15763. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15764. var steps = options.steps !== undefined ? options.steps : 1;
  15765. var extrudePath = options.extrudePath;
  15766. var extrudePts, extrudeByPath = false;
  15767. // Use default WorldUVGenerator if no UV generators are specified.
  15768. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15769. var splineTube, binormal, normal, position2;
  15770. if ( extrudePath ) {
  15771. extrudePts = extrudePath.getSpacedPoints( steps );
  15772. extrudeByPath = true;
  15773. bevelEnabled = false; // bevels not supported for path extrusion
  15774. // SETUP TNB variables
  15775. // TODO1 - have a .isClosed in spline?
  15776. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15777. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15778. binormal = new Vector3();
  15779. normal = new Vector3();
  15780. position2 = new Vector3();
  15781. }
  15782. // Safeguards if bevels are not enabled
  15783. if ( ! bevelEnabled ) {
  15784. bevelSegments = 0;
  15785. bevelThickness = 0;
  15786. bevelSize = 0;
  15787. }
  15788. // Variables initialization
  15789. var ahole, h, hl; // looping of holes
  15790. var scope = this;
  15791. var shapePoints = shape.extractPoints( curveSegments );
  15792. var vertices = shapePoints.shape;
  15793. var holes = shapePoints.holes;
  15794. var reverse = ! ShapeUtils.isClockWise( vertices );
  15795. if ( reverse ) {
  15796. vertices = vertices.reverse();
  15797. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15798. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15799. ahole = holes[ h ];
  15800. if ( ShapeUtils.isClockWise( ahole ) ) {
  15801. holes[ h ] = ahole.reverse();
  15802. }
  15803. }
  15804. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15805. }
  15806. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15807. /* Vertices */
  15808. var contour = vertices; // vertices has all points but contour has only points of circumference
  15809. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15810. ahole = holes[ h ];
  15811. vertices = vertices.concat( ahole );
  15812. }
  15813. function scalePt2( pt, vec, size ) {
  15814. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15815. return vec.clone().multiplyScalar( size ).add( pt );
  15816. }
  15817. var b, bs, t, z,
  15818. vert, vlen = vertices.length,
  15819. face, flen = faces.length;
  15820. // Find directions for point movement
  15821. function getBevelVec( inPt, inPrev, inNext ) {
  15822. // computes for inPt the corresponding point inPt' on a new contour
  15823. // shifted by 1 unit (length of normalized vector) to the left
  15824. // if we walk along contour clockwise, this new contour is outside the old one
  15825. //
  15826. // inPt' is the intersection of the two lines parallel to the two
  15827. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15828. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15829. // good reading for geometry algorithms (here: line-line intersection)
  15830. // http://geomalgorithms.com/a05-_intersect-1.html
  15831. var v_prev_x = inPt.x - inPrev.x,
  15832. v_prev_y = inPt.y - inPrev.y;
  15833. var v_next_x = inNext.x - inPt.x,
  15834. v_next_y = inNext.y - inPt.y;
  15835. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15836. // check for collinear edges
  15837. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15838. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15839. // not collinear
  15840. // length of vectors for normalizing
  15841. var v_prev_len = Math.sqrt( v_prev_lensq );
  15842. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15843. // shift adjacent points by unit vectors to the left
  15844. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15845. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15846. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15847. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15848. // scaling factor for v_prev to intersection point
  15849. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15850. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15851. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15852. // vector from inPt to intersection point
  15853. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15854. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15855. // Don't normalize!, otherwise sharp corners become ugly
  15856. // but prevent crazy spikes
  15857. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15858. if ( v_trans_lensq <= 2 ) {
  15859. return new Vector2( v_trans_x, v_trans_y );
  15860. } else {
  15861. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15862. }
  15863. } else {
  15864. // handle special case of collinear edges
  15865. var direction_eq = false; // assumes: opposite
  15866. if ( v_prev_x > Number.EPSILON ) {
  15867. if ( v_next_x > Number.EPSILON ) {
  15868. direction_eq = true;
  15869. }
  15870. } else {
  15871. if ( v_prev_x < - Number.EPSILON ) {
  15872. if ( v_next_x < - Number.EPSILON ) {
  15873. direction_eq = true;
  15874. }
  15875. } else {
  15876. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15877. direction_eq = true;
  15878. }
  15879. }
  15880. }
  15881. if ( direction_eq ) {
  15882. // console.log("Warning: lines are a straight sequence");
  15883. v_trans_x = - v_prev_y;
  15884. v_trans_y = v_prev_x;
  15885. shrink_by = Math.sqrt( v_prev_lensq );
  15886. } else {
  15887. // console.log("Warning: lines are a straight spike");
  15888. v_trans_x = v_prev_x;
  15889. v_trans_y = v_prev_y;
  15890. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15891. }
  15892. }
  15893. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15894. }
  15895. var contourMovements = [];
  15896. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15897. if ( j === il ) j = 0;
  15898. if ( k === il ) k = 0;
  15899. // (j)---(i)---(k)
  15900. // console.log('i,j,k', i, j , k)
  15901. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15902. }
  15903. var holesMovements = [],
  15904. oneHoleMovements, verticesMovements = contourMovements.concat();
  15905. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15906. ahole = holes[ h ];
  15907. oneHoleMovements = [];
  15908. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15909. if ( j === il ) j = 0;
  15910. if ( k === il ) k = 0;
  15911. // (j)---(i)---(k)
  15912. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15913. }
  15914. holesMovements.push( oneHoleMovements );
  15915. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15916. }
  15917. // Loop bevelSegments, 1 for the front, 1 for the back
  15918. for ( b = 0; b < bevelSegments; b ++ ) {
  15919. //for ( b = bevelSegments; b > 0; b -- ) {
  15920. t = b / bevelSegments;
  15921. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15922. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15923. // contract shape
  15924. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15925. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15926. v( vert.x, vert.y, - z );
  15927. }
  15928. // expand holes
  15929. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15930. ahole = holes[ h ];
  15931. oneHoleMovements = holesMovements[ h ];
  15932. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15933. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15934. v( vert.x, vert.y, - z );
  15935. }
  15936. }
  15937. }
  15938. bs = bevelSize;
  15939. // Back facing vertices
  15940. for ( i = 0; i < vlen; i ++ ) {
  15941. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15942. if ( ! extrudeByPath ) {
  15943. v( vert.x, vert.y, 0 );
  15944. } else {
  15945. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15946. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15947. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15948. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15949. v( position2.x, position2.y, position2.z );
  15950. }
  15951. }
  15952. // Add stepped vertices...
  15953. // Including front facing vertices
  15954. var s;
  15955. for ( s = 1; s <= steps; s ++ ) {
  15956. for ( i = 0; i < vlen; i ++ ) {
  15957. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15958. if ( ! extrudeByPath ) {
  15959. v( vert.x, vert.y, amount / steps * s );
  15960. } else {
  15961. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15962. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15963. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15964. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15965. v( position2.x, position2.y, position2.z );
  15966. }
  15967. }
  15968. }
  15969. // Add bevel segments planes
  15970. //for ( b = 1; b <= bevelSegments; b ++ ) {
  15971. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  15972. t = b / bevelSegments;
  15973. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15974. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15975. // contract shape
  15976. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15977. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15978. v( vert.x, vert.y, amount + z );
  15979. }
  15980. // expand holes
  15981. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15982. ahole = holes[ h ];
  15983. oneHoleMovements = holesMovements[ h ];
  15984. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15985. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15986. if ( ! extrudeByPath ) {
  15987. v( vert.x, vert.y, amount + z );
  15988. } else {
  15989. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  15990. }
  15991. }
  15992. }
  15993. }
  15994. /* Faces */
  15995. // Top and bottom faces
  15996. buildLidFaces();
  15997. // Sides faces
  15998. buildSideFaces();
  15999. ///// Internal functions
  16000. function buildLidFaces() {
  16001. var start = verticesArray.length/3;
  16002. if ( bevelEnabled ) {
  16003. var layer = 0; // steps + 1
  16004. var offset = vlen * layer;
  16005. // Bottom faces
  16006. for ( i = 0; i < flen; i ++ ) {
  16007. face = faces[ i ];
  16008. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16009. }
  16010. layer = steps + bevelSegments * 2;
  16011. offset = vlen * layer;
  16012. // Top faces
  16013. for ( i = 0; i < flen; i ++ ) {
  16014. face = faces[ i ];
  16015. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16016. }
  16017. } else {
  16018. // Bottom faces
  16019. for ( i = 0; i < flen; i ++ ) {
  16020. face = faces[ i ];
  16021. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16022. }
  16023. // Top faces
  16024. for ( i = 0; i < flen; i ++ ) {
  16025. face = faces[ i ];
  16026. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16027. }
  16028. }
  16029. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16030. }
  16031. // Create faces for the z-sides of the shape
  16032. function buildSideFaces() {
  16033. var start = verticesArray.length/3;
  16034. var layeroffset = 0;
  16035. sidewalls( contour, layeroffset );
  16036. layeroffset += contour.length;
  16037. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16038. ahole = holes[ h ];
  16039. sidewalls( ahole, layeroffset );
  16040. //, true
  16041. layeroffset += ahole.length;
  16042. }
  16043. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16044. }
  16045. function sidewalls( contour, layeroffset ) {
  16046. var j, k;
  16047. i = contour.length;
  16048. while ( -- i >= 0 ) {
  16049. j = i;
  16050. k = i - 1;
  16051. if ( k < 0 ) k = contour.length - 1;
  16052. //console.log('b', i,j, i-1, k,vertices.length);
  16053. var s = 0,
  16054. sl = steps + bevelSegments * 2;
  16055. for ( s = 0; s < sl; s ++ ) {
  16056. var slen1 = vlen * s;
  16057. var slen2 = vlen * ( s + 1 );
  16058. var a = layeroffset + j + slen1,
  16059. b = layeroffset + k + slen1,
  16060. c = layeroffset + k + slen2,
  16061. d = layeroffset + j + slen2;
  16062. f4( a, b, c, d, contour, s, sl, j, k );
  16063. }
  16064. }
  16065. }
  16066. function v( x, y, z ) {
  16067. placeholder.push( x );
  16068. placeholder.push( y );
  16069. placeholder.push( z );
  16070. }
  16071. function f3( a, b, c ) {
  16072. addVertex( a );
  16073. addVertex( b );
  16074. addVertex( c );
  16075. var nextIndex = verticesArray.length / 3;
  16076. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16077. addUV( uvs[ 0 ] );
  16078. addUV( uvs[ 1 ] );
  16079. addUV( uvs[ 2 ] );
  16080. }
  16081. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16082. addVertex( a );
  16083. addVertex( b );
  16084. addVertex( d );
  16085. addVertex( b );
  16086. addVertex( c );
  16087. addVertex( d );
  16088. var nextIndex = verticesArray.length / 3;
  16089. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16090. addUV( uvs[ 0 ] );
  16091. addUV( uvs[ 1 ] );
  16092. addUV( uvs[ 3 ] );
  16093. addUV( uvs[ 1 ] );
  16094. addUV( uvs[ 2 ] );
  16095. addUV( uvs[ 3 ] );
  16096. }
  16097. function addVertex( index ) {
  16098. indicesArray.push( verticesArray.length / 3 );
  16099. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16100. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16101. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16102. }
  16103. function addUV( vector2 ) {
  16104. uvArray.push( vector2.x );
  16105. uvArray.push( vector2.y );
  16106. }
  16107. if ( ! options.arrays ) {
  16108. this.setIndex( indicesArray );
  16109. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16110. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16111. }
  16112. };
  16113. ExtrudeGeometry.WorldUVGenerator = {
  16114. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16115. var a_x = vertices[ indexA * 3 ];
  16116. var a_y = vertices[ indexA * 3 + 1 ];
  16117. var b_x = vertices[ indexB * 3 ];
  16118. var b_y = vertices[ indexB * 3 + 1 ];
  16119. var c_x = vertices[ indexC * 3 ];
  16120. var c_y = vertices[ indexC * 3 + 1 ];
  16121. return [
  16122. new Vector2( a_x, a_y ),
  16123. new Vector2( b_x, b_y ),
  16124. new Vector2( c_x, c_y )
  16125. ];
  16126. },
  16127. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16128. var a_x = vertices[ indexA * 3 ];
  16129. var a_y = vertices[ indexA * 3 + 1 ];
  16130. var a_z = vertices[ indexA * 3 + 2 ];
  16131. var b_x = vertices[ indexB * 3 ];
  16132. var b_y = vertices[ indexB * 3 + 1 ];
  16133. var b_z = vertices[ indexB * 3 + 2 ];
  16134. var c_x = vertices[ indexC * 3 ];
  16135. var c_y = vertices[ indexC * 3 + 1 ];
  16136. var c_z = vertices[ indexC * 3 + 2 ];
  16137. var d_x = vertices[ indexD * 3 ];
  16138. var d_y = vertices[ indexD * 3 + 1 ];
  16139. var d_z = vertices[ indexD * 3 + 2 ];
  16140. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16141. return [
  16142. new Vector2( a_x, 1 - a_z ),
  16143. new Vector2( b_x, 1 - b_z ),
  16144. new Vector2( c_x, 1 - c_z ),
  16145. new Vector2( d_x, 1 - d_z )
  16146. ];
  16147. } else {
  16148. return [
  16149. new Vector2( a_y, 1 - a_z ),
  16150. new Vector2( b_y, 1 - b_z ),
  16151. new Vector2( c_y, 1 - c_z ),
  16152. new Vector2( d_y, 1 - d_z )
  16153. ];
  16154. }
  16155. }
  16156. };
  16157. /**
  16158. * @author zz85 / http://www.lab4games.net/zz85/blog
  16159. * @author alteredq / http://alteredqualia.com/
  16160. *
  16161. * Text = 3D Text
  16162. *
  16163. * parameters = {
  16164. * font: <THREE.Font>, // font
  16165. *
  16166. * size: <float>, // size of the text
  16167. * height: <float>, // thickness to extrude text
  16168. * curveSegments: <int>, // number of points on the curves
  16169. *
  16170. * bevelEnabled: <bool>, // turn on bevel
  16171. * bevelThickness: <float>, // how deep into text bevel goes
  16172. * bevelSize: <float> // how far from text outline is bevel
  16173. * }
  16174. */
  16175. // TextGeometry
  16176. function TextGeometry( text, parameters ) {
  16177. Geometry.call( this );
  16178. this.type = 'TextGeometry';
  16179. this.parameters = {
  16180. text: text,
  16181. parameters: parameters
  16182. };
  16183. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16184. this.mergeVertices();
  16185. }
  16186. TextGeometry.prototype = Object.create( Geometry.prototype );
  16187. TextGeometry.prototype.constructor = TextGeometry;
  16188. // TextBufferGeometry
  16189. function TextBufferGeometry( text, parameters ) {
  16190. parameters = parameters || {};
  16191. var font = parameters.font;
  16192. if ( ( font && font.isFont ) === false ) {
  16193. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16194. return new Geometry();
  16195. }
  16196. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16197. // translate parameters to ExtrudeGeometry API
  16198. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16199. // defaults
  16200. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16201. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16202. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16203. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16204. this.type = 'TextBufferGeometry';
  16205. }
  16206. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16207. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16208. /**
  16209. * @author mrdoob / http://mrdoob.com/
  16210. * @author benaadams / https://twitter.com/ben_a_adams
  16211. * @author Mugen87 / https://github.com/Mugen87
  16212. */
  16213. // SphereGeometry
  16214. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16215. Geometry.call( this );
  16216. this.type = 'SphereGeometry';
  16217. this.parameters = {
  16218. radius: radius,
  16219. widthSegments: widthSegments,
  16220. heightSegments: heightSegments,
  16221. phiStart: phiStart,
  16222. phiLength: phiLength,
  16223. thetaStart: thetaStart,
  16224. thetaLength: thetaLength
  16225. };
  16226. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16227. this.mergeVertices();
  16228. }
  16229. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16230. SphereGeometry.prototype.constructor = SphereGeometry;
  16231. // SphereBufferGeometry
  16232. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16233. BufferGeometry.call( this );
  16234. this.type = 'SphereBufferGeometry';
  16235. this.parameters = {
  16236. radius: radius,
  16237. widthSegments: widthSegments,
  16238. heightSegments: heightSegments,
  16239. phiStart: phiStart,
  16240. phiLength: phiLength,
  16241. thetaStart: thetaStart,
  16242. thetaLength: thetaLength
  16243. };
  16244. radius = radius || 50;
  16245. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16246. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16247. phiStart = phiStart !== undefined ? phiStart : 0;
  16248. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16249. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16250. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16251. var thetaEnd = thetaStart + thetaLength;
  16252. var ix, iy;
  16253. var index = 0;
  16254. var grid = [];
  16255. var vertex = new Vector3();
  16256. var normal = new Vector3();
  16257. // buffers
  16258. var indices = [];
  16259. var vertices = [];
  16260. var normals = [];
  16261. var uvs = [];
  16262. // generate vertices, normals and uvs
  16263. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16264. var verticesRow = [];
  16265. var v = iy / heightSegments;
  16266. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16267. var u = ix / widthSegments;
  16268. // vertex
  16269. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16270. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16271. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16272. vertices.push( vertex.x, vertex.y, vertex.z );
  16273. // normal
  16274. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16275. normals.push( normal.x, normal.y, normal.z );
  16276. // uv
  16277. uvs.push( u, 1 - v );
  16278. verticesRow.push( index ++ );
  16279. }
  16280. grid.push( verticesRow );
  16281. }
  16282. // indices
  16283. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16284. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16285. var a = grid[ iy ][ ix + 1 ];
  16286. var b = grid[ iy ][ ix ];
  16287. var c = grid[ iy + 1 ][ ix ];
  16288. var d = grid[ iy + 1 ][ ix + 1 ];
  16289. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16290. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16291. }
  16292. }
  16293. // build geometry
  16294. this.setIndex( indices );
  16295. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16296. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16297. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16298. }
  16299. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16300. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16301. /**
  16302. * @author Kaleb Murphy
  16303. * @author Mugen87 / https://github.com/Mugen87
  16304. */
  16305. // RingGeometry
  16306. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16307. Geometry.call( this );
  16308. this.type = 'RingGeometry';
  16309. this.parameters = {
  16310. innerRadius: innerRadius,
  16311. outerRadius: outerRadius,
  16312. thetaSegments: thetaSegments,
  16313. phiSegments: phiSegments,
  16314. thetaStart: thetaStart,
  16315. thetaLength: thetaLength
  16316. };
  16317. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16318. this.mergeVertices();
  16319. }
  16320. RingGeometry.prototype = Object.create( Geometry.prototype );
  16321. RingGeometry.prototype.constructor = RingGeometry;
  16322. // RingBufferGeometry
  16323. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16324. BufferGeometry.call( this );
  16325. this.type = 'RingBufferGeometry';
  16326. this.parameters = {
  16327. innerRadius: innerRadius,
  16328. outerRadius: outerRadius,
  16329. thetaSegments: thetaSegments,
  16330. phiSegments: phiSegments,
  16331. thetaStart: thetaStart,
  16332. thetaLength: thetaLength
  16333. };
  16334. innerRadius = innerRadius || 20;
  16335. outerRadius = outerRadius || 50;
  16336. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16337. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16338. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16339. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16340. // buffers
  16341. var indices = [];
  16342. var vertices = [];
  16343. var normals = [];
  16344. var uvs = [];
  16345. // some helper variables
  16346. var segment;
  16347. var radius = innerRadius;
  16348. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16349. var vertex = new Vector3();
  16350. var uv = new Vector2();
  16351. var j, i;
  16352. // generate vertices, normals and uvs
  16353. for ( j = 0; j <= phiSegments; j ++ ) {
  16354. for ( i = 0; i <= thetaSegments; i ++ ) {
  16355. // values are generate from the inside of the ring to the outside
  16356. segment = thetaStart + i / thetaSegments * thetaLength;
  16357. // vertex
  16358. vertex.x = radius * Math.cos( segment );
  16359. vertex.y = radius * Math.sin( segment );
  16360. vertices.push( vertex.x, vertex.y, vertex.z );
  16361. // normal
  16362. normals.push( 0, 0, 1 );
  16363. // uv
  16364. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16365. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16366. uvs.push( uv.x, uv.y );
  16367. }
  16368. // increase the radius for next row of vertices
  16369. radius += radiusStep;
  16370. }
  16371. // indices
  16372. for ( j = 0; j < phiSegments; j ++ ) {
  16373. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16374. for ( i = 0; i < thetaSegments; i ++ ) {
  16375. segment = i + thetaSegmentLevel;
  16376. var a = segment;
  16377. var b = segment + thetaSegments + 1;
  16378. var c = segment + thetaSegments + 2;
  16379. var d = segment + 1;
  16380. // faces
  16381. indices.push( a, b, d );
  16382. indices.push( b, c, d );
  16383. }
  16384. }
  16385. // build geometry
  16386. this.setIndex( indices );
  16387. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16388. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16389. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16390. }
  16391. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16392. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16393. /**
  16394. * @author astrodud / http://astrodud.isgreat.org/
  16395. * @author zz85 / https://github.com/zz85
  16396. * @author bhouston / http://clara.io
  16397. * @author Mugen87 / https://github.com/Mugen87
  16398. */
  16399. // LatheGeometry
  16400. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16401. Geometry.call( this );
  16402. this.type = 'LatheGeometry';
  16403. this.parameters = {
  16404. points: points,
  16405. segments: segments,
  16406. phiStart: phiStart,
  16407. phiLength: phiLength
  16408. };
  16409. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16410. this.mergeVertices();
  16411. }
  16412. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16413. LatheGeometry.prototype.constructor = LatheGeometry;
  16414. // LatheBufferGeometry
  16415. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16416. BufferGeometry.call( this );
  16417. this.type = 'LatheBufferGeometry';
  16418. this.parameters = {
  16419. points: points,
  16420. segments: segments,
  16421. phiStart: phiStart,
  16422. phiLength: phiLength
  16423. };
  16424. segments = Math.floor( segments ) || 12;
  16425. phiStart = phiStart || 0;
  16426. phiLength = phiLength || Math.PI * 2;
  16427. // clamp phiLength so it's in range of [ 0, 2PI ]
  16428. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16429. // buffers
  16430. var indices = [];
  16431. var vertices = [];
  16432. var uvs = [];
  16433. // helper variables
  16434. var base;
  16435. var inverseSegments = 1.0 / segments;
  16436. var vertex = new Vector3();
  16437. var uv = new Vector2();
  16438. var i, j;
  16439. // generate vertices and uvs
  16440. for ( i = 0; i <= segments; i ++ ) {
  16441. var phi = phiStart + i * inverseSegments * phiLength;
  16442. var sin = Math.sin( phi );
  16443. var cos = Math.cos( phi );
  16444. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16445. // vertex
  16446. vertex.x = points[ j ].x * sin;
  16447. vertex.y = points[ j ].y;
  16448. vertex.z = points[ j ].x * cos;
  16449. vertices.push( vertex.x, vertex.y, vertex.z );
  16450. // uv
  16451. uv.x = i / segments;
  16452. uv.y = j / ( points.length - 1 );
  16453. uvs.push( uv.x, uv.y );
  16454. }
  16455. }
  16456. // indices
  16457. for ( i = 0; i < segments; i ++ ) {
  16458. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16459. base = j + i * points.length;
  16460. var a = base;
  16461. var b = base + points.length;
  16462. var c = base + points.length + 1;
  16463. var d = base + 1;
  16464. // faces
  16465. indices.push( a, b, d );
  16466. indices.push( b, c, d );
  16467. }
  16468. }
  16469. // build geometry
  16470. this.setIndex( indices );
  16471. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16472. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16473. // generate normals
  16474. this.computeVertexNormals();
  16475. // if the geometry is closed, we need to average the normals along the seam.
  16476. // because the corresponding vertices are identical (but still have different UVs).
  16477. if ( phiLength === Math.PI * 2 ) {
  16478. var normals = this.attributes.normal.array;
  16479. var n1 = new Vector3();
  16480. var n2 = new Vector3();
  16481. var n = new Vector3();
  16482. // this is the buffer offset for the last line of vertices
  16483. base = segments * points.length * 3;
  16484. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16485. // select the normal of the vertex in the first line
  16486. n1.x = normals[ j + 0 ];
  16487. n1.y = normals[ j + 1 ];
  16488. n1.z = normals[ j + 2 ];
  16489. // select the normal of the vertex in the last line
  16490. n2.x = normals[ base + j + 0 ];
  16491. n2.y = normals[ base + j + 1 ];
  16492. n2.z = normals[ base + j + 2 ];
  16493. // average normals
  16494. n.addVectors( n1, n2 ).normalize();
  16495. // assign the new values to both normals
  16496. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16497. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16498. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16499. }
  16500. }
  16501. }
  16502. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16503. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16504. /**
  16505. * @author jonobr1 / http://jonobr1.com
  16506. * @author Mugen87 / https://github.com/Mugen87
  16507. */
  16508. // ShapeGeometry
  16509. function ShapeGeometry( shapes, curveSegments ) {
  16510. Geometry.call( this );
  16511. this.type = 'ShapeGeometry';
  16512. if ( typeof curveSegments === 'object' ) {
  16513. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16514. curveSegments = curveSegments.curveSegments;
  16515. }
  16516. this.parameters = {
  16517. shapes: shapes,
  16518. curveSegments: curveSegments
  16519. };
  16520. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16521. this.mergeVertices();
  16522. }
  16523. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16524. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16525. // ShapeBufferGeometry
  16526. function ShapeBufferGeometry( shapes, curveSegments ) {
  16527. BufferGeometry.call( this );
  16528. this.type = 'ShapeBufferGeometry';
  16529. this.parameters = {
  16530. shapes: shapes,
  16531. curveSegments: curveSegments
  16532. };
  16533. curveSegments = curveSegments || 12;
  16534. // buffers
  16535. var indices = [];
  16536. var vertices = [];
  16537. var normals = [];
  16538. var uvs = [];
  16539. // helper variables
  16540. var groupStart = 0;
  16541. var groupCount = 0;
  16542. // allow single and array values for "shapes" parameter
  16543. if ( Array.isArray( shapes ) === false ) {
  16544. addShape( shapes );
  16545. } else {
  16546. for ( var i = 0; i < shapes.length; i ++ ) {
  16547. addShape( shapes[ i ] );
  16548. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16549. groupStart += groupCount;
  16550. groupCount = 0;
  16551. }
  16552. }
  16553. // build geometry
  16554. this.setIndex( indices );
  16555. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16556. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16557. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16558. // helper functions
  16559. function addShape( shape ) {
  16560. var i, l, shapeHole;
  16561. var indexOffset = vertices.length / 3;
  16562. var points = shape.extractPoints( curveSegments );
  16563. var shapeVertices = points.shape;
  16564. var shapeHoles = points.holes;
  16565. // check direction of vertices
  16566. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16567. shapeVertices = shapeVertices.reverse();
  16568. // also check if holes are in the opposite direction
  16569. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16570. shapeHole = shapeHoles[ i ];
  16571. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16572. shapeHoles[ i ] = shapeHole.reverse();
  16573. }
  16574. }
  16575. }
  16576. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16577. // join vertices of inner and outer paths to a single array
  16578. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16579. shapeHole = shapeHoles[ i ];
  16580. shapeVertices = shapeVertices.concat( shapeHole );
  16581. }
  16582. // vertices, normals, uvs
  16583. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16584. var vertex = shapeVertices[ i ];
  16585. vertices.push( vertex.x, vertex.y, 0 );
  16586. normals.push( 0, 0, 1 );
  16587. uvs.push( vertex.x, vertex.y ); // world uvs
  16588. }
  16589. // incides
  16590. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16591. var face = faces[ i ];
  16592. var a = face[ 0 ] + indexOffset;
  16593. var b = face[ 1 ] + indexOffset;
  16594. var c = face[ 2 ] + indexOffset;
  16595. indices.push( a, b, c );
  16596. groupCount += 3;
  16597. }
  16598. }
  16599. }
  16600. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16601. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16602. /**
  16603. * @author WestLangley / http://github.com/WestLangley
  16604. * @author Mugen87 / https://github.com/Mugen87
  16605. */
  16606. function EdgesGeometry( geometry, thresholdAngle ) {
  16607. BufferGeometry.call( this );
  16608. this.type = 'EdgesGeometry';
  16609. this.parameters = {
  16610. thresholdAngle: thresholdAngle
  16611. };
  16612. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16613. // buffer
  16614. var vertices = [];
  16615. // helper variables
  16616. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16617. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16618. var key, keys = [ 'a', 'b', 'c' ];
  16619. // prepare source geometry
  16620. var geometry2;
  16621. if ( geometry.isBufferGeometry ) {
  16622. geometry2 = new Geometry();
  16623. geometry2.fromBufferGeometry( geometry );
  16624. } else {
  16625. geometry2 = geometry.clone();
  16626. }
  16627. geometry2.mergeVertices();
  16628. geometry2.computeFaceNormals();
  16629. var sourceVertices = geometry2.vertices;
  16630. var faces = geometry2.faces;
  16631. // now create a data structure where each entry represents an edge with its adjoining faces
  16632. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16633. var face = faces[ i ];
  16634. for ( var j = 0; j < 3; j ++ ) {
  16635. edge1 = face[ keys[ j ] ];
  16636. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16637. edge[ 0 ] = Math.min( edge1, edge2 );
  16638. edge[ 1 ] = Math.max( edge1, edge2 );
  16639. key = edge[ 0 ] + ',' + edge[ 1 ];
  16640. if ( edges[ key ] === undefined ) {
  16641. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  16642. } else {
  16643. edges[ key ].face2 = i;
  16644. }
  16645. }
  16646. }
  16647. // generate vertices
  16648. for ( key in edges ) {
  16649. var e = edges[ key ];
  16650. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16651. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  16652. var vertex = sourceVertices[ e.index1 ];
  16653. vertices.push( vertex.x, vertex.y, vertex.z );
  16654. vertex = sourceVertices[ e.index2 ];
  16655. vertices.push( vertex.x, vertex.y, vertex.z );
  16656. }
  16657. }
  16658. // build geometry
  16659. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16660. }
  16661. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16662. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16663. /**
  16664. * @author mrdoob / http://mrdoob.com/
  16665. * @author Mugen87 / https://github.com/Mugen87
  16666. */
  16667. // CylinderGeometry
  16668. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16669. Geometry.call( this );
  16670. this.type = 'CylinderGeometry';
  16671. this.parameters = {
  16672. radiusTop: radiusTop,
  16673. radiusBottom: radiusBottom,
  16674. height: height,
  16675. radialSegments: radialSegments,
  16676. heightSegments: heightSegments,
  16677. openEnded: openEnded,
  16678. thetaStart: thetaStart,
  16679. thetaLength: thetaLength
  16680. };
  16681. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16682. this.mergeVertices();
  16683. }
  16684. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16685. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16686. // CylinderBufferGeometry
  16687. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16688. BufferGeometry.call( this );
  16689. this.type = 'CylinderBufferGeometry';
  16690. this.parameters = {
  16691. radiusTop: radiusTop,
  16692. radiusBottom: radiusBottom,
  16693. height: height,
  16694. radialSegments: radialSegments,
  16695. heightSegments: heightSegments,
  16696. openEnded: openEnded,
  16697. thetaStart: thetaStart,
  16698. thetaLength: thetaLength
  16699. };
  16700. var scope = this;
  16701. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16702. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16703. height = height !== undefined ? height : 100;
  16704. radialSegments = Math.floor( radialSegments ) || 8;
  16705. heightSegments = Math.floor( heightSegments ) || 1;
  16706. openEnded = openEnded !== undefined ? openEnded : false;
  16707. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16708. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16709. // buffers
  16710. var indices = [];
  16711. var vertices = [];
  16712. var normals = [];
  16713. var uvs = [];
  16714. // helper variables
  16715. var index = 0;
  16716. var indexArray = [];
  16717. var halfHeight = height / 2;
  16718. var groupStart = 0;
  16719. // generate geometry
  16720. generateTorso();
  16721. if ( openEnded === false ) {
  16722. if ( radiusTop > 0 ) generateCap( true );
  16723. if ( radiusBottom > 0 ) generateCap( false );
  16724. }
  16725. // build geometry
  16726. this.setIndex( indices );
  16727. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16728. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16729. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16730. function generateTorso() {
  16731. var x, y;
  16732. var normal = new Vector3();
  16733. var vertex = new Vector3();
  16734. var groupCount = 0;
  16735. // this will be used to calculate the normal
  16736. var slope = ( radiusBottom - radiusTop ) / height;
  16737. // generate vertices, normals and uvs
  16738. for ( y = 0; y <= heightSegments; y ++ ) {
  16739. var indexRow = [];
  16740. var v = y / heightSegments;
  16741. // calculate the radius of the current row
  16742. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16743. for ( x = 0; x <= radialSegments; x ++ ) {
  16744. var u = x / radialSegments;
  16745. var theta = u * thetaLength + thetaStart;
  16746. var sinTheta = Math.sin( theta );
  16747. var cosTheta = Math.cos( theta );
  16748. // vertex
  16749. vertex.x = radius * sinTheta;
  16750. vertex.y = - v * height + halfHeight;
  16751. vertex.z = radius * cosTheta;
  16752. vertices.push( vertex.x, vertex.y, vertex.z );
  16753. // normal
  16754. normal.set( sinTheta, slope, cosTheta ).normalize();
  16755. normals.push( normal.x, normal.y, normal.z );
  16756. // uv
  16757. uvs.push( u, 1 - v );
  16758. // save index of vertex in respective row
  16759. indexRow.push( index ++ );
  16760. }
  16761. // now save vertices of the row in our index array
  16762. indexArray.push( indexRow );
  16763. }
  16764. // generate indices
  16765. for ( x = 0; x < radialSegments; x ++ ) {
  16766. for ( y = 0; y < heightSegments; y ++ ) {
  16767. // we use the index array to access the correct indices
  16768. var a = indexArray[ y ][ x ];
  16769. var b = indexArray[ y + 1 ][ x ];
  16770. var c = indexArray[ y + 1 ][ x + 1 ];
  16771. var d = indexArray[ y ][ x + 1 ];
  16772. // faces
  16773. indices.push( a, b, d );
  16774. indices.push( b, c, d );
  16775. // update group counter
  16776. groupCount += 6;
  16777. }
  16778. }
  16779. // add a group to the geometry. this will ensure multi material support
  16780. scope.addGroup( groupStart, groupCount, 0 );
  16781. // calculate new start value for groups
  16782. groupStart += groupCount;
  16783. }
  16784. function generateCap( top ) {
  16785. var x, centerIndexStart, centerIndexEnd;
  16786. var uv = new Vector2();
  16787. var vertex = new Vector3();
  16788. var groupCount = 0;
  16789. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16790. var sign = ( top === true ) ? 1 : - 1;
  16791. // save the index of the first center vertex
  16792. centerIndexStart = index;
  16793. // first we generate the center vertex data of the cap.
  16794. // because the geometry needs one set of uvs per face,
  16795. // we must generate a center vertex per face/segment
  16796. for ( x = 1; x <= radialSegments; x ++ ) {
  16797. // vertex
  16798. vertices.push( 0, halfHeight * sign, 0 );
  16799. // normal
  16800. normals.push( 0, sign, 0 );
  16801. // uv
  16802. uvs.push( 0.5, 0.5 );
  16803. // increase index
  16804. index ++;
  16805. }
  16806. // save the index of the last center vertex
  16807. centerIndexEnd = index;
  16808. // now we generate the surrounding vertices, normals and uvs
  16809. for ( x = 0; x <= radialSegments; x ++ ) {
  16810. var u = x / radialSegments;
  16811. var theta = u * thetaLength + thetaStart;
  16812. var cosTheta = Math.cos( theta );
  16813. var sinTheta = Math.sin( theta );
  16814. // vertex
  16815. vertex.x = radius * sinTheta;
  16816. vertex.y = halfHeight * sign;
  16817. vertex.z = radius * cosTheta;
  16818. vertices.push( vertex.x, vertex.y, vertex.z );
  16819. // normal
  16820. normals.push( 0, sign, 0 );
  16821. // uv
  16822. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16823. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16824. uvs.push( uv.x, uv.y );
  16825. // increase index
  16826. index ++;
  16827. }
  16828. // generate indices
  16829. for ( x = 0; x < radialSegments; x ++ ) {
  16830. var c = centerIndexStart + x;
  16831. var i = centerIndexEnd + x;
  16832. if ( top === true ) {
  16833. // face top
  16834. indices.push( i, i + 1, c );
  16835. } else {
  16836. // face bottom
  16837. indices.push( i + 1, i, c );
  16838. }
  16839. groupCount += 3;
  16840. }
  16841. // add a group to the geometry. this will ensure multi material support
  16842. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16843. // calculate new start value for groups
  16844. groupStart += groupCount;
  16845. }
  16846. }
  16847. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16848. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16849. /**
  16850. * @author abelnation / http://github.com/abelnation
  16851. */
  16852. // ConeGeometry
  16853. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16854. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16855. this.type = 'ConeGeometry';
  16856. this.parameters = {
  16857. radius: radius,
  16858. height: height,
  16859. radialSegments: radialSegments,
  16860. heightSegments: heightSegments,
  16861. openEnded: openEnded,
  16862. thetaStart: thetaStart,
  16863. thetaLength: thetaLength
  16864. };
  16865. }
  16866. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16867. ConeGeometry.prototype.constructor = ConeGeometry;
  16868. // ConeBufferGeometry
  16869. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16870. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16871. this.type = 'ConeBufferGeometry';
  16872. this.parameters = {
  16873. radius: radius,
  16874. height: height,
  16875. radialSegments: radialSegments,
  16876. heightSegments: heightSegments,
  16877. openEnded: openEnded,
  16878. thetaStart: thetaStart,
  16879. thetaLength: thetaLength
  16880. };
  16881. }
  16882. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16883. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16884. /**
  16885. * @author benaadams / https://twitter.com/ben_a_adams
  16886. * @author Mugen87 / https://github.com/Mugen87
  16887. * @author hughes
  16888. */
  16889. // CircleGeometry
  16890. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16891. Geometry.call( this );
  16892. this.type = 'CircleGeometry';
  16893. this.parameters = {
  16894. radius: radius,
  16895. segments: segments,
  16896. thetaStart: thetaStart,
  16897. thetaLength: thetaLength
  16898. };
  16899. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16900. this.mergeVertices();
  16901. }
  16902. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16903. CircleGeometry.prototype.constructor = CircleGeometry;
  16904. // CircleBufferGeometry
  16905. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16906. BufferGeometry.call( this );
  16907. this.type = 'CircleBufferGeometry';
  16908. this.parameters = {
  16909. radius: radius,
  16910. segments: segments,
  16911. thetaStart: thetaStart,
  16912. thetaLength: thetaLength
  16913. };
  16914. radius = radius || 50;
  16915. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16916. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16917. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16918. // buffers
  16919. var indices = [];
  16920. var vertices = [];
  16921. var normals = [];
  16922. var uvs = [];
  16923. // helper variables
  16924. var i, s;
  16925. var vertex = new Vector3();
  16926. var uv = new Vector2();
  16927. // center point
  16928. vertices.push( 0, 0, 0 );
  16929. normals.push( 0, 0, 1 );
  16930. uvs.push( 0.5, 0.5 );
  16931. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  16932. var segment = thetaStart + s / segments * thetaLength;
  16933. // vertex
  16934. vertex.x = radius * Math.cos( segment );
  16935. vertex.y = radius * Math.sin( segment );
  16936. vertices.push( vertex.x, vertex.y, vertex.z );
  16937. // normal
  16938. normals.push( 0, 0, 1 );
  16939. // uvs
  16940. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  16941. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  16942. uvs.push( uv.x, uv.y );
  16943. }
  16944. // indices
  16945. for ( i = 1; i <= segments; i ++ ) {
  16946. indices.push( i, i + 1, 0 );
  16947. }
  16948. // build geometry
  16949. this.setIndex( indices );
  16950. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16951. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16952. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16953. }
  16954. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16955. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16956. var Geometries = Object.freeze({
  16957. WireframeGeometry: WireframeGeometry,
  16958. ParametricGeometry: ParametricGeometry,
  16959. ParametricBufferGeometry: ParametricBufferGeometry,
  16960. TetrahedronGeometry: TetrahedronGeometry,
  16961. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16962. OctahedronGeometry: OctahedronGeometry,
  16963. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16964. IcosahedronGeometry: IcosahedronGeometry,
  16965. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16966. DodecahedronGeometry: DodecahedronGeometry,
  16967. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  16968. PolyhedronGeometry: PolyhedronGeometry,
  16969. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  16970. TubeGeometry: TubeGeometry,
  16971. TubeBufferGeometry: TubeBufferGeometry,
  16972. TorusKnotGeometry: TorusKnotGeometry,
  16973. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  16974. TorusGeometry: TorusGeometry,
  16975. TorusBufferGeometry: TorusBufferGeometry,
  16976. TextGeometry: TextGeometry,
  16977. TextBufferGeometry: TextBufferGeometry,
  16978. SphereGeometry: SphereGeometry,
  16979. SphereBufferGeometry: SphereBufferGeometry,
  16980. RingGeometry: RingGeometry,
  16981. RingBufferGeometry: RingBufferGeometry,
  16982. PlaneGeometry: PlaneGeometry,
  16983. PlaneBufferGeometry: PlaneBufferGeometry,
  16984. LatheGeometry: LatheGeometry,
  16985. LatheBufferGeometry: LatheBufferGeometry,
  16986. ShapeGeometry: ShapeGeometry,
  16987. ShapeBufferGeometry: ShapeBufferGeometry,
  16988. ExtrudeGeometry: ExtrudeGeometry,
  16989. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  16990. EdgesGeometry: EdgesGeometry,
  16991. ConeGeometry: ConeGeometry,
  16992. ConeBufferGeometry: ConeBufferGeometry,
  16993. CylinderGeometry: CylinderGeometry,
  16994. CylinderBufferGeometry: CylinderBufferGeometry,
  16995. CircleGeometry: CircleGeometry,
  16996. CircleBufferGeometry: CircleBufferGeometry,
  16997. BoxGeometry: BoxGeometry,
  16998. BoxBufferGeometry: BoxBufferGeometry
  16999. });
  17000. /**
  17001. * @author mrdoob / http://mrdoob.com/
  17002. *
  17003. * parameters = {
  17004. * opacity: <float>
  17005. * }
  17006. */
  17007. function ShadowMaterial( parameters ) {
  17008. ShaderMaterial.call( this, {
  17009. uniforms: UniformsUtils.merge( [
  17010. UniformsLib.lights,
  17011. {
  17012. opacity: { value: 1.0 }
  17013. }
  17014. ] ),
  17015. vertexShader: ShaderChunk[ 'shadow_vert' ],
  17016. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  17017. } );
  17018. this.lights = true;
  17019. this.transparent = true;
  17020. Object.defineProperties( this, {
  17021. opacity: {
  17022. enumerable: true,
  17023. get: function () {
  17024. return this.uniforms.opacity.value;
  17025. },
  17026. set: function ( value ) {
  17027. this.uniforms.opacity.value = value;
  17028. }
  17029. }
  17030. } );
  17031. this.setValues( parameters );
  17032. }
  17033. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17034. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17035. ShadowMaterial.prototype.isShadowMaterial = true;
  17036. /**
  17037. * @author mrdoob / http://mrdoob.com/
  17038. */
  17039. function RawShaderMaterial( parameters ) {
  17040. ShaderMaterial.call( this, parameters );
  17041. this.type = 'RawShaderMaterial';
  17042. }
  17043. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17044. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17045. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17046. /**
  17047. * @author WestLangley / http://github.com/WestLangley
  17048. *
  17049. * parameters = {
  17050. * color: <hex>,
  17051. * roughness: <float>,
  17052. * metalness: <float>,
  17053. * opacity: <float>,
  17054. *
  17055. * map: new THREE.Texture( <Image> ),
  17056. *
  17057. * lightMap: new THREE.Texture( <Image> ),
  17058. * lightMapIntensity: <float>
  17059. *
  17060. * aoMap: new THREE.Texture( <Image> ),
  17061. * aoMapIntensity: <float>
  17062. *
  17063. * emissive: <hex>,
  17064. * emissiveIntensity: <float>
  17065. * emissiveMap: new THREE.Texture( <Image> ),
  17066. *
  17067. * bumpMap: new THREE.Texture( <Image> ),
  17068. * bumpScale: <float>,
  17069. *
  17070. * normalMap: new THREE.Texture( <Image> ),
  17071. * normalScale: <Vector2>,
  17072. *
  17073. * displacementMap: new THREE.Texture( <Image> ),
  17074. * displacementScale: <float>,
  17075. * displacementBias: <float>,
  17076. *
  17077. * roughnessMap: new THREE.Texture( <Image> ),
  17078. *
  17079. * metalnessMap: new THREE.Texture( <Image> ),
  17080. *
  17081. * alphaMap: new THREE.Texture( <Image> ),
  17082. *
  17083. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17084. * envMapIntensity: <float>
  17085. *
  17086. * refractionRatio: <float>,
  17087. *
  17088. * wireframe: <boolean>,
  17089. * wireframeLinewidth: <float>,
  17090. *
  17091. * skinning: <bool>,
  17092. * morphTargets: <bool>,
  17093. * morphNormals: <bool>
  17094. * }
  17095. */
  17096. function MeshStandardMaterial( parameters ) {
  17097. Material.call( this );
  17098. this.defines = { 'STANDARD': '' };
  17099. this.type = 'MeshStandardMaterial';
  17100. this.color = new Color( 0xffffff ); // diffuse
  17101. this.roughness = 0.5;
  17102. this.metalness = 0.5;
  17103. this.map = null;
  17104. this.lightMap = null;
  17105. this.lightMapIntensity = 1.0;
  17106. this.aoMap = null;
  17107. this.aoMapIntensity = 1.0;
  17108. this.emissive = new Color( 0x000000 );
  17109. this.emissiveIntensity = 1.0;
  17110. this.emissiveMap = null;
  17111. this.bumpMap = null;
  17112. this.bumpScale = 1;
  17113. this.normalMap = null;
  17114. this.normalScale = new Vector2( 1, 1 );
  17115. this.displacementMap = null;
  17116. this.displacementScale = 1;
  17117. this.displacementBias = 0;
  17118. this.roughnessMap = null;
  17119. this.metalnessMap = null;
  17120. this.alphaMap = null;
  17121. this.envMap = null;
  17122. this.envMapIntensity = 1.0;
  17123. this.refractionRatio = 0.98;
  17124. this.wireframe = false;
  17125. this.wireframeLinewidth = 1;
  17126. this.wireframeLinecap = 'round';
  17127. this.wireframeLinejoin = 'round';
  17128. this.skinning = false;
  17129. this.morphTargets = false;
  17130. this.morphNormals = false;
  17131. this.setValues( parameters );
  17132. }
  17133. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17134. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17135. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17136. MeshStandardMaterial.prototype.copy = function ( source ) {
  17137. Material.prototype.copy.call( this, source );
  17138. this.defines = { 'STANDARD': '' };
  17139. this.color.copy( source.color );
  17140. this.roughness = source.roughness;
  17141. this.metalness = source.metalness;
  17142. this.map = source.map;
  17143. this.lightMap = source.lightMap;
  17144. this.lightMapIntensity = source.lightMapIntensity;
  17145. this.aoMap = source.aoMap;
  17146. this.aoMapIntensity = source.aoMapIntensity;
  17147. this.emissive.copy( source.emissive );
  17148. this.emissiveMap = source.emissiveMap;
  17149. this.emissiveIntensity = source.emissiveIntensity;
  17150. this.bumpMap = source.bumpMap;
  17151. this.bumpScale = source.bumpScale;
  17152. this.normalMap = source.normalMap;
  17153. this.normalScale.copy( source.normalScale );
  17154. this.displacementMap = source.displacementMap;
  17155. this.displacementScale = source.displacementScale;
  17156. this.displacementBias = source.displacementBias;
  17157. this.roughnessMap = source.roughnessMap;
  17158. this.metalnessMap = source.metalnessMap;
  17159. this.alphaMap = source.alphaMap;
  17160. this.envMap = source.envMap;
  17161. this.envMapIntensity = source.envMapIntensity;
  17162. this.refractionRatio = source.refractionRatio;
  17163. this.wireframe = source.wireframe;
  17164. this.wireframeLinewidth = source.wireframeLinewidth;
  17165. this.wireframeLinecap = source.wireframeLinecap;
  17166. this.wireframeLinejoin = source.wireframeLinejoin;
  17167. this.skinning = source.skinning;
  17168. this.morphTargets = source.morphTargets;
  17169. this.morphNormals = source.morphNormals;
  17170. return this;
  17171. };
  17172. /**
  17173. * @author WestLangley / http://github.com/WestLangley
  17174. *
  17175. * parameters = {
  17176. * reflectivity: <float>
  17177. * }
  17178. */
  17179. function MeshPhysicalMaterial( parameters ) {
  17180. MeshStandardMaterial.call( this );
  17181. this.defines = { 'PHYSICAL': '' };
  17182. this.type = 'MeshPhysicalMaterial';
  17183. this.reflectivity = 0.5; // maps to F0 = 0.04
  17184. this.clearCoat = 0.0;
  17185. this.clearCoatRoughness = 0.0;
  17186. this.setValues( parameters );
  17187. }
  17188. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17189. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17190. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17191. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17192. MeshStandardMaterial.prototype.copy.call( this, source );
  17193. this.defines = { 'PHYSICAL': '' };
  17194. this.reflectivity = source.reflectivity;
  17195. this.clearCoat = source.clearCoat;
  17196. this.clearCoatRoughness = source.clearCoatRoughness;
  17197. return this;
  17198. };
  17199. /**
  17200. * @author mrdoob / http://mrdoob.com/
  17201. * @author alteredq / http://alteredqualia.com/
  17202. *
  17203. * parameters = {
  17204. * color: <hex>,
  17205. * specular: <hex>,
  17206. * shininess: <float>,
  17207. * opacity: <float>,
  17208. *
  17209. * map: new THREE.Texture( <Image> ),
  17210. *
  17211. * lightMap: new THREE.Texture( <Image> ),
  17212. * lightMapIntensity: <float>
  17213. *
  17214. * aoMap: new THREE.Texture( <Image> ),
  17215. * aoMapIntensity: <float>
  17216. *
  17217. * emissive: <hex>,
  17218. * emissiveIntensity: <float>
  17219. * emissiveMap: new THREE.Texture( <Image> ),
  17220. *
  17221. * bumpMap: new THREE.Texture( <Image> ),
  17222. * bumpScale: <float>,
  17223. *
  17224. * normalMap: new THREE.Texture( <Image> ),
  17225. * normalScale: <Vector2>,
  17226. *
  17227. * displacementMap: new THREE.Texture( <Image> ),
  17228. * displacementScale: <float>,
  17229. * displacementBias: <float>,
  17230. *
  17231. * specularMap: new THREE.Texture( <Image> ),
  17232. *
  17233. * alphaMap: new THREE.Texture( <Image> ),
  17234. *
  17235. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17236. * combine: THREE.Multiply,
  17237. * reflectivity: <float>,
  17238. * refractionRatio: <float>,
  17239. *
  17240. * wireframe: <boolean>,
  17241. * wireframeLinewidth: <float>,
  17242. *
  17243. * skinning: <bool>,
  17244. * morphTargets: <bool>,
  17245. * morphNormals: <bool>
  17246. * }
  17247. */
  17248. function MeshPhongMaterial( parameters ) {
  17249. Material.call( this );
  17250. this.type = 'MeshPhongMaterial';
  17251. this.color = new Color( 0xffffff ); // diffuse
  17252. this.specular = new Color( 0x111111 );
  17253. this.shininess = 30;
  17254. this.map = null;
  17255. this.lightMap = null;
  17256. this.lightMapIntensity = 1.0;
  17257. this.aoMap = null;
  17258. this.aoMapIntensity = 1.0;
  17259. this.emissive = new Color( 0x000000 );
  17260. this.emissiveIntensity = 1.0;
  17261. this.emissiveMap = null;
  17262. this.bumpMap = null;
  17263. this.bumpScale = 1;
  17264. this.normalMap = null;
  17265. this.normalScale = new Vector2( 1, 1 );
  17266. this.displacementMap = null;
  17267. this.displacementScale = 1;
  17268. this.displacementBias = 0;
  17269. this.specularMap = null;
  17270. this.alphaMap = null;
  17271. this.envMap = null;
  17272. this.combine = MultiplyOperation;
  17273. this.reflectivity = 1;
  17274. this.refractionRatio = 0.98;
  17275. this.wireframe = false;
  17276. this.wireframeLinewidth = 1;
  17277. this.wireframeLinecap = 'round';
  17278. this.wireframeLinejoin = 'round';
  17279. this.skinning = false;
  17280. this.morphTargets = false;
  17281. this.morphNormals = false;
  17282. this.setValues( parameters );
  17283. }
  17284. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17285. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17286. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17287. MeshPhongMaterial.prototype.copy = function ( source ) {
  17288. Material.prototype.copy.call( this, source );
  17289. this.color.copy( source.color );
  17290. this.specular.copy( source.specular );
  17291. this.shininess = source.shininess;
  17292. this.map = source.map;
  17293. this.lightMap = source.lightMap;
  17294. this.lightMapIntensity = source.lightMapIntensity;
  17295. this.aoMap = source.aoMap;
  17296. this.aoMapIntensity = source.aoMapIntensity;
  17297. this.emissive.copy( source.emissive );
  17298. this.emissiveMap = source.emissiveMap;
  17299. this.emissiveIntensity = source.emissiveIntensity;
  17300. this.bumpMap = source.bumpMap;
  17301. this.bumpScale = source.bumpScale;
  17302. this.normalMap = source.normalMap;
  17303. this.normalScale.copy( source.normalScale );
  17304. this.displacementMap = source.displacementMap;
  17305. this.displacementScale = source.displacementScale;
  17306. this.displacementBias = source.displacementBias;
  17307. this.specularMap = source.specularMap;
  17308. this.alphaMap = source.alphaMap;
  17309. this.envMap = source.envMap;
  17310. this.combine = source.combine;
  17311. this.reflectivity = source.reflectivity;
  17312. this.refractionRatio = source.refractionRatio;
  17313. this.wireframe = source.wireframe;
  17314. this.wireframeLinewidth = source.wireframeLinewidth;
  17315. this.wireframeLinecap = source.wireframeLinecap;
  17316. this.wireframeLinejoin = source.wireframeLinejoin;
  17317. this.skinning = source.skinning;
  17318. this.morphTargets = source.morphTargets;
  17319. this.morphNormals = source.morphNormals;
  17320. return this;
  17321. };
  17322. /**
  17323. * @author takahirox / http://github.com/takahirox
  17324. *
  17325. * parameters = {
  17326. * gradientMap: new THREE.Texture( <Image> )
  17327. * }
  17328. */
  17329. function MeshToonMaterial( parameters ) {
  17330. MeshPhongMaterial.call( this );
  17331. this.defines = { 'TOON': '' };
  17332. this.type = 'MeshToonMaterial';
  17333. this.gradientMap = null;
  17334. this.setValues( parameters );
  17335. }
  17336. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17337. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17338. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17339. MeshToonMaterial.prototype.copy = function ( source ) {
  17340. MeshPhongMaterial.prototype.copy.call( this, source );
  17341. this.gradientMap = source.gradientMap;
  17342. return this;
  17343. };
  17344. /**
  17345. * @author mrdoob / http://mrdoob.com/
  17346. * @author WestLangley / http://github.com/WestLangley
  17347. *
  17348. * parameters = {
  17349. * opacity: <float>,
  17350. *
  17351. * bumpMap: new THREE.Texture( <Image> ),
  17352. * bumpScale: <float>,
  17353. *
  17354. * normalMap: new THREE.Texture( <Image> ),
  17355. * normalScale: <Vector2>,
  17356. *
  17357. * displacementMap: new THREE.Texture( <Image> ),
  17358. * displacementScale: <float>,
  17359. * displacementBias: <float>,
  17360. *
  17361. * wireframe: <boolean>,
  17362. * wireframeLinewidth: <float>
  17363. *
  17364. * skinning: <bool>,
  17365. * morphTargets: <bool>,
  17366. * morphNormals: <bool>
  17367. * }
  17368. */
  17369. function MeshNormalMaterial( parameters ) {
  17370. Material.call( this, parameters );
  17371. this.type = 'MeshNormalMaterial';
  17372. this.bumpMap = null;
  17373. this.bumpScale = 1;
  17374. this.normalMap = null;
  17375. this.normalScale = new Vector2( 1, 1 );
  17376. this.displacementMap = null;
  17377. this.displacementScale = 1;
  17378. this.displacementBias = 0;
  17379. this.wireframe = false;
  17380. this.wireframeLinewidth = 1;
  17381. this.fog = false;
  17382. this.lights = false;
  17383. this.skinning = false;
  17384. this.morphTargets = false;
  17385. this.morphNormals = false;
  17386. this.setValues( parameters );
  17387. }
  17388. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17389. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17390. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17391. MeshNormalMaterial.prototype.copy = function ( source ) {
  17392. Material.prototype.copy.call( this, source );
  17393. this.bumpMap = source.bumpMap;
  17394. this.bumpScale = source.bumpScale;
  17395. this.normalMap = source.normalMap;
  17396. this.normalScale.copy( source.normalScale );
  17397. this.displacementMap = source.displacementMap;
  17398. this.displacementScale = source.displacementScale;
  17399. this.displacementBias = source.displacementBias;
  17400. this.wireframe = source.wireframe;
  17401. this.wireframeLinewidth = source.wireframeLinewidth;
  17402. this.skinning = source.skinning;
  17403. this.morphTargets = source.morphTargets;
  17404. this.morphNormals = source.morphNormals;
  17405. return this;
  17406. };
  17407. /**
  17408. * @author mrdoob / http://mrdoob.com/
  17409. * @author alteredq / http://alteredqualia.com/
  17410. *
  17411. * parameters = {
  17412. * color: <hex>,
  17413. * opacity: <float>,
  17414. *
  17415. * map: new THREE.Texture( <Image> ),
  17416. *
  17417. * lightMap: new THREE.Texture( <Image> ),
  17418. * lightMapIntensity: <float>
  17419. *
  17420. * aoMap: new THREE.Texture( <Image> ),
  17421. * aoMapIntensity: <float>
  17422. *
  17423. * emissive: <hex>,
  17424. * emissiveIntensity: <float>
  17425. * emissiveMap: new THREE.Texture( <Image> ),
  17426. *
  17427. * specularMap: new THREE.Texture( <Image> ),
  17428. *
  17429. * alphaMap: new THREE.Texture( <Image> ),
  17430. *
  17431. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17432. * combine: THREE.Multiply,
  17433. * reflectivity: <float>,
  17434. * refractionRatio: <float>,
  17435. *
  17436. * wireframe: <boolean>,
  17437. * wireframeLinewidth: <float>,
  17438. *
  17439. * skinning: <bool>,
  17440. * morphTargets: <bool>,
  17441. * morphNormals: <bool>
  17442. * }
  17443. */
  17444. function MeshLambertMaterial( parameters ) {
  17445. Material.call( this );
  17446. this.type = 'MeshLambertMaterial';
  17447. this.color = new Color( 0xffffff ); // diffuse
  17448. this.map = null;
  17449. this.lightMap = null;
  17450. this.lightMapIntensity = 1.0;
  17451. this.aoMap = null;
  17452. this.aoMapIntensity = 1.0;
  17453. this.emissive = new Color( 0x000000 );
  17454. this.emissiveIntensity = 1.0;
  17455. this.emissiveMap = null;
  17456. this.specularMap = null;
  17457. this.alphaMap = null;
  17458. this.envMap = null;
  17459. this.combine = MultiplyOperation;
  17460. this.reflectivity = 1;
  17461. this.refractionRatio = 0.98;
  17462. this.wireframe = false;
  17463. this.wireframeLinewidth = 1;
  17464. this.wireframeLinecap = 'round';
  17465. this.wireframeLinejoin = 'round';
  17466. this.skinning = false;
  17467. this.morphTargets = false;
  17468. this.morphNormals = false;
  17469. this.setValues( parameters );
  17470. }
  17471. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17472. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17473. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17474. MeshLambertMaterial.prototype.copy = function ( source ) {
  17475. Material.prototype.copy.call( this, source );
  17476. this.color.copy( source.color );
  17477. this.map = source.map;
  17478. this.lightMap = source.lightMap;
  17479. this.lightMapIntensity = source.lightMapIntensity;
  17480. this.aoMap = source.aoMap;
  17481. this.aoMapIntensity = source.aoMapIntensity;
  17482. this.emissive.copy( source.emissive );
  17483. this.emissiveMap = source.emissiveMap;
  17484. this.emissiveIntensity = source.emissiveIntensity;
  17485. this.specularMap = source.specularMap;
  17486. this.alphaMap = source.alphaMap;
  17487. this.envMap = source.envMap;
  17488. this.combine = source.combine;
  17489. this.reflectivity = source.reflectivity;
  17490. this.refractionRatio = source.refractionRatio;
  17491. this.wireframe = source.wireframe;
  17492. this.wireframeLinewidth = source.wireframeLinewidth;
  17493. this.wireframeLinecap = source.wireframeLinecap;
  17494. this.wireframeLinejoin = source.wireframeLinejoin;
  17495. this.skinning = source.skinning;
  17496. this.morphTargets = source.morphTargets;
  17497. this.morphNormals = source.morphNormals;
  17498. return this;
  17499. };
  17500. /**
  17501. * @author alteredq / http://alteredqualia.com/
  17502. *
  17503. * parameters = {
  17504. * color: <hex>,
  17505. * opacity: <float>,
  17506. *
  17507. * linewidth: <float>,
  17508. *
  17509. * scale: <float>,
  17510. * dashSize: <float>,
  17511. * gapSize: <float>
  17512. * }
  17513. */
  17514. function LineDashedMaterial( parameters ) {
  17515. Material.call( this );
  17516. this.type = 'LineDashedMaterial';
  17517. this.color = new Color( 0xffffff );
  17518. this.linewidth = 1;
  17519. this.scale = 1;
  17520. this.dashSize = 3;
  17521. this.gapSize = 1;
  17522. this.lights = false;
  17523. this.setValues( parameters );
  17524. }
  17525. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17526. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17527. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17528. LineDashedMaterial.prototype.copy = function ( source ) {
  17529. Material.prototype.copy.call( this, source );
  17530. this.color.copy( source.color );
  17531. this.linewidth = source.linewidth;
  17532. this.scale = source.scale;
  17533. this.dashSize = source.dashSize;
  17534. this.gapSize = source.gapSize;
  17535. return this;
  17536. };
  17537. var Materials = Object.freeze({
  17538. ShadowMaterial: ShadowMaterial,
  17539. SpriteMaterial: SpriteMaterial,
  17540. RawShaderMaterial: RawShaderMaterial,
  17541. ShaderMaterial: ShaderMaterial,
  17542. PointsMaterial: PointsMaterial,
  17543. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17544. MeshStandardMaterial: MeshStandardMaterial,
  17545. MeshPhongMaterial: MeshPhongMaterial,
  17546. MeshToonMaterial: MeshToonMaterial,
  17547. MeshNormalMaterial: MeshNormalMaterial,
  17548. MeshLambertMaterial: MeshLambertMaterial,
  17549. MeshDepthMaterial: MeshDepthMaterial,
  17550. MeshBasicMaterial: MeshBasicMaterial,
  17551. LineDashedMaterial: LineDashedMaterial,
  17552. LineBasicMaterial: LineBasicMaterial,
  17553. Material: Material
  17554. });
  17555. /**
  17556. * @author mrdoob / http://mrdoob.com/
  17557. */
  17558. var Cache = {
  17559. enabled: false,
  17560. files: {},
  17561. add: function ( key, file ) {
  17562. if ( this.enabled === false ) return;
  17563. // console.log( 'THREE.Cache', 'Adding key:', key );
  17564. this.files[ key ] = file;
  17565. },
  17566. get: function ( key ) {
  17567. if ( this.enabled === false ) return;
  17568. // console.log( 'THREE.Cache', 'Checking key:', key );
  17569. return this.files[ key ];
  17570. },
  17571. remove: function ( key ) {
  17572. delete this.files[ key ];
  17573. },
  17574. clear: function () {
  17575. this.files = {};
  17576. }
  17577. };
  17578. /**
  17579. * @author mrdoob / http://mrdoob.com/
  17580. */
  17581. function LoadingManager( onLoad, onProgress, onError ) {
  17582. var scope = this;
  17583. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17584. this.onStart = undefined;
  17585. this.onLoad = onLoad;
  17586. this.onProgress = onProgress;
  17587. this.onError = onError;
  17588. this.itemStart = function ( url ) {
  17589. itemsTotal ++;
  17590. if ( isLoading === false ) {
  17591. if ( scope.onStart !== undefined ) {
  17592. scope.onStart( url, itemsLoaded, itemsTotal );
  17593. }
  17594. }
  17595. isLoading = true;
  17596. };
  17597. this.itemEnd = function ( url ) {
  17598. itemsLoaded ++;
  17599. if ( scope.onProgress !== undefined ) {
  17600. scope.onProgress( url, itemsLoaded, itemsTotal );
  17601. }
  17602. if ( itemsLoaded === itemsTotal ) {
  17603. isLoading = false;
  17604. if ( scope.onLoad !== undefined ) {
  17605. scope.onLoad();
  17606. }
  17607. }
  17608. };
  17609. this.itemError = function ( url ) {
  17610. if ( scope.onError !== undefined ) {
  17611. scope.onError( url );
  17612. }
  17613. };
  17614. }
  17615. var DefaultLoadingManager = new LoadingManager();
  17616. /**
  17617. * @author mrdoob / http://mrdoob.com/
  17618. */
  17619. function FileLoader( manager ) {
  17620. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17621. }
  17622. Object.assign( FileLoader.prototype, {
  17623. load: function ( url, onLoad, onProgress, onError ) {
  17624. if ( url === undefined ) url = '';
  17625. if ( this.path !== undefined ) url = this.path + url;
  17626. var scope = this;
  17627. var cached = Cache.get( url );
  17628. if ( cached !== undefined ) {
  17629. scope.manager.itemStart( url );
  17630. setTimeout( function () {
  17631. if ( onLoad ) onLoad( cached );
  17632. scope.manager.itemEnd( url );
  17633. }, 0 );
  17634. return cached;
  17635. }
  17636. // Check for data: URI
  17637. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17638. var dataUriRegexResult = url.match( dataUriRegex );
  17639. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17640. if ( dataUriRegexResult ) {
  17641. var mimeType = dataUriRegexResult[ 1 ];
  17642. var isBase64 = !! dataUriRegexResult[ 2 ];
  17643. var data = dataUriRegexResult[ 3 ];
  17644. data = window.decodeURIComponent( data );
  17645. if ( isBase64 ) data = window.atob( data );
  17646. try {
  17647. var response;
  17648. var responseType = ( this.responseType || '' ).toLowerCase();
  17649. switch ( responseType ) {
  17650. case 'arraybuffer':
  17651. case 'blob':
  17652. response = new ArrayBuffer( data.length );
  17653. var view = new Uint8Array( response );
  17654. for ( var i = 0; i < data.length; i ++ ) {
  17655. view[ i ] = data.charCodeAt( i );
  17656. }
  17657. if ( responseType === 'blob' ) {
  17658. response = new Blob( [ response ], { type: mimeType } );
  17659. }
  17660. break;
  17661. case 'document':
  17662. var parser = new DOMParser();
  17663. response = parser.parseFromString( data, mimeType );
  17664. break;
  17665. case 'json':
  17666. response = JSON.parse( data );
  17667. break;
  17668. default: // 'text' or other
  17669. response = data;
  17670. break;
  17671. }
  17672. // Wait for next browser tick
  17673. window.setTimeout( function () {
  17674. if ( onLoad ) onLoad( response );
  17675. scope.manager.itemEnd( url );
  17676. }, 0 );
  17677. } catch ( error ) {
  17678. // Wait for next browser tick
  17679. window.setTimeout( function () {
  17680. if ( onError ) onError( error );
  17681. scope.manager.itemEnd( url );
  17682. scope.manager.itemError( url );
  17683. }, 0 );
  17684. }
  17685. } else {
  17686. var request = new XMLHttpRequest();
  17687. request.open( 'GET', url, true );
  17688. request.addEventListener( 'load', function ( event ) {
  17689. var response = event.target.response;
  17690. Cache.add( url, response );
  17691. if ( this.status === 200 ) {
  17692. if ( onLoad ) onLoad( response );
  17693. scope.manager.itemEnd( url );
  17694. } else if ( this.status === 0 ) {
  17695. // Some browsers return HTTP Status 0 when using non-http protocol
  17696. // e.g. 'file://' or 'data://'. Handle as success.
  17697. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17698. if ( onLoad ) onLoad( response );
  17699. scope.manager.itemEnd( url );
  17700. } else {
  17701. if ( onError ) onError( event );
  17702. scope.manager.itemEnd( url );
  17703. scope.manager.itemError( url );
  17704. }
  17705. }, false );
  17706. if ( onProgress !== undefined ) {
  17707. request.addEventListener( 'progress', function ( event ) {
  17708. onProgress( event );
  17709. }, false );
  17710. }
  17711. request.addEventListener( 'error', function ( event ) {
  17712. if ( onError ) onError( event );
  17713. scope.manager.itemEnd( url );
  17714. scope.manager.itemError( url );
  17715. }, false );
  17716. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17717. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17718. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17719. for ( var header in this.requestHeader ) {
  17720. request.setRequestHeader( header, this.requestHeader[ header ] );
  17721. }
  17722. request.send( null );
  17723. }
  17724. scope.manager.itemStart( url );
  17725. return request;
  17726. },
  17727. setPath: function ( value ) {
  17728. this.path = value;
  17729. return this;
  17730. },
  17731. setResponseType: function ( value ) {
  17732. this.responseType = value;
  17733. return this;
  17734. },
  17735. setWithCredentials: function ( value ) {
  17736. this.withCredentials = value;
  17737. return this;
  17738. },
  17739. setMimeType: function ( value ) {
  17740. this.mimeType = value;
  17741. return this;
  17742. },
  17743. setRequestHeader: function ( value ) {
  17744. this.requestHeader = value;
  17745. return this;
  17746. }
  17747. } );
  17748. /**
  17749. * @author mrdoob / http://mrdoob.com/
  17750. *
  17751. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17752. */
  17753. function CompressedTextureLoader( manager ) {
  17754. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17755. // override in sub classes
  17756. this._parser = null;
  17757. }
  17758. Object.assign( CompressedTextureLoader.prototype, {
  17759. load: function ( url, onLoad, onProgress, onError ) {
  17760. var scope = this;
  17761. var images = [];
  17762. var texture = new CompressedTexture();
  17763. texture.image = images;
  17764. var loader = new FileLoader( this.manager );
  17765. loader.setPath( this.path );
  17766. loader.setResponseType( 'arraybuffer' );
  17767. function loadTexture( i ) {
  17768. loader.load( url[ i ], function ( buffer ) {
  17769. var texDatas = scope._parser( buffer, true );
  17770. images[ i ] = {
  17771. width: texDatas.width,
  17772. height: texDatas.height,
  17773. format: texDatas.format,
  17774. mipmaps: texDatas.mipmaps
  17775. };
  17776. loaded += 1;
  17777. if ( loaded === 6 ) {
  17778. if ( texDatas.mipmapCount === 1 )
  17779. texture.minFilter = LinearFilter;
  17780. texture.format = texDatas.format;
  17781. texture.needsUpdate = true;
  17782. if ( onLoad ) onLoad( texture );
  17783. }
  17784. }, onProgress, onError );
  17785. }
  17786. if ( Array.isArray( url ) ) {
  17787. var loaded = 0;
  17788. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17789. loadTexture( i );
  17790. }
  17791. } else {
  17792. // compressed cubemap texture stored in a single DDS file
  17793. loader.load( url, function ( buffer ) {
  17794. var texDatas = scope._parser( buffer, true );
  17795. if ( texDatas.isCubemap ) {
  17796. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17797. for ( var f = 0; f < faces; f ++ ) {
  17798. images[ f ] = { mipmaps : [] };
  17799. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17800. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17801. images[ f ].format = texDatas.format;
  17802. images[ f ].width = texDatas.width;
  17803. images[ f ].height = texDatas.height;
  17804. }
  17805. }
  17806. } else {
  17807. texture.image.width = texDatas.width;
  17808. texture.image.height = texDatas.height;
  17809. texture.mipmaps = texDatas.mipmaps;
  17810. }
  17811. if ( texDatas.mipmapCount === 1 ) {
  17812. texture.minFilter = LinearFilter;
  17813. }
  17814. texture.format = texDatas.format;
  17815. texture.needsUpdate = true;
  17816. if ( onLoad ) onLoad( texture );
  17817. }, onProgress, onError );
  17818. }
  17819. return texture;
  17820. },
  17821. setPath: function ( value ) {
  17822. this.path = value;
  17823. return this;
  17824. }
  17825. } );
  17826. /**
  17827. * @author Nikos M. / https://github.com/foo123/
  17828. *
  17829. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17830. */
  17831. function DataTextureLoader( manager ) {
  17832. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17833. // override in sub classes
  17834. this._parser = null;
  17835. }
  17836. Object.assign( DataTextureLoader.prototype, {
  17837. load: function ( url, onLoad, onProgress, onError ) {
  17838. var scope = this;
  17839. var texture = new DataTexture();
  17840. var loader = new FileLoader( this.manager );
  17841. loader.setResponseType( 'arraybuffer' );
  17842. loader.load( url, function ( buffer ) {
  17843. var texData = scope._parser( buffer );
  17844. if ( ! texData ) return;
  17845. if ( undefined !== texData.image ) {
  17846. texture.image = texData.image;
  17847. } else if ( undefined !== texData.data ) {
  17848. texture.image.width = texData.width;
  17849. texture.image.height = texData.height;
  17850. texture.image.data = texData.data;
  17851. }
  17852. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17853. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17854. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17855. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17856. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17857. if ( undefined !== texData.format ) {
  17858. texture.format = texData.format;
  17859. }
  17860. if ( undefined !== texData.type ) {
  17861. texture.type = texData.type;
  17862. }
  17863. if ( undefined !== texData.mipmaps ) {
  17864. texture.mipmaps = texData.mipmaps;
  17865. }
  17866. if ( 1 === texData.mipmapCount ) {
  17867. texture.minFilter = LinearFilter;
  17868. }
  17869. texture.needsUpdate = true;
  17870. if ( onLoad ) onLoad( texture, texData );
  17871. }, onProgress, onError );
  17872. return texture;
  17873. }
  17874. } );
  17875. /**
  17876. * @author mrdoob / http://mrdoob.com/
  17877. */
  17878. function ImageLoader( manager ) {
  17879. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17880. }
  17881. Object.assign( ImageLoader.prototype, {
  17882. load: function ( url, onLoad, onProgress, onError ) {
  17883. if ( url === undefined ) url = '';
  17884. if ( this.path !== undefined ) url = this.path + url;
  17885. var scope = this;
  17886. var cached = Cache.get( url );
  17887. if ( cached !== undefined ) {
  17888. scope.manager.itemStart( url );
  17889. setTimeout( function () {
  17890. if ( onLoad ) onLoad( cached );
  17891. scope.manager.itemEnd( url );
  17892. }, 0 );
  17893. return cached;
  17894. }
  17895. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17896. image.addEventListener( 'load', function () {
  17897. Cache.add( url, this );
  17898. if ( onLoad ) onLoad( this );
  17899. scope.manager.itemEnd( url );
  17900. }, false );
  17901. /*
  17902. image.addEventListener( 'progress', function ( event ) {
  17903. if ( onProgress ) onProgress( event );
  17904. }, false );
  17905. */
  17906. image.addEventListener( 'error', function ( event ) {
  17907. if ( onError ) onError( event );
  17908. scope.manager.itemEnd( url );
  17909. scope.manager.itemError( url );
  17910. }, false );
  17911. if ( url.substr( 0, 5 ) !== 'data:' ) {
  17912. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  17913. }
  17914. scope.manager.itemStart( url );
  17915. image.src = url;
  17916. return image;
  17917. },
  17918. setCrossOrigin: function ( value ) {
  17919. this.crossOrigin = value;
  17920. return this;
  17921. },
  17922. setPath: function ( value ) {
  17923. this.path = value;
  17924. return this;
  17925. }
  17926. } );
  17927. /**
  17928. * @author mrdoob / http://mrdoob.com/
  17929. */
  17930. function CubeTextureLoader( manager ) {
  17931. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17932. }
  17933. Object.assign( CubeTextureLoader.prototype, {
  17934. load: function ( urls, onLoad, onProgress, onError ) {
  17935. var texture = new CubeTexture();
  17936. var loader = new ImageLoader( this.manager );
  17937. loader.setCrossOrigin( this.crossOrigin );
  17938. loader.setPath( this.path );
  17939. var loaded = 0;
  17940. function loadTexture( i ) {
  17941. loader.load( urls[ i ], function ( image ) {
  17942. texture.images[ i ] = image;
  17943. loaded ++;
  17944. if ( loaded === 6 ) {
  17945. texture.needsUpdate = true;
  17946. if ( onLoad ) onLoad( texture );
  17947. }
  17948. }, undefined, onError );
  17949. }
  17950. for ( var i = 0; i < urls.length; ++ i ) {
  17951. loadTexture( i );
  17952. }
  17953. return texture;
  17954. },
  17955. setCrossOrigin: function ( value ) {
  17956. this.crossOrigin = value;
  17957. return this;
  17958. },
  17959. setPath: function ( value ) {
  17960. this.path = value;
  17961. return this;
  17962. }
  17963. } );
  17964. /**
  17965. * @author mrdoob / http://mrdoob.com/
  17966. */
  17967. function TextureLoader( manager ) {
  17968. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17969. }
  17970. Object.assign( TextureLoader.prototype, {
  17971. load: function ( url, onLoad, onProgress, onError ) {
  17972. var loader = new ImageLoader( this.manager );
  17973. loader.setCrossOrigin( this.crossOrigin );
  17974. loader.setPath( this.path );
  17975. var texture = new Texture();
  17976. texture.image = loader.load( url, function () {
  17977. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  17978. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  17979. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  17980. texture.needsUpdate = true;
  17981. if ( onLoad !== undefined ) {
  17982. onLoad( texture );
  17983. }
  17984. }, onProgress, onError );
  17985. return texture;
  17986. },
  17987. setCrossOrigin: function ( value ) {
  17988. this.crossOrigin = value;
  17989. return this;
  17990. },
  17991. setPath: function ( value ) {
  17992. this.path = value;
  17993. return this;
  17994. }
  17995. } );
  17996. /**
  17997. * @author mrdoob / http://mrdoob.com/
  17998. * @author alteredq / http://alteredqualia.com/
  17999. */
  18000. function Light( color, intensity ) {
  18001. Object3D.call( this );
  18002. this.type = 'Light';
  18003. this.color = new Color( color );
  18004. this.intensity = intensity !== undefined ? intensity : 1;
  18005. this.receiveShadow = undefined;
  18006. }
  18007. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18008. constructor: Light,
  18009. isLight: true,
  18010. copy: function ( source ) {
  18011. Object3D.prototype.copy.call( this, source );
  18012. this.color.copy( source.color );
  18013. this.intensity = source.intensity;
  18014. return this;
  18015. },
  18016. toJSON: function ( meta ) {
  18017. var data = Object3D.prototype.toJSON.call( this, meta );
  18018. data.object.color = this.color.getHex();
  18019. data.object.intensity = this.intensity;
  18020. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18021. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18022. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18023. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18024. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18025. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18026. return data;
  18027. }
  18028. } );
  18029. /**
  18030. * @author alteredq / http://alteredqualia.com/
  18031. */
  18032. function HemisphereLight( skyColor, groundColor, intensity ) {
  18033. Light.call( this, skyColor, intensity );
  18034. this.type = 'HemisphereLight';
  18035. this.castShadow = undefined;
  18036. this.position.copy( Object3D.DefaultUp );
  18037. this.updateMatrix();
  18038. this.groundColor = new Color( groundColor );
  18039. }
  18040. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18041. constructor: HemisphereLight,
  18042. isHemisphereLight: true,
  18043. copy: function ( source ) {
  18044. Light.prototype.copy.call( this, source );
  18045. this.groundColor.copy( source.groundColor );
  18046. return this;
  18047. }
  18048. } );
  18049. /**
  18050. * @author mrdoob / http://mrdoob.com/
  18051. */
  18052. function LightShadow( camera ) {
  18053. this.camera = camera;
  18054. this.bias = 0;
  18055. this.radius = 1;
  18056. this.mapSize = new Vector2( 512, 512 );
  18057. this.map = null;
  18058. this.matrix = new Matrix4();
  18059. }
  18060. Object.assign( LightShadow.prototype, {
  18061. copy: function ( source ) {
  18062. this.camera = source.camera.clone();
  18063. this.bias = source.bias;
  18064. this.radius = source.radius;
  18065. this.mapSize.copy( source.mapSize );
  18066. return this;
  18067. },
  18068. clone: function () {
  18069. return new this.constructor().copy( this );
  18070. },
  18071. toJSON: function () {
  18072. var object = {};
  18073. if ( this.bias !== 0 ) object.bias = this.bias;
  18074. if ( this.radius !== 1 ) object.radius = this.radius;
  18075. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18076. object.camera = this.camera.toJSON( false ).object;
  18077. delete object.camera.matrix;
  18078. return object;
  18079. }
  18080. } );
  18081. /**
  18082. * @author mrdoob / http://mrdoob.com/
  18083. */
  18084. function SpotLightShadow() {
  18085. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18086. }
  18087. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18088. constructor: SpotLightShadow,
  18089. isSpotLightShadow: true,
  18090. update: function ( light ) {
  18091. var camera = this.camera;
  18092. var fov = _Math.RAD2DEG * 2 * light.angle;
  18093. var aspect = this.mapSize.width / this.mapSize.height;
  18094. var far = light.distance || camera.far;
  18095. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18096. camera.fov = fov;
  18097. camera.aspect = aspect;
  18098. camera.far = far;
  18099. camera.updateProjectionMatrix();
  18100. }
  18101. }
  18102. } );
  18103. /**
  18104. * @author alteredq / http://alteredqualia.com/
  18105. */
  18106. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18107. Light.call( this, color, intensity );
  18108. this.type = 'SpotLight';
  18109. this.position.copy( Object3D.DefaultUp );
  18110. this.updateMatrix();
  18111. this.target = new Object3D();
  18112. Object.defineProperty( this, 'power', {
  18113. get: function () {
  18114. // intensity = power per solid angle.
  18115. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18116. return this.intensity * Math.PI;
  18117. },
  18118. set: function ( power ) {
  18119. // intensity = power per solid angle.
  18120. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18121. this.intensity = power / Math.PI;
  18122. }
  18123. } );
  18124. this.distance = ( distance !== undefined ) ? distance : 0;
  18125. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18126. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18127. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18128. this.shadow = new SpotLightShadow();
  18129. }
  18130. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18131. constructor: SpotLight,
  18132. isSpotLight: true,
  18133. copy: function ( source ) {
  18134. Light.prototype.copy.call( this, source );
  18135. this.distance = source.distance;
  18136. this.angle = source.angle;
  18137. this.penumbra = source.penumbra;
  18138. this.decay = source.decay;
  18139. this.target = source.target.clone();
  18140. this.shadow = source.shadow.clone();
  18141. return this;
  18142. }
  18143. } );
  18144. /**
  18145. * @author mrdoob / http://mrdoob.com/
  18146. */
  18147. function PointLight( color, intensity, distance, decay ) {
  18148. Light.call( this, color, intensity );
  18149. this.type = 'PointLight';
  18150. Object.defineProperty( this, 'power', {
  18151. get: function () {
  18152. // intensity = power per solid angle.
  18153. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18154. return this.intensity * 4 * Math.PI;
  18155. },
  18156. set: function ( power ) {
  18157. // intensity = power per solid angle.
  18158. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18159. this.intensity = power / ( 4 * Math.PI );
  18160. }
  18161. } );
  18162. this.distance = ( distance !== undefined ) ? distance : 0;
  18163. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18164. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18165. }
  18166. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18167. constructor: PointLight,
  18168. isPointLight: true,
  18169. copy: function ( source ) {
  18170. Light.prototype.copy.call( this, source );
  18171. this.distance = source.distance;
  18172. this.decay = source.decay;
  18173. this.shadow = source.shadow.clone();
  18174. return this;
  18175. }
  18176. } );
  18177. /**
  18178. * @author mrdoob / http://mrdoob.com/
  18179. */
  18180. function DirectionalLightShadow( ) {
  18181. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18182. }
  18183. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18184. constructor: DirectionalLightShadow
  18185. } );
  18186. /**
  18187. * @author mrdoob / http://mrdoob.com/
  18188. * @author alteredq / http://alteredqualia.com/
  18189. */
  18190. function DirectionalLight( color, intensity ) {
  18191. Light.call( this, color, intensity );
  18192. this.type = 'DirectionalLight';
  18193. this.position.copy( Object3D.DefaultUp );
  18194. this.updateMatrix();
  18195. this.target = new Object3D();
  18196. this.shadow = new DirectionalLightShadow();
  18197. }
  18198. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18199. constructor: DirectionalLight,
  18200. isDirectionalLight: true,
  18201. copy: function ( source ) {
  18202. Light.prototype.copy.call( this, source );
  18203. this.target = source.target.clone();
  18204. this.shadow = source.shadow.clone();
  18205. return this;
  18206. }
  18207. } );
  18208. /**
  18209. * @author mrdoob / http://mrdoob.com/
  18210. */
  18211. function AmbientLight( color, intensity ) {
  18212. Light.call( this, color, intensity );
  18213. this.type = 'AmbientLight';
  18214. this.castShadow = undefined;
  18215. }
  18216. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18217. constructor: AmbientLight,
  18218. isAmbientLight: true
  18219. } );
  18220. /**
  18221. * @author abelnation / http://github.com/abelnation
  18222. */
  18223. function RectAreaLight( color, intensity, width, height ) {
  18224. Light.call( this, color, intensity );
  18225. this.type = 'RectAreaLight';
  18226. this.position.set( 0, 1, 0 );
  18227. this.updateMatrix();
  18228. this.width = ( width !== undefined ) ? width : 10;
  18229. this.height = ( height !== undefined ) ? height : 10;
  18230. // TODO (abelnation): distance/decay
  18231. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18232. // TODO (abelnation): shadows
  18233. }
  18234. // TODO (abelnation): RectAreaLight update when light shape is changed
  18235. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18236. constructor: RectAreaLight,
  18237. isRectAreaLight: true,
  18238. copy: function ( source ) {
  18239. Light.prototype.copy.call( this, source );
  18240. this.width = source.width;
  18241. this.height = source.height;
  18242. return this;
  18243. },
  18244. toJSON: function ( meta ) {
  18245. var data = Light.prototype.toJSON.call( this, meta );
  18246. data.object.width = this.width;
  18247. data.object.height = this.height;
  18248. return data;
  18249. }
  18250. } );
  18251. /**
  18252. * @author tschw
  18253. * @author Ben Houston / http://clara.io/
  18254. * @author David Sarno / http://lighthaus.us/
  18255. */
  18256. var AnimationUtils = {
  18257. // same as Array.prototype.slice, but also works on typed arrays
  18258. arraySlice: function ( array, from, to ) {
  18259. if ( AnimationUtils.isTypedArray( array ) ) {
  18260. // in ios9 array.subarray(from, undefined) will return empty array
  18261. // but array.subarray(from) or array.subarray(from, len) is correct
  18262. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18263. }
  18264. return array.slice( from, to );
  18265. },
  18266. // converts an array to a specific type
  18267. convertArray: function ( array, type, forceClone ) {
  18268. if ( ! array || // let 'undefined' and 'null' pass
  18269. ! forceClone && array.constructor === type ) return array;
  18270. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18271. return new type( array ); // create typed array
  18272. }
  18273. return Array.prototype.slice.call( array ); // create Array
  18274. },
  18275. isTypedArray: function ( object ) {
  18276. return ArrayBuffer.isView( object ) &&
  18277. ! ( object instanceof DataView );
  18278. },
  18279. // returns an array by which times and values can be sorted
  18280. getKeyframeOrder: function ( times ) {
  18281. function compareTime( i, j ) {
  18282. return times[ i ] - times[ j ];
  18283. }
  18284. var n = times.length;
  18285. var result = new Array( n );
  18286. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18287. result.sort( compareTime );
  18288. return result;
  18289. },
  18290. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18291. sortedArray: function ( values, stride, order ) {
  18292. var nValues = values.length;
  18293. var result = new values.constructor( nValues );
  18294. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18295. var srcOffset = order[ i ] * stride;
  18296. for ( var j = 0; j !== stride; ++ j ) {
  18297. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18298. }
  18299. }
  18300. return result;
  18301. },
  18302. // function for parsing AOS keyframe formats
  18303. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18304. var i = 1, key = jsonKeys[ 0 ];
  18305. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18306. key = jsonKeys[ i ++ ];
  18307. }
  18308. if ( key === undefined ) return; // no data
  18309. var value = key[ valuePropertyName ];
  18310. if ( value === undefined ) return; // no data
  18311. if ( Array.isArray( value ) ) {
  18312. do {
  18313. value = key[ valuePropertyName ];
  18314. if ( value !== undefined ) {
  18315. times.push( key.time );
  18316. values.push.apply( values, value ); // push all elements
  18317. }
  18318. key = jsonKeys[ i ++ ];
  18319. } while ( key !== undefined );
  18320. } else if ( value.toArray !== undefined ) {
  18321. // ...assume THREE.Math-ish
  18322. do {
  18323. value = key[ valuePropertyName ];
  18324. if ( value !== undefined ) {
  18325. times.push( key.time );
  18326. value.toArray( values, values.length );
  18327. }
  18328. key = jsonKeys[ i ++ ];
  18329. } while ( key !== undefined );
  18330. } else {
  18331. // otherwise push as-is
  18332. do {
  18333. value = key[ valuePropertyName ];
  18334. if ( value !== undefined ) {
  18335. times.push( key.time );
  18336. values.push( value );
  18337. }
  18338. key = jsonKeys[ i ++ ];
  18339. } while ( key !== undefined );
  18340. }
  18341. }
  18342. };
  18343. /**
  18344. * Abstract base class of interpolants over parametric samples.
  18345. *
  18346. * The parameter domain is one dimensional, typically the time or a path
  18347. * along a curve defined by the data.
  18348. *
  18349. * The sample values can have any dimensionality and derived classes may
  18350. * apply special interpretations to the data.
  18351. *
  18352. * This class provides the interval seek in a Template Method, deferring
  18353. * the actual interpolation to derived classes.
  18354. *
  18355. * Time complexity is O(1) for linear access crossing at most two points
  18356. * and O(log N) for random access, where N is the number of positions.
  18357. *
  18358. * References:
  18359. *
  18360. * http://www.oodesign.com/template-method-pattern.html
  18361. *
  18362. * @author tschw
  18363. */
  18364. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18365. this.parameterPositions = parameterPositions;
  18366. this._cachedIndex = 0;
  18367. this.resultBuffer = resultBuffer !== undefined ?
  18368. resultBuffer : new sampleValues.constructor( sampleSize );
  18369. this.sampleValues = sampleValues;
  18370. this.valueSize = sampleSize;
  18371. }
  18372. Object.assign( Interpolant.prototype, {
  18373. evaluate: function( t ) {
  18374. var pp = this.parameterPositions,
  18375. i1 = this._cachedIndex,
  18376. t1 = pp[ i1 ],
  18377. t0 = pp[ i1 - 1 ];
  18378. validate_interval: {
  18379. seek: {
  18380. var right;
  18381. linear_scan: {
  18382. //- See http://jsperf.com/comparison-to-undefined/3
  18383. //- slower code:
  18384. //-
  18385. //- if ( t >= t1 || t1 === undefined ) {
  18386. forward_scan: if ( ! ( t < t1 ) ) {
  18387. for ( var giveUpAt = i1 + 2; ;) {
  18388. if ( t1 === undefined ) {
  18389. if ( t < t0 ) break forward_scan;
  18390. // after end
  18391. i1 = pp.length;
  18392. this._cachedIndex = i1;
  18393. return this.afterEnd_( i1 - 1, t, t0 );
  18394. }
  18395. if ( i1 === giveUpAt ) break; // this loop
  18396. t0 = t1;
  18397. t1 = pp[ ++ i1 ];
  18398. if ( t < t1 ) {
  18399. // we have arrived at the sought interval
  18400. break seek;
  18401. }
  18402. }
  18403. // prepare binary search on the right side of the index
  18404. right = pp.length;
  18405. break linear_scan;
  18406. }
  18407. //- slower code:
  18408. //- if ( t < t0 || t0 === undefined ) {
  18409. if ( ! ( t >= t0 ) ) {
  18410. // looping?
  18411. var t1global = pp[ 1 ];
  18412. if ( t < t1global ) {
  18413. i1 = 2; // + 1, using the scan for the details
  18414. t0 = t1global;
  18415. }
  18416. // linear reverse scan
  18417. for ( var giveUpAt = i1 - 2; ;) {
  18418. if ( t0 === undefined ) {
  18419. // before start
  18420. this._cachedIndex = 0;
  18421. return this.beforeStart_( 0, t, t1 );
  18422. }
  18423. if ( i1 === giveUpAt ) break; // this loop
  18424. t1 = t0;
  18425. t0 = pp[ -- i1 - 1 ];
  18426. if ( t >= t0 ) {
  18427. // we have arrived at the sought interval
  18428. break seek;
  18429. }
  18430. }
  18431. // prepare binary search on the left side of the index
  18432. right = i1;
  18433. i1 = 0;
  18434. break linear_scan;
  18435. }
  18436. // the interval is valid
  18437. break validate_interval;
  18438. } // linear scan
  18439. // binary search
  18440. while ( i1 < right ) {
  18441. var mid = ( i1 + right ) >>> 1;
  18442. if ( t < pp[ mid ] ) {
  18443. right = mid;
  18444. } else {
  18445. i1 = mid + 1;
  18446. }
  18447. }
  18448. t1 = pp[ i1 ];
  18449. t0 = pp[ i1 - 1 ];
  18450. // check boundary cases, again
  18451. if ( t0 === undefined ) {
  18452. this._cachedIndex = 0;
  18453. return this.beforeStart_( 0, t, t1 );
  18454. }
  18455. if ( t1 === undefined ) {
  18456. i1 = pp.length;
  18457. this._cachedIndex = i1;
  18458. return this.afterEnd_( i1 - 1, t0, t );
  18459. }
  18460. } // seek
  18461. this._cachedIndex = i1;
  18462. this.intervalChanged_( i1, t0, t1 );
  18463. } // validate_interval
  18464. return this.interpolate_( i1, t0, t, t1 );
  18465. },
  18466. settings: null, // optional, subclass-specific settings structure
  18467. // Note: The indirection allows central control of many interpolants.
  18468. // --- Protected interface
  18469. DefaultSettings_: {},
  18470. getSettings_: function() {
  18471. return this.settings || this.DefaultSettings_;
  18472. },
  18473. copySampleValue_: function( index ) {
  18474. // copies a sample value to the result buffer
  18475. var result = this.resultBuffer,
  18476. values = this.sampleValues,
  18477. stride = this.valueSize,
  18478. offset = index * stride;
  18479. for ( var i = 0; i !== stride; ++ i ) {
  18480. result[ i ] = values[ offset + i ];
  18481. }
  18482. return result;
  18483. },
  18484. // Template methods for derived classes:
  18485. interpolate_: function( i1, t0, t, t1 ) {
  18486. throw new Error( "call to abstract method" );
  18487. // implementations shall return this.resultBuffer
  18488. },
  18489. intervalChanged_: function( i1, t0, t1 ) {
  18490. // empty
  18491. }
  18492. } );
  18493. //!\ DECLARE ALIAS AFTER assign prototype !
  18494. Object.assign( Interpolant.prototype, {
  18495. //( 0, t, t0 ), returns this.resultBuffer
  18496. beforeStart_: Interpolant.prototype.copySampleValue_,
  18497. //( N-1, tN-1, t ), returns this.resultBuffer
  18498. afterEnd_: Interpolant.prototype.copySampleValue_,
  18499. } );
  18500. /**
  18501. * Fast and simple cubic spline interpolant.
  18502. *
  18503. * It was derived from a Hermitian construction setting the first derivative
  18504. * at each sample position to the linear slope between neighboring positions
  18505. * over their parameter interval.
  18506. *
  18507. * @author tschw
  18508. */
  18509. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18510. Interpolant.call(
  18511. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18512. this._weightPrev = -0;
  18513. this._offsetPrev = -0;
  18514. this._weightNext = -0;
  18515. this._offsetNext = -0;
  18516. }
  18517. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18518. constructor: CubicInterpolant,
  18519. DefaultSettings_: {
  18520. endingStart: ZeroCurvatureEnding,
  18521. endingEnd: ZeroCurvatureEnding
  18522. },
  18523. intervalChanged_: function( i1, t0, t1 ) {
  18524. var pp = this.parameterPositions,
  18525. iPrev = i1 - 2,
  18526. iNext = i1 + 1,
  18527. tPrev = pp[ iPrev ],
  18528. tNext = pp[ iNext ];
  18529. if ( tPrev === undefined ) {
  18530. switch ( this.getSettings_().endingStart ) {
  18531. case ZeroSlopeEnding:
  18532. // f'(t0) = 0
  18533. iPrev = i1;
  18534. tPrev = 2 * t0 - t1;
  18535. break;
  18536. case WrapAroundEnding:
  18537. // use the other end of the curve
  18538. iPrev = pp.length - 2;
  18539. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18540. break;
  18541. default: // ZeroCurvatureEnding
  18542. // f''(t0) = 0 a.k.a. Natural Spline
  18543. iPrev = i1;
  18544. tPrev = t1;
  18545. }
  18546. }
  18547. if ( tNext === undefined ) {
  18548. switch ( this.getSettings_().endingEnd ) {
  18549. case ZeroSlopeEnding:
  18550. // f'(tN) = 0
  18551. iNext = i1;
  18552. tNext = 2 * t1 - t0;
  18553. break;
  18554. case WrapAroundEnding:
  18555. // use the other end of the curve
  18556. iNext = 1;
  18557. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18558. break;
  18559. default: // ZeroCurvatureEnding
  18560. // f''(tN) = 0, a.k.a. Natural Spline
  18561. iNext = i1 - 1;
  18562. tNext = t0;
  18563. }
  18564. }
  18565. var halfDt = ( t1 - t0 ) * 0.5,
  18566. stride = this.valueSize;
  18567. this._weightPrev = halfDt / ( t0 - tPrev );
  18568. this._weightNext = halfDt / ( tNext - t1 );
  18569. this._offsetPrev = iPrev * stride;
  18570. this._offsetNext = iNext * stride;
  18571. },
  18572. interpolate_: function( i1, t0, t, t1 ) {
  18573. var result = this.resultBuffer,
  18574. values = this.sampleValues,
  18575. stride = this.valueSize,
  18576. o1 = i1 * stride, o0 = o1 - stride,
  18577. oP = this._offsetPrev, oN = this._offsetNext,
  18578. wP = this._weightPrev, wN = this._weightNext,
  18579. p = ( t - t0 ) / ( t1 - t0 ),
  18580. pp = p * p,
  18581. ppp = pp * p;
  18582. // evaluate polynomials
  18583. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18584. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18585. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18586. var sN = wN * ppp - wN * pp;
  18587. // combine data linearly
  18588. for ( var i = 0; i !== stride; ++ i ) {
  18589. result[ i ] =
  18590. sP * values[ oP + i ] +
  18591. s0 * values[ o0 + i ] +
  18592. s1 * values[ o1 + i ] +
  18593. sN * values[ oN + i ];
  18594. }
  18595. return result;
  18596. }
  18597. } );
  18598. /**
  18599. * @author tschw
  18600. */
  18601. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18602. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18603. }
  18604. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18605. constructor: LinearInterpolant,
  18606. interpolate_: function( i1, t0, t, t1 ) {
  18607. var result = this.resultBuffer,
  18608. values = this.sampleValues,
  18609. stride = this.valueSize,
  18610. offset1 = i1 * stride,
  18611. offset0 = offset1 - stride,
  18612. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18613. weight0 = 1 - weight1;
  18614. for ( var i = 0; i !== stride; ++ i ) {
  18615. result[ i ] =
  18616. values[ offset0 + i ] * weight0 +
  18617. values[ offset1 + i ] * weight1;
  18618. }
  18619. return result;
  18620. }
  18621. } );
  18622. /**
  18623. *
  18624. * Interpolant that evaluates to the sample value at the position preceeding
  18625. * the parameter.
  18626. *
  18627. * @author tschw
  18628. */
  18629. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18630. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18631. }
  18632. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18633. constructor: DiscreteInterpolant,
  18634. interpolate_: function( i1, t0, t, t1 ) {
  18635. return this.copySampleValue_( i1 - 1 );
  18636. }
  18637. } );
  18638. var KeyframeTrackPrototype;
  18639. KeyframeTrackPrototype = {
  18640. TimeBufferType: Float32Array,
  18641. ValueBufferType: Float32Array,
  18642. DefaultInterpolation: InterpolateLinear,
  18643. InterpolantFactoryMethodDiscrete: function ( result ) {
  18644. return new DiscreteInterpolant(
  18645. this.times, this.values, this.getValueSize(), result );
  18646. },
  18647. InterpolantFactoryMethodLinear: function ( result ) {
  18648. return new LinearInterpolant(
  18649. this.times, this.values, this.getValueSize(), result );
  18650. },
  18651. InterpolantFactoryMethodSmooth: function ( result ) {
  18652. return new CubicInterpolant(
  18653. this.times, this.values, this.getValueSize(), result );
  18654. },
  18655. setInterpolation: function ( interpolation ) {
  18656. var factoryMethod;
  18657. switch ( interpolation ) {
  18658. case InterpolateDiscrete:
  18659. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18660. break;
  18661. case InterpolateLinear:
  18662. factoryMethod = this.InterpolantFactoryMethodLinear;
  18663. break;
  18664. case InterpolateSmooth:
  18665. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18666. break;
  18667. }
  18668. if ( factoryMethod === undefined ) {
  18669. var message = "unsupported interpolation for " +
  18670. this.ValueTypeName + " keyframe track named " + this.name;
  18671. if ( this.createInterpolant === undefined ) {
  18672. // fall back to default, unless the default itself is messed up
  18673. if ( interpolation !== this.DefaultInterpolation ) {
  18674. this.setInterpolation( this.DefaultInterpolation );
  18675. } else {
  18676. throw new Error( message ); // fatal, in this case
  18677. }
  18678. }
  18679. console.warn( message );
  18680. return;
  18681. }
  18682. this.createInterpolant = factoryMethod;
  18683. },
  18684. getInterpolation: function () {
  18685. switch ( this.createInterpolant ) {
  18686. case this.InterpolantFactoryMethodDiscrete:
  18687. return InterpolateDiscrete;
  18688. case this.InterpolantFactoryMethodLinear:
  18689. return InterpolateLinear;
  18690. case this.InterpolantFactoryMethodSmooth:
  18691. return InterpolateSmooth;
  18692. }
  18693. },
  18694. getValueSize: function () {
  18695. return this.values.length / this.times.length;
  18696. },
  18697. // move all keyframes either forwards or backwards in time
  18698. shift: function ( timeOffset ) {
  18699. if ( timeOffset !== 0.0 ) {
  18700. var times = this.times;
  18701. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18702. times[ i ] += timeOffset;
  18703. }
  18704. }
  18705. return this;
  18706. },
  18707. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18708. scale: function ( timeScale ) {
  18709. if ( timeScale !== 1.0 ) {
  18710. var times = this.times;
  18711. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18712. times[ i ] *= timeScale;
  18713. }
  18714. }
  18715. return this;
  18716. },
  18717. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18718. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18719. trim: function ( startTime, endTime ) {
  18720. var times = this.times,
  18721. nKeys = times.length,
  18722. from = 0,
  18723. to = nKeys - 1;
  18724. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18725. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18726. ++ to; // inclusive -> exclusive bound
  18727. if ( from !== 0 || to !== nKeys ) {
  18728. // empty tracks are forbidden, so keep at least one keyframe
  18729. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18730. var stride = this.getValueSize();
  18731. this.times = AnimationUtils.arraySlice( times, from, to );
  18732. this.values = AnimationUtils.
  18733. arraySlice( this.values, from * stride, to * stride );
  18734. }
  18735. return this;
  18736. },
  18737. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18738. validate: function () {
  18739. var valid = true;
  18740. var valueSize = this.getValueSize();
  18741. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18742. console.error( "invalid value size in track", this );
  18743. valid = false;
  18744. }
  18745. var times = this.times,
  18746. values = this.values,
  18747. nKeys = times.length;
  18748. if ( nKeys === 0 ) {
  18749. console.error( "track is empty", this );
  18750. valid = false;
  18751. }
  18752. var prevTime = null;
  18753. for ( var i = 0; i !== nKeys; i ++ ) {
  18754. var currTime = times[ i ];
  18755. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18756. console.error( "time is not a valid number", this, i, currTime );
  18757. valid = false;
  18758. break;
  18759. }
  18760. if ( prevTime !== null && prevTime > currTime ) {
  18761. console.error( "out of order keys", this, i, currTime, prevTime );
  18762. valid = false;
  18763. break;
  18764. }
  18765. prevTime = currTime;
  18766. }
  18767. if ( values !== undefined ) {
  18768. if ( AnimationUtils.isTypedArray( values ) ) {
  18769. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18770. var value = values[ i ];
  18771. if ( isNaN( value ) ) {
  18772. console.error( "value is not a valid number", this, i, value );
  18773. valid = false;
  18774. break;
  18775. }
  18776. }
  18777. }
  18778. }
  18779. return valid;
  18780. },
  18781. // removes equivalent sequential keys as common in morph target sequences
  18782. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18783. optimize: function () {
  18784. var times = this.times,
  18785. values = this.values,
  18786. stride = this.getValueSize(),
  18787. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18788. writeIndex = 1,
  18789. lastIndex = times.length - 1;
  18790. for ( var i = 1; i < lastIndex; ++ i ) {
  18791. var keep = false;
  18792. var time = times[ i ];
  18793. var timeNext = times[ i + 1 ];
  18794. // remove adjacent keyframes scheduled at the same time
  18795. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18796. if ( ! smoothInterpolation ) {
  18797. // remove unnecessary keyframes same as their neighbors
  18798. var offset = i * stride,
  18799. offsetP = offset - stride,
  18800. offsetN = offset + stride;
  18801. for ( var j = 0; j !== stride; ++ j ) {
  18802. var value = values[ offset + j ];
  18803. if ( value !== values[ offsetP + j ] ||
  18804. value !== values[ offsetN + j ] ) {
  18805. keep = true;
  18806. break;
  18807. }
  18808. }
  18809. } else keep = true;
  18810. }
  18811. // in-place compaction
  18812. if ( keep ) {
  18813. if ( i !== writeIndex ) {
  18814. times[ writeIndex ] = times[ i ];
  18815. var readOffset = i * stride,
  18816. writeOffset = writeIndex * stride;
  18817. for ( var j = 0; j !== stride; ++ j )
  18818. values[ writeOffset + j ] = values[ readOffset + j ];
  18819. }
  18820. ++ writeIndex;
  18821. }
  18822. }
  18823. // flush last keyframe (compaction looks ahead)
  18824. if ( lastIndex > 0 ) {
  18825. times[ writeIndex ] = times[ lastIndex ];
  18826. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18827. values[ writeOffset + j ] = values[ readOffset + j ];
  18828. ++ writeIndex;
  18829. }
  18830. if ( writeIndex !== times.length ) {
  18831. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18832. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18833. }
  18834. return this;
  18835. }
  18836. };
  18837. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18838. if ( name === undefined ) throw new Error( "track name is undefined" );
  18839. if ( times === undefined || times.length === 0 ) {
  18840. throw new Error( "no keyframes in track named " + name );
  18841. }
  18842. this.name = name;
  18843. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18844. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18845. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18846. this.validate();
  18847. this.optimize();
  18848. }
  18849. /**
  18850. *
  18851. * A Track of vectored keyframe values.
  18852. *
  18853. *
  18854. * @author Ben Houston / http://clara.io/
  18855. * @author David Sarno / http://lighthaus.us/
  18856. * @author tschw
  18857. */
  18858. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18859. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18860. }
  18861. VectorKeyframeTrack.prototype =
  18862. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18863. constructor: VectorKeyframeTrack,
  18864. ValueTypeName: 'vector'
  18865. // ValueBufferType is inherited
  18866. // DefaultInterpolation is inherited
  18867. } );
  18868. /**
  18869. * Spherical linear unit quaternion interpolant.
  18870. *
  18871. * @author tschw
  18872. */
  18873. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18874. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18875. }
  18876. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18877. constructor: QuaternionLinearInterpolant,
  18878. interpolate_: function( i1, t0, t, t1 ) {
  18879. var result = this.resultBuffer,
  18880. values = this.sampleValues,
  18881. stride = this.valueSize,
  18882. offset = i1 * stride,
  18883. alpha = ( t - t0 ) / ( t1 - t0 );
  18884. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18885. Quaternion.slerpFlat( result, 0,
  18886. values, offset - stride, values, offset, alpha );
  18887. }
  18888. return result;
  18889. }
  18890. } );
  18891. /**
  18892. *
  18893. * A Track of quaternion keyframe values.
  18894. *
  18895. * @author Ben Houston / http://clara.io/
  18896. * @author David Sarno / http://lighthaus.us/
  18897. * @author tschw
  18898. */
  18899. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18900. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18901. }
  18902. QuaternionKeyframeTrack.prototype =
  18903. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18904. constructor: QuaternionKeyframeTrack,
  18905. ValueTypeName: 'quaternion',
  18906. // ValueBufferType is inherited
  18907. DefaultInterpolation: InterpolateLinear,
  18908. InterpolantFactoryMethodLinear: function( result ) {
  18909. return new QuaternionLinearInterpolant(
  18910. this.times, this.values, this.getValueSize(), result );
  18911. },
  18912. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18913. } );
  18914. /**
  18915. *
  18916. * A Track of numeric keyframe values.
  18917. *
  18918. * @author Ben Houston / http://clara.io/
  18919. * @author David Sarno / http://lighthaus.us/
  18920. * @author tschw
  18921. */
  18922. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18923. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18924. }
  18925. NumberKeyframeTrack.prototype =
  18926. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18927. constructor: NumberKeyframeTrack,
  18928. ValueTypeName: 'number'
  18929. // ValueBufferType is inherited
  18930. // DefaultInterpolation is inherited
  18931. } );
  18932. /**
  18933. *
  18934. * A Track that interpolates Strings
  18935. *
  18936. *
  18937. * @author Ben Houston / http://clara.io/
  18938. * @author David Sarno / http://lighthaus.us/
  18939. * @author tschw
  18940. */
  18941. function StringKeyframeTrack( name, times, values, interpolation ) {
  18942. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18943. }
  18944. StringKeyframeTrack.prototype =
  18945. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18946. constructor: StringKeyframeTrack,
  18947. ValueTypeName: 'string',
  18948. ValueBufferType: Array,
  18949. DefaultInterpolation: InterpolateDiscrete,
  18950. InterpolantFactoryMethodLinear: undefined,
  18951. InterpolantFactoryMethodSmooth: undefined
  18952. } );
  18953. /**
  18954. *
  18955. * A Track of Boolean keyframe values.
  18956. *
  18957. *
  18958. * @author Ben Houston / http://clara.io/
  18959. * @author David Sarno / http://lighthaus.us/
  18960. * @author tschw
  18961. */
  18962. function BooleanKeyframeTrack( name, times, values ) {
  18963. KeyframeTrackConstructor.call( this, name, times, values );
  18964. }
  18965. BooleanKeyframeTrack.prototype =
  18966. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18967. constructor: BooleanKeyframeTrack,
  18968. ValueTypeName: 'bool',
  18969. ValueBufferType: Array,
  18970. DefaultInterpolation: InterpolateDiscrete,
  18971. InterpolantFactoryMethodLinear: undefined,
  18972. InterpolantFactoryMethodSmooth: undefined
  18973. // Note: Actually this track could have a optimized / compressed
  18974. // representation of a single value and a custom interpolant that
  18975. // computes "firstValue ^ isOdd( index )".
  18976. } );
  18977. /**
  18978. *
  18979. * A Track of keyframe values that represent color.
  18980. *
  18981. *
  18982. * @author Ben Houston / http://clara.io/
  18983. * @author David Sarno / http://lighthaus.us/
  18984. * @author tschw
  18985. */
  18986. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18987. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18988. }
  18989. ColorKeyframeTrack.prototype =
  18990. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18991. constructor: ColorKeyframeTrack,
  18992. ValueTypeName: 'color'
  18993. // ValueBufferType is inherited
  18994. // DefaultInterpolation is inherited
  18995. // Note: Very basic implementation and nothing special yet.
  18996. // However, this is the place for color space parameterization.
  18997. } );
  18998. /**
  18999. *
  19000. * A timed sequence of keyframes for a specific property.
  19001. *
  19002. *
  19003. * @author Ben Houston / http://clara.io/
  19004. * @author David Sarno / http://lighthaus.us/
  19005. * @author tschw
  19006. */
  19007. function KeyframeTrack( name, times, values, interpolation ) {
  19008. KeyframeTrackConstructor.apply( this, arguments );
  19009. }
  19010. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19011. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19012. // Static methods:
  19013. Object.assign( KeyframeTrack, {
  19014. // Serialization (in static context, because of constructor invocation
  19015. // and automatic invocation of .toJSON):
  19016. parse: function( json ) {
  19017. if( json.type === undefined ) {
  19018. throw new Error( "track type undefined, can not parse" );
  19019. }
  19020. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19021. if ( json.times === undefined ) {
  19022. var times = [], values = [];
  19023. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19024. json.times = times;
  19025. json.values = values;
  19026. }
  19027. // derived classes can define a static parse method
  19028. if ( trackType.parse !== undefined ) {
  19029. return trackType.parse( json );
  19030. } else {
  19031. // by default, we asssume a constructor compatible with the base
  19032. return new trackType(
  19033. json.name, json.times, json.values, json.interpolation );
  19034. }
  19035. },
  19036. toJSON: function( track ) {
  19037. var trackType = track.constructor;
  19038. var json;
  19039. // derived classes can define a static toJSON method
  19040. if ( trackType.toJSON !== undefined ) {
  19041. json = trackType.toJSON( track );
  19042. } else {
  19043. // by default, we assume the data can be serialized as-is
  19044. json = {
  19045. 'name': track.name,
  19046. 'times': AnimationUtils.convertArray( track.times, Array ),
  19047. 'values': AnimationUtils.convertArray( track.values, Array )
  19048. };
  19049. var interpolation = track.getInterpolation();
  19050. if ( interpolation !== track.DefaultInterpolation ) {
  19051. json.interpolation = interpolation;
  19052. }
  19053. }
  19054. json.type = track.ValueTypeName; // mandatory
  19055. return json;
  19056. },
  19057. _getTrackTypeForValueTypeName: function( typeName ) {
  19058. switch( typeName.toLowerCase() ) {
  19059. case "scalar":
  19060. case "double":
  19061. case "float":
  19062. case "number":
  19063. case "integer":
  19064. return NumberKeyframeTrack;
  19065. case "vector":
  19066. case "vector2":
  19067. case "vector3":
  19068. case "vector4":
  19069. return VectorKeyframeTrack;
  19070. case "color":
  19071. return ColorKeyframeTrack;
  19072. case "quaternion":
  19073. return QuaternionKeyframeTrack;
  19074. case "bool":
  19075. case "boolean":
  19076. return BooleanKeyframeTrack;
  19077. case "string":
  19078. return StringKeyframeTrack;
  19079. }
  19080. throw new Error( "Unsupported typeName: " + typeName );
  19081. }
  19082. } );
  19083. /**
  19084. *
  19085. * Reusable set of Tracks that represent an animation.
  19086. *
  19087. * @author Ben Houston / http://clara.io/
  19088. * @author David Sarno / http://lighthaus.us/
  19089. */
  19090. function AnimationClip( name, duration, tracks ) {
  19091. this.name = name;
  19092. this.tracks = tracks;
  19093. this.duration = ( duration !== undefined ) ? duration : - 1;
  19094. this.uuid = _Math.generateUUID();
  19095. // this means it should figure out its duration by scanning the tracks
  19096. if ( this.duration < 0 ) {
  19097. this.resetDuration();
  19098. }
  19099. this.optimize();
  19100. }
  19101. Object.assign( AnimationClip, {
  19102. parse: function ( json ) {
  19103. var tracks = [],
  19104. jsonTracks = json.tracks,
  19105. frameTime = 1.0 / ( json.fps || 1.0 );
  19106. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19107. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19108. }
  19109. return new AnimationClip( json.name, json.duration, tracks );
  19110. },
  19111. toJSON: function ( clip ) {
  19112. var tracks = [],
  19113. clipTracks = clip.tracks;
  19114. var json = {
  19115. 'name': clip.name,
  19116. 'duration': clip.duration,
  19117. 'tracks': tracks
  19118. };
  19119. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19120. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19121. }
  19122. return json;
  19123. },
  19124. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19125. var numMorphTargets = morphTargetSequence.length;
  19126. var tracks = [];
  19127. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19128. var times = [];
  19129. var values = [];
  19130. times.push(
  19131. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19132. i,
  19133. ( i + 1 ) % numMorphTargets );
  19134. values.push( 0, 1, 0 );
  19135. var order = AnimationUtils.getKeyframeOrder( times );
  19136. times = AnimationUtils.sortedArray( times, 1, order );
  19137. values = AnimationUtils.sortedArray( values, 1, order );
  19138. // if there is a key at the first frame, duplicate it as the
  19139. // last frame as well for perfect loop.
  19140. if ( ! noLoop && times[ 0 ] === 0 ) {
  19141. times.push( numMorphTargets );
  19142. values.push( values[ 0 ] );
  19143. }
  19144. tracks.push(
  19145. new NumberKeyframeTrack(
  19146. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19147. times, values
  19148. ).scale( 1.0 / fps ) );
  19149. }
  19150. return new AnimationClip( name, - 1, tracks );
  19151. },
  19152. findByName: function ( objectOrClipArray, name ) {
  19153. var clipArray = objectOrClipArray;
  19154. if ( ! Array.isArray( objectOrClipArray ) ) {
  19155. var o = objectOrClipArray;
  19156. clipArray = o.geometry && o.geometry.animations || o.animations;
  19157. }
  19158. for ( var i = 0; i < clipArray.length; i ++ ) {
  19159. if ( clipArray[ i ].name === name ) {
  19160. return clipArray[ i ];
  19161. }
  19162. }
  19163. return null;
  19164. },
  19165. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19166. var animationToMorphTargets = {};
  19167. // tested with https://regex101.com/ on trick sequences
  19168. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19169. var pattern = /^([\w-]*?)([\d]+)$/;
  19170. // sort morph target names into animation groups based
  19171. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19172. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19173. var morphTarget = morphTargets[ i ];
  19174. var parts = morphTarget.name.match( pattern );
  19175. if ( parts && parts.length > 1 ) {
  19176. var name = parts[ 1 ];
  19177. var animationMorphTargets = animationToMorphTargets[ name ];
  19178. if ( ! animationMorphTargets ) {
  19179. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19180. }
  19181. animationMorphTargets.push( morphTarget );
  19182. }
  19183. }
  19184. var clips = [];
  19185. for ( var name in animationToMorphTargets ) {
  19186. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19187. }
  19188. return clips;
  19189. },
  19190. // parse the animation.hierarchy format
  19191. parseAnimation: function ( animation, bones ) {
  19192. if ( ! animation ) {
  19193. console.error( " no animation in JSONLoader data" );
  19194. return null;
  19195. }
  19196. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19197. // only return track if there are actually keys.
  19198. if ( animationKeys.length !== 0 ) {
  19199. var times = [];
  19200. var values = [];
  19201. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19202. // empty keys are filtered out, so check again
  19203. if ( times.length !== 0 ) {
  19204. destTracks.push( new trackType( trackName, times, values ) );
  19205. }
  19206. }
  19207. };
  19208. var tracks = [];
  19209. var clipName = animation.name || 'default';
  19210. // automatic length determination in AnimationClip.
  19211. var duration = animation.length || - 1;
  19212. var fps = animation.fps || 30;
  19213. var hierarchyTracks = animation.hierarchy || [];
  19214. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19215. var animationKeys = hierarchyTracks[ h ].keys;
  19216. // skip empty tracks
  19217. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19218. // process morph targets
  19219. if ( animationKeys[ 0 ].morphTargets ) {
  19220. // figure out all morph targets used in this track
  19221. var morphTargetNames = {};
  19222. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19223. if ( animationKeys[ k ].morphTargets ) {
  19224. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19225. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19226. }
  19227. }
  19228. }
  19229. // create a track for each morph target with all zero
  19230. // morphTargetInfluences except for the keys in which
  19231. // the morphTarget is named.
  19232. for ( var morphTargetName in morphTargetNames ) {
  19233. var times = [];
  19234. var values = [];
  19235. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19236. var animationKey = animationKeys[ k ];
  19237. times.push( animationKey.time );
  19238. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19239. }
  19240. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19241. }
  19242. duration = morphTargetNames.length * ( fps || 1.0 );
  19243. } else {
  19244. // ...assume skeletal animation
  19245. var boneName = '.bones[' + bones[ h ].name + ']';
  19246. addNonemptyTrack(
  19247. VectorKeyframeTrack, boneName + '.position',
  19248. animationKeys, 'pos', tracks );
  19249. addNonemptyTrack(
  19250. QuaternionKeyframeTrack, boneName + '.quaternion',
  19251. animationKeys, 'rot', tracks );
  19252. addNonemptyTrack(
  19253. VectorKeyframeTrack, boneName + '.scale',
  19254. animationKeys, 'scl', tracks );
  19255. }
  19256. }
  19257. if ( tracks.length === 0 ) {
  19258. return null;
  19259. }
  19260. var clip = new AnimationClip( clipName, duration, tracks );
  19261. return clip;
  19262. }
  19263. } );
  19264. Object.assign( AnimationClip.prototype, {
  19265. resetDuration: function () {
  19266. var tracks = this.tracks, duration = 0;
  19267. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19268. var track = this.tracks[ i ];
  19269. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19270. }
  19271. this.duration = duration;
  19272. },
  19273. trim: function () {
  19274. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19275. this.tracks[ i ].trim( 0, this.duration );
  19276. }
  19277. return this;
  19278. },
  19279. optimize: function () {
  19280. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19281. this.tracks[ i ].optimize();
  19282. }
  19283. return this;
  19284. }
  19285. } );
  19286. /**
  19287. * @author mrdoob / http://mrdoob.com/
  19288. */
  19289. function MaterialLoader( manager ) {
  19290. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19291. this.textures = {};
  19292. }
  19293. Object.assign( MaterialLoader.prototype, {
  19294. load: function ( url, onLoad, onProgress, onError ) {
  19295. var scope = this;
  19296. var loader = new FileLoader( scope.manager );
  19297. loader.load( url, function ( text ) {
  19298. onLoad( scope.parse( JSON.parse( text ) ) );
  19299. }, onProgress, onError );
  19300. },
  19301. setTextures: function ( value ) {
  19302. this.textures = value;
  19303. },
  19304. parse: function ( json ) {
  19305. var textures = this.textures;
  19306. function getTexture( name ) {
  19307. if ( textures[ name ] === undefined ) {
  19308. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19309. }
  19310. return textures[ name ];
  19311. }
  19312. var material = new Materials[ json.type ]();
  19313. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19314. if ( json.name !== undefined ) material.name = json.name;
  19315. if ( json.color !== undefined ) material.color.setHex( json.color );
  19316. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19317. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19318. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19319. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19320. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19321. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19322. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19323. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19324. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19325. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19326. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19327. if ( json.fog !== undefined ) material.fog = json.fog;
  19328. if ( json.shading !== undefined ) material.shading = json.shading;
  19329. if ( json.blending !== undefined ) material.blending = json.blending;
  19330. if ( json.side !== undefined ) material.side = json.side;
  19331. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19332. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19333. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19334. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19335. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19336. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19337. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19338. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19339. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19340. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19341. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19342. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19343. // for PointsMaterial
  19344. if ( json.size !== undefined ) material.size = json.size;
  19345. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19346. // maps
  19347. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19348. if ( json.alphaMap !== undefined ) {
  19349. material.alphaMap = getTexture( json.alphaMap );
  19350. material.transparent = true;
  19351. }
  19352. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19353. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19354. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19355. if ( json.normalScale !== undefined ) {
  19356. var normalScale = json.normalScale;
  19357. if ( Array.isArray( normalScale ) === false ) {
  19358. // Blender exporter used to export a scalar. See #7459
  19359. normalScale = [ normalScale, normalScale ];
  19360. }
  19361. material.normalScale = new Vector2().fromArray( normalScale );
  19362. }
  19363. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19364. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19365. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19366. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19367. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19368. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19369. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19370. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19371. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19372. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19373. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19374. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19375. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19376. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19377. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19378. return material;
  19379. }
  19380. } );
  19381. /**
  19382. * @author mrdoob / http://mrdoob.com/
  19383. */
  19384. function BufferGeometryLoader( manager ) {
  19385. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19386. }
  19387. Object.assign( BufferGeometryLoader.prototype, {
  19388. load: function ( url, onLoad, onProgress, onError ) {
  19389. var scope = this;
  19390. var loader = new FileLoader( scope.manager );
  19391. loader.load( url, function ( text ) {
  19392. onLoad( scope.parse( JSON.parse( text ) ) );
  19393. }, onProgress, onError );
  19394. },
  19395. parse: function ( json ) {
  19396. var geometry = new BufferGeometry();
  19397. var index = json.data.index;
  19398. if ( index !== undefined ) {
  19399. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19400. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19401. }
  19402. var attributes = json.data.attributes;
  19403. for ( var key in attributes ) {
  19404. var attribute = attributes[ key ];
  19405. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19406. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19407. }
  19408. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19409. if ( groups !== undefined ) {
  19410. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19411. var group = groups[ i ];
  19412. geometry.addGroup( group.start, group.count, group.materialIndex );
  19413. }
  19414. }
  19415. var boundingSphere = json.data.boundingSphere;
  19416. if ( boundingSphere !== undefined ) {
  19417. var center = new Vector3();
  19418. if ( boundingSphere.center !== undefined ) {
  19419. center.fromArray( boundingSphere.center );
  19420. }
  19421. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19422. }
  19423. return geometry;
  19424. }
  19425. } );
  19426. var TYPED_ARRAYS = {
  19427. Int8Array: Int8Array,
  19428. Uint8Array: Uint8Array,
  19429. Uint8ClampedArray: Uint8ClampedArray,
  19430. Int16Array: Int16Array,
  19431. Uint16Array: Uint16Array,
  19432. Int32Array: Int32Array,
  19433. Uint32Array: Uint32Array,
  19434. Float32Array: Float32Array,
  19435. Float64Array: Float64Array
  19436. };
  19437. /**
  19438. * @author alteredq / http://alteredqualia.com/
  19439. */
  19440. function Loader() {
  19441. this.onLoadStart = function () {};
  19442. this.onLoadProgress = function () {};
  19443. this.onLoadComplete = function () {};
  19444. }
  19445. Loader.Handlers = {
  19446. handlers: [],
  19447. add: function ( regex, loader ) {
  19448. this.handlers.push( regex, loader );
  19449. },
  19450. get: function ( file ) {
  19451. var handlers = this.handlers;
  19452. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19453. var regex = handlers[ i ];
  19454. var loader = handlers[ i + 1 ];
  19455. if ( regex.test( file ) ) {
  19456. return loader;
  19457. }
  19458. }
  19459. return null;
  19460. }
  19461. };
  19462. Object.assign( Loader.prototype, {
  19463. crossOrigin: undefined,
  19464. extractUrlBase: function ( url ) {
  19465. var parts = url.split( '/' );
  19466. if ( parts.length === 1 ) return './';
  19467. parts.pop();
  19468. return parts.join( '/' ) + '/';
  19469. },
  19470. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19471. var array = [];
  19472. for ( var i = 0; i < materials.length; ++ i ) {
  19473. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19474. }
  19475. return array;
  19476. },
  19477. createMaterial: ( function () {
  19478. var BlendingMode = {
  19479. NoBlending: NoBlending,
  19480. NormalBlending: NormalBlending,
  19481. AdditiveBlending: AdditiveBlending,
  19482. SubtractiveBlending: SubtractiveBlending,
  19483. MultiplyBlending: MultiplyBlending,
  19484. CustomBlending: CustomBlending
  19485. };
  19486. var color = new Color();
  19487. var textureLoader = new TextureLoader();
  19488. var materialLoader = new MaterialLoader();
  19489. return function createMaterial( m, texturePath, crossOrigin ) {
  19490. // convert from old material format
  19491. var textures = {};
  19492. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19493. var fullPath = texturePath + path;
  19494. var loader = Loader.Handlers.get( fullPath );
  19495. var texture;
  19496. if ( loader !== null ) {
  19497. texture = loader.load( fullPath );
  19498. } else {
  19499. textureLoader.setCrossOrigin( crossOrigin );
  19500. texture = textureLoader.load( fullPath );
  19501. }
  19502. if ( repeat !== undefined ) {
  19503. texture.repeat.fromArray( repeat );
  19504. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19505. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19506. }
  19507. if ( offset !== undefined ) {
  19508. texture.offset.fromArray( offset );
  19509. }
  19510. if ( wrap !== undefined ) {
  19511. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19512. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19513. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19514. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19515. }
  19516. if ( anisotropy !== undefined ) {
  19517. texture.anisotropy = anisotropy;
  19518. }
  19519. var uuid = _Math.generateUUID();
  19520. textures[ uuid ] = texture;
  19521. return uuid;
  19522. }
  19523. //
  19524. var json = {
  19525. uuid: _Math.generateUUID(),
  19526. type: 'MeshLambertMaterial'
  19527. };
  19528. for ( var name in m ) {
  19529. var value = m[ name ];
  19530. switch ( name ) {
  19531. case 'DbgColor':
  19532. case 'DbgIndex':
  19533. case 'opticalDensity':
  19534. case 'illumination':
  19535. break;
  19536. case 'DbgName':
  19537. json.name = value;
  19538. break;
  19539. case 'blending':
  19540. json.blending = BlendingMode[ value ];
  19541. break;
  19542. case 'colorAmbient':
  19543. case 'mapAmbient':
  19544. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19545. break;
  19546. case 'colorDiffuse':
  19547. json.color = color.fromArray( value ).getHex();
  19548. break;
  19549. case 'colorSpecular':
  19550. json.specular = color.fromArray( value ).getHex();
  19551. break;
  19552. case 'colorEmissive':
  19553. json.emissive = color.fromArray( value ).getHex();
  19554. break;
  19555. case 'specularCoef':
  19556. json.shininess = value;
  19557. break;
  19558. case 'shading':
  19559. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19560. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19561. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19562. break;
  19563. case 'mapDiffuse':
  19564. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19565. break;
  19566. case 'mapDiffuseRepeat':
  19567. case 'mapDiffuseOffset':
  19568. case 'mapDiffuseWrap':
  19569. case 'mapDiffuseAnisotropy':
  19570. break;
  19571. case 'mapEmissive':
  19572. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19573. break;
  19574. case 'mapEmissiveRepeat':
  19575. case 'mapEmissiveOffset':
  19576. case 'mapEmissiveWrap':
  19577. case 'mapEmissiveAnisotropy':
  19578. break;
  19579. case 'mapLight':
  19580. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19581. break;
  19582. case 'mapLightRepeat':
  19583. case 'mapLightOffset':
  19584. case 'mapLightWrap':
  19585. case 'mapLightAnisotropy':
  19586. break;
  19587. case 'mapAO':
  19588. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19589. break;
  19590. case 'mapAORepeat':
  19591. case 'mapAOOffset':
  19592. case 'mapAOWrap':
  19593. case 'mapAOAnisotropy':
  19594. break;
  19595. case 'mapBump':
  19596. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19597. break;
  19598. case 'mapBumpScale':
  19599. json.bumpScale = value;
  19600. break;
  19601. case 'mapBumpRepeat':
  19602. case 'mapBumpOffset':
  19603. case 'mapBumpWrap':
  19604. case 'mapBumpAnisotropy':
  19605. break;
  19606. case 'mapNormal':
  19607. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19608. break;
  19609. case 'mapNormalFactor':
  19610. json.normalScale = [ value, value ];
  19611. break;
  19612. case 'mapNormalRepeat':
  19613. case 'mapNormalOffset':
  19614. case 'mapNormalWrap':
  19615. case 'mapNormalAnisotropy':
  19616. break;
  19617. case 'mapSpecular':
  19618. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19619. break;
  19620. case 'mapSpecularRepeat':
  19621. case 'mapSpecularOffset':
  19622. case 'mapSpecularWrap':
  19623. case 'mapSpecularAnisotropy':
  19624. break;
  19625. case 'mapMetalness':
  19626. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19627. break;
  19628. case 'mapMetalnessRepeat':
  19629. case 'mapMetalnessOffset':
  19630. case 'mapMetalnessWrap':
  19631. case 'mapMetalnessAnisotropy':
  19632. break;
  19633. case 'mapRoughness':
  19634. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19635. break;
  19636. case 'mapRoughnessRepeat':
  19637. case 'mapRoughnessOffset':
  19638. case 'mapRoughnessWrap':
  19639. case 'mapRoughnessAnisotropy':
  19640. break;
  19641. case 'mapAlpha':
  19642. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19643. break;
  19644. case 'mapAlphaRepeat':
  19645. case 'mapAlphaOffset':
  19646. case 'mapAlphaWrap':
  19647. case 'mapAlphaAnisotropy':
  19648. break;
  19649. case 'flipSided':
  19650. json.side = BackSide;
  19651. break;
  19652. case 'doubleSided':
  19653. json.side = DoubleSide;
  19654. break;
  19655. case 'transparency':
  19656. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19657. json.opacity = value;
  19658. break;
  19659. case 'depthTest':
  19660. case 'depthWrite':
  19661. case 'colorWrite':
  19662. case 'opacity':
  19663. case 'reflectivity':
  19664. case 'transparent':
  19665. case 'visible':
  19666. case 'wireframe':
  19667. json[ name ] = value;
  19668. break;
  19669. case 'vertexColors':
  19670. if ( value === true ) json.vertexColors = VertexColors;
  19671. if ( value === 'face' ) json.vertexColors = FaceColors;
  19672. break;
  19673. default:
  19674. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19675. break;
  19676. }
  19677. }
  19678. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19679. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19680. if ( json.opacity < 1 ) json.transparent = true;
  19681. materialLoader.setTextures( textures );
  19682. return materialLoader.parse( json );
  19683. };
  19684. } )()
  19685. } );
  19686. /**
  19687. * @author mrdoob / http://mrdoob.com/
  19688. * @author alteredq / http://alteredqualia.com/
  19689. */
  19690. function JSONLoader( manager ) {
  19691. if ( typeof manager === 'boolean' ) {
  19692. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19693. manager = undefined;
  19694. }
  19695. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19696. this.withCredentials = false;
  19697. }
  19698. Object.assign( JSONLoader.prototype, {
  19699. load: function ( url, onLoad, onProgress, onError ) {
  19700. var scope = this;
  19701. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19702. var loader = new FileLoader( this.manager );
  19703. loader.setWithCredentials( this.withCredentials );
  19704. loader.load( url, function ( text ) {
  19705. var json = JSON.parse( text );
  19706. var metadata = json.metadata;
  19707. if ( metadata !== undefined ) {
  19708. var type = metadata.type;
  19709. if ( type !== undefined ) {
  19710. if ( type.toLowerCase() === 'object' ) {
  19711. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19712. return;
  19713. }
  19714. if ( type.toLowerCase() === 'scene' ) {
  19715. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19716. return;
  19717. }
  19718. }
  19719. }
  19720. var object = scope.parse( json, texturePath );
  19721. onLoad( object.geometry, object.materials );
  19722. }, onProgress, onError );
  19723. },
  19724. setTexturePath: function ( value ) {
  19725. this.texturePath = value;
  19726. },
  19727. parse: ( function () {
  19728. function parseModel( json, geometry ) {
  19729. function isBitSet( value, position ) {
  19730. return value & ( 1 << position );
  19731. }
  19732. var i, j, fi,
  19733. offset, zLength,
  19734. colorIndex, normalIndex, uvIndex, materialIndex,
  19735. type,
  19736. isQuad,
  19737. hasMaterial,
  19738. hasFaceVertexUv,
  19739. hasFaceNormal, hasFaceVertexNormal,
  19740. hasFaceColor, hasFaceVertexColor,
  19741. vertex, face, faceA, faceB, hex, normal,
  19742. uvLayer, uv, u, v,
  19743. faces = json.faces,
  19744. vertices = json.vertices,
  19745. normals = json.normals,
  19746. colors = json.colors,
  19747. scale = json.scale,
  19748. nUvLayers = 0;
  19749. if ( json.uvs !== undefined ) {
  19750. // disregard empty arrays
  19751. for ( i = 0; i < json.uvs.length; i ++ ) {
  19752. if ( json.uvs[ i ].length ) nUvLayers ++;
  19753. }
  19754. for ( i = 0; i < nUvLayers; i ++ ) {
  19755. geometry.faceVertexUvs[ i ] = [];
  19756. }
  19757. }
  19758. offset = 0;
  19759. zLength = vertices.length;
  19760. while ( offset < zLength ) {
  19761. vertex = new Vector3();
  19762. vertex.x = vertices[ offset ++ ] * scale;
  19763. vertex.y = vertices[ offset ++ ] * scale;
  19764. vertex.z = vertices[ offset ++ ] * scale;
  19765. geometry.vertices.push( vertex );
  19766. }
  19767. offset = 0;
  19768. zLength = faces.length;
  19769. while ( offset < zLength ) {
  19770. type = faces[ offset ++ ];
  19771. isQuad = isBitSet( type, 0 );
  19772. hasMaterial = isBitSet( type, 1 );
  19773. hasFaceVertexUv = isBitSet( type, 3 );
  19774. hasFaceNormal = isBitSet( type, 4 );
  19775. hasFaceVertexNormal = isBitSet( type, 5 );
  19776. hasFaceColor = isBitSet( type, 6 );
  19777. hasFaceVertexColor = isBitSet( type, 7 );
  19778. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19779. if ( isQuad ) {
  19780. faceA = new Face3();
  19781. faceA.a = faces[ offset ];
  19782. faceA.b = faces[ offset + 1 ];
  19783. faceA.c = faces[ offset + 3 ];
  19784. faceB = new Face3();
  19785. faceB.a = faces[ offset + 1 ];
  19786. faceB.b = faces[ offset + 2 ];
  19787. faceB.c = faces[ offset + 3 ];
  19788. offset += 4;
  19789. if ( hasMaterial ) {
  19790. materialIndex = faces[ offset ++ ];
  19791. faceA.materialIndex = materialIndex;
  19792. faceB.materialIndex = materialIndex;
  19793. }
  19794. // to get face <=> uv index correspondence
  19795. fi = geometry.faces.length;
  19796. if ( hasFaceVertexUv ) {
  19797. for ( i = 0; i < nUvLayers; i ++ ) {
  19798. uvLayer = json.uvs[ i ];
  19799. geometry.faceVertexUvs[ i ][ fi ] = [];
  19800. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19801. for ( j = 0; j < 4; j ++ ) {
  19802. uvIndex = faces[ offset ++ ];
  19803. u = uvLayer[ uvIndex * 2 ];
  19804. v = uvLayer[ uvIndex * 2 + 1 ];
  19805. uv = new Vector2( u, v );
  19806. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19807. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19808. }
  19809. }
  19810. }
  19811. if ( hasFaceNormal ) {
  19812. normalIndex = faces[ offset ++ ] * 3;
  19813. faceA.normal.set(
  19814. normals[ normalIndex ++ ],
  19815. normals[ normalIndex ++ ],
  19816. normals[ normalIndex ]
  19817. );
  19818. faceB.normal.copy( faceA.normal );
  19819. }
  19820. if ( hasFaceVertexNormal ) {
  19821. for ( i = 0; i < 4; i ++ ) {
  19822. normalIndex = faces[ offset ++ ] * 3;
  19823. normal = new Vector3(
  19824. normals[ normalIndex ++ ],
  19825. normals[ normalIndex ++ ],
  19826. normals[ normalIndex ]
  19827. );
  19828. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19829. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19830. }
  19831. }
  19832. if ( hasFaceColor ) {
  19833. colorIndex = faces[ offset ++ ];
  19834. hex = colors[ colorIndex ];
  19835. faceA.color.setHex( hex );
  19836. faceB.color.setHex( hex );
  19837. }
  19838. if ( hasFaceVertexColor ) {
  19839. for ( i = 0; i < 4; i ++ ) {
  19840. colorIndex = faces[ offset ++ ];
  19841. hex = colors[ colorIndex ];
  19842. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19843. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19844. }
  19845. }
  19846. geometry.faces.push( faceA );
  19847. geometry.faces.push( faceB );
  19848. } else {
  19849. face = new Face3();
  19850. face.a = faces[ offset ++ ];
  19851. face.b = faces[ offset ++ ];
  19852. face.c = faces[ offset ++ ];
  19853. if ( hasMaterial ) {
  19854. materialIndex = faces[ offset ++ ];
  19855. face.materialIndex = materialIndex;
  19856. }
  19857. // to get face <=> uv index correspondence
  19858. fi = geometry.faces.length;
  19859. if ( hasFaceVertexUv ) {
  19860. for ( i = 0; i < nUvLayers; i ++ ) {
  19861. uvLayer = json.uvs[ i ];
  19862. geometry.faceVertexUvs[ i ][ fi ] = [];
  19863. for ( j = 0; j < 3; j ++ ) {
  19864. uvIndex = faces[ offset ++ ];
  19865. u = uvLayer[ uvIndex * 2 ];
  19866. v = uvLayer[ uvIndex * 2 + 1 ];
  19867. uv = new Vector2( u, v );
  19868. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19869. }
  19870. }
  19871. }
  19872. if ( hasFaceNormal ) {
  19873. normalIndex = faces[ offset ++ ] * 3;
  19874. face.normal.set(
  19875. normals[ normalIndex ++ ],
  19876. normals[ normalIndex ++ ],
  19877. normals[ normalIndex ]
  19878. );
  19879. }
  19880. if ( hasFaceVertexNormal ) {
  19881. for ( i = 0; i < 3; i ++ ) {
  19882. normalIndex = faces[ offset ++ ] * 3;
  19883. normal = new Vector3(
  19884. normals[ normalIndex ++ ],
  19885. normals[ normalIndex ++ ],
  19886. normals[ normalIndex ]
  19887. );
  19888. face.vertexNormals.push( normal );
  19889. }
  19890. }
  19891. if ( hasFaceColor ) {
  19892. colorIndex = faces[ offset ++ ];
  19893. face.color.setHex( colors[ colorIndex ] );
  19894. }
  19895. if ( hasFaceVertexColor ) {
  19896. for ( i = 0; i < 3; i ++ ) {
  19897. colorIndex = faces[ offset ++ ];
  19898. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19899. }
  19900. }
  19901. geometry.faces.push( face );
  19902. }
  19903. }
  19904. }
  19905. function parseSkin( json, geometry ) {
  19906. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19907. if ( json.skinWeights ) {
  19908. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19909. var x = json.skinWeights[ i ];
  19910. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19911. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19912. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19913. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19914. }
  19915. }
  19916. if ( json.skinIndices ) {
  19917. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19918. var a = json.skinIndices[ i ];
  19919. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19920. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19921. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19922. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19923. }
  19924. }
  19925. geometry.bones = json.bones;
  19926. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19927. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19928. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19929. }
  19930. }
  19931. function parseMorphing( json, geometry ) {
  19932. var scale = json.scale;
  19933. if ( json.morphTargets !== undefined ) {
  19934. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19935. geometry.morphTargets[ i ] = {};
  19936. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19937. geometry.morphTargets[ i ].vertices = [];
  19938. var dstVertices = geometry.morphTargets[ i ].vertices;
  19939. var srcVertices = json.morphTargets[ i ].vertices;
  19940. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19941. var vertex = new Vector3();
  19942. vertex.x = srcVertices[ v ] * scale;
  19943. vertex.y = srcVertices[ v + 1 ] * scale;
  19944. vertex.z = srcVertices[ v + 2 ] * scale;
  19945. dstVertices.push( vertex );
  19946. }
  19947. }
  19948. }
  19949. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19950. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19951. var faces = geometry.faces;
  19952. var morphColors = json.morphColors[ 0 ].colors;
  19953. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19954. faces[ i ].color.fromArray( morphColors, i * 3 );
  19955. }
  19956. }
  19957. }
  19958. function parseAnimations( json, geometry ) {
  19959. var outputAnimations = [];
  19960. // parse old style Bone/Hierarchy animations
  19961. var animations = [];
  19962. if ( json.animation !== undefined ) {
  19963. animations.push( json.animation );
  19964. }
  19965. if ( json.animations !== undefined ) {
  19966. if ( json.animations.length ) {
  19967. animations = animations.concat( json.animations );
  19968. } else {
  19969. animations.push( json.animations );
  19970. }
  19971. }
  19972. for ( var i = 0; i < animations.length; i ++ ) {
  19973. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  19974. if ( clip ) outputAnimations.push( clip );
  19975. }
  19976. // parse implicit morph animations
  19977. if ( geometry.morphTargets ) {
  19978. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  19979. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  19980. outputAnimations = outputAnimations.concat( morphAnimationClips );
  19981. }
  19982. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  19983. }
  19984. return function ( json, texturePath ) {
  19985. if ( json.data !== undefined ) {
  19986. // Geometry 4.0 spec
  19987. json = json.data;
  19988. }
  19989. if ( json.scale !== undefined ) {
  19990. json.scale = 1.0 / json.scale;
  19991. } else {
  19992. json.scale = 1.0;
  19993. }
  19994. var geometry = new Geometry();
  19995. parseModel( json, geometry );
  19996. parseSkin( json, geometry );
  19997. parseMorphing( json, geometry );
  19998. parseAnimations( json, geometry );
  19999. geometry.computeFaceNormals();
  20000. geometry.computeBoundingSphere();
  20001. if ( json.materials === undefined || json.materials.length === 0 ) {
  20002. return { geometry: geometry };
  20003. } else {
  20004. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20005. return { geometry: geometry, materials: materials };
  20006. }
  20007. };
  20008. } )()
  20009. } );
  20010. /**
  20011. * @author mrdoob / http://mrdoob.com/
  20012. */
  20013. function ObjectLoader( manager ) {
  20014. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20015. this.texturePath = '';
  20016. }
  20017. Object.assign( ObjectLoader.prototype, {
  20018. load: function ( url, onLoad, onProgress, onError ) {
  20019. if ( this.texturePath === '' ) {
  20020. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20021. }
  20022. var scope = this;
  20023. var loader = new FileLoader( scope.manager );
  20024. loader.load( url, function ( text ) {
  20025. var json = null;
  20026. try {
  20027. json = JSON.parse( text );
  20028. } catch ( error ) {
  20029. if ( onError !== undefined ) onError( error );
  20030. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20031. return;
  20032. }
  20033. var metadata = json.metadata;
  20034. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20035. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20036. return;
  20037. }
  20038. scope.parse( json, onLoad );
  20039. }, onProgress, onError );
  20040. },
  20041. setTexturePath: function ( value ) {
  20042. this.texturePath = value;
  20043. },
  20044. setCrossOrigin: function ( value ) {
  20045. this.crossOrigin = value;
  20046. },
  20047. parse: function ( json, onLoad ) {
  20048. var geometries = this.parseGeometries( json.geometries );
  20049. var images = this.parseImages( json.images, function () {
  20050. if ( onLoad !== undefined ) onLoad( object );
  20051. } );
  20052. var textures = this.parseTextures( json.textures, images );
  20053. var materials = this.parseMaterials( json.materials, textures );
  20054. var object = this.parseObject( json.object, geometries, materials );
  20055. if ( json.animations ) {
  20056. object.animations = this.parseAnimations( json.animations );
  20057. }
  20058. if ( json.images === undefined || json.images.length === 0 ) {
  20059. if ( onLoad !== undefined ) onLoad( object );
  20060. }
  20061. return object;
  20062. },
  20063. parseGeometries: function ( json ) {
  20064. var geometries = {};
  20065. if ( json !== undefined ) {
  20066. var geometryLoader = new JSONLoader();
  20067. var bufferGeometryLoader = new BufferGeometryLoader();
  20068. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20069. var geometry;
  20070. var data = json[ i ];
  20071. switch ( data.type ) {
  20072. case 'PlaneGeometry':
  20073. case 'PlaneBufferGeometry':
  20074. geometry = new Geometries[ data.type ](
  20075. data.width,
  20076. data.height,
  20077. data.widthSegments,
  20078. data.heightSegments
  20079. );
  20080. break;
  20081. case 'BoxGeometry':
  20082. case 'BoxBufferGeometry':
  20083. case 'CubeGeometry': // backwards compatible
  20084. geometry = new Geometries[ data.type ](
  20085. data.width,
  20086. data.height,
  20087. data.depth,
  20088. data.widthSegments,
  20089. data.heightSegments,
  20090. data.depthSegments
  20091. );
  20092. break;
  20093. case 'CircleGeometry':
  20094. case 'CircleBufferGeometry':
  20095. geometry = new Geometries[ data.type ](
  20096. data.radius,
  20097. data.segments,
  20098. data.thetaStart,
  20099. data.thetaLength
  20100. );
  20101. break;
  20102. case 'CylinderGeometry':
  20103. case 'CylinderBufferGeometry':
  20104. geometry = new Geometries[ data.type ](
  20105. data.radiusTop,
  20106. data.radiusBottom,
  20107. data.height,
  20108. data.radialSegments,
  20109. data.heightSegments,
  20110. data.openEnded,
  20111. data.thetaStart,
  20112. data.thetaLength
  20113. );
  20114. break;
  20115. case 'ConeGeometry':
  20116. case 'ConeBufferGeometry':
  20117. geometry = new Geometries[ data.type ](
  20118. data.radius,
  20119. data.height,
  20120. data.radialSegments,
  20121. data.heightSegments,
  20122. data.openEnded,
  20123. data.thetaStart,
  20124. data.thetaLength
  20125. );
  20126. break;
  20127. case 'SphereGeometry':
  20128. case 'SphereBufferGeometry':
  20129. geometry = new Geometries[ data.type ](
  20130. data.radius,
  20131. data.widthSegments,
  20132. data.heightSegments,
  20133. data.phiStart,
  20134. data.phiLength,
  20135. data.thetaStart,
  20136. data.thetaLength
  20137. );
  20138. break;
  20139. case 'DodecahedronGeometry':
  20140. case 'IcosahedronGeometry':
  20141. case 'OctahedronGeometry':
  20142. case 'TetrahedronGeometry':
  20143. geometry = new Geometries[ data.type ](
  20144. data.radius,
  20145. data.detail
  20146. );
  20147. break;
  20148. case 'RingGeometry':
  20149. case 'RingBufferGeometry':
  20150. geometry = new Geometries[ data.type ](
  20151. data.innerRadius,
  20152. data.outerRadius,
  20153. data.thetaSegments,
  20154. data.phiSegments,
  20155. data.thetaStart,
  20156. data.thetaLength
  20157. );
  20158. break;
  20159. case 'TorusGeometry':
  20160. case 'TorusBufferGeometry':
  20161. geometry = new Geometries[ data.type ](
  20162. data.radius,
  20163. data.tube,
  20164. data.radialSegments,
  20165. data.tubularSegments,
  20166. data.arc
  20167. );
  20168. break;
  20169. case 'TorusKnotGeometry':
  20170. case 'TorusKnotBufferGeometry':
  20171. geometry = new Geometries[ data.type ](
  20172. data.radius,
  20173. data.tube,
  20174. data.tubularSegments,
  20175. data.radialSegments,
  20176. data.p,
  20177. data.q
  20178. );
  20179. break;
  20180. case 'LatheGeometry':
  20181. case 'LatheBufferGeometry':
  20182. geometry = new Geometries[ data.type ](
  20183. data.points,
  20184. data.segments,
  20185. data.phiStart,
  20186. data.phiLength
  20187. );
  20188. break;
  20189. case 'BufferGeometry':
  20190. geometry = bufferGeometryLoader.parse( data );
  20191. break;
  20192. case 'Geometry':
  20193. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20194. break;
  20195. default:
  20196. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20197. continue;
  20198. }
  20199. geometry.uuid = data.uuid;
  20200. if ( data.name !== undefined ) geometry.name = data.name;
  20201. geometries[ data.uuid ] = geometry;
  20202. }
  20203. }
  20204. return geometries;
  20205. },
  20206. parseMaterials: function ( json, textures ) {
  20207. var materials = {};
  20208. if ( json !== undefined ) {
  20209. var loader = new MaterialLoader();
  20210. loader.setTextures( textures );
  20211. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20212. var data = json[ i ];
  20213. if ( data.type === 'MultiMaterial' ) {
  20214. // Deprecated
  20215. var array = [];
  20216. for ( var j = 0; j < data.materials.length; j ++ ) {
  20217. array.push( loader.parse( data.materials[ j ] ) );
  20218. }
  20219. materials[ data.uuid ] = array;
  20220. } else {
  20221. materials[ data.uuid ] = loader.parse( data );
  20222. }
  20223. }
  20224. }
  20225. return materials;
  20226. },
  20227. parseAnimations: function ( json ) {
  20228. var animations = [];
  20229. for ( var i = 0; i < json.length; i ++ ) {
  20230. var clip = AnimationClip.parse( json[ i ] );
  20231. animations.push( clip );
  20232. }
  20233. return animations;
  20234. },
  20235. parseImages: function ( json, onLoad ) {
  20236. var scope = this;
  20237. var images = {};
  20238. function loadImage( url ) {
  20239. scope.manager.itemStart( url );
  20240. return loader.load( url, function () {
  20241. scope.manager.itemEnd( url );
  20242. }, undefined, function () {
  20243. scope.manager.itemEnd( url );
  20244. scope.manager.itemError( url );
  20245. } );
  20246. }
  20247. if ( json !== undefined && json.length > 0 ) {
  20248. var manager = new LoadingManager( onLoad );
  20249. var loader = new ImageLoader( manager );
  20250. loader.setCrossOrigin( this.crossOrigin );
  20251. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20252. var image = json[ i ];
  20253. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20254. images[ image.uuid ] = loadImage( path );
  20255. }
  20256. }
  20257. return images;
  20258. },
  20259. parseTextures: function ( json, images ) {
  20260. function parseConstant( value, type ) {
  20261. if ( typeof( value ) === 'number' ) return value;
  20262. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20263. return type[ value ];
  20264. }
  20265. var textures = {};
  20266. if ( json !== undefined ) {
  20267. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20268. var data = json[ i ];
  20269. if ( data.image === undefined ) {
  20270. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20271. }
  20272. if ( images[ data.image ] === undefined ) {
  20273. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20274. }
  20275. var texture = new Texture( images[ data.image ] );
  20276. texture.needsUpdate = true;
  20277. texture.uuid = data.uuid;
  20278. if ( data.name !== undefined ) texture.name = data.name;
  20279. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20280. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20281. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20282. if ( data.wrap !== undefined ) {
  20283. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20284. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20285. }
  20286. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20287. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20288. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20289. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20290. textures[ data.uuid ] = texture;
  20291. }
  20292. }
  20293. return textures;
  20294. },
  20295. parseObject: function () {
  20296. var matrix = new Matrix4();
  20297. return function parseObject( data, geometries, materials ) {
  20298. var object;
  20299. function getGeometry( name ) {
  20300. if ( geometries[ name ] === undefined ) {
  20301. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20302. }
  20303. return geometries[ name ];
  20304. }
  20305. function getMaterial( name ) {
  20306. if ( name === undefined ) return undefined;
  20307. if ( Array.isArray( name ) ) {
  20308. var array = [];
  20309. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20310. var uuid = name[ i ];
  20311. if ( materials[ uuid ] === undefined ) {
  20312. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20313. }
  20314. array.push( materials[ uuid ] );
  20315. }
  20316. return array;
  20317. }
  20318. if ( materials[ name ] === undefined ) {
  20319. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20320. }
  20321. return materials[ name ];
  20322. }
  20323. switch ( data.type ) {
  20324. case 'Scene':
  20325. object = new Scene();
  20326. if ( data.background !== undefined ) {
  20327. if ( Number.isInteger( data.background ) ) {
  20328. object.background = new Color( data.background );
  20329. }
  20330. }
  20331. if ( data.fog !== undefined ) {
  20332. if ( data.fog.type === 'Fog' ) {
  20333. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20334. } else if ( data.fog.type === 'FogExp2' ) {
  20335. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20336. }
  20337. }
  20338. break;
  20339. case 'PerspectiveCamera':
  20340. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20341. if ( data.focus !== undefined ) object.focus = data.focus;
  20342. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20343. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20344. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20345. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20346. break;
  20347. case 'OrthographicCamera':
  20348. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20349. break;
  20350. case 'AmbientLight':
  20351. object = new AmbientLight( data.color, data.intensity );
  20352. break;
  20353. case 'DirectionalLight':
  20354. object = new DirectionalLight( data.color, data.intensity );
  20355. break;
  20356. case 'PointLight':
  20357. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20358. break;
  20359. case 'RectAreaLight':
  20360. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20361. break;
  20362. case 'SpotLight':
  20363. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20364. break;
  20365. case 'HemisphereLight':
  20366. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20367. break;
  20368. case 'SkinnedMesh':
  20369. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20370. case 'Mesh':
  20371. var geometry = getGeometry( data.geometry );
  20372. var material = getMaterial( data.material );
  20373. if ( geometry.bones && geometry.bones.length > 0 ) {
  20374. object = new SkinnedMesh( geometry, material );
  20375. } else {
  20376. object = new Mesh( geometry, material );
  20377. }
  20378. break;
  20379. case 'LOD':
  20380. object = new LOD();
  20381. break;
  20382. case 'Line':
  20383. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20384. break;
  20385. case 'LineLoop':
  20386. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20387. break;
  20388. case 'LineSegments':
  20389. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20390. break;
  20391. case 'PointCloud':
  20392. case 'Points':
  20393. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20394. break;
  20395. case 'Sprite':
  20396. object = new Sprite( getMaterial( data.material ) );
  20397. break;
  20398. case 'Group':
  20399. object = new Group();
  20400. break;
  20401. default:
  20402. object = new Object3D();
  20403. }
  20404. object.uuid = data.uuid;
  20405. if ( data.name !== undefined ) object.name = data.name;
  20406. if ( data.matrix !== undefined ) {
  20407. matrix.fromArray( data.matrix );
  20408. matrix.decompose( object.position, object.quaternion, object.scale );
  20409. } else {
  20410. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20411. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20412. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20413. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20414. }
  20415. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20416. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20417. if ( data.shadow ) {
  20418. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20419. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20420. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20421. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20422. }
  20423. if ( data.visible !== undefined ) object.visible = data.visible;
  20424. if ( data.userData !== undefined ) object.userData = data.userData;
  20425. if ( data.children !== undefined ) {
  20426. for ( var child in data.children ) {
  20427. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20428. }
  20429. }
  20430. if ( data.type === 'LOD' ) {
  20431. var levels = data.levels;
  20432. for ( var l = 0; l < levels.length; l ++ ) {
  20433. var level = levels[ l ];
  20434. var child = object.getObjectByProperty( 'uuid', level.object );
  20435. if ( child !== undefined ) {
  20436. object.addLevel( child, level.distance );
  20437. }
  20438. }
  20439. }
  20440. return object;
  20441. };
  20442. }()
  20443. } );
  20444. var TEXTURE_MAPPING = {
  20445. UVMapping: UVMapping,
  20446. CubeReflectionMapping: CubeReflectionMapping,
  20447. CubeRefractionMapping: CubeRefractionMapping,
  20448. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20449. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20450. SphericalReflectionMapping: SphericalReflectionMapping,
  20451. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20452. CubeUVRefractionMapping: CubeUVRefractionMapping
  20453. };
  20454. var TEXTURE_WRAPPING = {
  20455. RepeatWrapping: RepeatWrapping,
  20456. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20457. MirroredRepeatWrapping: MirroredRepeatWrapping
  20458. };
  20459. var TEXTURE_FILTER = {
  20460. NearestFilter: NearestFilter,
  20461. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20462. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20463. LinearFilter: LinearFilter,
  20464. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20465. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20466. };
  20467. /**
  20468. * @author zz85 / http://www.lab4games.net/zz85/blog
  20469. *
  20470. * Bezier Curves formulas obtained from
  20471. * http://en.wikipedia.org/wiki/Bézier_curve
  20472. */
  20473. function CatmullRom( t, p0, p1, p2, p3 ) {
  20474. var v0 = ( p2 - p0 ) * 0.5;
  20475. var v1 = ( p3 - p1 ) * 0.5;
  20476. var t2 = t * t;
  20477. var t3 = t * t2;
  20478. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20479. }
  20480. //
  20481. function QuadraticBezierP0( t, p ) {
  20482. var k = 1 - t;
  20483. return k * k * p;
  20484. }
  20485. function QuadraticBezierP1( t, p ) {
  20486. return 2 * ( 1 - t ) * t * p;
  20487. }
  20488. function QuadraticBezierP2( t, p ) {
  20489. return t * t * p;
  20490. }
  20491. function QuadraticBezier( t, p0, p1, p2 ) {
  20492. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20493. QuadraticBezierP2( t, p2 );
  20494. }
  20495. //
  20496. function CubicBezierP0( t, p ) {
  20497. var k = 1 - t;
  20498. return k * k * k * p;
  20499. }
  20500. function CubicBezierP1( t, p ) {
  20501. var k = 1 - t;
  20502. return 3 * k * k * t * p;
  20503. }
  20504. function CubicBezierP2( t, p ) {
  20505. return 3 * ( 1 - t ) * t * t * p;
  20506. }
  20507. function CubicBezierP3( t, p ) {
  20508. return t * t * t * p;
  20509. }
  20510. function CubicBezier( t, p0, p1, p2, p3 ) {
  20511. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20512. CubicBezierP3( t, p3 );
  20513. }
  20514. /**
  20515. * @author zz85 / http://www.lab4games.net/zz85/blog
  20516. * Extensible curve object
  20517. *
  20518. * Some common of curve methods:
  20519. * .getPoint(t), getTangent(t)
  20520. * .getPointAt(u), getTangentAt(u)
  20521. * .getPoints(), .getSpacedPoints()
  20522. * .getLength()
  20523. * .updateArcLengths()
  20524. *
  20525. * This following curves inherit from THREE.Curve:
  20526. *
  20527. * -- 2D curves --
  20528. * THREE.ArcCurve
  20529. * THREE.CubicBezierCurve
  20530. * THREE.EllipseCurve
  20531. * THREE.LineCurve
  20532. * THREE.QuadraticBezierCurve
  20533. * THREE.SplineCurve
  20534. *
  20535. * -- 3D curves --
  20536. * THREE.CatmullRomCurve3
  20537. * THREE.CubicBezierCurve3
  20538. * THREE.LineCurve3
  20539. * THREE.QuadraticBezierCurve3
  20540. *
  20541. * A series of curves can be represented as a THREE.CurvePath.
  20542. *
  20543. **/
  20544. /**************************************************************
  20545. * Abstract Curve base class
  20546. **************************************************************/
  20547. function Curve() {
  20548. this.arcLengthDivisions = 200;
  20549. }
  20550. Object.assign( Curve.prototype, {
  20551. // Virtual base class method to overwrite and implement in subclasses
  20552. // - t [0 .. 1]
  20553. getPoint: function () {
  20554. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20555. return null;
  20556. },
  20557. // Get point at relative position in curve according to arc length
  20558. // - u [0 .. 1]
  20559. getPointAt: function ( u ) {
  20560. var t = this.getUtoTmapping( u );
  20561. return this.getPoint( t );
  20562. },
  20563. // Get sequence of points using getPoint( t )
  20564. getPoints: function ( divisions ) {
  20565. if ( divisions === undefined ) divisions = 5;
  20566. var points = [];
  20567. for ( var d = 0; d <= divisions; d ++ ) {
  20568. points.push( this.getPoint( d / divisions ) );
  20569. }
  20570. return points;
  20571. },
  20572. // Get sequence of points using getPointAt( u )
  20573. getSpacedPoints: function ( divisions ) {
  20574. if ( divisions === undefined ) divisions = 5;
  20575. var points = [];
  20576. for ( var d = 0; d <= divisions; d ++ ) {
  20577. points.push( this.getPointAt( d / divisions ) );
  20578. }
  20579. return points;
  20580. },
  20581. // Get total curve arc length
  20582. getLength: function () {
  20583. var lengths = this.getLengths();
  20584. return lengths[ lengths.length - 1 ];
  20585. },
  20586. // Get list of cumulative segment lengths
  20587. getLengths: function ( divisions ) {
  20588. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20589. if ( this.cacheArcLengths &&
  20590. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20591. ! this.needsUpdate ) {
  20592. return this.cacheArcLengths;
  20593. }
  20594. this.needsUpdate = false;
  20595. var cache = [];
  20596. var current, last = this.getPoint( 0 );
  20597. var p, sum = 0;
  20598. cache.push( 0 );
  20599. for ( p = 1; p <= divisions; p ++ ) {
  20600. current = this.getPoint( p / divisions );
  20601. sum += current.distanceTo( last );
  20602. cache.push( sum );
  20603. last = current;
  20604. }
  20605. this.cacheArcLengths = cache;
  20606. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20607. },
  20608. updateArcLengths: function () {
  20609. this.needsUpdate = true;
  20610. this.getLengths();
  20611. },
  20612. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20613. getUtoTmapping: function ( u, distance ) {
  20614. var arcLengths = this.getLengths();
  20615. var i = 0, il = arcLengths.length;
  20616. var targetArcLength; // The targeted u distance value to get
  20617. if ( distance ) {
  20618. targetArcLength = distance;
  20619. } else {
  20620. targetArcLength = u * arcLengths[ il - 1 ];
  20621. }
  20622. // binary search for the index with largest value smaller than target u distance
  20623. var low = 0, high = il - 1, comparison;
  20624. while ( low <= high ) {
  20625. 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
  20626. comparison = arcLengths[ i ] - targetArcLength;
  20627. if ( comparison < 0 ) {
  20628. low = i + 1;
  20629. } else if ( comparison > 0 ) {
  20630. high = i - 1;
  20631. } else {
  20632. high = i;
  20633. break;
  20634. // DONE
  20635. }
  20636. }
  20637. i = high;
  20638. if ( arcLengths[ i ] === targetArcLength ) {
  20639. return i / ( il - 1 );
  20640. }
  20641. // we could get finer grain at lengths, or use simple interpolation between two points
  20642. var lengthBefore = arcLengths[ i ];
  20643. var lengthAfter = arcLengths[ i + 1 ];
  20644. var segmentLength = lengthAfter - lengthBefore;
  20645. // determine where we are between the 'before' and 'after' points
  20646. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20647. // add that fractional amount to t
  20648. var t = ( i + segmentFraction ) / ( il - 1 );
  20649. return t;
  20650. },
  20651. // Returns a unit vector tangent at t
  20652. // In case any sub curve does not implement its tangent derivation,
  20653. // 2 points a small delta apart will be used to find its gradient
  20654. // which seems to give a reasonable approximation
  20655. getTangent: function ( t ) {
  20656. var delta = 0.0001;
  20657. var t1 = t - delta;
  20658. var t2 = t + delta;
  20659. // Capping in case of danger
  20660. if ( t1 < 0 ) t1 = 0;
  20661. if ( t2 > 1 ) t2 = 1;
  20662. var pt1 = this.getPoint( t1 );
  20663. var pt2 = this.getPoint( t2 );
  20664. var vec = pt2.clone().sub( pt1 );
  20665. return vec.normalize();
  20666. },
  20667. getTangentAt: function ( u ) {
  20668. var t = this.getUtoTmapping( u );
  20669. return this.getTangent( t );
  20670. },
  20671. computeFrenetFrames: function ( segments, closed ) {
  20672. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20673. var normal = new Vector3();
  20674. var tangents = [];
  20675. var normals = [];
  20676. var binormals = [];
  20677. var vec = new Vector3();
  20678. var mat = new Matrix4();
  20679. var i, u, theta;
  20680. // compute the tangent vectors for each segment on the curve
  20681. for ( i = 0; i <= segments; i ++ ) {
  20682. u = i / segments;
  20683. tangents[ i ] = this.getTangentAt( u );
  20684. tangents[ i ].normalize();
  20685. }
  20686. // select an initial normal vector perpendicular to the first tangent vector,
  20687. // and in the direction of the minimum tangent xyz component
  20688. normals[ 0 ] = new Vector3();
  20689. binormals[ 0 ] = new Vector3();
  20690. var min = Number.MAX_VALUE;
  20691. var tx = Math.abs( tangents[ 0 ].x );
  20692. var ty = Math.abs( tangents[ 0 ].y );
  20693. var tz = Math.abs( tangents[ 0 ].z );
  20694. if ( tx <= min ) {
  20695. min = tx;
  20696. normal.set( 1, 0, 0 );
  20697. }
  20698. if ( ty <= min ) {
  20699. min = ty;
  20700. normal.set( 0, 1, 0 );
  20701. }
  20702. if ( tz <= min ) {
  20703. normal.set( 0, 0, 1 );
  20704. }
  20705. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20706. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20707. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20708. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20709. for ( i = 1; i <= segments; i ++ ) {
  20710. normals[ i ] = normals[ i - 1 ].clone();
  20711. binormals[ i ] = binormals[ i - 1 ].clone();
  20712. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20713. if ( vec.length() > Number.EPSILON ) {
  20714. vec.normalize();
  20715. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20716. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20717. }
  20718. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20719. }
  20720. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20721. if ( closed === true ) {
  20722. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20723. theta /= segments;
  20724. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20725. theta = - theta;
  20726. }
  20727. for ( i = 1; i <= segments; i ++ ) {
  20728. // twist a little...
  20729. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20730. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20731. }
  20732. }
  20733. return {
  20734. tangents: tangents,
  20735. normals: normals,
  20736. binormals: binormals
  20737. };
  20738. }
  20739. } );
  20740. function LineCurve( v1, v2 ) {
  20741. Curve.call( this );
  20742. this.v1 = v1;
  20743. this.v2 = v2;
  20744. }
  20745. LineCurve.prototype = Object.create( Curve.prototype );
  20746. LineCurve.prototype.constructor = LineCurve;
  20747. LineCurve.prototype.isLineCurve = true;
  20748. LineCurve.prototype.getPoint = function ( t ) {
  20749. if ( t === 1 ) {
  20750. return this.v2.clone();
  20751. }
  20752. var point = this.v2.clone().sub( this.v1 );
  20753. point.multiplyScalar( t ).add( this.v1 );
  20754. return point;
  20755. };
  20756. // Line curve is linear, so we can overwrite default getPointAt
  20757. LineCurve.prototype.getPointAt = function ( u ) {
  20758. return this.getPoint( u );
  20759. };
  20760. LineCurve.prototype.getTangent = function ( t ) {
  20761. var tangent = this.v2.clone().sub( this.v1 );
  20762. return tangent.normalize();
  20763. };
  20764. /**
  20765. * @author zz85 / http://www.lab4games.net/zz85/blog
  20766. *
  20767. **/
  20768. /**************************************************************
  20769. * Curved Path - a curve path is simply a array of connected
  20770. * curves, but retains the api of a curve
  20771. **************************************************************/
  20772. function CurvePath() {
  20773. Curve.call( this );
  20774. this.curves = [];
  20775. this.autoClose = false; // Automatically closes the path
  20776. }
  20777. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20778. constructor: CurvePath,
  20779. add: function ( curve ) {
  20780. this.curves.push( curve );
  20781. },
  20782. closePath: function () {
  20783. // Add a line curve if start and end of lines are not connected
  20784. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20785. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20786. if ( ! startPoint.equals( endPoint ) ) {
  20787. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20788. }
  20789. },
  20790. // To get accurate point with reference to
  20791. // entire path distance at time t,
  20792. // following has to be done:
  20793. // 1. Length of each sub path have to be known
  20794. // 2. Locate and identify type of curve
  20795. // 3. Get t for the curve
  20796. // 4. Return curve.getPointAt(t')
  20797. getPoint: function ( t ) {
  20798. var d = t * this.getLength();
  20799. var curveLengths = this.getCurveLengths();
  20800. var i = 0;
  20801. // To think about boundaries points.
  20802. while ( i < curveLengths.length ) {
  20803. if ( curveLengths[ i ] >= d ) {
  20804. var diff = curveLengths[ i ] - d;
  20805. var curve = this.curves[ i ];
  20806. var segmentLength = curve.getLength();
  20807. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20808. return curve.getPointAt( u );
  20809. }
  20810. i ++;
  20811. }
  20812. return null;
  20813. // loop where sum != 0, sum > d , sum+1 <d
  20814. },
  20815. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20816. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20817. // getPoint() depends on getLength
  20818. getLength: function () {
  20819. var lens = this.getCurveLengths();
  20820. return lens[ lens.length - 1 ];
  20821. },
  20822. // cacheLengths must be recalculated.
  20823. updateArcLengths: function () {
  20824. this.needsUpdate = true;
  20825. this.cacheLengths = null;
  20826. this.getCurveLengths();
  20827. },
  20828. // Compute lengths and cache them
  20829. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20830. getCurveLengths: function () {
  20831. // We use cache values if curves and cache array are same length
  20832. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20833. return this.cacheLengths;
  20834. }
  20835. // Get length of sub-curve
  20836. // Push sums into cached array
  20837. var lengths = [], sums = 0;
  20838. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20839. sums += this.curves[ i ].getLength();
  20840. lengths.push( sums );
  20841. }
  20842. this.cacheLengths = lengths;
  20843. return lengths;
  20844. },
  20845. getSpacedPoints: function ( divisions ) {
  20846. if ( divisions === undefined ) divisions = 40;
  20847. var points = [];
  20848. for ( var i = 0; i <= divisions; i ++ ) {
  20849. points.push( this.getPoint( i / divisions ) );
  20850. }
  20851. if ( this.autoClose ) {
  20852. points.push( points[ 0 ] );
  20853. }
  20854. return points;
  20855. },
  20856. getPoints: function ( divisions ) {
  20857. divisions = divisions || 12;
  20858. var points = [], last;
  20859. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20860. var curve = curves[ i ];
  20861. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20862. : (curve && curve.isLineCurve) ? 1
  20863. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20864. : divisions;
  20865. var pts = curve.getPoints( resolution );
  20866. for ( var j = 0; j < pts.length; j++ ) {
  20867. var point = pts[ j ];
  20868. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20869. points.push( point );
  20870. last = point;
  20871. }
  20872. }
  20873. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20874. points.push( points[ 0 ] );
  20875. }
  20876. return points;
  20877. },
  20878. /**************************************************************
  20879. * Create Geometries Helpers
  20880. **************************************************************/
  20881. /// Generate geometry from path points (for Line or Points objects)
  20882. createPointsGeometry: function ( divisions ) {
  20883. var pts = this.getPoints( divisions );
  20884. return this.createGeometry( pts );
  20885. },
  20886. // Generate geometry from equidistant sampling along the path
  20887. createSpacedPointsGeometry: function ( divisions ) {
  20888. var pts = this.getSpacedPoints( divisions );
  20889. return this.createGeometry( pts );
  20890. },
  20891. createGeometry: function ( points ) {
  20892. var geometry = new Geometry();
  20893. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20894. var point = points[ i ];
  20895. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20896. }
  20897. return geometry;
  20898. }
  20899. } );
  20900. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20901. Curve.call( this );
  20902. this.aX = aX;
  20903. this.aY = aY;
  20904. this.xRadius = xRadius;
  20905. this.yRadius = yRadius;
  20906. this.aStartAngle = aStartAngle;
  20907. this.aEndAngle = aEndAngle;
  20908. this.aClockwise = aClockwise;
  20909. this.aRotation = aRotation || 0;
  20910. }
  20911. EllipseCurve.prototype = Object.create( Curve.prototype );
  20912. EllipseCurve.prototype.constructor = EllipseCurve;
  20913. EllipseCurve.prototype.isEllipseCurve = true;
  20914. EllipseCurve.prototype.getPoint = function ( t ) {
  20915. var twoPi = Math.PI * 2;
  20916. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20917. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20918. // ensures that deltaAngle is 0 .. 2 PI
  20919. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20920. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20921. if ( deltaAngle < Number.EPSILON ) {
  20922. if ( samePoints ) {
  20923. deltaAngle = 0;
  20924. } else {
  20925. deltaAngle = twoPi;
  20926. }
  20927. }
  20928. if ( this.aClockwise === true && ! samePoints ) {
  20929. if ( deltaAngle === twoPi ) {
  20930. deltaAngle = - twoPi;
  20931. } else {
  20932. deltaAngle = deltaAngle - twoPi;
  20933. }
  20934. }
  20935. var angle = this.aStartAngle + t * deltaAngle;
  20936. var x = this.aX + this.xRadius * Math.cos( angle );
  20937. var y = this.aY + this.yRadius * Math.sin( angle );
  20938. if ( this.aRotation !== 0 ) {
  20939. var cos = Math.cos( this.aRotation );
  20940. var sin = Math.sin( this.aRotation );
  20941. var tx = x - this.aX;
  20942. var ty = y - this.aY;
  20943. // Rotate the point about the center of the ellipse.
  20944. x = tx * cos - ty * sin + this.aX;
  20945. y = tx * sin + ty * cos + this.aY;
  20946. }
  20947. return new Vector2( x, y );
  20948. };
  20949. function SplineCurve( points /* array of Vector2 */ ) {
  20950. Curve.call( this );
  20951. this.points = ( points === undefined ) ? [] : points;
  20952. }
  20953. SplineCurve.prototype = Object.create( Curve.prototype );
  20954. SplineCurve.prototype.constructor = SplineCurve;
  20955. SplineCurve.prototype.isSplineCurve = true;
  20956. SplineCurve.prototype.getPoint = function ( t ) {
  20957. var points = this.points;
  20958. var point = ( points.length - 1 ) * t;
  20959. var intPoint = Math.floor( point );
  20960. var weight = point - intPoint;
  20961. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20962. var point1 = points[ intPoint ];
  20963. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20964. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20965. return new Vector2(
  20966. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  20967. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  20968. );
  20969. };
  20970. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20971. Curve.call( this );
  20972. this.v0 = v0;
  20973. this.v1 = v1;
  20974. this.v2 = v2;
  20975. this.v3 = v3;
  20976. }
  20977. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20978. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20979. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20980. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20981. return new Vector2(
  20982. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20983. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  20984. );
  20985. };
  20986. function QuadraticBezierCurve( v0, v1, v2 ) {
  20987. Curve.call( this );
  20988. this.v0 = v0;
  20989. this.v1 = v1;
  20990. this.v2 = v2;
  20991. }
  20992. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20993. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20994. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20995. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20996. return new Vector2(
  20997. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20998. QuadraticBezier( t, v0.y, v1.y, v2.y )
  20999. );
  21000. };
  21001. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21002. fromPoints: function ( vectors ) {
  21003. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21004. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21005. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21006. }
  21007. },
  21008. moveTo: function ( x, y ) {
  21009. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21010. },
  21011. lineTo: function ( x, y ) {
  21012. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21013. this.curves.push( curve );
  21014. this.currentPoint.set( x, y );
  21015. },
  21016. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21017. var curve = new QuadraticBezierCurve(
  21018. this.currentPoint.clone(),
  21019. new Vector2( aCPx, aCPy ),
  21020. new Vector2( aX, aY )
  21021. );
  21022. this.curves.push( curve );
  21023. this.currentPoint.set( aX, aY );
  21024. },
  21025. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21026. var curve = new CubicBezierCurve(
  21027. this.currentPoint.clone(),
  21028. new Vector2( aCP1x, aCP1y ),
  21029. new Vector2( aCP2x, aCP2y ),
  21030. new Vector2( aX, aY )
  21031. );
  21032. this.curves.push( curve );
  21033. this.currentPoint.set( aX, aY );
  21034. },
  21035. splineThru: function ( pts /*Array of Vector*/ ) {
  21036. var npts = [ this.currentPoint.clone() ].concat( pts );
  21037. var curve = new SplineCurve( npts );
  21038. this.curves.push( curve );
  21039. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21040. },
  21041. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21042. var x0 = this.currentPoint.x;
  21043. var y0 = this.currentPoint.y;
  21044. this.absarc( aX + x0, aY + y0, aRadius,
  21045. aStartAngle, aEndAngle, aClockwise );
  21046. },
  21047. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21048. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21049. },
  21050. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21051. var x0 = this.currentPoint.x;
  21052. var y0 = this.currentPoint.y;
  21053. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21054. },
  21055. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21056. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21057. if ( this.curves.length > 0 ) {
  21058. // if a previous curve is present, attempt to join
  21059. var firstPoint = curve.getPoint( 0 );
  21060. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21061. this.lineTo( firstPoint.x, firstPoint.y );
  21062. }
  21063. }
  21064. this.curves.push( curve );
  21065. var lastPoint = curve.getPoint( 1 );
  21066. this.currentPoint.copy( lastPoint );
  21067. }
  21068. } );
  21069. /**
  21070. * @author zz85 / http://www.lab4games.net/zz85/blog
  21071. * Creates free form 2d path using series of points, lines or curves.
  21072. **/
  21073. function Path( points ) {
  21074. CurvePath.call( this );
  21075. this.currentPoint = new Vector2();
  21076. if ( points ) {
  21077. this.fromPoints( points );
  21078. }
  21079. }
  21080. Path.prototype = PathPrototype;
  21081. PathPrototype.constructor = Path;
  21082. /**
  21083. * @author zz85 / http://www.lab4games.net/zz85/blog
  21084. * Defines a 2d shape plane using paths.
  21085. **/
  21086. // STEP 1 Create a path.
  21087. // STEP 2 Turn path into shape.
  21088. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21089. // STEP 3a - Extract points from each shape, turn to vertices
  21090. // STEP 3b - Triangulate each shape, add faces.
  21091. function Shape() {
  21092. Path.apply( this, arguments );
  21093. this.holes = [];
  21094. }
  21095. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21096. constructor: Shape,
  21097. getPointsHoles: function ( divisions ) {
  21098. var holesPts = [];
  21099. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21100. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21101. }
  21102. return holesPts;
  21103. },
  21104. // Get points of shape and holes (keypoints based on segments parameter)
  21105. extractAllPoints: function ( divisions ) {
  21106. return {
  21107. shape: this.getPoints( divisions ),
  21108. holes: this.getPointsHoles( divisions )
  21109. };
  21110. },
  21111. extractPoints: function ( divisions ) {
  21112. return this.extractAllPoints( divisions );
  21113. }
  21114. } );
  21115. /**
  21116. * @author zz85 / http://www.lab4games.net/zz85/blog
  21117. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21118. **/
  21119. function ShapePath() {
  21120. this.subPaths = [];
  21121. this.currentPath = null;
  21122. }
  21123. Object.assign( ShapePath.prototype, {
  21124. moveTo: function ( x, y ) {
  21125. this.currentPath = new Path();
  21126. this.subPaths.push( this.currentPath );
  21127. this.currentPath.moveTo( x, y );
  21128. },
  21129. lineTo: function ( x, y ) {
  21130. this.currentPath.lineTo( x, y );
  21131. },
  21132. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21133. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21134. },
  21135. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21136. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21137. },
  21138. splineThru: function ( pts ) {
  21139. this.currentPath.splineThru( pts );
  21140. },
  21141. toShapes: function ( isCCW, noHoles ) {
  21142. function toShapesNoHoles( inSubpaths ) {
  21143. var shapes = [];
  21144. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21145. var tmpPath = inSubpaths[ i ];
  21146. var tmpShape = new Shape();
  21147. tmpShape.curves = tmpPath.curves;
  21148. shapes.push( tmpShape );
  21149. }
  21150. return shapes;
  21151. }
  21152. function isPointInsidePolygon( inPt, inPolygon ) {
  21153. var polyLen = inPolygon.length;
  21154. // inPt on polygon contour => immediate success or
  21155. // toggling of inside/outside at every single! intersection point of an edge
  21156. // with the horizontal line through inPt, left of inPt
  21157. // not counting lowerY endpoints of edges and whole edges on that line
  21158. var inside = false;
  21159. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21160. var edgeLowPt = inPolygon[ p ];
  21161. var edgeHighPt = inPolygon[ q ];
  21162. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21163. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21164. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21165. // not parallel
  21166. if ( edgeDy < 0 ) {
  21167. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21168. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21169. }
  21170. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21171. if ( inPt.y === edgeLowPt.y ) {
  21172. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21173. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21174. } else {
  21175. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21176. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21177. if ( perpEdge < 0 ) continue;
  21178. inside = ! inside; // true intersection left of inPt
  21179. }
  21180. } else {
  21181. // parallel or collinear
  21182. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21183. // edge lies on the same horizontal line as inPt
  21184. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21185. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21186. // continue;
  21187. }
  21188. }
  21189. return inside;
  21190. }
  21191. var isClockWise = ShapeUtils.isClockWise;
  21192. var subPaths = this.subPaths;
  21193. if ( subPaths.length === 0 ) return [];
  21194. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21195. var solid, tmpPath, tmpShape, shapes = [];
  21196. if ( subPaths.length === 1 ) {
  21197. tmpPath = subPaths[ 0 ];
  21198. tmpShape = new Shape();
  21199. tmpShape.curves = tmpPath.curves;
  21200. shapes.push( tmpShape );
  21201. return shapes;
  21202. }
  21203. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21204. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21205. // console.log("Holes first", holesFirst);
  21206. var betterShapeHoles = [];
  21207. var newShapes = [];
  21208. var newShapeHoles = [];
  21209. var mainIdx = 0;
  21210. var tmpPoints;
  21211. newShapes[ mainIdx ] = undefined;
  21212. newShapeHoles[ mainIdx ] = [];
  21213. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21214. tmpPath = subPaths[ i ];
  21215. tmpPoints = tmpPath.getPoints();
  21216. solid = isClockWise( tmpPoints );
  21217. solid = isCCW ? ! solid : solid;
  21218. if ( solid ) {
  21219. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21220. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21221. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21222. if ( holesFirst ) mainIdx ++;
  21223. newShapeHoles[ mainIdx ] = [];
  21224. //console.log('cw', i);
  21225. } else {
  21226. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21227. //console.log('ccw', i);
  21228. }
  21229. }
  21230. // only Holes? -> probably all Shapes with wrong orientation
  21231. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21232. if ( newShapes.length > 1 ) {
  21233. var ambiguous = false;
  21234. var toChange = [];
  21235. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21236. betterShapeHoles[ sIdx ] = [];
  21237. }
  21238. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21239. var sho = newShapeHoles[ sIdx ];
  21240. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21241. var ho = sho[ hIdx ];
  21242. var hole_unassigned = true;
  21243. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21244. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21245. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21246. if ( hole_unassigned ) {
  21247. hole_unassigned = false;
  21248. betterShapeHoles[ s2Idx ].push( ho );
  21249. } else {
  21250. ambiguous = true;
  21251. }
  21252. }
  21253. }
  21254. if ( hole_unassigned ) {
  21255. betterShapeHoles[ sIdx ].push( ho );
  21256. }
  21257. }
  21258. }
  21259. // console.log("ambiguous: ", ambiguous);
  21260. if ( toChange.length > 0 ) {
  21261. // console.log("to change: ", toChange);
  21262. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21263. }
  21264. }
  21265. var tmpHoles;
  21266. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21267. tmpShape = newShapes[ i ].s;
  21268. shapes.push( tmpShape );
  21269. tmpHoles = newShapeHoles[ i ];
  21270. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21271. tmpShape.holes.push( tmpHoles[ j ].h );
  21272. }
  21273. }
  21274. //console.log("shape", shapes);
  21275. return shapes;
  21276. }
  21277. } );
  21278. /**
  21279. * @author zz85 / http://www.lab4games.net/zz85/blog
  21280. * @author mrdoob / http://mrdoob.com/
  21281. */
  21282. function Font( data ) {
  21283. this.data = data;
  21284. }
  21285. Object.assign( Font.prototype, {
  21286. isFont: true,
  21287. generateShapes: function ( text, size, divisions ) {
  21288. function createPaths( text ) {
  21289. var chars = String( text ).split( '' );
  21290. var scale = size / data.resolution;
  21291. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21292. var offsetX = 0, offsetY = 0;
  21293. var paths = [];
  21294. for ( var i = 0; i < chars.length; i ++ ) {
  21295. var char = chars[ i ];
  21296. if ( char === '\n' ) {
  21297. offsetX = 0;
  21298. offsetY -= line_height;
  21299. } else {
  21300. var ret = createPath( char, scale, offsetX, offsetY );
  21301. offsetX += ret.offsetX;
  21302. paths.push( ret.path );
  21303. }
  21304. }
  21305. return paths;
  21306. }
  21307. function createPath( c, scale, offsetX, offsetY ) {
  21308. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21309. if ( ! glyph ) return;
  21310. var path = new ShapePath();
  21311. var pts = [];
  21312. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21313. if ( glyph.o ) {
  21314. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21315. for ( var i = 0, l = outline.length; i < l; ) {
  21316. var action = outline[ i ++ ];
  21317. switch ( action ) {
  21318. case 'm': // moveTo
  21319. x = outline[ i ++ ] * scale + offsetX;
  21320. y = outline[ i ++ ] * scale + offsetY;
  21321. path.moveTo( x, y );
  21322. break;
  21323. case 'l': // lineTo
  21324. x = outline[ i ++ ] * scale + offsetX;
  21325. y = outline[ i ++ ] * scale + offsetY;
  21326. path.lineTo( x, y );
  21327. break;
  21328. case 'q': // quadraticCurveTo
  21329. cpx = outline[ i ++ ] * scale + offsetX;
  21330. cpy = outline[ i ++ ] * scale + offsetY;
  21331. cpx1 = outline[ i ++ ] * scale + offsetX;
  21332. cpy1 = outline[ i ++ ] * scale + offsetY;
  21333. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21334. laste = pts[ pts.length - 1 ];
  21335. if ( laste ) {
  21336. cpx0 = laste.x;
  21337. cpy0 = laste.y;
  21338. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21339. var t = i2 / divisions;
  21340. QuadraticBezier( t, cpx0, cpx1, cpx );
  21341. QuadraticBezier( t, cpy0, cpy1, cpy );
  21342. }
  21343. }
  21344. break;
  21345. case 'b': // bezierCurveTo
  21346. cpx = outline[ i ++ ] * scale + offsetX;
  21347. cpy = outline[ i ++ ] * scale + offsetY;
  21348. cpx1 = outline[ i ++ ] * scale + offsetX;
  21349. cpy1 = outline[ i ++ ] * scale + offsetY;
  21350. cpx2 = outline[ i ++ ] * scale + offsetX;
  21351. cpy2 = outline[ i ++ ] * scale + offsetY;
  21352. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21353. laste = pts[ pts.length - 1 ];
  21354. if ( laste ) {
  21355. cpx0 = laste.x;
  21356. cpy0 = laste.y;
  21357. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21358. var t = i2 / divisions;
  21359. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21360. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21361. }
  21362. }
  21363. break;
  21364. }
  21365. }
  21366. }
  21367. return { offsetX: glyph.ha * scale, path: path };
  21368. }
  21369. //
  21370. if ( size === undefined ) size = 100;
  21371. if ( divisions === undefined ) divisions = 4;
  21372. var data = this.data;
  21373. var paths = createPaths( text );
  21374. var shapes = [];
  21375. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21376. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21377. }
  21378. return shapes;
  21379. }
  21380. } );
  21381. /**
  21382. * @author mrdoob / http://mrdoob.com/
  21383. */
  21384. function FontLoader( manager ) {
  21385. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21386. }
  21387. Object.assign( FontLoader.prototype, {
  21388. load: function ( url, onLoad, onProgress, onError ) {
  21389. var scope = this;
  21390. var loader = new FileLoader( this.manager );
  21391. loader.load( url, function ( text ) {
  21392. var json;
  21393. try {
  21394. json = JSON.parse( text );
  21395. } catch ( e ) {
  21396. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21397. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21398. }
  21399. var font = scope.parse( json );
  21400. if ( onLoad ) onLoad( font );
  21401. }, onProgress, onError );
  21402. },
  21403. parse: function ( json ) {
  21404. return new Font( json );
  21405. }
  21406. } );
  21407. var context;
  21408. var AudioContext = {
  21409. getContext: function () {
  21410. if ( context === undefined ) {
  21411. context = new ( window.AudioContext || window.webkitAudioContext )();
  21412. }
  21413. return context;
  21414. },
  21415. setContext: function ( value ) {
  21416. context = value;
  21417. }
  21418. };
  21419. /**
  21420. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21421. */
  21422. function AudioLoader( manager ) {
  21423. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21424. }
  21425. Object.assign( AudioLoader.prototype, {
  21426. load: function ( url, onLoad, onProgress, onError ) {
  21427. var loader = new FileLoader( this.manager );
  21428. loader.setResponseType( 'arraybuffer' );
  21429. loader.load( url, function ( buffer ) {
  21430. var context = AudioContext.getContext();
  21431. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21432. onLoad( audioBuffer );
  21433. } );
  21434. }, onProgress, onError );
  21435. }
  21436. } );
  21437. /**
  21438. * @author mrdoob / http://mrdoob.com/
  21439. */
  21440. function StereoCamera() {
  21441. this.type = 'StereoCamera';
  21442. this.aspect = 1;
  21443. this.eyeSep = 0.064;
  21444. this.cameraL = new PerspectiveCamera();
  21445. this.cameraL.layers.enable( 1 );
  21446. this.cameraL.matrixAutoUpdate = false;
  21447. this.cameraR = new PerspectiveCamera();
  21448. this.cameraR.layers.enable( 2 );
  21449. this.cameraR.matrixAutoUpdate = false;
  21450. }
  21451. Object.assign( StereoCamera.prototype, {
  21452. update: ( function () {
  21453. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21454. var eyeRight = new Matrix4();
  21455. var eyeLeft = new Matrix4();
  21456. return function update( camera ) {
  21457. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21458. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21459. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21460. if ( needsUpdate ) {
  21461. instance = this;
  21462. focus = camera.focus;
  21463. fov = camera.fov;
  21464. aspect = camera.aspect * this.aspect;
  21465. near = camera.near;
  21466. far = camera.far;
  21467. zoom = camera.zoom;
  21468. // Off-axis stereoscopic effect based on
  21469. // http://paulbourke.net/stereographics/stereorender/
  21470. var projectionMatrix = camera.projectionMatrix.clone();
  21471. eyeSep = this.eyeSep / 2;
  21472. var eyeSepOnProjection = eyeSep * near / focus;
  21473. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21474. var xmin, xmax;
  21475. // translate xOffset
  21476. eyeLeft.elements[ 12 ] = - eyeSep;
  21477. eyeRight.elements[ 12 ] = eyeSep;
  21478. // for left eye
  21479. xmin = - ymax * aspect + eyeSepOnProjection;
  21480. xmax = ymax * aspect + eyeSepOnProjection;
  21481. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21482. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21483. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21484. // for right eye
  21485. xmin = - ymax * aspect - eyeSepOnProjection;
  21486. xmax = ymax * aspect - eyeSepOnProjection;
  21487. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21488. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21489. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21490. }
  21491. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21492. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21493. };
  21494. } )()
  21495. } );
  21496. /**
  21497. * Camera for rendering cube maps
  21498. * - renders scene into axis-aligned cube
  21499. *
  21500. * @author alteredq / http://alteredqualia.com/
  21501. */
  21502. function CubeCamera( near, far, cubeResolution ) {
  21503. Object3D.call( this );
  21504. this.type = 'CubeCamera';
  21505. var fov = 90, aspect = 1;
  21506. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21507. cameraPX.up.set( 0, - 1, 0 );
  21508. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21509. this.add( cameraPX );
  21510. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21511. cameraNX.up.set( 0, - 1, 0 );
  21512. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21513. this.add( cameraNX );
  21514. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21515. cameraPY.up.set( 0, 0, 1 );
  21516. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21517. this.add( cameraPY );
  21518. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21519. cameraNY.up.set( 0, 0, - 1 );
  21520. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21521. this.add( cameraNY );
  21522. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21523. cameraPZ.up.set( 0, - 1, 0 );
  21524. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21525. this.add( cameraPZ );
  21526. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21527. cameraNZ.up.set( 0, - 1, 0 );
  21528. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21529. this.add( cameraNZ );
  21530. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21531. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21532. this.renderTarget.texture.name = "CubeCamera";
  21533. this.updateCubeMap = function ( renderer, scene ) {
  21534. if ( this.parent === null ) this.updateMatrixWorld();
  21535. var renderTarget = this.renderTarget;
  21536. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21537. renderTarget.texture.generateMipmaps = false;
  21538. renderTarget.activeCubeFace = 0;
  21539. renderer.render( scene, cameraPX, renderTarget );
  21540. renderTarget.activeCubeFace = 1;
  21541. renderer.render( scene, cameraNX, renderTarget );
  21542. renderTarget.activeCubeFace = 2;
  21543. renderer.render( scene, cameraPY, renderTarget );
  21544. renderTarget.activeCubeFace = 3;
  21545. renderer.render( scene, cameraNY, renderTarget );
  21546. renderTarget.activeCubeFace = 4;
  21547. renderer.render( scene, cameraPZ, renderTarget );
  21548. renderTarget.texture.generateMipmaps = generateMipmaps;
  21549. renderTarget.activeCubeFace = 5;
  21550. renderer.render( scene, cameraNZ, renderTarget );
  21551. renderer.setRenderTarget( null );
  21552. };
  21553. }
  21554. CubeCamera.prototype = Object.create( Object3D.prototype );
  21555. CubeCamera.prototype.constructor = CubeCamera;
  21556. /**
  21557. * @author mrdoob / http://mrdoob.com/
  21558. */
  21559. function ArrayCamera( array ) {
  21560. PerspectiveCamera.call( this );
  21561. this.enabled = false;
  21562. this.cameras = array || [];
  21563. }
  21564. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  21565. constructor: ArrayCamera,
  21566. isArrayCamera: true
  21567. } );
  21568. /**
  21569. * @author mrdoob / http://mrdoob.com/
  21570. */
  21571. function AudioListener() {
  21572. Object3D.call( this );
  21573. this.type = 'AudioListener';
  21574. this.context = AudioContext.getContext();
  21575. this.gain = this.context.createGain();
  21576. this.gain.connect( this.context.destination );
  21577. this.filter = null;
  21578. }
  21579. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21580. constructor: AudioListener,
  21581. getInput: function () {
  21582. return this.gain;
  21583. },
  21584. removeFilter: function ( ) {
  21585. if ( this.filter !== null ) {
  21586. this.gain.disconnect( this.filter );
  21587. this.filter.disconnect( this.context.destination );
  21588. this.gain.connect( this.context.destination );
  21589. this.filter = null;
  21590. }
  21591. },
  21592. getFilter: function () {
  21593. return this.filter;
  21594. },
  21595. setFilter: function ( value ) {
  21596. if ( this.filter !== null ) {
  21597. this.gain.disconnect( this.filter );
  21598. this.filter.disconnect( this.context.destination );
  21599. } else {
  21600. this.gain.disconnect( this.context.destination );
  21601. }
  21602. this.filter = value;
  21603. this.gain.connect( this.filter );
  21604. this.filter.connect( this.context.destination );
  21605. },
  21606. getMasterVolume: function () {
  21607. return this.gain.gain.value;
  21608. },
  21609. setMasterVolume: function ( value ) {
  21610. this.gain.gain.value = value;
  21611. },
  21612. updateMatrixWorld: ( function () {
  21613. var position = new Vector3();
  21614. var quaternion = new Quaternion();
  21615. var scale = new Vector3();
  21616. var orientation = new Vector3();
  21617. return function updateMatrixWorld( force ) {
  21618. Object3D.prototype.updateMatrixWorld.call( this, force );
  21619. var listener = this.context.listener;
  21620. var up = this.up;
  21621. this.matrixWorld.decompose( position, quaternion, scale );
  21622. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21623. if ( listener.positionX ) {
  21624. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21625. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21626. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21627. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21628. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21629. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21630. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21631. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21632. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21633. } else {
  21634. listener.setPosition( position.x, position.y, position.z );
  21635. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21636. }
  21637. };
  21638. } )()
  21639. } );
  21640. /**
  21641. * @author mrdoob / http://mrdoob.com/
  21642. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21643. */
  21644. function Audio( listener ) {
  21645. Object3D.call( this );
  21646. this.type = 'Audio';
  21647. this.context = listener.context;
  21648. this.gain = this.context.createGain();
  21649. this.gain.connect( listener.getInput() );
  21650. this.autoplay = false;
  21651. this.buffer = null;
  21652. this.loop = false;
  21653. this.startTime = 0;
  21654. this.playbackRate = 1;
  21655. this.isPlaying = false;
  21656. this.hasPlaybackControl = true;
  21657. this.sourceType = 'empty';
  21658. this.filters = [];
  21659. }
  21660. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21661. constructor: Audio,
  21662. getOutput: function () {
  21663. return this.gain;
  21664. },
  21665. setNodeSource: function ( audioNode ) {
  21666. this.hasPlaybackControl = false;
  21667. this.sourceType = 'audioNode';
  21668. this.source = audioNode;
  21669. this.connect();
  21670. return this;
  21671. },
  21672. setBuffer: function ( audioBuffer ) {
  21673. this.buffer = audioBuffer;
  21674. this.sourceType = 'buffer';
  21675. if ( this.autoplay ) this.play();
  21676. return this;
  21677. },
  21678. play: function () {
  21679. if ( this.isPlaying === true ) {
  21680. console.warn( 'THREE.Audio: Audio is already playing.' );
  21681. return;
  21682. }
  21683. if ( this.hasPlaybackControl === false ) {
  21684. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21685. return;
  21686. }
  21687. var source = this.context.createBufferSource();
  21688. source.buffer = this.buffer;
  21689. source.loop = this.loop;
  21690. source.onended = this.onEnded.bind( this );
  21691. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21692. source.start( 0, this.startTime );
  21693. this.isPlaying = true;
  21694. this.source = source;
  21695. return this.connect();
  21696. },
  21697. pause: function () {
  21698. if ( this.hasPlaybackControl === false ) {
  21699. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21700. return;
  21701. }
  21702. this.source.stop();
  21703. this.startTime = this.context.currentTime;
  21704. this.isPlaying = false;
  21705. return this;
  21706. },
  21707. stop: function () {
  21708. if ( this.hasPlaybackControl === false ) {
  21709. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21710. return;
  21711. }
  21712. this.source.stop();
  21713. this.startTime = 0;
  21714. this.isPlaying = false;
  21715. return this;
  21716. },
  21717. connect: function () {
  21718. if ( this.filters.length > 0 ) {
  21719. this.source.connect( this.filters[ 0 ] );
  21720. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21721. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21722. }
  21723. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21724. } else {
  21725. this.source.connect( this.getOutput() );
  21726. }
  21727. return this;
  21728. },
  21729. disconnect: function () {
  21730. if ( this.filters.length > 0 ) {
  21731. this.source.disconnect( this.filters[ 0 ] );
  21732. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21733. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21734. }
  21735. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21736. } else {
  21737. this.source.disconnect( this.getOutput() );
  21738. }
  21739. return this;
  21740. },
  21741. getFilters: function () {
  21742. return this.filters;
  21743. },
  21744. setFilters: function ( value ) {
  21745. if ( ! value ) value = [];
  21746. if ( this.isPlaying === true ) {
  21747. this.disconnect();
  21748. this.filters = value;
  21749. this.connect();
  21750. } else {
  21751. this.filters = value;
  21752. }
  21753. return this;
  21754. },
  21755. getFilter: function () {
  21756. return this.getFilters()[ 0 ];
  21757. },
  21758. setFilter: function ( filter ) {
  21759. return this.setFilters( filter ? [ filter ] : [] );
  21760. },
  21761. setPlaybackRate: function ( value ) {
  21762. if ( this.hasPlaybackControl === false ) {
  21763. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21764. return;
  21765. }
  21766. this.playbackRate = value;
  21767. if ( this.isPlaying === true ) {
  21768. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21769. }
  21770. return this;
  21771. },
  21772. getPlaybackRate: function () {
  21773. return this.playbackRate;
  21774. },
  21775. onEnded: function () {
  21776. this.isPlaying = false;
  21777. },
  21778. getLoop: function () {
  21779. if ( this.hasPlaybackControl === false ) {
  21780. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21781. return false;
  21782. }
  21783. return this.loop;
  21784. },
  21785. setLoop: function ( value ) {
  21786. if ( this.hasPlaybackControl === false ) {
  21787. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21788. return;
  21789. }
  21790. this.loop = value;
  21791. if ( this.isPlaying === true ) {
  21792. this.source.loop = this.loop;
  21793. }
  21794. return this;
  21795. },
  21796. getVolume: function () {
  21797. return this.gain.gain.value;
  21798. },
  21799. setVolume: function ( value ) {
  21800. this.gain.gain.value = value;
  21801. return this;
  21802. }
  21803. } );
  21804. /**
  21805. * @author mrdoob / http://mrdoob.com/
  21806. */
  21807. function PositionalAudio( listener ) {
  21808. Audio.call( this, listener );
  21809. this.panner = this.context.createPanner();
  21810. this.panner.connect( this.gain );
  21811. }
  21812. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21813. constructor: PositionalAudio,
  21814. getOutput: function () {
  21815. return this.panner;
  21816. },
  21817. getRefDistance: function () {
  21818. return this.panner.refDistance;
  21819. },
  21820. setRefDistance: function ( value ) {
  21821. this.panner.refDistance = value;
  21822. },
  21823. getRolloffFactor: function () {
  21824. return this.panner.rolloffFactor;
  21825. },
  21826. setRolloffFactor: function ( value ) {
  21827. this.panner.rolloffFactor = value;
  21828. },
  21829. getDistanceModel: function () {
  21830. return this.panner.distanceModel;
  21831. },
  21832. setDistanceModel: function ( value ) {
  21833. this.panner.distanceModel = value;
  21834. },
  21835. getMaxDistance: function () {
  21836. return this.panner.maxDistance;
  21837. },
  21838. setMaxDistance: function ( value ) {
  21839. this.panner.maxDistance = value;
  21840. },
  21841. updateMatrixWorld: ( function () {
  21842. var position = new Vector3();
  21843. return function updateMatrixWorld( force ) {
  21844. Object3D.prototype.updateMatrixWorld.call( this, force );
  21845. position.setFromMatrixPosition( this.matrixWorld );
  21846. this.panner.setPosition( position.x, position.y, position.z );
  21847. };
  21848. } )()
  21849. } );
  21850. /**
  21851. * @author mrdoob / http://mrdoob.com/
  21852. */
  21853. function AudioAnalyser( audio, fftSize ) {
  21854. this.analyser = audio.context.createAnalyser();
  21855. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21856. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21857. audio.getOutput().connect( this.analyser );
  21858. }
  21859. Object.assign( AudioAnalyser.prototype, {
  21860. getFrequencyData: function () {
  21861. this.analyser.getByteFrequencyData( this.data );
  21862. return this.data;
  21863. },
  21864. getAverageFrequency: function () {
  21865. var value = 0, data = this.getFrequencyData();
  21866. for ( var i = 0; i < data.length; i ++ ) {
  21867. value += data[ i ];
  21868. }
  21869. return value / data.length;
  21870. }
  21871. } );
  21872. /**
  21873. *
  21874. * Buffered scene graph property that allows weighted accumulation.
  21875. *
  21876. *
  21877. * @author Ben Houston / http://clara.io/
  21878. * @author David Sarno / http://lighthaus.us/
  21879. * @author tschw
  21880. */
  21881. function PropertyMixer( binding, typeName, valueSize ) {
  21882. this.binding = binding;
  21883. this.valueSize = valueSize;
  21884. var bufferType = Float64Array,
  21885. mixFunction;
  21886. switch ( typeName ) {
  21887. case 'quaternion':
  21888. mixFunction = this._slerp;
  21889. break;
  21890. case 'string':
  21891. case 'bool':
  21892. bufferType = Array;
  21893. mixFunction = this._select;
  21894. break;
  21895. default:
  21896. mixFunction = this._lerp;
  21897. }
  21898. this.buffer = new bufferType( valueSize * 4 );
  21899. // layout: [ incoming | accu0 | accu1 | orig ]
  21900. //
  21901. // interpolators can use .buffer as their .result
  21902. // the data then goes to 'incoming'
  21903. //
  21904. // 'accu0' and 'accu1' are used frame-interleaved for
  21905. // the cumulative result and are compared to detect
  21906. // changes
  21907. //
  21908. // 'orig' stores the original state of the property
  21909. this._mixBufferRegion = mixFunction;
  21910. this.cumulativeWeight = 0;
  21911. this.useCount = 0;
  21912. this.referenceCount = 0;
  21913. }
  21914. Object.assign( PropertyMixer.prototype, {
  21915. // accumulate data in the 'incoming' region into 'accu<i>'
  21916. accumulate: function ( accuIndex, weight ) {
  21917. // note: happily accumulating nothing when weight = 0, the caller knows
  21918. // the weight and shouldn't have made the call in the first place
  21919. var buffer = this.buffer,
  21920. stride = this.valueSize,
  21921. offset = accuIndex * stride + stride,
  21922. currentWeight = this.cumulativeWeight;
  21923. if ( currentWeight === 0 ) {
  21924. // accuN := incoming * weight
  21925. for ( var i = 0; i !== stride; ++ i ) {
  21926. buffer[ offset + i ] = buffer[ i ];
  21927. }
  21928. currentWeight = weight;
  21929. } else {
  21930. // accuN := accuN + incoming * weight
  21931. currentWeight += weight;
  21932. var mix = weight / currentWeight;
  21933. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21934. }
  21935. this.cumulativeWeight = currentWeight;
  21936. },
  21937. // apply the state of 'accu<i>' to the binding when accus differ
  21938. apply: function ( accuIndex ) {
  21939. var stride = this.valueSize,
  21940. buffer = this.buffer,
  21941. offset = accuIndex * stride + stride,
  21942. weight = this.cumulativeWeight,
  21943. binding = this.binding;
  21944. this.cumulativeWeight = 0;
  21945. if ( weight < 1 ) {
  21946. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21947. var originalValueOffset = stride * 3;
  21948. this._mixBufferRegion(
  21949. buffer, offset, originalValueOffset, 1 - weight, stride );
  21950. }
  21951. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21952. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21953. // value has changed -> update scene graph
  21954. binding.setValue( buffer, offset );
  21955. break;
  21956. }
  21957. }
  21958. },
  21959. // remember the state of the bound property and copy it to both accus
  21960. saveOriginalState: function () {
  21961. var binding = this.binding;
  21962. var buffer = this.buffer,
  21963. stride = this.valueSize,
  21964. originalValueOffset = stride * 3;
  21965. binding.getValue( buffer, originalValueOffset );
  21966. // accu[0..1] := orig -- initially detect changes against the original
  21967. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21968. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21969. }
  21970. this.cumulativeWeight = 0;
  21971. },
  21972. // apply the state previously taken via 'saveOriginalState' to the binding
  21973. restoreOriginalState: function () {
  21974. var originalValueOffset = this.valueSize * 3;
  21975. this.binding.setValue( this.buffer, originalValueOffset );
  21976. },
  21977. // mix functions
  21978. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  21979. if ( t >= 0.5 ) {
  21980. for ( var i = 0; i !== stride; ++ i ) {
  21981. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21982. }
  21983. }
  21984. },
  21985. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  21986. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  21987. },
  21988. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  21989. var s = 1 - t;
  21990. for ( var i = 0; i !== stride; ++ i ) {
  21991. var j = dstOffset + i;
  21992. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21993. }
  21994. }
  21995. } );
  21996. /**
  21997. *
  21998. * A reference to a real property in the scene graph.
  21999. *
  22000. *
  22001. * @author Ben Houston / http://clara.io/
  22002. * @author David Sarno / http://lighthaus.us/
  22003. * @author tschw
  22004. */
  22005. function Composite( targetGroup, path, optionalParsedPath ) {
  22006. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22007. this._targetGroup = targetGroup;
  22008. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22009. }
  22010. Object.assign( Composite.prototype, {
  22011. getValue: function ( array, offset ) {
  22012. this.bind(); // bind all binding
  22013. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22014. binding = this._bindings[ firstValidIndex ];
  22015. // and only call .getValue on the first
  22016. if ( binding !== undefined ) binding.getValue( array, offset );
  22017. },
  22018. setValue: function ( array, offset ) {
  22019. var bindings = this._bindings;
  22020. for ( var i = this._targetGroup.nCachedObjects_,
  22021. n = bindings.length; i !== n; ++ i ) {
  22022. bindings[ i ].setValue( array, offset );
  22023. }
  22024. },
  22025. bind: function () {
  22026. var bindings = this._bindings;
  22027. for ( var i = this._targetGroup.nCachedObjects_,
  22028. n = bindings.length; i !== n; ++ i ) {
  22029. bindings[ i ].bind();
  22030. }
  22031. },
  22032. unbind: function () {
  22033. var bindings = this._bindings;
  22034. for ( var i = this._targetGroup.nCachedObjects_,
  22035. n = bindings.length; i !== n; ++ i ) {
  22036. bindings[ i ].unbind();
  22037. }
  22038. }
  22039. } );
  22040. function PropertyBinding( rootNode, path, parsedPath ) {
  22041. this.path = path;
  22042. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22043. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22044. this.rootNode = rootNode;
  22045. }
  22046. Object.assign( PropertyBinding, {
  22047. Composite: Composite,
  22048. create: function ( root, path, parsedPath ) {
  22049. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22050. return new PropertyBinding( root, path, parsedPath );
  22051. } else {
  22052. return new PropertyBinding.Composite( root, path, parsedPath );
  22053. }
  22054. },
  22055. parseTrackName: function () {
  22056. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22057. // be matched to parse the rest of the track name.
  22058. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22059. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22060. var nodeRe = /([\w-\.]+)?/;
  22061. // Object on target node, and accessor. Name may contain only word
  22062. // characters. Accessor may contain any character except closing bracket.
  22063. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22064. // Property and accessor. May contain only word characters. Accessor may
  22065. // contain any non-bracket characters.
  22066. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22067. var trackRe = new RegExp(''
  22068. + '^'
  22069. + directoryRe.source
  22070. + nodeRe.source
  22071. + objectRe.source
  22072. + propertyRe.source
  22073. + '$'
  22074. );
  22075. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22076. return function ( trackName ) {
  22077. var matches = trackRe.exec( trackName );
  22078. if ( ! matches ) {
  22079. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22080. }
  22081. var results = {
  22082. // directoryName: matches[ 1 ], // (tschw) currently unused
  22083. nodeName: matches[ 2 ],
  22084. objectName: matches[ 3 ],
  22085. objectIndex: matches[ 4 ],
  22086. propertyName: matches[ 5 ], // required
  22087. propertyIndex: matches[ 6 ]
  22088. };
  22089. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22090. if ( lastDot !== undefined && lastDot !== -1 ) {
  22091. var objectName = results.nodeName.substring( lastDot + 1 );
  22092. // Object names must be checked against a whitelist. Otherwise, there
  22093. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22094. // 'bar' could be the objectName, or part of a nodeName (which can
  22095. // include '.' characters).
  22096. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22097. results.nodeName = results.nodeName.substring( 0, lastDot );
  22098. results.objectName = objectName;
  22099. }
  22100. }
  22101. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22102. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22103. }
  22104. return results;
  22105. };
  22106. }(),
  22107. findNode: function ( root, nodeName ) {
  22108. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22109. return root;
  22110. }
  22111. // search into skeleton bones.
  22112. if ( root.skeleton ) {
  22113. var searchSkeleton = function ( skeleton ) {
  22114. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22115. var bone = skeleton.bones[ i ];
  22116. if ( bone.name === nodeName ) {
  22117. return bone;
  22118. }
  22119. }
  22120. return null;
  22121. };
  22122. var bone = searchSkeleton( root.skeleton );
  22123. if ( bone ) {
  22124. return bone;
  22125. }
  22126. }
  22127. // search into node subtree.
  22128. if ( root.children ) {
  22129. var searchNodeSubtree = function ( children ) {
  22130. for ( var i = 0; i < children.length; i ++ ) {
  22131. var childNode = children[ i ];
  22132. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22133. return childNode;
  22134. }
  22135. var result = searchNodeSubtree( childNode.children );
  22136. if ( result ) return result;
  22137. }
  22138. return null;
  22139. };
  22140. var subTreeNode = searchNodeSubtree( root.children );
  22141. if ( subTreeNode ) {
  22142. return subTreeNode;
  22143. }
  22144. }
  22145. return null;
  22146. }
  22147. } );
  22148. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22149. // these are used to "bind" a nonexistent property
  22150. _getValue_unavailable: function () {},
  22151. _setValue_unavailable: function () {},
  22152. BindingType: {
  22153. Direct: 0,
  22154. EntireArray: 1,
  22155. ArrayElement: 2,
  22156. HasFromToArray: 3
  22157. },
  22158. Versioning: {
  22159. None: 0,
  22160. NeedsUpdate: 1,
  22161. MatrixWorldNeedsUpdate: 2
  22162. },
  22163. GetterByBindingType: [
  22164. function getValue_direct( buffer, offset ) {
  22165. buffer[ offset ] = this.node[ this.propertyName ];
  22166. },
  22167. function getValue_array( buffer, offset ) {
  22168. var source = this.resolvedProperty;
  22169. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22170. buffer[ offset ++ ] = source[ i ];
  22171. }
  22172. },
  22173. function getValue_arrayElement( buffer, offset ) {
  22174. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22175. },
  22176. function getValue_toArray( buffer, offset ) {
  22177. this.resolvedProperty.toArray( buffer, offset );
  22178. }
  22179. ],
  22180. SetterByBindingTypeAndVersioning: [
  22181. [
  22182. // Direct
  22183. function setValue_direct( buffer, offset ) {
  22184. this.node[ this.propertyName ] = buffer[ offset ];
  22185. },
  22186. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22187. this.node[ this.propertyName ] = buffer[ offset ];
  22188. this.targetObject.needsUpdate = true;
  22189. },
  22190. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22191. this.node[ this.propertyName ] = buffer[ offset ];
  22192. this.targetObject.matrixWorldNeedsUpdate = true;
  22193. }
  22194. ], [
  22195. // EntireArray
  22196. function setValue_array( buffer, offset ) {
  22197. var dest = this.resolvedProperty;
  22198. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22199. dest[ i ] = buffer[ offset ++ ];
  22200. }
  22201. },
  22202. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22203. var dest = this.resolvedProperty;
  22204. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22205. dest[ i ] = buffer[ offset ++ ];
  22206. }
  22207. this.targetObject.needsUpdate = true;
  22208. },
  22209. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22210. var dest = this.resolvedProperty;
  22211. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22212. dest[ i ] = buffer[ offset ++ ];
  22213. }
  22214. this.targetObject.matrixWorldNeedsUpdate = true;
  22215. }
  22216. ], [
  22217. // ArrayElement
  22218. function setValue_arrayElement( buffer, offset ) {
  22219. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22220. },
  22221. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22222. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22223. this.targetObject.needsUpdate = true;
  22224. },
  22225. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22226. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22227. this.targetObject.matrixWorldNeedsUpdate = true;
  22228. }
  22229. ], [
  22230. // HasToFromArray
  22231. function setValue_fromArray( buffer, offset ) {
  22232. this.resolvedProperty.fromArray( buffer, offset );
  22233. },
  22234. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22235. this.resolvedProperty.fromArray( buffer, offset );
  22236. this.targetObject.needsUpdate = true;
  22237. },
  22238. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22239. this.resolvedProperty.fromArray( buffer, offset );
  22240. this.targetObject.matrixWorldNeedsUpdate = true;
  22241. }
  22242. ]
  22243. ],
  22244. getValue: function getValue_unbound( targetArray, offset ) {
  22245. this.bind();
  22246. this.getValue( targetArray, offset );
  22247. // Note: This class uses a State pattern on a per-method basis:
  22248. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22249. // prototype version of these methods with one that represents
  22250. // the bound state. When the property is not found, the methods
  22251. // become no-ops.
  22252. },
  22253. setValue: function getValue_unbound( sourceArray, offset ) {
  22254. this.bind();
  22255. this.setValue( sourceArray, offset );
  22256. },
  22257. // create getter / setter pair for a property in the scene graph
  22258. bind: function () {
  22259. var targetObject = this.node,
  22260. parsedPath = this.parsedPath,
  22261. objectName = parsedPath.objectName,
  22262. propertyName = parsedPath.propertyName,
  22263. propertyIndex = parsedPath.propertyIndex;
  22264. if ( ! targetObject ) {
  22265. targetObject = PropertyBinding.findNode(
  22266. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22267. this.node = targetObject;
  22268. }
  22269. // set fail state so we can just 'return' on error
  22270. this.getValue = this._getValue_unavailable;
  22271. this.setValue = this._setValue_unavailable;
  22272. // ensure there is a value node
  22273. if ( ! targetObject ) {
  22274. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  22275. return;
  22276. }
  22277. if ( objectName ) {
  22278. var objectIndex = parsedPath.objectIndex;
  22279. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22280. switch ( objectName ) {
  22281. case 'materials':
  22282. if ( ! targetObject.material ) {
  22283. console.error( ' can not bind to material as node does not have a material', this );
  22284. return;
  22285. }
  22286. if ( ! targetObject.material.materials ) {
  22287. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  22288. return;
  22289. }
  22290. targetObject = targetObject.material.materials;
  22291. break;
  22292. case 'bones':
  22293. if ( ! targetObject.skeleton ) {
  22294. console.error( ' can not bind to bones as node does not have a skeleton', this );
  22295. return;
  22296. }
  22297. // potential future optimization: skip this if propertyIndex is already an integer
  22298. // and convert the integer string to a true integer.
  22299. targetObject = targetObject.skeleton.bones;
  22300. // support resolving morphTarget names into indices.
  22301. for ( var i = 0; i < targetObject.length; i ++ ) {
  22302. if ( targetObject[ i ].name === objectIndex ) {
  22303. objectIndex = i;
  22304. break;
  22305. }
  22306. }
  22307. break;
  22308. default:
  22309. if ( targetObject[ objectName ] === undefined ) {
  22310. console.error( ' can not bind to objectName of node, undefined', this );
  22311. return;
  22312. }
  22313. targetObject = targetObject[ objectName ];
  22314. }
  22315. if ( objectIndex !== undefined ) {
  22316. if ( targetObject[ objectIndex ] === undefined ) {
  22317. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  22318. return;
  22319. }
  22320. targetObject = targetObject[ objectIndex ];
  22321. }
  22322. }
  22323. // resolve property
  22324. var nodeProperty = targetObject[ propertyName ];
  22325. if ( nodeProperty === undefined ) {
  22326. var nodeName = parsedPath.nodeName;
  22327. console.error( " trying to update property for track: " + nodeName +
  22328. '.' + propertyName + " but it wasn't found.", targetObject );
  22329. return;
  22330. }
  22331. // determine versioning scheme
  22332. var versioning = this.Versioning.None;
  22333. if ( targetObject.needsUpdate !== undefined ) { // material
  22334. versioning = this.Versioning.NeedsUpdate;
  22335. this.targetObject = targetObject;
  22336. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22337. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22338. this.targetObject = targetObject;
  22339. }
  22340. // determine how the property gets bound
  22341. var bindingType = this.BindingType.Direct;
  22342. if ( propertyIndex !== undefined ) {
  22343. // access a sub element of the property array (only primitives are supported right now)
  22344. if ( propertyName === "morphTargetInfluences" ) {
  22345. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22346. // support resolving morphTarget names into indices.
  22347. if ( ! targetObject.geometry ) {
  22348. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  22349. return;
  22350. }
  22351. if ( ! targetObject.geometry.morphTargets ) {
  22352. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  22353. return;
  22354. }
  22355. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22356. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22357. propertyIndex = i;
  22358. break;
  22359. }
  22360. }
  22361. }
  22362. bindingType = this.BindingType.ArrayElement;
  22363. this.resolvedProperty = nodeProperty;
  22364. this.propertyIndex = propertyIndex;
  22365. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22366. // must use copy for Object3D.Euler/Quaternion
  22367. bindingType = this.BindingType.HasFromToArray;
  22368. this.resolvedProperty = nodeProperty;
  22369. } else if ( Array.isArray( nodeProperty ) ) {
  22370. bindingType = this.BindingType.EntireArray;
  22371. this.resolvedProperty = nodeProperty;
  22372. } else {
  22373. this.propertyName = propertyName;
  22374. }
  22375. // select getter / setter
  22376. this.getValue = this.GetterByBindingType[ bindingType ];
  22377. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22378. },
  22379. unbind: function () {
  22380. this.node = null;
  22381. // back to the prototype version of getValue / setValue
  22382. // note: avoiding to mutate the shape of 'this' via 'delete'
  22383. this.getValue = this._getValue_unbound;
  22384. this.setValue = this._setValue_unbound;
  22385. }
  22386. } );
  22387. //!\ DECLARE ALIAS AFTER assign prototype !
  22388. Object.assign( PropertyBinding.prototype, {
  22389. // initial state of these methods that calls 'bind'
  22390. _getValue_unbound: PropertyBinding.prototype.getValue,
  22391. _setValue_unbound: PropertyBinding.prototype.setValue,
  22392. } );
  22393. /**
  22394. *
  22395. * A group of objects that receives a shared animation state.
  22396. *
  22397. * Usage:
  22398. *
  22399. * - Add objects you would otherwise pass as 'root' to the
  22400. * constructor or the .clipAction method of AnimationMixer.
  22401. *
  22402. * - Instead pass this object as 'root'.
  22403. *
  22404. * - You can also add and remove objects later when the mixer
  22405. * is running.
  22406. *
  22407. * Note:
  22408. *
  22409. * Objects of this class appear as one object to the mixer,
  22410. * so cache control of the individual objects must be done
  22411. * on the group.
  22412. *
  22413. * Limitation:
  22414. *
  22415. * - The animated properties must be compatible among the
  22416. * all objects in the group.
  22417. *
  22418. * - A single property can either be controlled through a
  22419. * target group or directly, but not both.
  22420. *
  22421. * @author tschw
  22422. */
  22423. function AnimationObjectGroup( var_args ) {
  22424. this.uuid = _Math.generateUUID();
  22425. // cached objects followed by the active ones
  22426. this._objects = Array.prototype.slice.call( arguments );
  22427. this.nCachedObjects_ = 0; // threshold
  22428. // note: read by PropertyBinding.Composite
  22429. var indices = {};
  22430. this._indicesByUUID = indices; // for bookkeeping
  22431. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22432. indices[ arguments[ i ].uuid ] = i;
  22433. }
  22434. this._paths = []; // inside: string
  22435. this._parsedPaths = []; // inside: { we don't care, here }
  22436. this._bindings = []; // inside: Array< PropertyBinding >
  22437. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22438. var scope = this;
  22439. this.stats = {
  22440. objects: {
  22441. get total() { return scope._objects.length; },
  22442. get inUse() { return this.total - scope.nCachedObjects_; }
  22443. },
  22444. get bindingsPerObject() { return scope._bindings.length; }
  22445. };
  22446. }
  22447. Object.assign( AnimationObjectGroup.prototype, {
  22448. isAnimationObjectGroup: true,
  22449. add: function( var_args ) {
  22450. var objects = this._objects,
  22451. nObjects = objects.length,
  22452. nCachedObjects = this.nCachedObjects_,
  22453. indicesByUUID = this._indicesByUUID,
  22454. paths = this._paths,
  22455. parsedPaths = this._parsedPaths,
  22456. bindings = this._bindings,
  22457. nBindings = bindings.length;
  22458. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22459. var object = arguments[ i ],
  22460. uuid = object.uuid,
  22461. index = indicesByUUID[ uuid ],
  22462. knownObject = undefined;
  22463. if ( index === undefined ) {
  22464. // unknown object -> add it to the ACTIVE region
  22465. index = nObjects ++;
  22466. indicesByUUID[ uuid ] = index;
  22467. objects.push( object );
  22468. // accounting is done, now do the same for all bindings
  22469. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22470. bindings[ j ].push(
  22471. new PropertyBinding(
  22472. object, paths[ j ], parsedPaths[ j ] ) );
  22473. }
  22474. } else if ( index < nCachedObjects ) {
  22475. knownObject = objects[ index ];
  22476. // move existing object to the ACTIVE region
  22477. var firstActiveIndex = -- nCachedObjects,
  22478. lastCachedObject = objects[ firstActiveIndex ];
  22479. indicesByUUID[ lastCachedObject.uuid ] = index;
  22480. objects[ index ] = lastCachedObject;
  22481. indicesByUUID[ uuid ] = firstActiveIndex;
  22482. objects[ firstActiveIndex ] = object;
  22483. // accounting is done, now do the same for all bindings
  22484. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22485. var bindingsForPath = bindings[ j ],
  22486. lastCached = bindingsForPath[ firstActiveIndex ],
  22487. binding = bindingsForPath[ index ];
  22488. bindingsForPath[ index ] = lastCached;
  22489. if ( binding === undefined ) {
  22490. // since we do not bother to create new bindings
  22491. // for objects that are cached, the binding may
  22492. // or may not exist
  22493. binding = new PropertyBinding(
  22494. object, paths[ j ], parsedPaths[ j ] );
  22495. }
  22496. bindingsForPath[ firstActiveIndex ] = binding;
  22497. }
  22498. } else if ( objects[ index ] !== knownObject ) {
  22499. console.error( "Different objects with the same UUID " +
  22500. "detected. Clean the caches or recreate your " +
  22501. "infrastructure when reloading scenes..." );
  22502. } // else the object is already where we want it to be
  22503. } // for arguments
  22504. this.nCachedObjects_ = nCachedObjects;
  22505. },
  22506. remove: function( var_args ) {
  22507. var objects = this._objects,
  22508. nCachedObjects = this.nCachedObjects_,
  22509. indicesByUUID = this._indicesByUUID,
  22510. bindings = this._bindings,
  22511. nBindings = bindings.length;
  22512. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22513. var object = arguments[ i ],
  22514. uuid = object.uuid,
  22515. index = indicesByUUID[ uuid ];
  22516. if ( index !== undefined && index >= nCachedObjects ) {
  22517. // move existing object into the CACHED region
  22518. var lastCachedIndex = nCachedObjects ++,
  22519. firstActiveObject = objects[ lastCachedIndex ];
  22520. indicesByUUID[ firstActiveObject.uuid ] = index;
  22521. objects[ index ] = firstActiveObject;
  22522. indicesByUUID[ uuid ] = lastCachedIndex;
  22523. objects[ lastCachedIndex ] = object;
  22524. // accounting is done, now do the same for all bindings
  22525. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22526. var bindingsForPath = bindings[ j ],
  22527. firstActive = bindingsForPath[ lastCachedIndex ],
  22528. binding = bindingsForPath[ index ];
  22529. bindingsForPath[ index ] = firstActive;
  22530. bindingsForPath[ lastCachedIndex ] = binding;
  22531. }
  22532. }
  22533. } // for arguments
  22534. this.nCachedObjects_ = nCachedObjects;
  22535. },
  22536. // remove & forget
  22537. uncache: function( var_args ) {
  22538. var objects = this._objects,
  22539. nObjects = objects.length,
  22540. nCachedObjects = this.nCachedObjects_,
  22541. indicesByUUID = this._indicesByUUID,
  22542. bindings = this._bindings,
  22543. nBindings = bindings.length;
  22544. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22545. var object = arguments[ i ],
  22546. uuid = object.uuid,
  22547. index = indicesByUUID[ uuid ];
  22548. if ( index !== undefined ) {
  22549. delete indicesByUUID[ uuid ];
  22550. if ( index < nCachedObjects ) {
  22551. // object is cached, shrink the CACHED region
  22552. var firstActiveIndex = -- nCachedObjects,
  22553. lastCachedObject = objects[ firstActiveIndex ],
  22554. lastIndex = -- nObjects,
  22555. lastObject = objects[ lastIndex ];
  22556. // last cached object takes this object's place
  22557. indicesByUUID[ lastCachedObject.uuid ] = index;
  22558. objects[ index ] = lastCachedObject;
  22559. // last object goes to the activated slot and pop
  22560. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22561. objects[ firstActiveIndex ] = lastObject;
  22562. objects.pop();
  22563. // accounting is done, now do the same for all bindings
  22564. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22565. var bindingsForPath = bindings[ j ],
  22566. lastCached = bindingsForPath[ firstActiveIndex ],
  22567. last = bindingsForPath[ lastIndex ];
  22568. bindingsForPath[ index ] = lastCached;
  22569. bindingsForPath[ firstActiveIndex ] = last;
  22570. bindingsForPath.pop();
  22571. }
  22572. } else {
  22573. // object is active, just swap with the last and pop
  22574. var lastIndex = -- nObjects,
  22575. lastObject = objects[ lastIndex ];
  22576. indicesByUUID[ lastObject.uuid ] = index;
  22577. objects[ index ] = lastObject;
  22578. objects.pop();
  22579. // accounting is done, now do the same for all bindings
  22580. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22581. var bindingsForPath = bindings[ j ];
  22582. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22583. bindingsForPath.pop();
  22584. }
  22585. } // cached or active
  22586. } // if object is known
  22587. } // for arguments
  22588. this.nCachedObjects_ = nCachedObjects;
  22589. },
  22590. // Internal interface used by befriended PropertyBinding.Composite:
  22591. subscribe_: function ( path, parsedPath ) {
  22592. // returns an array of bindings for the given path that is changed
  22593. // according to the contained objects in the group
  22594. var indicesByPath = this._bindingsIndicesByPath,
  22595. index = indicesByPath[ path ],
  22596. bindings = this._bindings;
  22597. if ( index !== undefined ) return bindings[ index ];
  22598. var paths = this._paths,
  22599. parsedPaths = this._parsedPaths,
  22600. objects = this._objects,
  22601. nObjects = objects.length,
  22602. nCachedObjects = this.nCachedObjects_,
  22603. bindingsForPath = new Array( nObjects );
  22604. index = bindings.length;
  22605. indicesByPath[ path ] = index;
  22606. paths.push( path );
  22607. parsedPaths.push( parsedPath );
  22608. bindings.push( bindingsForPath );
  22609. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22610. var object = objects[ i ];
  22611. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22612. }
  22613. return bindingsForPath;
  22614. },
  22615. unsubscribe_: function ( path ) {
  22616. // tells the group to forget about a property path and no longer
  22617. // update the array previously obtained with 'subscribe_'
  22618. var indicesByPath = this._bindingsIndicesByPath,
  22619. index = indicesByPath[ path ];
  22620. if ( index !== undefined ) {
  22621. var paths = this._paths,
  22622. parsedPaths = this._parsedPaths,
  22623. bindings = this._bindings,
  22624. lastBindingsIndex = bindings.length - 1,
  22625. lastBindings = bindings[ lastBindingsIndex ],
  22626. lastBindingsPath = path[ lastBindingsIndex ];
  22627. indicesByPath[ lastBindingsPath ] = index;
  22628. bindings[ index ] = lastBindings;
  22629. bindings.pop();
  22630. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22631. parsedPaths.pop();
  22632. paths[ index ] = paths[ lastBindingsIndex ];
  22633. paths.pop();
  22634. }
  22635. }
  22636. } );
  22637. /**
  22638. *
  22639. * Action provided by AnimationMixer for scheduling clip playback on specific
  22640. * objects.
  22641. *
  22642. * @author Ben Houston / http://clara.io/
  22643. * @author David Sarno / http://lighthaus.us/
  22644. * @author tschw
  22645. *
  22646. */
  22647. function AnimationAction( mixer, clip, localRoot ) {
  22648. this._mixer = mixer;
  22649. this._clip = clip;
  22650. this._localRoot = localRoot || null;
  22651. var tracks = clip.tracks,
  22652. nTracks = tracks.length,
  22653. interpolants = new Array( nTracks );
  22654. var interpolantSettings = {
  22655. endingStart: ZeroCurvatureEnding,
  22656. endingEnd: ZeroCurvatureEnding
  22657. };
  22658. for ( var i = 0; i !== nTracks; ++ i ) {
  22659. var interpolant = tracks[ i ].createInterpolant( null );
  22660. interpolants[ i ] = interpolant;
  22661. interpolant.settings = interpolantSettings;
  22662. }
  22663. this._interpolantSettings = interpolantSettings;
  22664. this._interpolants = interpolants; // bound by the mixer
  22665. // inside: PropertyMixer (managed by the mixer)
  22666. this._propertyBindings = new Array( nTracks );
  22667. this._cacheIndex = null; // for the memory manager
  22668. this._byClipCacheIndex = null; // for the memory manager
  22669. this._timeScaleInterpolant = null;
  22670. this._weightInterpolant = null;
  22671. this.loop = LoopRepeat;
  22672. this._loopCount = -1;
  22673. // global mixer time when the action is to be started
  22674. // it's set back to 'null' upon start of the action
  22675. this._startTime = null;
  22676. // scaled local time of the action
  22677. // gets clamped or wrapped to 0..clip.duration according to loop
  22678. this.time = 0;
  22679. this.timeScale = 1;
  22680. this._effectiveTimeScale = 1;
  22681. this.weight = 1;
  22682. this._effectiveWeight = 1;
  22683. this.repetitions = Infinity; // no. of repetitions when looping
  22684. this.paused = false; // true -> zero effective time scale
  22685. this.enabled = true; // false -> zero effective weight
  22686. this.clampWhenFinished = false; // keep feeding the last frame?
  22687. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22688. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22689. }
  22690. Object.assign( AnimationAction.prototype, {
  22691. // State & Scheduling
  22692. play: function() {
  22693. this._mixer._activateAction( this );
  22694. return this;
  22695. },
  22696. stop: function() {
  22697. this._mixer._deactivateAction( this );
  22698. return this.reset();
  22699. },
  22700. reset: function() {
  22701. this.paused = false;
  22702. this.enabled = true;
  22703. this.time = 0; // restart clip
  22704. this._loopCount = -1; // forget previous loops
  22705. this._startTime = null; // forget scheduling
  22706. return this.stopFading().stopWarping();
  22707. },
  22708. isRunning: function() {
  22709. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22710. this._startTime === null && this._mixer._isActiveAction( this );
  22711. },
  22712. // return true when play has been called
  22713. isScheduled: function() {
  22714. return this._mixer._isActiveAction( this );
  22715. },
  22716. startAt: function( time ) {
  22717. this._startTime = time;
  22718. return this;
  22719. },
  22720. setLoop: function( mode, repetitions ) {
  22721. this.loop = mode;
  22722. this.repetitions = repetitions;
  22723. return this;
  22724. },
  22725. // Weight
  22726. // set the weight stopping any scheduled fading
  22727. // although .enabled = false yields an effective weight of zero, this
  22728. // method does *not* change .enabled, because it would be confusing
  22729. setEffectiveWeight: function( weight ) {
  22730. this.weight = weight;
  22731. // note: same logic as when updated at runtime
  22732. this._effectiveWeight = this.enabled ? weight : 0;
  22733. return this.stopFading();
  22734. },
  22735. // return the weight considering fading and .enabled
  22736. getEffectiveWeight: function() {
  22737. return this._effectiveWeight;
  22738. },
  22739. fadeIn: function( duration ) {
  22740. return this._scheduleFading( duration, 0, 1 );
  22741. },
  22742. fadeOut: function( duration ) {
  22743. return this._scheduleFading( duration, 1, 0 );
  22744. },
  22745. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22746. fadeOutAction.fadeOut( duration );
  22747. this.fadeIn( duration );
  22748. if( warp ) {
  22749. var fadeInDuration = this._clip.duration,
  22750. fadeOutDuration = fadeOutAction._clip.duration,
  22751. startEndRatio = fadeOutDuration / fadeInDuration,
  22752. endStartRatio = fadeInDuration / fadeOutDuration;
  22753. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22754. this.warp( endStartRatio, 1.0, duration );
  22755. }
  22756. return this;
  22757. },
  22758. crossFadeTo: function( fadeInAction, duration, warp ) {
  22759. return fadeInAction.crossFadeFrom( this, duration, warp );
  22760. },
  22761. stopFading: function() {
  22762. var weightInterpolant = this._weightInterpolant;
  22763. if ( weightInterpolant !== null ) {
  22764. this._weightInterpolant = null;
  22765. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22766. }
  22767. return this;
  22768. },
  22769. // Time Scale Control
  22770. // set the time scale stopping any scheduled warping
  22771. // although .paused = true yields an effective time scale of zero, this
  22772. // method does *not* change .paused, because it would be confusing
  22773. setEffectiveTimeScale: function( timeScale ) {
  22774. this.timeScale = timeScale;
  22775. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22776. return this.stopWarping();
  22777. },
  22778. // return the time scale considering warping and .paused
  22779. getEffectiveTimeScale: function() {
  22780. return this._effectiveTimeScale;
  22781. },
  22782. setDuration: function( duration ) {
  22783. this.timeScale = this._clip.duration / duration;
  22784. return this.stopWarping();
  22785. },
  22786. syncWith: function( action ) {
  22787. this.time = action.time;
  22788. this.timeScale = action.timeScale;
  22789. return this.stopWarping();
  22790. },
  22791. halt: function( duration ) {
  22792. return this.warp( this._effectiveTimeScale, 0, duration );
  22793. },
  22794. warp: function( startTimeScale, endTimeScale, duration ) {
  22795. var mixer = this._mixer, now = mixer.time,
  22796. interpolant = this._timeScaleInterpolant,
  22797. timeScale = this.timeScale;
  22798. if ( interpolant === null ) {
  22799. interpolant = mixer._lendControlInterpolant();
  22800. this._timeScaleInterpolant = interpolant;
  22801. }
  22802. var times = interpolant.parameterPositions,
  22803. values = interpolant.sampleValues;
  22804. times[ 0 ] = now;
  22805. times[ 1 ] = now + duration;
  22806. values[ 0 ] = startTimeScale / timeScale;
  22807. values[ 1 ] = endTimeScale / timeScale;
  22808. return this;
  22809. },
  22810. stopWarping: function() {
  22811. var timeScaleInterpolant = this._timeScaleInterpolant;
  22812. if ( timeScaleInterpolant !== null ) {
  22813. this._timeScaleInterpolant = null;
  22814. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22815. }
  22816. return this;
  22817. },
  22818. // Object Accessors
  22819. getMixer: function() {
  22820. return this._mixer;
  22821. },
  22822. getClip: function() {
  22823. return this._clip;
  22824. },
  22825. getRoot: function() {
  22826. return this._localRoot || this._mixer._root;
  22827. },
  22828. // Interna
  22829. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22830. // called by the mixer
  22831. if ( ! this.enabled ) {
  22832. // call ._updateWeight() to update ._effectiveWeight
  22833. this._updateWeight( time );
  22834. return;
  22835. }
  22836. var startTime = this._startTime;
  22837. if ( startTime !== null ) {
  22838. // check for scheduled start of action
  22839. var timeRunning = ( time - startTime ) * timeDirection;
  22840. if ( timeRunning < 0 || timeDirection === 0 ) {
  22841. return; // yet to come / don't decide when delta = 0
  22842. }
  22843. // start
  22844. this._startTime = null; // unschedule
  22845. deltaTime = timeDirection * timeRunning;
  22846. }
  22847. // apply time scale and advance time
  22848. deltaTime *= this._updateTimeScale( time );
  22849. var clipTime = this._updateTime( deltaTime );
  22850. // note: _updateTime may disable the action resulting in
  22851. // an effective weight of 0
  22852. var weight = this._updateWeight( time );
  22853. if ( weight > 0 ) {
  22854. var interpolants = this._interpolants;
  22855. var propertyMixers = this._propertyBindings;
  22856. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22857. interpolants[ j ].evaluate( clipTime );
  22858. propertyMixers[ j ].accumulate( accuIndex, weight );
  22859. }
  22860. }
  22861. },
  22862. _updateWeight: function( time ) {
  22863. var weight = 0;
  22864. if ( this.enabled ) {
  22865. weight = this.weight;
  22866. var interpolant = this._weightInterpolant;
  22867. if ( interpolant !== null ) {
  22868. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22869. weight *= interpolantValue;
  22870. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22871. this.stopFading();
  22872. if ( interpolantValue === 0 ) {
  22873. // faded out, disable
  22874. this.enabled = false;
  22875. }
  22876. }
  22877. }
  22878. }
  22879. this._effectiveWeight = weight;
  22880. return weight;
  22881. },
  22882. _updateTimeScale: function( time ) {
  22883. var timeScale = 0;
  22884. if ( ! this.paused ) {
  22885. timeScale = this.timeScale;
  22886. var interpolant = this._timeScaleInterpolant;
  22887. if ( interpolant !== null ) {
  22888. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22889. timeScale *= interpolantValue;
  22890. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22891. this.stopWarping();
  22892. if ( timeScale === 0 ) {
  22893. // motion has halted, pause
  22894. this.paused = true;
  22895. } else {
  22896. // warp done - apply final time scale
  22897. this.timeScale = timeScale;
  22898. }
  22899. }
  22900. }
  22901. }
  22902. this._effectiveTimeScale = timeScale;
  22903. return timeScale;
  22904. },
  22905. _updateTime: function( deltaTime ) {
  22906. var time = this.time + deltaTime;
  22907. if ( deltaTime === 0 ) return time;
  22908. var duration = this._clip.duration,
  22909. loop = this.loop,
  22910. loopCount = this._loopCount;
  22911. if ( loop === LoopOnce ) {
  22912. if ( loopCount === -1 ) {
  22913. // just started
  22914. this._loopCount = 0;
  22915. this._setEndings( true, true, false );
  22916. }
  22917. handle_stop: {
  22918. if ( time >= duration ) {
  22919. time = duration;
  22920. } else if ( time < 0 ) {
  22921. time = 0;
  22922. } else break handle_stop;
  22923. if ( this.clampWhenFinished ) this.paused = true;
  22924. else this.enabled = false;
  22925. this._mixer.dispatchEvent( {
  22926. type: 'finished', action: this,
  22927. direction: deltaTime < 0 ? -1 : 1
  22928. } );
  22929. }
  22930. } else { // repetitive Repeat or PingPong
  22931. var pingPong = ( loop === LoopPingPong );
  22932. if ( loopCount === -1 ) {
  22933. // just started
  22934. if ( deltaTime >= 0 ) {
  22935. loopCount = 0;
  22936. this._setEndings(
  22937. true, this.repetitions === 0, pingPong );
  22938. } else {
  22939. // when looping in reverse direction, the initial
  22940. // transition through zero counts as a repetition,
  22941. // so leave loopCount at -1
  22942. this._setEndings(
  22943. this.repetitions === 0, true, pingPong );
  22944. }
  22945. }
  22946. if ( time >= duration || time < 0 ) {
  22947. // wrap around
  22948. var loopDelta = Math.floor( time / duration ); // signed
  22949. time -= duration * loopDelta;
  22950. loopCount += Math.abs( loopDelta );
  22951. var pending = this.repetitions - loopCount;
  22952. if ( pending < 0 ) {
  22953. // have to stop (switch state, clamp time, fire event)
  22954. if ( this.clampWhenFinished ) this.paused = true;
  22955. else this.enabled = false;
  22956. time = deltaTime > 0 ? duration : 0;
  22957. this._mixer.dispatchEvent( {
  22958. type: 'finished', action: this,
  22959. direction: deltaTime > 0 ? 1 : -1
  22960. } );
  22961. } else {
  22962. // keep running
  22963. if ( pending === 0 ) {
  22964. // entering the last round
  22965. var atStart = deltaTime < 0;
  22966. this._setEndings( atStart, ! atStart, pingPong );
  22967. } else {
  22968. this._setEndings( false, false, pingPong );
  22969. }
  22970. this._loopCount = loopCount;
  22971. this._mixer.dispatchEvent( {
  22972. type: 'loop', action: this, loopDelta: loopDelta
  22973. } );
  22974. }
  22975. }
  22976. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22977. // invert time for the "pong round"
  22978. this.time = time;
  22979. return duration - time;
  22980. }
  22981. }
  22982. this.time = time;
  22983. return time;
  22984. },
  22985. _setEndings: function( atStart, atEnd, pingPong ) {
  22986. var settings = this._interpolantSettings;
  22987. if ( pingPong ) {
  22988. settings.endingStart = ZeroSlopeEnding;
  22989. settings.endingEnd = ZeroSlopeEnding;
  22990. } else {
  22991. // assuming for LoopOnce atStart == atEnd == true
  22992. if ( atStart ) {
  22993. settings.endingStart = this.zeroSlopeAtStart ?
  22994. ZeroSlopeEnding : ZeroCurvatureEnding;
  22995. } else {
  22996. settings.endingStart = WrapAroundEnding;
  22997. }
  22998. if ( atEnd ) {
  22999. settings.endingEnd = this.zeroSlopeAtEnd ?
  23000. ZeroSlopeEnding : ZeroCurvatureEnding;
  23001. } else {
  23002. settings.endingEnd = WrapAroundEnding;
  23003. }
  23004. }
  23005. },
  23006. _scheduleFading: function( duration, weightNow, weightThen ) {
  23007. var mixer = this._mixer, now = mixer.time,
  23008. interpolant = this._weightInterpolant;
  23009. if ( interpolant === null ) {
  23010. interpolant = mixer._lendControlInterpolant();
  23011. this._weightInterpolant = interpolant;
  23012. }
  23013. var times = interpolant.parameterPositions,
  23014. values = interpolant.sampleValues;
  23015. times[ 0 ] = now; values[ 0 ] = weightNow;
  23016. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23017. return this;
  23018. }
  23019. } );
  23020. /**
  23021. *
  23022. * Player for AnimationClips.
  23023. *
  23024. *
  23025. * @author Ben Houston / http://clara.io/
  23026. * @author David Sarno / http://lighthaus.us/
  23027. * @author tschw
  23028. */
  23029. function AnimationMixer( root ) {
  23030. this._root = root;
  23031. this._initMemoryManager();
  23032. this._accuIndex = 0;
  23033. this.time = 0;
  23034. this.timeScale = 1.0;
  23035. }
  23036. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23037. _bindAction: function ( action, prototypeAction ) {
  23038. var root = action._localRoot || this._root,
  23039. tracks = action._clip.tracks,
  23040. nTracks = tracks.length,
  23041. bindings = action._propertyBindings,
  23042. interpolants = action._interpolants,
  23043. rootUuid = root.uuid,
  23044. bindingsByRoot = this._bindingsByRootAndName,
  23045. bindingsByName = bindingsByRoot[ rootUuid ];
  23046. if ( bindingsByName === undefined ) {
  23047. bindingsByName = {};
  23048. bindingsByRoot[ rootUuid ] = bindingsByName;
  23049. }
  23050. for ( var i = 0; i !== nTracks; ++ i ) {
  23051. var track = tracks[ i ],
  23052. trackName = track.name,
  23053. binding = bindingsByName[ trackName ];
  23054. if ( binding !== undefined ) {
  23055. bindings[ i ] = binding;
  23056. } else {
  23057. binding = bindings[ i ];
  23058. if ( binding !== undefined ) {
  23059. // existing binding, make sure the cache knows
  23060. if ( binding._cacheIndex === null ) {
  23061. ++ binding.referenceCount;
  23062. this._addInactiveBinding( binding, rootUuid, trackName );
  23063. }
  23064. continue;
  23065. }
  23066. var path = prototypeAction && prototypeAction.
  23067. _propertyBindings[ i ].binding.parsedPath;
  23068. binding = new PropertyMixer(
  23069. PropertyBinding.create( root, trackName, path ),
  23070. track.ValueTypeName, track.getValueSize() );
  23071. ++ binding.referenceCount;
  23072. this._addInactiveBinding( binding, rootUuid, trackName );
  23073. bindings[ i ] = binding;
  23074. }
  23075. interpolants[ i ].resultBuffer = binding.buffer;
  23076. }
  23077. },
  23078. _activateAction: function ( action ) {
  23079. if ( ! this._isActiveAction( action ) ) {
  23080. if ( action._cacheIndex === null ) {
  23081. // this action has been forgotten by the cache, but the user
  23082. // appears to be still using it -> rebind
  23083. var rootUuid = ( action._localRoot || this._root ).uuid,
  23084. clipUuid = action._clip.uuid,
  23085. actionsForClip = this._actionsByClip[ clipUuid ];
  23086. this._bindAction( action,
  23087. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23088. this._addInactiveAction( action, clipUuid, rootUuid );
  23089. }
  23090. var bindings = action._propertyBindings;
  23091. // increment reference counts / sort out state
  23092. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23093. var binding = bindings[ i ];
  23094. if ( binding.useCount ++ === 0 ) {
  23095. this._lendBinding( binding );
  23096. binding.saveOriginalState();
  23097. }
  23098. }
  23099. this._lendAction( action );
  23100. }
  23101. },
  23102. _deactivateAction: function ( action ) {
  23103. if ( this._isActiveAction( action ) ) {
  23104. var bindings = action._propertyBindings;
  23105. // decrement reference counts / sort out state
  23106. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23107. var binding = bindings[ i ];
  23108. if ( -- binding.useCount === 0 ) {
  23109. binding.restoreOriginalState();
  23110. this._takeBackBinding( binding );
  23111. }
  23112. }
  23113. this._takeBackAction( action );
  23114. }
  23115. },
  23116. // Memory manager
  23117. _initMemoryManager: function () {
  23118. this._actions = []; // 'nActiveActions' followed by inactive ones
  23119. this._nActiveActions = 0;
  23120. this._actionsByClip = {};
  23121. // inside:
  23122. // {
  23123. // knownActions: Array< AnimationAction > - used as prototypes
  23124. // actionByRoot: AnimationAction - lookup
  23125. // }
  23126. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23127. this._nActiveBindings = 0;
  23128. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23129. this._controlInterpolants = []; // same game as above
  23130. this._nActiveControlInterpolants = 0;
  23131. var scope = this;
  23132. this.stats = {
  23133. actions: {
  23134. get total() { return scope._actions.length; },
  23135. get inUse() { return scope._nActiveActions; }
  23136. },
  23137. bindings: {
  23138. get total() { return scope._bindings.length; },
  23139. get inUse() { return scope._nActiveBindings; }
  23140. },
  23141. controlInterpolants: {
  23142. get total() { return scope._controlInterpolants.length; },
  23143. get inUse() { return scope._nActiveControlInterpolants; }
  23144. }
  23145. };
  23146. },
  23147. // Memory management for AnimationAction objects
  23148. _isActiveAction: function ( action ) {
  23149. var index = action._cacheIndex;
  23150. return index !== null && index < this._nActiveActions;
  23151. },
  23152. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23153. var actions = this._actions,
  23154. actionsByClip = this._actionsByClip,
  23155. actionsForClip = actionsByClip[ clipUuid ];
  23156. if ( actionsForClip === undefined ) {
  23157. actionsForClip = {
  23158. knownActions: [ action ],
  23159. actionByRoot: {}
  23160. };
  23161. action._byClipCacheIndex = 0;
  23162. actionsByClip[ clipUuid ] = actionsForClip;
  23163. } else {
  23164. var knownActions = actionsForClip.knownActions;
  23165. action._byClipCacheIndex = knownActions.length;
  23166. knownActions.push( action );
  23167. }
  23168. action._cacheIndex = actions.length;
  23169. actions.push( action );
  23170. actionsForClip.actionByRoot[ rootUuid ] = action;
  23171. },
  23172. _removeInactiveAction: function ( action ) {
  23173. var actions = this._actions,
  23174. lastInactiveAction = actions[ actions.length - 1 ],
  23175. cacheIndex = action._cacheIndex;
  23176. lastInactiveAction._cacheIndex = cacheIndex;
  23177. actions[ cacheIndex ] = lastInactiveAction;
  23178. actions.pop();
  23179. action._cacheIndex = null;
  23180. var clipUuid = action._clip.uuid,
  23181. actionsByClip = this._actionsByClip,
  23182. actionsForClip = actionsByClip[ clipUuid ],
  23183. knownActionsForClip = actionsForClip.knownActions,
  23184. lastKnownAction =
  23185. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23186. byClipCacheIndex = action._byClipCacheIndex;
  23187. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23188. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23189. knownActionsForClip.pop();
  23190. action._byClipCacheIndex = null;
  23191. var actionByRoot = actionsForClip.actionByRoot,
  23192. rootUuid = ( action._localRoot || this._root ).uuid;
  23193. delete actionByRoot[ rootUuid ];
  23194. if ( knownActionsForClip.length === 0 ) {
  23195. delete actionsByClip[ clipUuid ];
  23196. }
  23197. this._removeInactiveBindingsForAction( action );
  23198. },
  23199. _removeInactiveBindingsForAction: function ( action ) {
  23200. var bindings = action._propertyBindings;
  23201. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23202. var binding = bindings[ i ];
  23203. if ( -- binding.referenceCount === 0 ) {
  23204. this._removeInactiveBinding( binding );
  23205. }
  23206. }
  23207. },
  23208. _lendAction: function ( action ) {
  23209. // [ active actions | inactive actions ]
  23210. // [ active actions >| inactive actions ]
  23211. // s a
  23212. // <-swap->
  23213. // a s
  23214. var actions = this._actions,
  23215. prevIndex = action._cacheIndex,
  23216. lastActiveIndex = this._nActiveActions ++,
  23217. firstInactiveAction = actions[ lastActiveIndex ];
  23218. action._cacheIndex = lastActiveIndex;
  23219. actions[ lastActiveIndex ] = action;
  23220. firstInactiveAction._cacheIndex = prevIndex;
  23221. actions[ prevIndex ] = firstInactiveAction;
  23222. },
  23223. _takeBackAction: function ( action ) {
  23224. // [ active actions | inactive actions ]
  23225. // [ active actions |< inactive actions ]
  23226. // a s
  23227. // <-swap->
  23228. // s a
  23229. var actions = this._actions,
  23230. prevIndex = action._cacheIndex,
  23231. firstInactiveIndex = -- this._nActiveActions,
  23232. lastActiveAction = actions[ firstInactiveIndex ];
  23233. action._cacheIndex = firstInactiveIndex;
  23234. actions[ firstInactiveIndex ] = action;
  23235. lastActiveAction._cacheIndex = prevIndex;
  23236. actions[ prevIndex ] = lastActiveAction;
  23237. },
  23238. // Memory management for PropertyMixer objects
  23239. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23240. var bindingsByRoot = this._bindingsByRootAndName,
  23241. bindingByName = bindingsByRoot[ rootUuid ],
  23242. bindings = this._bindings;
  23243. if ( bindingByName === undefined ) {
  23244. bindingByName = {};
  23245. bindingsByRoot[ rootUuid ] = bindingByName;
  23246. }
  23247. bindingByName[ trackName ] = binding;
  23248. binding._cacheIndex = bindings.length;
  23249. bindings.push( binding );
  23250. },
  23251. _removeInactiveBinding: function ( binding ) {
  23252. var bindings = this._bindings,
  23253. propBinding = binding.binding,
  23254. rootUuid = propBinding.rootNode.uuid,
  23255. trackName = propBinding.path,
  23256. bindingsByRoot = this._bindingsByRootAndName,
  23257. bindingByName = bindingsByRoot[ rootUuid ],
  23258. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23259. cacheIndex = binding._cacheIndex;
  23260. lastInactiveBinding._cacheIndex = cacheIndex;
  23261. bindings[ cacheIndex ] = lastInactiveBinding;
  23262. bindings.pop();
  23263. delete bindingByName[ trackName ];
  23264. remove_empty_map: {
  23265. for ( var _ in bindingByName ) break remove_empty_map;
  23266. delete bindingsByRoot[ rootUuid ];
  23267. }
  23268. },
  23269. _lendBinding: function ( binding ) {
  23270. var bindings = this._bindings,
  23271. prevIndex = binding._cacheIndex,
  23272. lastActiveIndex = this._nActiveBindings ++,
  23273. firstInactiveBinding = bindings[ lastActiveIndex ];
  23274. binding._cacheIndex = lastActiveIndex;
  23275. bindings[ lastActiveIndex ] = binding;
  23276. firstInactiveBinding._cacheIndex = prevIndex;
  23277. bindings[ prevIndex ] = firstInactiveBinding;
  23278. },
  23279. _takeBackBinding: function ( binding ) {
  23280. var bindings = this._bindings,
  23281. prevIndex = binding._cacheIndex,
  23282. firstInactiveIndex = -- this._nActiveBindings,
  23283. lastActiveBinding = bindings[ firstInactiveIndex ];
  23284. binding._cacheIndex = firstInactiveIndex;
  23285. bindings[ firstInactiveIndex ] = binding;
  23286. lastActiveBinding._cacheIndex = prevIndex;
  23287. bindings[ prevIndex ] = lastActiveBinding;
  23288. },
  23289. // Memory management of Interpolants for weight and time scale
  23290. _lendControlInterpolant: function () {
  23291. var interpolants = this._controlInterpolants,
  23292. lastActiveIndex = this._nActiveControlInterpolants ++,
  23293. interpolant = interpolants[ lastActiveIndex ];
  23294. if ( interpolant === undefined ) {
  23295. interpolant = new LinearInterpolant(
  23296. new Float32Array( 2 ), new Float32Array( 2 ),
  23297. 1, this._controlInterpolantsResultBuffer );
  23298. interpolant.__cacheIndex = lastActiveIndex;
  23299. interpolants[ lastActiveIndex ] = interpolant;
  23300. }
  23301. return interpolant;
  23302. },
  23303. _takeBackControlInterpolant: function ( interpolant ) {
  23304. var interpolants = this._controlInterpolants,
  23305. prevIndex = interpolant.__cacheIndex,
  23306. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23307. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23308. interpolant.__cacheIndex = firstInactiveIndex;
  23309. interpolants[ firstInactiveIndex ] = interpolant;
  23310. lastActiveInterpolant.__cacheIndex = prevIndex;
  23311. interpolants[ prevIndex ] = lastActiveInterpolant;
  23312. },
  23313. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23314. // return an action for a clip optionally using a custom root target
  23315. // object (this method allocates a lot of dynamic memory in case a
  23316. // previously unknown clip/root combination is specified)
  23317. clipAction: function ( clip, optionalRoot ) {
  23318. var root = optionalRoot || this._root,
  23319. rootUuid = root.uuid,
  23320. clipObject = typeof clip === 'string' ?
  23321. AnimationClip.findByName( root, clip ) : clip,
  23322. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23323. actionsForClip = this._actionsByClip[ clipUuid ],
  23324. prototypeAction = null;
  23325. if ( actionsForClip !== undefined ) {
  23326. var existingAction =
  23327. actionsForClip.actionByRoot[ rootUuid ];
  23328. if ( existingAction !== undefined ) {
  23329. return existingAction;
  23330. }
  23331. // we know the clip, so we don't have to parse all
  23332. // the bindings again but can just copy
  23333. prototypeAction = actionsForClip.knownActions[ 0 ];
  23334. // also, take the clip from the prototype action
  23335. if ( clipObject === null )
  23336. clipObject = prototypeAction._clip;
  23337. }
  23338. // clip must be known when specified via string
  23339. if ( clipObject === null ) return null;
  23340. // allocate all resources required to run it
  23341. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23342. this._bindAction( newAction, prototypeAction );
  23343. // and make the action known to the memory manager
  23344. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23345. return newAction;
  23346. },
  23347. // get an existing action
  23348. existingAction: function ( clip, optionalRoot ) {
  23349. var root = optionalRoot || this._root,
  23350. rootUuid = root.uuid,
  23351. clipObject = typeof clip === 'string' ?
  23352. AnimationClip.findByName( root, clip ) : clip,
  23353. clipUuid = clipObject ? clipObject.uuid : clip,
  23354. actionsForClip = this._actionsByClip[ clipUuid ];
  23355. if ( actionsForClip !== undefined ) {
  23356. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23357. }
  23358. return null;
  23359. },
  23360. // deactivates all previously scheduled actions
  23361. stopAllAction: function () {
  23362. var actions = this._actions,
  23363. nActions = this._nActiveActions,
  23364. bindings = this._bindings,
  23365. nBindings = this._nActiveBindings;
  23366. this._nActiveActions = 0;
  23367. this._nActiveBindings = 0;
  23368. for ( var i = 0; i !== nActions; ++ i ) {
  23369. actions[ i ].reset();
  23370. }
  23371. for ( var i = 0; i !== nBindings; ++ i ) {
  23372. bindings[ i ].useCount = 0;
  23373. }
  23374. return this;
  23375. },
  23376. // advance the time and update apply the animation
  23377. update: function ( deltaTime ) {
  23378. deltaTime *= this.timeScale;
  23379. var actions = this._actions,
  23380. nActions = this._nActiveActions,
  23381. time = this.time += deltaTime,
  23382. timeDirection = Math.sign( deltaTime ),
  23383. accuIndex = this._accuIndex ^= 1;
  23384. // run active actions
  23385. for ( var i = 0; i !== nActions; ++ i ) {
  23386. var action = actions[ i ];
  23387. action._update( time, deltaTime, timeDirection, accuIndex );
  23388. }
  23389. // update scene graph
  23390. var bindings = this._bindings,
  23391. nBindings = this._nActiveBindings;
  23392. for ( var i = 0; i !== nBindings; ++ i ) {
  23393. bindings[ i ].apply( accuIndex );
  23394. }
  23395. return this;
  23396. },
  23397. // return this mixer's root target object
  23398. getRoot: function () {
  23399. return this._root;
  23400. },
  23401. // free all resources specific to a particular clip
  23402. uncacheClip: function ( clip ) {
  23403. var actions = this._actions,
  23404. clipUuid = clip.uuid,
  23405. actionsByClip = this._actionsByClip,
  23406. actionsForClip = actionsByClip[ clipUuid ];
  23407. if ( actionsForClip !== undefined ) {
  23408. // note: just calling _removeInactiveAction would mess up the
  23409. // iteration state and also require updating the state we can
  23410. // just throw away
  23411. var actionsToRemove = actionsForClip.knownActions;
  23412. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23413. var action = actionsToRemove[ i ];
  23414. this._deactivateAction( action );
  23415. var cacheIndex = action._cacheIndex,
  23416. lastInactiveAction = actions[ actions.length - 1 ];
  23417. action._cacheIndex = null;
  23418. action._byClipCacheIndex = null;
  23419. lastInactiveAction._cacheIndex = cacheIndex;
  23420. actions[ cacheIndex ] = lastInactiveAction;
  23421. actions.pop();
  23422. this._removeInactiveBindingsForAction( action );
  23423. }
  23424. delete actionsByClip[ clipUuid ];
  23425. }
  23426. },
  23427. // free all resources specific to a particular root target object
  23428. uncacheRoot: function ( root ) {
  23429. var rootUuid = root.uuid,
  23430. actionsByClip = this._actionsByClip;
  23431. for ( var clipUuid in actionsByClip ) {
  23432. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23433. action = actionByRoot[ rootUuid ];
  23434. if ( action !== undefined ) {
  23435. this._deactivateAction( action );
  23436. this._removeInactiveAction( action );
  23437. }
  23438. }
  23439. var bindingsByRoot = this._bindingsByRootAndName,
  23440. bindingByName = bindingsByRoot[ rootUuid ];
  23441. if ( bindingByName !== undefined ) {
  23442. for ( var trackName in bindingByName ) {
  23443. var binding = bindingByName[ trackName ];
  23444. binding.restoreOriginalState();
  23445. this._removeInactiveBinding( binding );
  23446. }
  23447. }
  23448. },
  23449. // remove a targeted clip from the cache
  23450. uncacheAction: function ( clip, optionalRoot ) {
  23451. var action = this.existingAction( clip, optionalRoot );
  23452. if ( action !== null ) {
  23453. this._deactivateAction( action );
  23454. this._removeInactiveAction( action );
  23455. }
  23456. }
  23457. } );
  23458. /**
  23459. * @author mrdoob / http://mrdoob.com/
  23460. */
  23461. function Uniform( value ) {
  23462. if ( typeof value === 'string' ) {
  23463. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23464. value = arguments[ 1 ];
  23465. }
  23466. this.value = value;
  23467. }
  23468. Uniform.prototype.clone = function () {
  23469. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23470. };
  23471. /**
  23472. * @author benaadams / https://twitter.com/ben_a_adams
  23473. */
  23474. function InstancedBufferGeometry() {
  23475. BufferGeometry.call( this );
  23476. this.type = 'InstancedBufferGeometry';
  23477. this.maxInstancedCount = undefined;
  23478. }
  23479. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23480. constructor: InstancedBufferGeometry,
  23481. isInstancedBufferGeometry: true,
  23482. addGroup: function ( start, count, materialIndex ) {
  23483. this.groups.push( {
  23484. start: start,
  23485. count: count,
  23486. materialIndex: materialIndex
  23487. } );
  23488. },
  23489. copy: function ( source ) {
  23490. var index = source.index;
  23491. if ( index !== null ) {
  23492. this.setIndex( index.clone() );
  23493. }
  23494. var attributes = source.attributes;
  23495. for ( var name in attributes ) {
  23496. var attribute = attributes[ name ];
  23497. this.addAttribute( name, attribute.clone() );
  23498. }
  23499. var groups = source.groups;
  23500. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23501. var group = groups[ i ];
  23502. this.addGroup( group.start, group.count, group.materialIndex );
  23503. }
  23504. return this;
  23505. }
  23506. } );
  23507. /**
  23508. * @author benaadams / https://twitter.com/ben_a_adams
  23509. */
  23510. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23511. this.uuid = _Math.generateUUID();
  23512. this.data = interleavedBuffer;
  23513. this.itemSize = itemSize;
  23514. this.offset = offset;
  23515. this.normalized = normalized === true;
  23516. }
  23517. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23518. count: {
  23519. get: function () {
  23520. return this.data.count;
  23521. }
  23522. },
  23523. array: {
  23524. get: function () {
  23525. return this.data.array;
  23526. }
  23527. }
  23528. } );
  23529. Object.assign( InterleavedBufferAttribute.prototype, {
  23530. isInterleavedBufferAttribute: true,
  23531. setX: function ( index, x ) {
  23532. this.data.array[ index * this.data.stride + this.offset ] = x;
  23533. return this;
  23534. },
  23535. setY: function ( index, y ) {
  23536. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23537. return this;
  23538. },
  23539. setZ: function ( index, z ) {
  23540. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23541. return this;
  23542. },
  23543. setW: function ( index, w ) {
  23544. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23545. return this;
  23546. },
  23547. getX: function ( index ) {
  23548. return this.data.array[ index * this.data.stride + this.offset ];
  23549. },
  23550. getY: function ( index ) {
  23551. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23552. },
  23553. getZ: function ( index ) {
  23554. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23555. },
  23556. getW: function ( index ) {
  23557. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23558. },
  23559. setXY: function ( index, x, y ) {
  23560. index = index * this.data.stride + this.offset;
  23561. this.data.array[ index + 0 ] = x;
  23562. this.data.array[ index + 1 ] = y;
  23563. return this;
  23564. },
  23565. setXYZ: function ( index, x, y, z ) {
  23566. index = index * this.data.stride + this.offset;
  23567. this.data.array[ index + 0 ] = x;
  23568. this.data.array[ index + 1 ] = y;
  23569. this.data.array[ index + 2 ] = z;
  23570. return this;
  23571. },
  23572. setXYZW: function ( index, x, y, z, w ) {
  23573. index = index * this.data.stride + this.offset;
  23574. this.data.array[ index + 0 ] = x;
  23575. this.data.array[ index + 1 ] = y;
  23576. this.data.array[ index + 2 ] = z;
  23577. this.data.array[ index + 3 ] = w;
  23578. return this;
  23579. }
  23580. } );
  23581. /**
  23582. * @author benaadams / https://twitter.com/ben_a_adams
  23583. */
  23584. function InterleavedBuffer( array, stride ) {
  23585. this.uuid = _Math.generateUUID();
  23586. this.array = array;
  23587. this.stride = stride;
  23588. this.count = array !== undefined ? array.length / stride : 0;
  23589. this.dynamic = false;
  23590. this.updateRange = { offset: 0, count: - 1 };
  23591. this.onUploadCallback = function () {};
  23592. this.version = 0;
  23593. }
  23594. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23595. set: function ( value ) {
  23596. if ( value === true ) this.version ++;
  23597. }
  23598. } );
  23599. Object.assign( InterleavedBuffer.prototype, {
  23600. isInterleavedBuffer: true,
  23601. setArray: function ( array ) {
  23602. if ( Array.isArray( array ) ) {
  23603. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23604. }
  23605. this.count = array !== undefined ? array.length / this.stride : 0;
  23606. this.array = array;
  23607. },
  23608. setDynamic: function ( value ) {
  23609. this.dynamic = value;
  23610. return this;
  23611. },
  23612. copy: function ( source ) {
  23613. this.array = new source.array.constructor( source.array );
  23614. this.count = source.count;
  23615. this.stride = source.stride;
  23616. this.dynamic = source.dynamic;
  23617. return this;
  23618. },
  23619. copyAt: function ( index1, attribute, index2 ) {
  23620. index1 *= this.stride;
  23621. index2 *= attribute.stride;
  23622. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23623. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23624. }
  23625. return this;
  23626. },
  23627. set: function ( value, offset ) {
  23628. if ( offset === undefined ) offset = 0;
  23629. this.array.set( value, offset );
  23630. return this;
  23631. },
  23632. clone: function () {
  23633. return new this.constructor().copy( this );
  23634. },
  23635. onUpload: function ( callback ) {
  23636. this.onUploadCallback = callback;
  23637. return this;
  23638. }
  23639. } );
  23640. /**
  23641. * @author benaadams / https://twitter.com/ben_a_adams
  23642. */
  23643. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23644. InterleavedBuffer.call( this, array, stride );
  23645. this.meshPerAttribute = meshPerAttribute || 1;
  23646. }
  23647. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  23648. constructor: InstancedInterleavedBuffer,
  23649. isInstancedInterleavedBuffer: true,
  23650. copy: function ( source ) {
  23651. InterleavedBuffer.prototype.copy.call( this, source );
  23652. this.meshPerAttribute = source.meshPerAttribute;
  23653. return this;
  23654. }
  23655. } );
  23656. /**
  23657. * @author benaadams / https://twitter.com/ben_a_adams
  23658. */
  23659. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23660. BufferAttribute.call( this, array, itemSize );
  23661. this.meshPerAttribute = meshPerAttribute || 1;
  23662. }
  23663. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  23664. constructor: InstancedBufferAttribute,
  23665. isInstancedBufferAttribute: true,
  23666. copy: function ( source ) {
  23667. BufferAttribute.prototype.copy.call( this, source );
  23668. this.meshPerAttribute = source.meshPerAttribute;
  23669. return this;
  23670. }
  23671. } );
  23672. /**
  23673. * @author mrdoob / http://mrdoob.com/
  23674. * @author bhouston / http://clara.io/
  23675. * @author stephomi / http://stephaneginier.com/
  23676. */
  23677. function Raycaster( origin, direction, near, far ) {
  23678. this.ray = new Ray( origin, direction );
  23679. // direction is assumed to be normalized (for accurate distance calculations)
  23680. this.near = near || 0;
  23681. this.far = far || Infinity;
  23682. this.params = {
  23683. Mesh: {},
  23684. Line: {},
  23685. LOD: {},
  23686. Points: { threshold: 1 },
  23687. Sprite: {}
  23688. };
  23689. Object.defineProperties( this.params, {
  23690. PointCloud: {
  23691. get: function () {
  23692. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23693. return this.Points;
  23694. }
  23695. }
  23696. } );
  23697. }
  23698. function ascSort( a, b ) {
  23699. return a.distance - b.distance;
  23700. }
  23701. function intersectObject( object, raycaster, intersects, recursive ) {
  23702. if ( object.visible === false ) return;
  23703. object.raycast( raycaster, intersects );
  23704. if ( recursive === true ) {
  23705. var children = object.children;
  23706. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23707. intersectObject( children[ i ], raycaster, intersects, true );
  23708. }
  23709. }
  23710. }
  23711. Object.assign( Raycaster.prototype, {
  23712. linePrecision: 1,
  23713. set: function ( origin, direction ) {
  23714. // direction is assumed to be normalized (for accurate distance calculations)
  23715. this.ray.set( origin, direction );
  23716. },
  23717. setFromCamera: function ( coords, camera ) {
  23718. if ( ( camera && camera.isPerspectiveCamera ) ) {
  23719. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23720. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23721. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  23722. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23723. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23724. } else {
  23725. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23726. }
  23727. },
  23728. intersectObject: function ( object, recursive ) {
  23729. var intersects = [];
  23730. intersectObject( object, this, intersects, recursive );
  23731. intersects.sort( ascSort );
  23732. return intersects;
  23733. },
  23734. intersectObjects: function ( objects, recursive ) {
  23735. var intersects = [];
  23736. if ( Array.isArray( objects ) === false ) {
  23737. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23738. return intersects;
  23739. }
  23740. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23741. intersectObject( objects[ i ], this, intersects, recursive );
  23742. }
  23743. intersects.sort( ascSort );
  23744. return intersects;
  23745. }
  23746. } );
  23747. /**
  23748. * @author alteredq / http://alteredqualia.com/
  23749. */
  23750. function Clock( autoStart ) {
  23751. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23752. this.startTime = 0;
  23753. this.oldTime = 0;
  23754. this.elapsedTime = 0;
  23755. this.running = false;
  23756. }
  23757. Object.assign( Clock.prototype, {
  23758. start: function () {
  23759. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  23760. this.oldTime = this.startTime;
  23761. this.elapsedTime = 0;
  23762. this.running = true;
  23763. },
  23764. stop: function () {
  23765. this.getElapsedTime();
  23766. this.running = false;
  23767. },
  23768. getElapsedTime: function () {
  23769. this.getDelta();
  23770. return this.elapsedTime;
  23771. },
  23772. getDelta: function () {
  23773. var diff = 0;
  23774. if ( this.autoStart && ! this.running ) {
  23775. this.start();
  23776. return 0;
  23777. }
  23778. if ( this.running ) {
  23779. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  23780. diff = ( newTime - this.oldTime ) / 1000;
  23781. this.oldTime = newTime;
  23782. this.elapsedTime += diff;
  23783. }
  23784. return diff;
  23785. }
  23786. } );
  23787. /**
  23788. * @author bhouston / http://clara.io
  23789. * @author WestLangley / http://github.com/WestLangley
  23790. *
  23791. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23792. *
  23793. * The poles (phi) are at the positive and negative y axis.
  23794. * The equator starts at positive z.
  23795. */
  23796. function Spherical( radius, phi, theta ) {
  23797. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23798. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23799. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23800. return this;
  23801. }
  23802. Object.assign( Spherical.prototype, {
  23803. set: function ( radius, phi, theta ) {
  23804. this.radius = radius;
  23805. this.phi = phi;
  23806. this.theta = theta;
  23807. return this;
  23808. },
  23809. clone: function () {
  23810. return new this.constructor().copy( this );
  23811. },
  23812. copy: function ( other ) {
  23813. this.radius = other.radius;
  23814. this.phi = other.phi;
  23815. this.theta = other.theta;
  23816. return this;
  23817. },
  23818. // restrict phi to be betwee EPS and PI-EPS
  23819. makeSafe: function() {
  23820. var EPS = 0.000001;
  23821. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23822. return this;
  23823. },
  23824. setFromVector3: function( vec3 ) {
  23825. this.radius = vec3.length();
  23826. if ( this.radius === 0 ) {
  23827. this.theta = 0;
  23828. this.phi = 0;
  23829. } else {
  23830. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23831. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23832. }
  23833. return this;
  23834. }
  23835. } );
  23836. /**
  23837. * @author Mugen87 / https://github.com/Mugen87
  23838. *
  23839. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  23840. *
  23841. */
  23842. function Cylindrical( radius, theta, y ) {
  23843. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  23844. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  23845. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  23846. return this;
  23847. }
  23848. Object.assign( Cylindrical.prototype, {
  23849. set: function ( radius, theta, y ) {
  23850. this.radius = radius;
  23851. this.theta = theta;
  23852. this.y = y;
  23853. return this;
  23854. },
  23855. clone: function () {
  23856. return new this.constructor().copy( this );
  23857. },
  23858. copy: function ( other ) {
  23859. this.radius = other.radius;
  23860. this.theta = other.theta;
  23861. this.y = other.y;
  23862. return this;
  23863. },
  23864. setFromVector3: function( vec3 ) {
  23865. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  23866. this.theta = Math.atan2( vec3.x, vec3.z );
  23867. this.y = vec3.y;
  23868. return this;
  23869. }
  23870. } );
  23871. /**
  23872. * @author alteredq / http://alteredqualia.com/
  23873. */
  23874. function MorphBlendMesh( geometry, material ) {
  23875. Mesh.call( this, geometry, material );
  23876. this.animationsMap = {};
  23877. this.animationsList = [];
  23878. // prepare default animation
  23879. // (all frames played together in 1 second)
  23880. var numFrames = this.geometry.morphTargets.length;
  23881. var name = "__default";
  23882. var startFrame = 0;
  23883. var endFrame = numFrames - 1;
  23884. var fps = numFrames / 1;
  23885. this.createAnimation( name, startFrame, endFrame, fps );
  23886. this.setAnimationWeight( name, 1 );
  23887. }
  23888. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23889. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23890. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23891. var animation = {
  23892. start: start,
  23893. end: end,
  23894. length: end - start + 1,
  23895. fps: fps,
  23896. duration: ( end - start ) / fps,
  23897. lastFrame: 0,
  23898. currentFrame: 0,
  23899. active: false,
  23900. time: 0,
  23901. direction: 1,
  23902. weight: 1,
  23903. directionBackwards: false,
  23904. mirroredLoop: false
  23905. };
  23906. this.animationsMap[ name ] = animation;
  23907. this.animationsList.push( animation );
  23908. };
  23909. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23910. var pattern = /([a-z]+)_?(\d+)/i;
  23911. var firstAnimation, frameRanges = {};
  23912. var geometry = this.geometry;
  23913. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23914. var morph = geometry.morphTargets[ i ];
  23915. var chunks = morph.name.match( pattern );
  23916. if ( chunks && chunks.length > 1 ) {
  23917. var name = chunks[ 1 ];
  23918. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23919. var range = frameRanges[ name ];
  23920. if ( i < range.start ) range.start = i;
  23921. if ( i > range.end ) range.end = i;
  23922. if ( ! firstAnimation ) firstAnimation = name;
  23923. }
  23924. }
  23925. for ( var name in frameRanges ) {
  23926. var range = frameRanges[ name ];
  23927. this.createAnimation( name, range.start, range.end, fps );
  23928. }
  23929. this.firstAnimation = firstAnimation;
  23930. };
  23931. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23932. var animation = this.animationsMap[ name ];
  23933. if ( animation ) {
  23934. animation.direction = 1;
  23935. animation.directionBackwards = false;
  23936. }
  23937. };
  23938. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23939. var animation = this.animationsMap[ name ];
  23940. if ( animation ) {
  23941. animation.direction = - 1;
  23942. animation.directionBackwards = true;
  23943. }
  23944. };
  23945. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23946. var animation = this.animationsMap[ name ];
  23947. if ( animation ) {
  23948. animation.fps = fps;
  23949. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23950. }
  23951. };
  23952. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23953. var animation = this.animationsMap[ name ];
  23954. if ( animation ) {
  23955. animation.duration = duration;
  23956. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23957. }
  23958. };
  23959. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23960. var animation = this.animationsMap[ name ];
  23961. if ( animation ) {
  23962. animation.weight = weight;
  23963. }
  23964. };
  23965. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23966. var animation = this.animationsMap[ name ];
  23967. if ( animation ) {
  23968. animation.time = time;
  23969. }
  23970. };
  23971. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23972. var time = 0;
  23973. var animation = this.animationsMap[ name ];
  23974. if ( animation ) {
  23975. time = animation.time;
  23976. }
  23977. return time;
  23978. };
  23979. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23980. var duration = - 1;
  23981. var animation = this.animationsMap[ name ];
  23982. if ( animation ) {
  23983. duration = animation.duration;
  23984. }
  23985. return duration;
  23986. };
  23987. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23988. var animation = this.animationsMap[ name ];
  23989. if ( animation ) {
  23990. animation.time = 0;
  23991. animation.active = true;
  23992. } else {
  23993. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23994. }
  23995. };
  23996. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23997. var animation = this.animationsMap[ name ];
  23998. if ( animation ) {
  23999. animation.active = false;
  24000. }
  24001. };
  24002. MorphBlendMesh.prototype.update = function ( delta ) {
  24003. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24004. var animation = this.animationsList[ i ];
  24005. if ( ! animation.active ) continue;
  24006. var frameTime = animation.duration / animation.length;
  24007. animation.time += animation.direction * delta;
  24008. if ( animation.mirroredLoop ) {
  24009. if ( animation.time > animation.duration || animation.time < 0 ) {
  24010. animation.direction *= - 1;
  24011. if ( animation.time > animation.duration ) {
  24012. animation.time = animation.duration;
  24013. animation.directionBackwards = true;
  24014. }
  24015. if ( animation.time < 0 ) {
  24016. animation.time = 0;
  24017. animation.directionBackwards = false;
  24018. }
  24019. }
  24020. } else {
  24021. animation.time = animation.time % animation.duration;
  24022. if ( animation.time < 0 ) animation.time += animation.duration;
  24023. }
  24024. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24025. var weight = animation.weight;
  24026. if ( keyframe !== animation.currentFrame ) {
  24027. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24028. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24029. this.morphTargetInfluences[ keyframe ] = 0;
  24030. animation.lastFrame = animation.currentFrame;
  24031. animation.currentFrame = keyframe;
  24032. }
  24033. var mix = ( animation.time % frameTime ) / frameTime;
  24034. if ( animation.directionBackwards ) mix = 1 - mix;
  24035. if ( animation.currentFrame !== animation.lastFrame ) {
  24036. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24037. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24038. } else {
  24039. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24040. }
  24041. }
  24042. };
  24043. /**
  24044. * @author alteredq / http://alteredqualia.com/
  24045. */
  24046. function ImmediateRenderObject( material ) {
  24047. Object3D.call( this );
  24048. this.material = material;
  24049. this.render = function ( renderCallback ) {};
  24050. }
  24051. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24052. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24053. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24054. /**
  24055. * @author mrdoob / http://mrdoob.com/
  24056. * @author WestLangley / http://github.com/WestLangley
  24057. */
  24058. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24059. this.object = object;
  24060. this.size = ( size !== undefined ) ? size : 1;
  24061. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24062. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24063. //
  24064. var nNormals = 0;
  24065. var objGeometry = this.object.geometry;
  24066. if ( objGeometry && objGeometry.isGeometry ) {
  24067. nNormals = objGeometry.faces.length * 3;
  24068. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24069. nNormals = objGeometry.attributes.normal.count;
  24070. }
  24071. //
  24072. var geometry = new BufferGeometry();
  24073. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24074. geometry.addAttribute( 'position', positions );
  24075. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24076. //
  24077. this.matrixAutoUpdate = false;
  24078. this.update();
  24079. }
  24080. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24081. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24082. VertexNormalsHelper.prototype.update = ( function () {
  24083. var v1 = new Vector3();
  24084. var v2 = new Vector3();
  24085. var normalMatrix = new Matrix3();
  24086. return function update() {
  24087. var keys = [ 'a', 'b', 'c' ];
  24088. this.object.updateMatrixWorld( true );
  24089. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24090. var matrixWorld = this.object.matrixWorld;
  24091. var position = this.geometry.attributes.position;
  24092. //
  24093. var objGeometry = this.object.geometry;
  24094. if ( objGeometry && objGeometry.isGeometry ) {
  24095. var vertices = objGeometry.vertices;
  24096. var faces = objGeometry.faces;
  24097. var idx = 0;
  24098. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24099. var face = faces[ i ];
  24100. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24101. var vertex = vertices[ face[ keys[ j ] ] ];
  24102. var normal = face.vertexNormals[ j ];
  24103. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24104. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24105. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24106. idx = idx + 1;
  24107. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24108. idx = idx + 1;
  24109. }
  24110. }
  24111. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24112. var objPos = objGeometry.attributes.position;
  24113. var objNorm = objGeometry.attributes.normal;
  24114. var idx = 0;
  24115. // for simplicity, ignore index and drawcalls, and render every normal
  24116. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24117. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24118. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24119. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24120. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24121. idx = idx + 1;
  24122. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24123. idx = idx + 1;
  24124. }
  24125. }
  24126. position.needsUpdate = true;
  24127. };
  24128. }() );
  24129. /**
  24130. * @author alteredq / http://alteredqualia.com/
  24131. * @author mrdoob / http://mrdoob.com/
  24132. * @author WestLangley / http://github.com/WestLangley
  24133. */
  24134. function SpotLightHelper( light ) {
  24135. Object3D.call( this );
  24136. this.light = light;
  24137. this.light.updateMatrixWorld();
  24138. this.matrix = light.matrixWorld;
  24139. this.matrixAutoUpdate = false;
  24140. var geometry = new BufferGeometry();
  24141. var positions = [
  24142. 0, 0, 0, 0, 0, 1,
  24143. 0, 0, 0, 1, 0, 1,
  24144. 0, 0, 0, - 1, 0, 1,
  24145. 0, 0, 0, 0, 1, 1,
  24146. 0, 0, 0, 0, - 1, 1
  24147. ];
  24148. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24149. var p1 = ( i / l ) * Math.PI * 2;
  24150. var p2 = ( j / l ) * Math.PI * 2;
  24151. positions.push(
  24152. Math.cos( p1 ), Math.sin( p1 ), 1,
  24153. Math.cos( p2 ), Math.sin( p2 ), 1
  24154. );
  24155. }
  24156. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24157. var material = new LineBasicMaterial( { fog: false } );
  24158. this.cone = new LineSegments( geometry, material );
  24159. this.add( this.cone );
  24160. this.update();
  24161. }
  24162. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24163. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24164. SpotLightHelper.prototype.dispose = function () {
  24165. this.cone.geometry.dispose();
  24166. this.cone.material.dispose();
  24167. };
  24168. SpotLightHelper.prototype.update = function () {
  24169. var vector = new Vector3();
  24170. var vector2 = new Vector3();
  24171. return function update() {
  24172. var coneLength = this.light.distance ? this.light.distance : 1000;
  24173. var coneWidth = coneLength * Math.tan( this.light.angle );
  24174. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24175. vector.setFromMatrixPosition( this.light.matrixWorld );
  24176. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24177. this.cone.lookAt( vector2.sub( vector ) );
  24178. this.cone.material.color.copy( this.light.color );
  24179. };
  24180. }();
  24181. /**
  24182. * @author Sean Griffin / http://twitter.com/sgrif
  24183. * @author Michael Guerrero / http://realitymeltdown.com
  24184. * @author mrdoob / http://mrdoob.com/
  24185. * @author ikerr / http://verold.com
  24186. * @author Mugen87 / https://github.com/Mugen87
  24187. */
  24188. function SkeletonHelper( object ) {
  24189. this.bones = this.getBoneList( object );
  24190. var geometry = new BufferGeometry();
  24191. var vertices = [];
  24192. var colors = [];
  24193. var color1 = new Color( 0, 0, 1 );
  24194. var color2 = new Color( 0, 1, 0 );
  24195. for ( var i = 0; i < this.bones.length; i ++ ) {
  24196. var bone = this.bones[ i ];
  24197. if ( bone.parent && bone.parent.isBone ) {
  24198. vertices.push( 0, 0, 0 );
  24199. vertices.push( 0, 0, 0 );
  24200. colors.push( color1.r, color1.g, color1.b );
  24201. colors.push( color2.r, color2.g, color2.b );
  24202. }
  24203. }
  24204. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24205. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24206. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24207. LineSegments.call( this, geometry, material );
  24208. this.root = object;
  24209. this.matrix = object.matrixWorld;
  24210. this.matrixAutoUpdate = false;
  24211. this.update();
  24212. }
  24213. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24214. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24215. SkeletonHelper.prototype.getBoneList = function( object ) {
  24216. var boneList = [];
  24217. if ( object && object.isBone ) {
  24218. boneList.push( object );
  24219. }
  24220. for ( var i = 0; i < object.children.length; i ++ ) {
  24221. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24222. }
  24223. return boneList;
  24224. };
  24225. SkeletonHelper.prototype.update = function () {
  24226. var vector = new Vector3();
  24227. var boneMatrix = new Matrix4();
  24228. var matrixWorldInv = new Matrix4();
  24229. return function update() {
  24230. var geometry = this.geometry;
  24231. var position = geometry.getAttribute( 'position' );
  24232. matrixWorldInv.getInverse( this.root.matrixWorld );
  24233. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  24234. var bone = this.bones[ i ];
  24235. if ( bone.parent && bone.parent.isBone ) {
  24236. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24237. vector.setFromMatrixPosition( boneMatrix );
  24238. position.setXYZ( j, vector.x, vector.y, vector.z );
  24239. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24240. vector.setFromMatrixPosition( boneMatrix );
  24241. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24242. j += 2;
  24243. }
  24244. }
  24245. geometry.getAttribute( 'position' ).needsUpdate = true;
  24246. };
  24247. }();
  24248. /**
  24249. * @author alteredq / http://alteredqualia.com/
  24250. * @author mrdoob / http://mrdoob.com/
  24251. */
  24252. function PointLightHelper( light, sphereSize ) {
  24253. this.light = light;
  24254. this.light.updateMatrixWorld();
  24255. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24256. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24257. material.color.copy( this.light.color );
  24258. Mesh.call( this, geometry, material );
  24259. this.matrix = this.light.matrixWorld;
  24260. this.matrixAutoUpdate = false;
  24261. /*
  24262. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24263. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24264. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24265. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24266. var d = light.distance;
  24267. if ( d === 0.0 ) {
  24268. this.lightDistance.visible = false;
  24269. } else {
  24270. this.lightDistance.scale.set( d, d, d );
  24271. }
  24272. this.add( this.lightDistance );
  24273. */
  24274. }
  24275. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24276. PointLightHelper.prototype.constructor = PointLightHelper;
  24277. PointLightHelper.prototype.dispose = function () {
  24278. this.geometry.dispose();
  24279. this.material.dispose();
  24280. };
  24281. PointLightHelper.prototype.update = function () {
  24282. this.material.color.copy( this.light.color );
  24283. /*
  24284. var d = this.light.distance;
  24285. if ( d === 0.0 ) {
  24286. this.lightDistance.visible = false;
  24287. } else {
  24288. this.lightDistance.visible = true;
  24289. this.lightDistance.scale.set( d, d, d );
  24290. }
  24291. */
  24292. };
  24293. /**
  24294. * @author abelnation / http://github.com/abelnation
  24295. * @author Mugen87 / http://github.com/Mugen87
  24296. * @author WestLangley / http://github.com/WestLangley
  24297. */
  24298. function RectAreaLightHelper( light ) {
  24299. Object3D.call( this );
  24300. this.light = light;
  24301. this.light.updateMatrixWorld();
  24302. this.matrix = light.matrixWorld;
  24303. this.matrixAutoUpdate = false;
  24304. var material = new LineBasicMaterial( { color: light.color } );
  24305. var geometry = new BufferGeometry();
  24306. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24307. this.add( new Line( geometry, material ) );
  24308. this.update();
  24309. }
  24310. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24311. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24312. RectAreaLightHelper.prototype.dispose = function () {
  24313. this.children[ 0 ].geometry.dispose();
  24314. this.children[ 0 ].material.dispose();
  24315. };
  24316. RectAreaLightHelper.prototype.update = function () {
  24317. var line = this.children[ 0 ];
  24318. // update material
  24319. line.material.color.copy( this.light.color );
  24320. // calculate new dimensions of the helper
  24321. var hx = this.light.width * 0.5;
  24322. var hy = this.light.height * 0.5;
  24323. var position = line.geometry.attributes.position;
  24324. var array = position.array;
  24325. // update vertices
  24326. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24327. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24328. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24329. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24330. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24331. position.needsUpdate = true;
  24332. };
  24333. /**
  24334. * @author alteredq / http://alteredqualia.com/
  24335. * @author mrdoob / http://mrdoob.com/
  24336. * @author Mugen87 / https://github.com/Mugen87
  24337. */
  24338. function HemisphereLightHelper( light, size ) {
  24339. Object3D.call( this );
  24340. this.light = light;
  24341. this.light.updateMatrixWorld();
  24342. this.matrix = light.matrixWorld;
  24343. this.matrixAutoUpdate = false;
  24344. var geometry = new OctahedronBufferGeometry( size );
  24345. geometry.rotateY( Math.PI * 0.5 );
  24346. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24347. var position = geometry.getAttribute( 'position' );
  24348. var colors = new Float32Array( position.count * 3 );
  24349. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24350. this.add( new Mesh( geometry, material ) );
  24351. this.update();
  24352. }
  24353. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24354. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24355. HemisphereLightHelper.prototype.dispose = function () {
  24356. this.children[ 0 ].geometry.dispose();
  24357. this.children[ 0 ].material.dispose();
  24358. };
  24359. HemisphereLightHelper.prototype.update = function () {
  24360. var vector = new Vector3();
  24361. var color1 = new Color();
  24362. var color2 = new Color();
  24363. return function update() {
  24364. var mesh = this.children[ 0 ];
  24365. var colors = mesh.geometry.getAttribute( 'color' );
  24366. color1.copy( this.light.color );
  24367. color2.copy( this.light.groundColor );
  24368. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24369. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24370. colors.setXYZ( i, color.r, color.g, color.b );
  24371. }
  24372. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24373. colors.needsUpdate = true;
  24374. };
  24375. }();
  24376. /**
  24377. * @author mrdoob / http://mrdoob.com/
  24378. */
  24379. function GridHelper( size, divisions, color1, color2 ) {
  24380. size = size || 10;
  24381. divisions = divisions || 10;
  24382. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24383. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24384. var center = divisions / 2;
  24385. var step = size / divisions;
  24386. var halfSize = size / 2;
  24387. var vertices = [], colors = [];
  24388. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24389. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24390. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24391. var color = i === center ? color1 : color2;
  24392. color.toArray( colors, j ); j += 3;
  24393. color.toArray( colors, j ); j += 3;
  24394. color.toArray( colors, j ); j += 3;
  24395. color.toArray( colors, j ); j += 3;
  24396. }
  24397. var geometry = new BufferGeometry();
  24398. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24399. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24400. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24401. LineSegments.call( this, geometry, material );
  24402. }
  24403. GridHelper.prototype = Object.create( LineSegments.prototype );
  24404. GridHelper.prototype.constructor = GridHelper;
  24405. /**
  24406. * @author mrdoob / http://mrdoob.com/
  24407. * @author Mugen87 / http://github.com/Mugen87
  24408. * @author Hectate / http://www.github.com/Hectate
  24409. */
  24410. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24411. radius = radius || 10;
  24412. radials = radials || 16;
  24413. circles = circles || 8;
  24414. divisions = divisions || 64;
  24415. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24416. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24417. var vertices = [];
  24418. var colors = [];
  24419. var x, z;
  24420. var v, i, j, r, color;
  24421. // create the radials
  24422. for ( i = 0; i <= radials; i ++ ) {
  24423. v = ( i / radials ) * ( Math.PI * 2 );
  24424. x = Math.sin( v ) * radius;
  24425. z = Math.cos( v ) * radius;
  24426. vertices.push( 0, 0, 0 );
  24427. vertices.push( x, 0, z );
  24428. color = ( i & 1 ) ? color1 : color2;
  24429. colors.push( color.r, color.g, color.b );
  24430. colors.push( color.r, color.g, color.b );
  24431. }
  24432. // create the circles
  24433. for ( i = 0; i <= circles; i ++ ) {
  24434. color = ( i & 1 ) ? color1 : color2;
  24435. r = radius - ( radius / circles * i );
  24436. for ( j = 0; j < divisions; j ++ ) {
  24437. // first vertex
  24438. v = ( j / divisions ) * ( Math.PI * 2 );
  24439. x = Math.sin( v ) * r;
  24440. z = Math.cos( v ) * r;
  24441. vertices.push( x, 0, z );
  24442. colors.push( color.r, color.g, color.b );
  24443. // second vertex
  24444. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24445. x = Math.sin( v ) * r;
  24446. z = Math.cos( v ) * r;
  24447. vertices.push( x, 0, z );
  24448. colors.push( color.r, color.g, color.b );
  24449. }
  24450. }
  24451. var geometry = new BufferGeometry();
  24452. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24453. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24454. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24455. LineSegments.call( this, geometry, material );
  24456. }
  24457. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24458. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24459. /**
  24460. * @author mrdoob / http://mrdoob.com/
  24461. * @author WestLangley / http://github.com/WestLangley
  24462. */
  24463. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24464. // FaceNormalsHelper only supports THREE.Geometry
  24465. this.object = object;
  24466. this.size = ( size !== undefined ) ? size : 1;
  24467. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24468. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24469. //
  24470. var nNormals = 0;
  24471. var objGeometry = this.object.geometry;
  24472. if ( objGeometry && objGeometry.isGeometry ) {
  24473. nNormals = objGeometry.faces.length;
  24474. } else {
  24475. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24476. }
  24477. //
  24478. var geometry = new BufferGeometry();
  24479. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24480. geometry.addAttribute( 'position', positions );
  24481. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24482. //
  24483. this.matrixAutoUpdate = false;
  24484. this.update();
  24485. }
  24486. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24487. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24488. FaceNormalsHelper.prototype.update = ( function () {
  24489. var v1 = new Vector3();
  24490. var v2 = new Vector3();
  24491. var normalMatrix = new Matrix3();
  24492. return function update() {
  24493. this.object.updateMatrixWorld( true );
  24494. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24495. var matrixWorld = this.object.matrixWorld;
  24496. var position = this.geometry.attributes.position;
  24497. //
  24498. var objGeometry = this.object.geometry;
  24499. var vertices = objGeometry.vertices;
  24500. var faces = objGeometry.faces;
  24501. var idx = 0;
  24502. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24503. var face = faces[ i ];
  24504. var normal = face.normal;
  24505. v1.copy( vertices[ face.a ] )
  24506. .add( vertices[ face.b ] )
  24507. .add( vertices[ face.c ] )
  24508. .divideScalar( 3 )
  24509. .applyMatrix4( matrixWorld );
  24510. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24511. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24512. idx = idx + 1;
  24513. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24514. idx = idx + 1;
  24515. }
  24516. position.needsUpdate = true;
  24517. };
  24518. }() );
  24519. /**
  24520. * @author alteredq / http://alteredqualia.com/
  24521. * @author mrdoob / http://mrdoob.com/
  24522. * @author WestLangley / http://github.com/WestLangley
  24523. */
  24524. function DirectionalLightHelper( light, size ) {
  24525. Object3D.call( this );
  24526. this.light = light;
  24527. this.light.updateMatrixWorld();
  24528. this.matrix = light.matrixWorld;
  24529. this.matrixAutoUpdate = false;
  24530. if ( size === undefined ) size = 1;
  24531. var geometry = new BufferGeometry();
  24532. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24533. - size, size, 0,
  24534. size, size, 0,
  24535. size, - size, 0,
  24536. - size, - size, 0,
  24537. - size, size, 0
  24538. ], 3 ) );
  24539. var material = new LineBasicMaterial( { fog: false } );
  24540. this.add( new Line( geometry, material ) );
  24541. geometry = new BufferGeometry();
  24542. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24543. this.add( new Line( geometry, material ));
  24544. this.update();
  24545. }
  24546. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24547. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24548. DirectionalLightHelper.prototype.dispose = function () {
  24549. var lightPlane = this.children[ 0 ];
  24550. var targetLine = this.children[ 1 ];
  24551. lightPlane.geometry.dispose();
  24552. lightPlane.material.dispose();
  24553. targetLine.geometry.dispose();
  24554. targetLine.material.dispose();
  24555. };
  24556. DirectionalLightHelper.prototype.update = function () {
  24557. var v1 = new Vector3();
  24558. var v2 = new Vector3();
  24559. var v3 = new Vector3();
  24560. return function update() {
  24561. v1.setFromMatrixPosition( this.light.matrixWorld );
  24562. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24563. v3.subVectors( v2, v1 );
  24564. var lightPlane = this.children[ 0 ];
  24565. var targetLine = this.children[ 1 ];
  24566. lightPlane.lookAt( v3 );
  24567. lightPlane.material.color.copy( this.light.color );
  24568. targetLine.lookAt( v3 );
  24569. targetLine.scale.z = v3.length();
  24570. };
  24571. }();
  24572. /**
  24573. * @author alteredq / http://alteredqualia.com/
  24574. * @author Mugen87 / https://github.com/Mugen87
  24575. *
  24576. * - shows frustum, line of sight and up of the camera
  24577. * - suitable for fast updates
  24578. * - based on frustum visualization in lightgl.js shadowmap example
  24579. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24580. */
  24581. function CameraHelper( camera ) {
  24582. var geometry = new BufferGeometry();
  24583. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24584. var vertices = [];
  24585. var colors = [];
  24586. var pointMap = {};
  24587. // colors
  24588. var colorFrustum = new Color( 0xffaa00 );
  24589. var colorCone = new Color( 0xff0000 );
  24590. var colorUp = new Color( 0x00aaff );
  24591. var colorTarget = new Color( 0xffffff );
  24592. var colorCross = new Color( 0x333333 );
  24593. // near
  24594. addLine( "n1", "n2", colorFrustum );
  24595. addLine( "n2", "n4", colorFrustum );
  24596. addLine( "n4", "n3", colorFrustum );
  24597. addLine( "n3", "n1", colorFrustum );
  24598. // far
  24599. addLine( "f1", "f2", colorFrustum );
  24600. addLine( "f2", "f4", colorFrustum );
  24601. addLine( "f4", "f3", colorFrustum );
  24602. addLine( "f3", "f1", colorFrustum );
  24603. // sides
  24604. addLine( "n1", "f1", colorFrustum );
  24605. addLine( "n2", "f2", colorFrustum );
  24606. addLine( "n3", "f3", colorFrustum );
  24607. addLine( "n4", "f4", colorFrustum );
  24608. // cone
  24609. addLine( "p", "n1", colorCone );
  24610. addLine( "p", "n2", colorCone );
  24611. addLine( "p", "n3", colorCone );
  24612. addLine( "p", "n4", colorCone );
  24613. // up
  24614. addLine( "u1", "u2", colorUp );
  24615. addLine( "u2", "u3", colorUp );
  24616. addLine( "u3", "u1", colorUp );
  24617. // target
  24618. addLine( "c", "t", colorTarget );
  24619. addLine( "p", "c", colorCross );
  24620. // cross
  24621. addLine( "cn1", "cn2", colorCross );
  24622. addLine( "cn3", "cn4", colorCross );
  24623. addLine( "cf1", "cf2", colorCross );
  24624. addLine( "cf3", "cf4", colorCross );
  24625. function addLine( a, b, color ) {
  24626. addPoint( a, color );
  24627. addPoint( b, color );
  24628. }
  24629. function addPoint( id, color ) {
  24630. vertices.push( 0, 0, 0 );
  24631. colors.push( color.r, color.g, color.b );
  24632. if ( pointMap[ id ] === undefined ) {
  24633. pointMap[ id ] = [];
  24634. }
  24635. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24636. }
  24637. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24638. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24639. LineSegments.call( this, geometry, material );
  24640. this.camera = camera;
  24641. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24642. this.matrix = camera.matrixWorld;
  24643. this.matrixAutoUpdate = false;
  24644. this.pointMap = pointMap;
  24645. this.update();
  24646. }
  24647. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24648. CameraHelper.prototype.constructor = CameraHelper;
  24649. CameraHelper.prototype.update = function () {
  24650. var geometry, pointMap;
  24651. var vector = new Vector3();
  24652. var camera = new Camera();
  24653. function setPoint( point, x, y, z ) {
  24654. vector.set( x, y, z ).unproject( camera );
  24655. var points = pointMap[ point ];
  24656. if ( points !== undefined ) {
  24657. var position = geometry.getAttribute( 'position' );
  24658. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24659. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24660. }
  24661. }
  24662. }
  24663. return function update() {
  24664. geometry = this.geometry;
  24665. pointMap = this.pointMap;
  24666. var w = 1, h = 1;
  24667. // we need just camera projection matrix
  24668. // world matrix must be identity
  24669. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24670. // center / target
  24671. setPoint( "c", 0, 0, - 1 );
  24672. setPoint( "t", 0, 0, 1 );
  24673. // near
  24674. setPoint( "n1", - w, - h, - 1 );
  24675. setPoint( "n2", w, - h, - 1 );
  24676. setPoint( "n3", - w, h, - 1 );
  24677. setPoint( "n4", w, h, - 1 );
  24678. // far
  24679. setPoint( "f1", - w, - h, 1 );
  24680. setPoint( "f2", w, - h, 1 );
  24681. setPoint( "f3", - w, h, 1 );
  24682. setPoint( "f4", w, h, 1 );
  24683. // up
  24684. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24685. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24686. setPoint( "u3", 0, h * 2, - 1 );
  24687. // cross
  24688. setPoint( "cf1", - w, 0, 1 );
  24689. setPoint( "cf2", w, 0, 1 );
  24690. setPoint( "cf3", 0, - h, 1 );
  24691. setPoint( "cf4", 0, h, 1 );
  24692. setPoint( "cn1", - w, 0, - 1 );
  24693. setPoint( "cn2", w, 0, - 1 );
  24694. setPoint( "cn3", 0, - h, - 1 );
  24695. setPoint( "cn4", 0, h, - 1 );
  24696. geometry.getAttribute( 'position' ).needsUpdate = true;
  24697. };
  24698. }();
  24699. /**
  24700. * @author mrdoob / http://mrdoob.com/
  24701. * @author Mugen87 / http://github.com/Mugen87
  24702. */
  24703. function BoxHelper( object, color ) {
  24704. this.object = object;
  24705. if ( color === undefined ) color = 0xffff00;
  24706. 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 ] );
  24707. var positions = new Float32Array( 8 * 3 );
  24708. var geometry = new BufferGeometry();
  24709. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24710. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24711. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24712. this.matrixAutoUpdate = false;
  24713. this.update();
  24714. }
  24715. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24716. BoxHelper.prototype.constructor = BoxHelper;
  24717. BoxHelper.prototype.update = ( function () {
  24718. var box = new Box3();
  24719. return function update( object ) {
  24720. if ( object !== undefined ) {
  24721. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  24722. }
  24723. if ( this.object !== undefined ) {
  24724. box.setFromObject( this.object );
  24725. }
  24726. if ( box.isEmpty() ) return;
  24727. var min = box.min;
  24728. var max = box.max;
  24729. /*
  24730. 5____4
  24731. 1/___0/|
  24732. | 6__|_7
  24733. 2/___3/
  24734. 0: max.x, max.y, max.z
  24735. 1: min.x, max.y, max.z
  24736. 2: min.x, min.y, max.z
  24737. 3: max.x, min.y, max.z
  24738. 4: max.x, max.y, min.z
  24739. 5: min.x, max.y, min.z
  24740. 6: min.x, min.y, min.z
  24741. 7: max.x, min.y, min.z
  24742. */
  24743. var position = this.geometry.attributes.position;
  24744. var array = position.array;
  24745. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24746. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24747. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24748. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24749. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24750. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24751. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24752. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24753. position.needsUpdate = true;
  24754. this.geometry.computeBoundingSphere();
  24755. };
  24756. } )();
  24757. BoxHelper.prototype.setFromObject = function ( object ) {
  24758. this.object = object;
  24759. this.update();
  24760. return this;
  24761. };
  24762. /**
  24763. * @author WestLangley / http://github.com/WestLangley
  24764. * @author zz85 / http://github.com/zz85
  24765. * @author bhouston / http://clara.io
  24766. *
  24767. * Creates an arrow for visualizing directions
  24768. *
  24769. * Parameters:
  24770. * dir - Vector3
  24771. * origin - Vector3
  24772. * length - Number
  24773. * color - color in hex value
  24774. * headLength - Number
  24775. * headWidth - Number
  24776. */
  24777. var lineGeometry;
  24778. var coneGeometry;
  24779. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24780. // dir is assumed to be normalized
  24781. Object3D.call( this );
  24782. if ( color === undefined ) color = 0xffff00;
  24783. if ( length === undefined ) length = 1;
  24784. if ( headLength === undefined ) headLength = 0.2 * length;
  24785. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24786. if ( lineGeometry === undefined ) {
  24787. lineGeometry = new BufferGeometry();
  24788. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24789. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24790. coneGeometry.translate( 0, - 0.5, 0 );
  24791. }
  24792. this.position.copy( origin );
  24793. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24794. this.line.matrixAutoUpdate = false;
  24795. this.add( this.line );
  24796. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24797. this.cone.matrixAutoUpdate = false;
  24798. this.add( this.cone );
  24799. this.setDirection( dir );
  24800. this.setLength( length, headLength, headWidth );
  24801. }
  24802. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24803. ArrowHelper.prototype.constructor = ArrowHelper;
  24804. ArrowHelper.prototype.setDirection = ( function () {
  24805. var axis = new Vector3();
  24806. var radians;
  24807. return function setDirection( dir ) {
  24808. // dir is assumed to be normalized
  24809. if ( dir.y > 0.99999 ) {
  24810. this.quaternion.set( 0, 0, 0, 1 );
  24811. } else if ( dir.y < - 0.99999 ) {
  24812. this.quaternion.set( 1, 0, 0, 0 );
  24813. } else {
  24814. axis.set( dir.z, 0, - dir.x ).normalize();
  24815. radians = Math.acos( dir.y );
  24816. this.quaternion.setFromAxisAngle( axis, radians );
  24817. }
  24818. };
  24819. }() );
  24820. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24821. if ( headLength === undefined ) headLength = 0.2 * length;
  24822. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24823. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24824. this.line.updateMatrix();
  24825. this.cone.scale.set( headWidth, headLength, headWidth );
  24826. this.cone.position.y = length;
  24827. this.cone.updateMatrix();
  24828. };
  24829. ArrowHelper.prototype.setColor = function ( color ) {
  24830. this.line.material.color.copy( color );
  24831. this.cone.material.color.copy( color );
  24832. };
  24833. /**
  24834. * @author sroucheray / http://sroucheray.org/
  24835. * @author mrdoob / http://mrdoob.com/
  24836. */
  24837. function AxisHelper( size ) {
  24838. size = size || 1;
  24839. var vertices = [
  24840. 0, 0, 0, size, 0, 0,
  24841. 0, 0, 0, 0, size, 0,
  24842. 0, 0, 0, 0, 0, size
  24843. ];
  24844. var colors = [
  24845. 1, 0, 0, 1, 0.6, 0,
  24846. 0, 1, 0, 0.6, 1, 0,
  24847. 0, 0, 1, 0, 0.6, 1
  24848. ];
  24849. var geometry = new BufferGeometry();
  24850. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24851. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24852. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24853. LineSegments.call( this, geometry, material );
  24854. }
  24855. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24856. AxisHelper.prototype.constructor = AxisHelper;
  24857. /**
  24858. * @author zz85 https://github.com/zz85
  24859. *
  24860. * Centripetal CatmullRom Curve - which is useful for avoiding
  24861. * cusps and self-intersections in non-uniform catmull rom curves.
  24862. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24863. *
  24864. * curve.type accepts centripetal(default), chordal and catmullrom
  24865. * curve.tension is used for catmullrom which defaults to 0.5
  24866. */
  24867. /*
  24868. Based on an optimized c++ solution in
  24869. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24870. - http://ideone.com/NoEbVM
  24871. This CubicPoly class could be used for reusing some variables and calculations,
  24872. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24873. which can be placed in CurveUtils.
  24874. */
  24875. function CubicPoly() {
  24876. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24877. /*
  24878. * Compute coefficients for a cubic polynomial
  24879. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24880. * such that
  24881. * p(0) = x0, p(1) = x1
  24882. * and
  24883. * p'(0) = t0, p'(1) = t1.
  24884. */
  24885. function init( x0, x1, t0, t1 ) {
  24886. c0 = x0;
  24887. c1 = t0;
  24888. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24889. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24890. }
  24891. return {
  24892. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24893. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24894. },
  24895. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24896. // compute tangents when parameterized in [t1,t2]
  24897. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24898. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24899. // rescale tangents for parametrization in [0,1]
  24900. t1 *= dt1;
  24901. t2 *= dt1;
  24902. init( x1, x2, t1, t2 );
  24903. },
  24904. calc: function ( t ) {
  24905. var t2 = t * t;
  24906. var t3 = t2 * t;
  24907. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24908. }
  24909. };
  24910. }
  24911. //
  24912. var tmp = new Vector3();
  24913. var px = new CubicPoly();
  24914. var py = new CubicPoly();
  24915. var pz = new CubicPoly();
  24916. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  24917. Curve.call( this );
  24918. this.points = p || [];
  24919. this.closed = false;
  24920. }
  24921. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  24922. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  24923. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  24924. var points = this.points;
  24925. var l = points.length;
  24926. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24927. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24928. var intPoint = Math.floor( point );
  24929. var weight = point - intPoint;
  24930. if ( this.closed ) {
  24931. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24932. } else if ( weight === 0 && intPoint === l - 1 ) {
  24933. intPoint = l - 2;
  24934. weight = 1;
  24935. }
  24936. var p0, p1, p2, p3; // 4 points
  24937. if ( this.closed || intPoint > 0 ) {
  24938. p0 = points[ ( intPoint - 1 ) % l ];
  24939. } else {
  24940. // extrapolate first point
  24941. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24942. p0 = tmp;
  24943. }
  24944. p1 = points[ intPoint % l ];
  24945. p2 = points[ ( intPoint + 1 ) % l ];
  24946. if ( this.closed || intPoint + 2 < l ) {
  24947. p3 = points[ ( intPoint + 2 ) % l ];
  24948. } else {
  24949. // extrapolate last point
  24950. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24951. p3 = tmp;
  24952. }
  24953. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24954. // init Centripetal / Chordal Catmull-Rom
  24955. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24956. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24957. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24958. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24959. // safety check for repeated points
  24960. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24961. if ( dt0 < 1e-4 ) dt0 = dt1;
  24962. if ( dt2 < 1e-4 ) dt2 = dt1;
  24963. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24964. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24965. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24966. } else if ( this.type === 'catmullrom' ) {
  24967. var tension = this.tension !== undefined ? this.tension : 0.5;
  24968. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24969. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24970. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24971. }
  24972. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  24973. };
  24974. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  24975. Curve.call( this );
  24976. this.v0 = v0;
  24977. this.v1 = v1;
  24978. this.v2 = v2;
  24979. this.v3 = v3;
  24980. }
  24981. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  24982. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  24983. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  24984. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24985. return new Vector3(
  24986. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24987. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24988. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24989. );
  24990. };
  24991. function QuadraticBezierCurve3( v0, v1, v2 ) {
  24992. Curve.call( this );
  24993. this.v0 = v0;
  24994. this.v1 = v1;
  24995. this.v2 = v2;
  24996. }
  24997. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  24998. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  24999. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25000. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25001. return new Vector3(
  25002. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25003. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25004. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25005. );
  25006. };
  25007. function LineCurve3( v1, v2 ) {
  25008. Curve.call( this );
  25009. this.v1 = v1;
  25010. this.v2 = v2;
  25011. }
  25012. LineCurve3.prototype = Object.create( Curve.prototype );
  25013. LineCurve3.prototype.constructor = LineCurve3;
  25014. LineCurve3.prototype.getPoint = function ( t ) {
  25015. if ( t === 1 ) {
  25016. return this.v2.clone();
  25017. }
  25018. var vector = new Vector3();
  25019. vector.subVectors( this.v2, this.v1 ); // diff
  25020. vector.multiplyScalar( t );
  25021. vector.add( this.v1 );
  25022. return vector;
  25023. };
  25024. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25025. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25026. }
  25027. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25028. ArcCurve.prototype.constructor = ArcCurve;
  25029. /**
  25030. * @author alteredq / http://alteredqualia.com/
  25031. */
  25032. var SceneUtils = {
  25033. createMultiMaterialObject: function ( geometry, materials ) {
  25034. var group = new Group();
  25035. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25036. group.add( new Mesh( geometry, materials[ i ] ) );
  25037. }
  25038. return group;
  25039. },
  25040. detach: function ( child, parent, scene ) {
  25041. child.applyMatrix( parent.matrixWorld );
  25042. parent.remove( child );
  25043. scene.add( child );
  25044. },
  25045. attach: function ( child, scene, parent ) {
  25046. var matrixWorldInverse = new Matrix4();
  25047. matrixWorldInverse.getInverse( parent.matrixWorld );
  25048. child.applyMatrix( matrixWorldInverse );
  25049. scene.remove( child );
  25050. parent.add( child );
  25051. }
  25052. };
  25053. /**
  25054. * @author mrdoob / http://mrdoob.com/
  25055. */
  25056. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25057. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25058. return new Face3( a, b, c, normal, color, materialIndex );
  25059. }
  25060. var LineStrip = 0;
  25061. var LinePieces = 1;
  25062. function MeshFaceMaterial( materials ) {
  25063. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25064. return materials;
  25065. }
  25066. function MultiMaterial( materials ) {
  25067. if ( materials === undefined ) materials = [];
  25068. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25069. materials.isMultiMaterial = true;
  25070. materials.materials = materials;
  25071. materials.clone = function () {
  25072. return materials.slice();
  25073. };
  25074. return materials;
  25075. }
  25076. function PointCloud( geometry, material ) {
  25077. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25078. return new Points( geometry, material );
  25079. }
  25080. function Particle( material ) {
  25081. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25082. return new Sprite( material );
  25083. }
  25084. function ParticleSystem( geometry, material ) {
  25085. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25086. return new Points( geometry, material );
  25087. }
  25088. function PointCloudMaterial( parameters ) {
  25089. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25090. return new PointsMaterial( parameters );
  25091. }
  25092. function ParticleBasicMaterial( parameters ) {
  25093. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25094. return new PointsMaterial( parameters );
  25095. }
  25096. function ParticleSystemMaterial( parameters ) {
  25097. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25098. return new PointsMaterial( parameters );
  25099. }
  25100. function Vertex( x, y, z ) {
  25101. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25102. return new Vector3( x, y, z );
  25103. }
  25104. //
  25105. function DynamicBufferAttribute( array, itemSize ) {
  25106. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25107. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25108. }
  25109. function Int8Attribute( array, itemSize ) {
  25110. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25111. return new Int8BufferAttribute( array, itemSize );
  25112. }
  25113. function Uint8Attribute( array, itemSize ) {
  25114. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25115. return new Uint8BufferAttribute( array, itemSize );
  25116. }
  25117. function Uint8ClampedAttribute( array, itemSize ) {
  25118. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25119. return new Uint8ClampedBufferAttribute( array, itemSize );
  25120. }
  25121. function Int16Attribute( array, itemSize ) {
  25122. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25123. return new Int16BufferAttribute( array, itemSize );
  25124. }
  25125. function Uint16Attribute( array, itemSize ) {
  25126. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25127. return new Uint16BufferAttribute( array, itemSize );
  25128. }
  25129. function Int32Attribute( array, itemSize ) {
  25130. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25131. return new Int32BufferAttribute( array, itemSize );
  25132. }
  25133. function Uint32Attribute( array, itemSize ) {
  25134. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25135. return new Uint32BufferAttribute( array, itemSize );
  25136. }
  25137. function Float32Attribute( array, itemSize ) {
  25138. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25139. return new Float32BufferAttribute( array, itemSize );
  25140. }
  25141. function Float64Attribute( array, itemSize ) {
  25142. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25143. return new Float64BufferAttribute( array, itemSize );
  25144. }
  25145. //
  25146. Curve.create = function ( construct, getPoint ) {
  25147. console.log( 'THREE.Curve.create() has been deprecated' );
  25148. construct.prototype = Object.create( Curve.prototype );
  25149. construct.prototype.constructor = construct;
  25150. construct.prototype.getPoint = getPoint;
  25151. return construct;
  25152. };
  25153. //
  25154. function ClosedSplineCurve3( points ) {
  25155. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25156. CatmullRomCurve3.call( this, points );
  25157. this.type = 'catmullrom';
  25158. this.closed = true;
  25159. }
  25160. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25161. //
  25162. function SplineCurve3( points ) {
  25163. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25164. CatmullRomCurve3.call( this, points );
  25165. this.type = 'catmullrom';
  25166. }
  25167. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25168. //
  25169. function Spline( points ) {
  25170. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25171. CatmullRomCurve3.call( this, points );
  25172. this.type = 'catmullrom';
  25173. }
  25174. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25175. Object.assign( Spline.prototype, {
  25176. initFromArray: function ( a ) {
  25177. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25178. },
  25179. getControlPointsArray: function ( optionalTarget ) {
  25180. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25181. },
  25182. reparametrizeByArcLength: function ( samplingCoef ) {
  25183. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25184. }
  25185. } );
  25186. //
  25187. function BoundingBoxHelper( object, color ) {
  25188. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25189. return new BoxHelper( object, color );
  25190. }
  25191. function EdgesHelper( object, hex ) {
  25192. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25193. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25194. }
  25195. GridHelper.prototype.setColors = function () {
  25196. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25197. };
  25198. function WireframeHelper( object, hex ) {
  25199. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25200. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25201. }
  25202. //
  25203. function XHRLoader( manager ) {
  25204. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25205. return new FileLoader( manager );
  25206. }
  25207. function BinaryTextureLoader( manager ) {
  25208. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25209. return new DataTextureLoader( manager );
  25210. }
  25211. //
  25212. Object.assign( Box2.prototype, {
  25213. center: function ( optionalTarget ) {
  25214. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25215. return this.getCenter( optionalTarget );
  25216. },
  25217. empty: function () {
  25218. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25219. return this.isEmpty();
  25220. },
  25221. isIntersectionBox: function ( box ) {
  25222. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25223. return this.intersectsBox( box );
  25224. },
  25225. size: function ( optionalTarget ) {
  25226. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25227. return this.getSize( optionalTarget );
  25228. }
  25229. } );
  25230. Object.assign( Box3.prototype, {
  25231. center: function ( optionalTarget ) {
  25232. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25233. return this.getCenter( optionalTarget );
  25234. },
  25235. empty: function () {
  25236. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25237. return this.isEmpty();
  25238. },
  25239. isIntersectionBox: function ( box ) {
  25240. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25241. return this.intersectsBox( box );
  25242. },
  25243. isIntersectionSphere: function ( sphere ) {
  25244. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25245. return this.intersectsSphere( sphere );
  25246. },
  25247. size: function ( optionalTarget ) {
  25248. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25249. return this.getSize( optionalTarget );
  25250. }
  25251. } );
  25252. Line3.prototype.center = function ( optionalTarget ) {
  25253. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25254. return this.getCenter( optionalTarget );
  25255. };
  25256. _Math.random16 = function () {
  25257. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25258. return Math.random();
  25259. };
  25260. Object.assign( Matrix3.prototype, {
  25261. flattenToArrayOffset: function ( array, offset ) {
  25262. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25263. return this.toArray( array, offset );
  25264. },
  25265. multiplyVector3: function ( vector ) {
  25266. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25267. return vector.applyMatrix3( this );
  25268. },
  25269. multiplyVector3Array: function ( a ) {
  25270. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25271. return this.applyToVector3Array( a );
  25272. },
  25273. applyToBuffer: function( buffer, offset, length ) {
  25274. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25275. return this.applyToBufferAttribute( buffer );
  25276. },
  25277. applyToVector3Array: function( array, offset, length ) {
  25278. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25279. }
  25280. } );
  25281. Object.assign( Matrix4.prototype, {
  25282. extractPosition: function ( m ) {
  25283. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25284. return this.copyPosition( m );
  25285. },
  25286. flattenToArrayOffset: function ( array, offset ) {
  25287. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25288. return this.toArray( array, offset );
  25289. },
  25290. getPosition: function () {
  25291. var v1;
  25292. return function getPosition() {
  25293. if ( v1 === undefined ) v1 = new Vector3();
  25294. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25295. return v1.setFromMatrixColumn( this, 3 );
  25296. };
  25297. }(),
  25298. setRotationFromQuaternion: function ( q ) {
  25299. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25300. return this.makeRotationFromQuaternion( q );
  25301. },
  25302. multiplyToArray: function () {
  25303. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25304. },
  25305. multiplyVector3: function ( vector ) {
  25306. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25307. return vector.applyMatrix4( this );
  25308. },
  25309. multiplyVector4: function ( vector ) {
  25310. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25311. return vector.applyMatrix4( this );
  25312. },
  25313. multiplyVector3Array: function ( a ) {
  25314. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25315. return this.applyToVector3Array( a );
  25316. },
  25317. rotateAxis: function ( v ) {
  25318. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25319. v.transformDirection( this );
  25320. },
  25321. crossVector: function ( vector ) {
  25322. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25323. return vector.applyMatrix4( this );
  25324. },
  25325. translate: function () {
  25326. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25327. },
  25328. rotateX: function () {
  25329. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25330. },
  25331. rotateY: function () {
  25332. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25333. },
  25334. rotateZ: function () {
  25335. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25336. },
  25337. rotateByAxis: function () {
  25338. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25339. },
  25340. applyToBuffer: function( buffer, offset, length ) {
  25341. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25342. return this.applyToBufferAttribute( buffer );
  25343. },
  25344. applyToVector3Array: function( array, offset, length ) {
  25345. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25346. },
  25347. makeFrustum: function( left, right, bottom, top, near, far ) {
  25348. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25349. return this.makePerspective( left, right, top, bottom, near, far );
  25350. }
  25351. } );
  25352. Plane.prototype.isIntersectionLine = function ( line ) {
  25353. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25354. return this.intersectsLine( line );
  25355. };
  25356. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25357. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25358. return vector.applyQuaternion( this );
  25359. };
  25360. Object.assign( Ray.prototype, {
  25361. isIntersectionBox: function ( box ) {
  25362. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25363. return this.intersectsBox( box );
  25364. },
  25365. isIntersectionPlane: function ( plane ) {
  25366. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25367. return this.intersectsPlane( plane );
  25368. },
  25369. isIntersectionSphere: function ( sphere ) {
  25370. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25371. return this.intersectsSphere( sphere );
  25372. }
  25373. } );
  25374. Object.assign( Shape.prototype, {
  25375. extrude: function ( options ) {
  25376. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25377. return new ExtrudeGeometry( this, options );
  25378. },
  25379. makeGeometry: function ( options ) {
  25380. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25381. return new ShapeGeometry( this, options );
  25382. }
  25383. } );
  25384. Object.assign( Vector2.prototype, {
  25385. fromAttribute: function ( attribute, index, offset ) {
  25386. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25387. return this.fromBufferAttribute( attribute, index, offset );
  25388. }
  25389. } );
  25390. Object.assign( Vector3.prototype, {
  25391. setEulerFromRotationMatrix: function () {
  25392. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25393. },
  25394. setEulerFromQuaternion: function () {
  25395. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25396. },
  25397. getPositionFromMatrix: function ( m ) {
  25398. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25399. return this.setFromMatrixPosition( m );
  25400. },
  25401. getScaleFromMatrix: function ( m ) {
  25402. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25403. return this.setFromMatrixScale( m );
  25404. },
  25405. getColumnFromMatrix: function ( index, matrix ) {
  25406. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25407. return this.setFromMatrixColumn( matrix, index );
  25408. },
  25409. applyProjection: function ( m ) {
  25410. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25411. return this.applyMatrix4( m );
  25412. },
  25413. fromAttribute: function ( attribute, index, offset ) {
  25414. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25415. return this.fromBufferAttribute( attribute, index, offset );
  25416. }
  25417. } );
  25418. Object.assign( Vector4.prototype, {
  25419. fromAttribute: function ( attribute, index, offset ) {
  25420. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25421. return this.fromBufferAttribute( attribute, index, offset );
  25422. }
  25423. } );
  25424. //
  25425. Geometry.prototype.computeTangents = function () {
  25426. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25427. };
  25428. Object.assign( Object3D.prototype, {
  25429. getChildByName: function ( name ) {
  25430. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25431. return this.getObjectByName( name );
  25432. },
  25433. renderDepth: function () {
  25434. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25435. },
  25436. translate: function ( distance, axis ) {
  25437. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25438. return this.translateOnAxis( axis, distance );
  25439. }
  25440. } );
  25441. Object.defineProperties( Object3D.prototype, {
  25442. eulerOrder: {
  25443. get: function () {
  25444. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25445. return this.rotation.order;
  25446. },
  25447. set: function ( value ) {
  25448. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25449. this.rotation.order = value;
  25450. }
  25451. },
  25452. useQuaternion: {
  25453. get: function () {
  25454. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25455. },
  25456. set: function () {
  25457. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25458. }
  25459. }
  25460. } );
  25461. Object.defineProperties( LOD.prototype, {
  25462. objects: {
  25463. get: function () {
  25464. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25465. return this.levels;
  25466. }
  25467. }
  25468. } );
  25469. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25470. get: function () {
  25471. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25472. },
  25473. set: function () {
  25474. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25475. }
  25476. } );
  25477. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25478. get: function () {
  25479. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25480. return this.arcLengthDivisions;
  25481. },
  25482. set: function ( value ) {
  25483. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25484. this.arcLengthDivisions = value;
  25485. }
  25486. } );
  25487. //
  25488. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25489. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25490. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25491. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25492. this.setFocalLength( focalLength );
  25493. };
  25494. //
  25495. Object.defineProperties( Light.prototype, {
  25496. onlyShadow: {
  25497. set: function () {
  25498. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25499. }
  25500. },
  25501. shadowCameraFov: {
  25502. set: function ( value ) {
  25503. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25504. this.shadow.camera.fov = value;
  25505. }
  25506. },
  25507. shadowCameraLeft: {
  25508. set: function ( value ) {
  25509. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25510. this.shadow.camera.left = value;
  25511. }
  25512. },
  25513. shadowCameraRight: {
  25514. set: function ( value ) {
  25515. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25516. this.shadow.camera.right = value;
  25517. }
  25518. },
  25519. shadowCameraTop: {
  25520. set: function ( value ) {
  25521. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25522. this.shadow.camera.top = value;
  25523. }
  25524. },
  25525. shadowCameraBottom: {
  25526. set: function ( value ) {
  25527. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25528. this.shadow.camera.bottom = value;
  25529. }
  25530. },
  25531. shadowCameraNear: {
  25532. set: function ( value ) {
  25533. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25534. this.shadow.camera.near = value;
  25535. }
  25536. },
  25537. shadowCameraFar: {
  25538. set: function ( value ) {
  25539. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25540. this.shadow.camera.far = value;
  25541. }
  25542. },
  25543. shadowCameraVisible: {
  25544. set: function () {
  25545. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25546. }
  25547. },
  25548. shadowBias: {
  25549. set: function ( value ) {
  25550. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25551. this.shadow.bias = value;
  25552. }
  25553. },
  25554. shadowDarkness: {
  25555. set: function () {
  25556. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25557. }
  25558. },
  25559. shadowMapWidth: {
  25560. set: function ( value ) {
  25561. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25562. this.shadow.mapSize.width = value;
  25563. }
  25564. },
  25565. shadowMapHeight: {
  25566. set: function ( value ) {
  25567. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25568. this.shadow.mapSize.height = value;
  25569. }
  25570. }
  25571. } );
  25572. //
  25573. Object.defineProperties( BufferAttribute.prototype, {
  25574. length: {
  25575. get: function () {
  25576. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25577. return this.array.length;
  25578. }
  25579. }
  25580. } );
  25581. Object.assign( BufferGeometry.prototype, {
  25582. addIndex: function ( index ) {
  25583. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25584. this.setIndex( index );
  25585. },
  25586. addDrawCall: function ( start, count, indexOffset ) {
  25587. if ( indexOffset !== undefined ) {
  25588. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25589. }
  25590. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25591. this.addGroup( start, count );
  25592. },
  25593. clearDrawCalls: function () {
  25594. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25595. this.clearGroups();
  25596. },
  25597. computeTangents: function () {
  25598. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25599. },
  25600. computeOffsets: function () {
  25601. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25602. }
  25603. } );
  25604. Object.defineProperties( BufferGeometry.prototype, {
  25605. drawcalls: {
  25606. get: function () {
  25607. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25608. return this.groups;
  25609. }
  25610. },
  25611. offsets: {
  25612. get: function () {
  25613. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25614. return this.groups;
  25615. }
  25616. }
  25617. } );
  25618. //
  25619. Object.defineProperties( Uniform.prototype, {
  25620. dynamic: {
  25621. set: function () {
  25622. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25623. }
  25624. },
  25625. onUpdate: {
  25626. value: function () {
  25627. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25628. return this;
  25629. }
  25630. }
  25631. } );
  25632. //
  25633. Object.defineProperties( Material.prototype, {
  25634. wrapAround: {
  25635. get: function () {
  25636. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25637. },
  25638. set: function () {
  25639. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25640. }
  25641. },
  25642. wrapRGB: {
  25643. get: function () {
  25644. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  25645. return new Color();
  25646. }
  25647. }
  25648. } );
  25649. Object.defineProperties( MeshPhongMaterial.prototype, {
  25650. metal: {
  25651. get: function () {
  25652. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25653. return false;
  25654. },
  25655. set: function () {
  25656. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25657. }
  25658. }
  25659. } );
  25660. Object.defineProperties( ShaderMaterial.prototype, {
  25661. derivatives: {
  25662. get: function () {
  25663. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25664. return this.extensions.derivatives;
  25665. },
  25666. set: function ( value ) {
  25667. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25668. this.extensions.derivatives = value;
  25669. }
  25670. }
  25671. } );
  25672. //
  25673. Object.assign( WebGLRenderer.prototype, {
  25674. getCurrentRenderTarget: function () {
  25675. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  25676. return this.getRenderTarget();
  25677. },
  25678. supportsFloatTextures: function () {
  25679. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25680. return this.extensions.get( 'OES_texture_float' );
  25681. },
  25682. supportsHalfFloatTextures: function () {
  25683. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25684. return this.extensions.get( 'OES_texture_half_float' );
  25685. },
  25686. supportsStandardDerivatives: function () {
  25687. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25688. return this.extensions.get( 'OES_standard_derivatives' );
  25689. },
  25690. supportsCompressedTextureS3TC: function () {
  25691. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25692. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25693. },
  25694. supportsCompressedTexturePVRTC: function () {
  25695. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25696. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25697. },
  25698. supportsBlendMinMax: function () {
  25699. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25700. return this.extensions.get( 'EXT_blend_minmax' );
  25701. },
  25702. supportsVertexTextures: function () {
  25703. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25704. return this.capabilities.vertexTextures;
  25705. },
  25706. supportsInstancedArrays: function () {
  25707. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25708. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25709. },
  25710. enableScissorTest: function ( boolean ) {
  25711. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25712. this.setScissorTest( boolean );
  25713. },
  25714. initMaterial: function () {
  25715. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25716. },
  25717. addPrePlugin: function () {
  25718. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25719. },
  25720. addPostPlugin: function () {
  25721. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25722. },
  25723. updateShadowMap: function () {
  25724. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25725. }
  25726. } );
  25727. Object.defineProperties( WebGLRenderer.prototype, {
  25728. shadowMapEnabled: {
  25729. get: function () {
  25730. return this.shadowMap.enabled;
  25731. },
  25732. set: function ( value ) {
  25733. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25734. this.shadowMap.enabled = value;
  25735. }
  25736. },
  25737. shadowMapType: {
  25738. get: function () {
  25739. return this.shadowMap.type;
  25740. },
  25741. set: function ( value ) {
  25742. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25743. this.shadowMap.type = value;
  25744. }
  25745. },
  25746. shadowMapCullFace: {
  25747. get: function () {
  25748. return this.shadowMap.cullFace;
  25749. },
  25750. set: function ( value ) {
  25751. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25752. this.shadowMap.cullFace = value;
  25753. }
  25754. }
  25755. } );
  25756. Object.defineProperties( WebGLShadowMap.prototype, {
  25757. cullFace: {
  25758. get: function () {
  25759. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25760. },
  25761. set: function ( cullFace ) {
  25762. var value = ( cullFace !== CullFaceBack );
  25763. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25764. this.renderReverseSided = value;
  25765. }
  25766. }
  25767. } );
  25768. //
  25769. Object.defineProperties( WebGLRenderTarget.prototype, {
  25770. wrapS: {
  25771. get: function () {
  25772. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25773. return this.texture.wrapS;
  25774. },
  25775. set: function ( value ) {
  25776. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25777. this.texture.wrapS = value;
  25778. }
  25779. },
  25780. wrapT: {
  25781. get: function () {
  25782. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25783. return this.texture.wrapT;
  25784. },
  25785. set: function ( value ) {
  25786. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25787. this.texture.wrapT = value;
  25788. }
  25789. },
  25790. magFilter: {
  25791. get: function () {
  25792. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25793. return this.texture.magFilter;
  25794. },
  25795. set: function ( value ) {
  25796. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25797. this.texture.magFilter = value;
  25798. }
  25799. },
  25800. minFilter: {
  25801. get: function () {
  25802. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25803. return this.texture.minFilter;
  25804. },
  25805. set: function ( value ) {
  25806. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25807. this.texture.minFilter = value;
  25808. }
  25809. },
  25810. anisotropy: {
  25811. get: function () {
  25812. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25813. return this.texture.anisotropy;
  25814. },
  25815. set: function ( value ) {
  25816. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25817. this.texture.anisotropy = value;
  25818. }
  25819. },
  25820. offset: {
  25821. get: function () {
  25822. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25823. return this.texture.offset;
  25824. },
  25825. set: function ( value ) {
  25826. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25827. this.texture.offset = value;
  25828. }
  25829. },
  25830. repeat: {
  25831. get: function () {
  25832. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25833. return this.texture.repeat;
  25834. },
  25835. set: function ( value ) {
  25836. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25837. this.texture.repeat = value;
  25838. }
  25839. },
  25840. format: {
  25841. get: function () {
  25842. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25843. return this.texture.format;
  25844. },
  25845. set: function ( value ) {
  25846. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25847. this.texture.format = value;
  25848. }
  25849. },
  25850. type: {
  25851. get: function () {
  25852. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25853. return this.texture.type;
  25854. },
  25855. set: function ( value ) {
  25856. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25857. this.texture.type = value;
  25858. }
  25859. },
  25860. generateMipmaps: {
  25861. get: function () {
  25862. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25863. return this.texture.generateMipmaps;
  25864. },
  25865. set: function ( value ) {
  25866. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25867. this.texture.generateMipmaps = value;
  25868. }
  25869. }
  25870. } );
  25871. //
  25872. Audio.prototype.load = function ( file ) {
  25873. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25874. var scope = this;
  25875. var audioLoader = new AudioLoader();
  25876. audioLoader.load( file, function ( buffer ) {
  25877. scope.setBuffer( buffer );
  25878. } );
  25879. return this;
  25880. };
  25881. AudioAnalyser.prototype.getData = function () {
  25882. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25883. return this.getFrequencyData();
  25884. };
  25885. //
  25886. var GeometryUtils = {
  25887. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25888. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25889. var matrix;
  25890. if ( geometry2.isMesh ) {
  25891. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25892. matrix = geometry2.matrix;
  25893. geometry2 = geometry2.geometry;
  25894. }
  25895. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25896. },
  25897. center: function ( geometry ) {
  25898. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25899. return geometry.center();
  25900. }
  25901. };
  25902. var ImageUtils = {
  25903. crossOrigin: undefined,
  25904. loadTexture: function ( url, mapping, onLoad, onError ) {
  25905. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25906. var loader = new TextureLoader();
  25907. loader.setCrossOrigin( this.crossOrigin );
  25908. var texture = loader.load( url, onLoad, undefined, onError );
  25909. if ( mapping ) texture.mapping = mapping;
  25910. return texture;
  25911. },
  25912. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25913. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25914. var loader = new CubeTextureLoader();
  25915. loader.setCrossOrigin( this.crossOrigin );
  25916. var texture = loader.load( urls, onLoad, undefined, onError );
  25917. if ( mapping ) texture.mapping = mapping;
  25918. return texture;
  25919. },
  25920. loadCompressedTexture: function () {
  25921. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25922. },
  25923. loadCompressedTextureCube: function () {
  25924. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25925. }
  25926. };
  25927. //
  25928. function Projector() {
  25929. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25930. this.projectVector = function ( vector, camera ) {
  25931. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25932. vector.project( camera );
  25933. };
  25934. this.unprojectVector = function ( vector, camera ) {
  25935. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25936. vector.unproject( camera );
  25937. };
  25938. this.pickingRay = function () {
  25939. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25940. };
  25941. }
  25942. //
  25943. function CanvasRenderer() {
  25944. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25945. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25946. this.clear = function () {};
  25947. this.render = function () {};
  25948. this.setClearColor = function () {};
  25949. this.setSize = function () {};
  25950. }
  25951. 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 };