three.module.js 988 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018
  1. // Polyfills
  2. if ( Number.EPSILON === undefined ) {
  3. Number.EPSILON = Math.pow( 2, - 52 );
  4. }
  5. if ( Number.isInteger === undefined ) {
  6. // Missing in IE
  7. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  8. Number.isInteger = function ( value ) {
  9. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  10. };
  11. }
  12. //
  13. if ( Math.sign === undefined ) {
  14. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  15. Math.sign = function ( x ) {
  16. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  17. };
  18. }
  19. if ( Function.prototype.name === undefined ) {
  20. // Missing in IE
  21. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  22. Object.defineProperty( Function.prototype, 'name', {
  23. get: function () {
  24. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  25. }
  26. } );
  27. }
  28. if ( Object.assign === undefined ) {
  29. // Missing in IE
  30. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  31. ( function () {
  32. Object.assign = function ( target ) {
  33. 'use strict';
  34. if ( target === undefined || target === null ) {
  35. throw new TypeError( 'Cannot convert undefined or null to object' );
  36. }
  37. var output = Object( target );
  38. for ( var index = 1; index < arguments.length; index ++ ) {
  39. var source = arguments[ index ];
  40. if ( source !== undefined && source !== null ) {
  41. for ( var nextKey in source ) {
  42. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  43. output[ nextKey ] = source[ nextKey ];
  44. }
  45. }
  46. }
  47. }
  48. return output;
  49. };
  50. } )();
  51. }
  52. /**
  53. * https://github.com/mrdoob/eventdispatcher.js/
  54. */
  55. function EventDispatcher() {}
  56. Object.assign( EventDispatcher.prototype, {
  57. addEventListener: function ( type, listener ) {
  58. if ( this._listeners === undefined ) this._listeners = {};
  59. var listeners = this._listeners;
  60. if ( listeners[ type ] === undefined ) {
  61. listeners[ type ] = [];
  62. }
  63. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  64. listeners[ type ].push( listener );
  65. }
  66. },
  67. hasEventListener: function ( type, listener ) {
  68. if ( this._listeners === undefined ) return false;
  69. var listeners = this._listeners;
  70. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  71. },
  72. removeEventListener: function ( type, listener ) {
  73. if ( this._listeners === undefined ) return;
  74. var listeners = this._listeners;
  75. var listenerArray = listeners[ type ];
  76. if ( listenerArray !== undefined ) {
  77. var index = listenerArray.indexOf( listener );
  78. if ( index !== - 1 ) {
  79. listenerArray.splice( index, 1 );
  80. }
  81. }
  82. },
  83. dispatchEvent: function ( event ) {
  84. if ( this._listeners === undefined ) return;
  85. var listeners = this._listeners;
  86. var listenerArray = listeners[ event.type ];
  87. if ( listenerArray !== undefined ) {
  88. event.target = this;
  89. var array = listenerArray.slice( 0 );
  90. for ( var i = 0, l = array.length; i < l; i ++ ) {
  91. array[ i ].call( this, event );
  92. }
  93. }
  94. }
  95. } );
  96. var REVISION = '87dev';
  97. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  98. var CullFaceNone = 0;
  99. var CullFaceBack = 1;
  100. var CullFaceFront = 2;
  101. var CullFaceFrontBack = 3;
  102. var FrontFaceDirectionCW = 0;
  103. var FrontFaceDirectionCCW = 1;
  104. var BasicShadowMap = 0;
  105. var PCFShadowMap = 1;
  106. var PCFSoftShadowMap = 2;
  107. var FrontSide = 0;
  108. var BackSide = 1;
  109. var DoubleSide = 2;
  110. var FlatShading = 1;
  111. var SmoothShading = 2;
  112. var NoColors = 0;
  113. var FaceColors = 1;
  114. var VertexColors = 2;
  115. var NoBlending = 0;
  116. var NormalBlending = 1;
  117. var AdditiveBlending = 2;
  118. var SubtractiveBlending = 3;
  119. var MultiplyBlending = 4;
  120. var CustomBlending = 5;
  121. var AddEquation = 100;
  122. var SubtractEquation = 101;
  123. var ReverseSubtractEquation = 102;
  124. var MinEquation = 103;
  125. var MaxEquation = 104;
  126. var ZeroFactor = 200;
  127. var OneFactor = 201;
  128. var SrcColorFactor = 202;
  129. var OneMinusSrcColorFactor = 203;
  130. var SrcAlphaFactor = 204;
  131. var OneMinusSrcAlphaFactor = 205;
  132. var DstAlphaFactor = 206;
  133. var OneMinusDstAlphaFactor = 207;
  134. var DstColorFactor = 208;
  135. var OneMinusDstColorFactor = 209;
  136. var SrcAlphaSaturateFactor = 210;
  137. var NeverDepth = 0;
  138. var AlwaysDepth = 1;
  139. var LessDepth = 2;
  140. var LessEqualDepth = 3;
  141. var EqualDepth = 4;
  142. var GreaterEqualDepth = 5;
  143. var GreaterDepth = 6;
  144. var NotEqualDepth = 7;
  145. var MultiplyOperation = 0;
  146. var MixOperation = 1;
  147. var AddOperation = 2;
  148. var NoToneMapping = 0;
  149. var LinearToneMapping = 1;
  150. var ReinhardToneMapping = 2;
  151. var Uncharted2ToneMapping = 3;
  152. var CineonToneMapping = 4;
  153. var UVMapping = 300;
  154. var CubeReflectionMapping = 301;
  155. var CubeRefractionMapping = 302;
  156. var EquirectangularReflectionMapping = 303;
  157. var EquirectangularRefractionMapping = 304;
  158. var SphericalReflectionMapping = 305;
  159. var CubeUVReflectionMapping = 306;
  160. var CubeUVRefractionMapping = 307;
  161. var RepeatWrapping = 1000;
  162. var ClampToEdgeWrapping = 1001;
  163. var MirroredRepeatWrapping = 1002;
  164. var NearestFilter = 1003;
  165. var NearestMipMapNearestFilter = 1004;
  166. var NearestMipMapLinearFilter = 1005;
  167. var LinearFilter = 1006;
  168. var LinearMipMapNearestFilter = 1007;
  169. var LinearMipMapLinearFilter = 1008;
  170. var UnsignedByteType = 1009;
  171. var ByteType = 1010;
  172. var ShortType = 1011;
  173. var UnsignedShortType = 1012;
  174. var IntType = 1013;
  175. var UnsignedIntType = 1014;
  176. var FloatType = 1015;
  177. var HalfFloatType = 1016;
  178. var UnsignedShort4444Type = 1017;
  179. var UnsignedShort5551Type = 1018;
  180. var UnsignedShort565Type = 1019;
  181. var UnsignedInt248Type = 1020;
  182. var AlphaFormat = 1021;
  183. var RGBFormat = 1022;
  184. var RGBAFormat = 1023;
  185. var LuminanceFormat = 1024;
  186. var LuminanceAlphaFormat = 1025;
  187. var RGBEFormat = RGBAFormat;
  188. var DepthFormat = 1026;
  189. var DepthStencilFormat = 1027;
  190. var RGB_S3TC_DXT1_Format = 2001;
  191. var RGBA_S3TC_DXT1_Format = 2002;
  192. var RGBA_S3TC_DXT3_Format = 2003;
  193. var RGBA_S3TC_DXT5_Format = 2004;
  194. var RGB_PVRTC_4BPPV1_Format = 2100;
  195. var RGB_PVRTC_2BPPV1_Format = 2101;
  196. var RGBA_PVRTC_4BPPV1_Format = 2102;
  197. var RGBA_PVRTC_2BPPV1_Format = 2103;
  198. var RGB_ETC1_Format = 2151;
  199. var LoopOnce = 2200;
  200. var LoopRepeat = 2201;
  201. var LoopPingPong = 2202;
  202. var InterpolateDiscrete = 2300;
  203. var InterpolateLinear = 2301;
  204. var InterpolateSmooth = 2302;
  205. var ZeroCurvatureEnding = 2400;
  206. var ZeroSlopeEnding = 2401;
  207. var WrapAroundEnding = 2402;
  208. var TrianglesDrawMode = 0;
  209. var TriangleStripDrawMode = 1;
  210. var TriangleFanDrawMode = 2;
  211. var LinearEncoding = 3000;
  212. var sRGBEncoding = 3001;
  213. var GammaEncoding = 3007;
  214. var RGBEEncoding = 3002;
  215. var LogLuvEncoding = 3003;
  216. var RGBM7Encoding = 3004;
  217. var RGBM16Encoding = 3005;
  218. var RGBDEncoding = 3006;
  219. var BasicDepthPacking = 3200;
  220. var RGBADepthPacking = 3201;
  221. /**
  222. * @author alteredq / http://alteredqualia.com/
  223. * @author mrdoob / http://mrdoob.com/
  224. */
  225. var _Math = {
  226. DEG2RAD: Math.PI / 180,
  227. RAD2DEG: 180 / Math.PI,
  228. generateUUID: function () {
  229. // http://www.broofa.com/Tools/Math.uuid.htm
  230. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  231. var uuid = new Array( 36 );
  232. var rnd = 0, r;
  233. return function generateUUID() {
  234. for ( var i = 0; i < 36; i ++ ) {
  235. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  236. uuid[ i ] = '-';
  237. } else if ( i === 14 ) {
  238. uuid[ i ] = '4';
  239. } else {
  240. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  241. r = rnd & 0xf;
  242. rnd = rnd >> 4;
  243. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  244. }
  245. }
  246. return uuid.join( '' );
  247. };
  248. }(),
  249. clamp: function ( value, min, max ) {
  250. return Math.max( min, Math.min( max, value ) );
  251. },
  252. // compute euclidian modulo of m % n
  253. // https://en.wikipedia.org/wiki/Modulo_operation
  254. euclideanModulo: function ( n, m ) {
  255. return ( ( n % m ) + m ) % m;
  256. },
  257. // Linear mapping from range <a1, a2> to range <b1, b2>
  258. mapLinear: function ( x, a1, a2, b1, b2 ) {
  259. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  260. },
  261. // https://en.wikipedia.org/wiki/Linear_interpolation
  262. lerp: function ( x, y, t ) {
  263. return ( 1 - t ) * x + t * y;
  264. },
  265. // http://en.wikipedia.org/wiki/Smoothstep
  266. smoothstep: function ( x, min, max ) {
  267. if ( x <= min ) return 0;
  268. if ( x >= max ) return 1;
  269. x = ( x - min ) / ( max - min );
  270. return x * x * ( 3 - 2 * x );
  271. },
  272. smootherstep: function ( x, min, max ) {
  273. if ( x <= min ) return 0;
  274. if ( x >= max ) return 1;
  275. x = ( x - min ) / ( max - min );
  276. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  277. },
  278. // Random integer from <low, high> interval
  279. randInt: function ( low, high ) {
  280. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  281. },
  282. // Random float from <low, high> interval
  283. randFloat: function ( low, high ) {
  284. return low + Math.random() * ( high - low );
  285. },
  286. // Random float from <-range/2, range/2> interval
  287. randFloatSpread: function ( range ) {
  288. return range * ( 0.5 - Math.random() );
  289. },
  290. degToRad: function ( degrees ) {
  291. return degrees * _Math.DEG2RAD;
  292. },
  293. radToDeg: function ( radians ) {
  294. return radians * _Math.RAD2DEG;
  295. },
  296. isPowerOfTwo: function ( value ) {
  297. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  298. },
  299. nearestPowerOfTwo: function ( value ) {
  300. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  301. },
  302. nextPowerOfTwo: function ( value ) {
  303. value --;
  304. value |= value >> 1;
  305. value |= value >> 2;
  306. value |= value >> 4;
  307. value |= value >> 8;
  308. value |= value >> 16;
  309. value ++;
  310. return value;
  311. }
  312. };
  313. /**
  314. * @author mrdoob / http://mrdoob.com/
  315. * @author philogb / http://blog.thejit.org/
  316. * @author egraether / http://egraether.com/
  317. * @author zz85 / http://www.lab4games.net/zz85/blog
  318. */
  319. function Vector2( x, y ) {
  320. this.x = x || 0;
  321. this.y = y || 0;
  322. }
  323. Object.defineProperties( Vector2.prototype, {
  324. "width" : {
  325. get: function () {
  326. return this.x;
  327. },
  328. set: function ( value ) {
  329. this.x = value;
  330. }
  331. },
  332. "height" : {
  333. get: function () {
  334. return this.y;
  335. },
  336. set: function ( value ) {
  337. this.y = value;
  338. }
  339. }
  340. } );
  341. Object.assign( Vector2.prototype, {
  342. isVector2: true,
  343. set: function ( x, y ) {
  344. this.x = x;
  345. this.y = y;
  346. return this;
  347. },
  348. setScalar: function ( scalar ) {
  349. this.x = scalar;
  350. this.y = scalar;
  351. return this;
  352. },
  353. setX: function ( x ) {
  354. this.x = x;
  355. return this;
  356. },
  357. setY: function ( y ) {
  358. this.y = y;
  359. return this;
  360. },
  361. setComponent: function ( index, value ) {
  362. switch ( index ) {
  363. case 0: this.x = value; break;
  364. case 1: this.y = value; break;
  365. default: throw new Error( 'index is out of range: ' + index );
  366. }
  367. return this;
  368. },
  369. getComponent: function ( index ) {
  370. switch ( index ) {
  371. case 0: return this.x;
  372. case 1: return this.y;
  373. default: throw new Error( 'index is out of range: ' + index );
  374. }
  375. },
  376. clone: function () {
  377. return new this.constructor( this.x, this.y );
  378. },
  379. copy: function ( v ) {
  380. this.x = v.x;
  381. this.y = v.y;
  382. return this;
  383. },
  384. add: function ( v, w ) {
  385. if ( w !== undefined ) {
  386. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  387. return this.addVectors( v, w );
  388. }
  389. this.x += v.x;
  390. this.y += v.y;
  391. return this;
  392. },
  393. addScalar: function ( s ) {
  394. this.x += s;
  395. this.y += s;
  396. return this;
  397. },
  398. addVectors: function ( a, b ) {
  399. this.x = a.x + b.x;
  400. this.y = a.y + b.y;
  401. return this;
  402. },
  403. addScaledVector: function ( v, s ) {
  404. this.x += v.x * s;
  405. this.y += v.y * s;
  406. return this;
  407. },
  408. sub: function ( v, w ) {
  409. if ( w !== undefined ) {
  410. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  411. return this.subVectors( v, w );
  412. }
  413. this.x -= v.x;
  414. this.y -= v.y;
  415. return this;
  416. },
  417. subScalar: function ( s ) {
  418. this.x -= s;
  419. this.y -= s;
  420. return this;
  421. },
  422. subVectors: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. multiply: function ( v ) {
  428. this.x *= v.x;
  429. this.y *= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( scalar ) {
  433. this.x *= scalar;
  434. this.y *= scalar;
  435. return this;
  436. },
  437. divide: function ( v ) {
  438. this.x /= v.x;
  439. this.y /= v.y;
  440. return this;
  441. },
  442. divideScalar: function ( scalar ) {
  443. return this.multiplyScalar( 1 / scalar );
  444. },
  445. min: function ( v ) {
  446. this.x = Math.min( this.x, v.x );
  447. this.y = Math.min( this.y, v.y );
  448. return this;
  449. },
  450. max: function ( v ) {
  451. this.x = Math.max( this.x, v.x );
  452. this.y = Math.max( this.y, v.y );
  453. return this;
  454. },
  455. clamp: function ( min, max ) {
  456. // assumes min < max, componentwise
  457. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  458. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  459. return this;
  460. },
  461. clampScalar: function () {
  462. var min = new Vector2();
  463. var max = new Vector2();
  464. return function clampScalar( minVal, maxVal ) {
  465. min.set( minVal, minVal );
  466. max.set( maxVal, maxVal );
  467. return this.clamp( min, max );
  468. };
  469. }(),
  470. clampLength: function ( min, max ) {
  471. var length = this.length();
  472. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  473. },
  474. floor: function () {
  475. this.x = Math.floor( this.x );
  476. this.y = Math.floor( this.y );
  477. return this;
  478. },
  479. ceil: function () {
  480. this.x = Math.ceil( this.x );
  481. this.y = Math.ceil( this.y );
  482. return this;
  483. },
  484. round: function () {
  485. this.x = Math.round( this.x );
  486. this.y = Math.round( this.y );
  487. return this;
  488. },
  489. roundToZero: function () {
  490. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  491. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  492. return this;
  493. },
  494. negate: function () {
  495. this.x = - this.x;
  496. this.y = - this.y;
  497. return this;
  498. },
  499. dot: function ( v ) {
  500. return this.x * v.x + this.y * v.y;
  501. },
  502. lengthSq: function () {
  503. return this.x * this.x + this.y * this.y;
  504. },
  505. length: function () {
  506. return Math.sqrt( this.x * this.x + this.y * this.y );
  507. },
  508. lengthManhattan: function() {
  509. return Math.abs( this.x ) + Math.abs( this.y );
  510. },
  511. normalize: function () {
  512. return this.divideScalar( this.length() || 1 );
  513. },
  514. angle: function () {
  515. // computes the angle in radians with respect to the positive x-axis
  516. var angle = Math.atan2( this.y, this.x );
  517. if ( angle < 0 ) angle += 2 * Math.PI;
  518. return angle;
  519. },
  520. distanceTo: function ( v ) {
  521. return Math.sqrt( this.distanceToSquared( v ) );
  522. },
  523. distanceToSquared: function ( v ) {
  524. var dx = this.x - v.x, dy = this.y - v.y;
  525. return dx * dx + dy * dy;
  526. },
  527. distanceToManhattan: function ( v ) {
  528. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  529. },
  530. setLength: function ( length ) {
  531. return this.normalize().multiplyScalar( length );
  532. },
  533. lerp: function ( v, alpha ) {
  534. this.x += ( v.x - this.x ) * alpha;
  535. this.y += ( v.y - this.y ) * alpha;
  536. return this;
  537. },
  538. lerpVectors: function ( v1, v2, alpha ) {
  539. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  540. },
  541. equals: function ( v ) {
  542. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  543. },
  544. fromArray: function ( array, offset ) {
  545. if ( offset === undefined ) offset = 0;
  546. this.x = array[ offset ];
  547. this.y = array[ offset + 1 ];
  548. return this;
  549. },
  550. toArray: function ( array, offset ) {
  551. if ( array === undefined ) array = [];
  552. if ( offset === undefined ) offset = 0;
  553. array[ offset ] = this.x;
  554. array[ offset + 1 ] = this.y;
  555. return array;
  556. },
  557. fromBufferAttribute: function ( attribute, index, offset ) {
  558. if ( offset !== undefined ) {
  559. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  560. }
  561. this.x = attribute.getX( index );
  562. this.y = attribute.getY( index );
  563. return this;
  564. },
  565. rotateAround: function ( center, angle ) {
  566. var c = Math.cos( angle ), s = Math.sin( angle );
  567. var x = this.x - center.x;
  568. var y = this.y - center.y;
  569. this.x = x * c - y * s + center.x;
  570. this.y = x * s + y * c + center.y;
  571. return this;
  572. }
  573. } );
  574. /**
  575. * @author mrdoob / http://mrdoob.com/
  576. * @author alteredq / http://alteredqualia.com/
  577. * @author szimek / https://github.com/szimek/
  578. */
  579. var textureId = 0;
  580. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  581. Object.defineProperty( this, 'id', { value: textureId ++ } );
  582. this.uuid = _Math.generateUUID();
  583. this.name = '';
  584. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  585. this.mipmaps = [];
  586. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  587. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  588. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  589. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  590. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  591. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  592. this.format = format !== undefined ? format : RGBAFormat;
  593. this.type = type !== undefined ? type : UnsignedByteType;
  594. this.offset = new Vector2( 0, 0 );
  595. this.repeat = new Vector2( 1, 1 );
  596. this.generateMipmaps = true;
  597. this.premultiplyAlpha = false;
  598. this.flipY = true;
  599. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  600. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  601. //
  602. // Also changing the encoding after already used by a Material will not automatically make the Material
  603. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  604. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  605. this.version = 0;
  606. this.onUpdate = null;
  607. }
  608. Texture.DEFAULT_IMAGE = undefined;
  609. Texture.DEFAULT_MAPPING = UVMapping;
  610. Object.defineProperty( Texture.prototype, "needsUpdate", {
  611. set: function ( value ) {
  612. if ( value === true ) this.version ++;
  613. }
  614. } );
  615. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  616. constructor: Texture,
  617. isTexture: true,
  618. clone: function () {
  619. return new this.constructor().copy( this );
  620. },
  621. copy: function ( source ) {
  622. this.name = source.name;
  623. this.image = source.image;
  624. this.mipmaps = source.mipmaps.slice( 0 );
  625. this.mapping = source.mapping;
  626. this.wrapS = source.wrapS;
  627. this.wrapT = source.wrapT;
  628. this.magFilter = source.magFilter;
  629. this.minFilter = source.minFilter;
  630. this.anisotropy = source.anisotropy;
  631. this.format = source.format;
  632. this.type = source.type;
  633. this.offset.copy( source.offset );
  634. this.repeat.copy( source.repeat );
  635. this.generateMipmaps = source.generateMipmaps;
  636. this.premultiplyAlpha = source.premultiplyAlpha;
  637. this.flipY = source.flipY;
  638. this.unpackAlignment = source.unpackAlignment;
  639. this.encoding = source.encoding;
  640. return this;
  641. },
  642. toJSON: function ( meta ) {
  643. if ( meta.textures[ this.uuid ] !== undefined ) {
  644. return meta.textures[ this.uuid ];
  645. }
  646. function getDataURL( image ) {
  647. var canvas;
  648. if ( image.toDataURL !== undefined ) {
  649. canvas = image;
  650. } else {
  651. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  652. canvas.width = image.width;
  653. canvas.height = image.height;
  654. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  655. }
  656. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  657. return canvas.toDataURL( 'image/jpeg', 0.6 );
  658. } else {
  659. return canvas.toDataURL( 'image/png' );
  660. }
  661. }
  662. var output = {
  663. metadata: {
  664. version: 4.5,
  665. type: 'Texture',
  666. generator: 'Texture.toJSON'
  667. },
  668. uuid: this.uuid,
  669. name: this.name,
  670. mapping: this.mapping,
  671. repeat: [ this.repeat.x, this.repeat.y ],
  672. offset: [ this.offset.x, this.offset.y ],
  673. wrap: [ this.wrapS, this.wrapT ],
  674. minFilter: this.minFilter,
  675. magFilter: this.magFilter,
  676. anisotropy: this.anisotropy,
  677. flipY: this.flipY
  678. };
  679. if ( this.image !== undefined ) {
  680. // TODO: Move to THREE.Image
  681. var image = this.image;
  682. if ( image.uuid === undefined ) {
  683. image.uuid = _Math.generateUUID(); // UGH
  684. }
  685. if ( meta.images[ image.uuid ] === undefined ) {
  686. meta.images[ image.uuid ] = {
  687. uuid: image.uuid,
  688. url: getDataURL( image )
  689. };
  690. }
  691. output.image = image.uuid;
  692. }
  693. meta.textures[ this.uuid ] = output;
  694. return output;
  695. },
  696. dispose: function () {
  697. this.dispatchEvent( { type: 'dispose' } );
  698. },
  699. transformUv: function ( uv ) {
  700. if ( this.mapping !== UVMapping ) return;
  701. uv.multiply( this.repeat );
  702. uv.add( this.offset );
  703. if ( uv.x < 0 || uv.x > 1 ) {
  704. switch ( this.wrapS ) {
  705. case RepeatWrapping:
  706. uv.x = uv.x - Math.floor( uv.x );
  707. break;
  708. case ClampToEdgeWrapping:
  709. uv.x = uv.x < 0 ? 0 : 1;
  710. break;
  711. case MirroredRepeatWrapping:
  712. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  713. uv.x = Math.ceil( uv.x ) - uv.x;
  714. } else {
  715. uv.x = uv.x - Math.floor( uv.x );
  716. }
  717. break;
  718. }
  719. }
  720. if ( uv.y < 0 || uv.y > 1 ) {
  721. switch ( this.wrapT ) {
  722. case RepeatWrapping:
  723. uv.y = uv.y - Math.floor( uv.y );
  724. break;
  725. case ClampToEdgeWrapping:
  726. uv.y = uv.y < 0 ? 0 : 1;
  727. break;
  728. case MirroredRepeatWrapping:
  729. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  730. uv.y = Math.ceil( uv.y ) - uv.y;
  731. } else {
  732. uv.y = uv.y - Math.floor( uv.y );
  733. }
  734. break;
  735. }
  736. }
  737. if ( this.flipY ) {
  738. uv.y = 1 - uv.y;
  739. }
  740. }
  741. } );
  742. /**
  743. * @author supereggbert / http://www.paulbrunt.co.uk/
  744. * @author philogb / http://blog.thejit.org/
  745. * @author mikael emtinger / http://gomo.se/
  746. * @author egraether / http://egraether.com/
  747. * @author WestLangley / http://github.com/WestLangley
  748. */
  749. function Vector4( x, y, z, w ) {
  750. this.x = x || 0;
  751. this.y = y || 0;
  752. this.z = z || 0;
  753. this.w = ( w !== undefined ) ? w : 1;
  754. }
  755. Object.assign( Vector4.prototype, {
  756. isVector4: true,
  757. set: function ( x, y, z, w ) {
  758. this.x = x;
  759. this.y = y;
  760. this.z = z;
  761. this.w = w;
  762. return this;
  763. },
  764. setScalar: function ( scalar ) {
  765. this.x = scalar;
  766. this.y = scalar;
  767. this.z = scalar;
  768. this.w = scalar;
  769. return this;
  770. },
  771. setX: function ( x ) {
  772. this.x = x;
  773. return this;
  774. },
  775. setY: function ( y ) {
  776. this.y = y;
  777. return this;
  778. },
  779. setZ: function ( z ) {
  780. this.z = z;
  781. return this;
  782. },
  783. setW: function ( w ) {
  784. this.w = w;
  785. return this;
  786. },
  787. setComponent: function ( index, value ) {
  788. switch ( index ) {
  789. case 0: this.x = value; break;
  790. case 1: this.y = value; break;
  791. case 2: this.z = value; break;
  792. case 3: this.w = value; break;
  793. default: throw new Error( 'index is out of range: ' + index );
  794. }
  795. return this;
  796. },
  797. getComponent: function ( index ) {
  798. switch ( index ) {
  799. case 0: return this.x;
  800. case 1: return this.y;
  801. case 2: return this.z;
  802. case 3: return this.w;
  803. default: throw new Error( 'index is out of range: ' + index );
  804. }
  805. },
  806. clone: function () {
  807. return new this.constructor( this.x, this.y, this.z, this.w );
  808. },
  809. copy: function ( v ) {
  810. this.x = v.x;
  811. this.y = v.y;
  812. this.z = v.z;
  813. this.w = ( v.w !== undefined ) ? v.w : 1;
  814. return this;
  815. },
  816. add: function ( v, w ) {
  817. if ( w !== undefined ) {
  818. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  819. return this.addVectors( v, w );
  820. }
  821. this.x += v.x;
  822. this.y += v.y;
  823. this.z += v.z;
  824. this.w += v.w;
  825. return this;
  826. },
  827. addScalar: function ( s ) {
  828. this.x += s;
  829. this.y += s;
  830. this.z += s;
  831. this.w += s;
  832. return this;
  833. },
  834. addVectors: function ( a, b ) {
  835. this.x = a.x + b.x;
  836. this.y = a.y + b.y;
  837. this.z = a.z + b.z;
  838. this.w = a.w + b.w;
  839. return this;
  840. },
  841. addScaledVector: function ( v, s ) {
  842. this.x += v.x * s;
  843. this.y += v.y * s;
  844. this.z += v.z * s;
  845. this.w += v.w * s;
  846. return this;
  847. },
  848. sub: function ( v, w ) {
  849. if ( w !== undefined ) {
  850. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  851. return this.subVectors( v, w );
  852. }
  853. this.x -= v.x;
  854. this.y -= v.y;
  855. this.z -= v.z;
  856. this.w -= v.w;
  857. return this;
  858. },
  859. subScalar: function ( s ) {
  860. this.x -= s;
  861. this.y -= s;
  862. this.z -= s;
  863. this.w -= s;
  864. return this;
  865. },
  866. subVectors: function ( a, b ) {
  867. this.x = a.x - b.x;
  868. this.y = a.y - b.y;
  869. this.z = a.z - b.z;
  870. this.w = a.w - b.w;
  871. return this;
  872. },
  873. multiplyScalar: function ( scalar ) {
  874. this.x *= scalar;
  875. this.y *= scalar;
  876. this.z *= scalar;
  877. this.w *= scalar;
  878. return this;
  879. },
  880. applyMatrix4: function ( m ) {
  881. var x = this.x, y = this.y, z = this.z, w = this.w;
  882. var e = m.elements;
  883. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  884. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  885. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  886. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  887. return this;
  888. },
  889. divideScalar: function ( scalar ) {
  890. return this.multiplyScalar( 1 / scalar );
  891. },
  892. setAxisAngleFromQuaternion: function ( q ) {
  893. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  894. // q is assumed to be normalized
  895. this.w = 2 * Math.acos( q.w );
  896. var s = Math.sqrt( 1 - q.w * q.w );
  897. if ( s < 0.0001 ) {
  898. this.x = 1;
  899. this.y = 0;
  900. this.z = 0;
  901. } else {
  902. this.x = q.x / s;
  903. this.y = q.y / s;
  904. this.z = q.z / s;
  905. }
  906. return this;
  907. },
  908. setAxisAngleFromRotationMatrix: function ( m ) {
  909. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  910. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  911. var angle, x, y, z, // variables for result
  912. epsilon = 0.01, // margin to allow for rounding errors
  913. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  914. te = m.elements,
  915. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  916. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  917. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  918. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  919. ( Math.abs( m13 - m31 ) < epsilon ) &&
  920. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  921. // singularity found
  922. // first check for identity matrix which must have +1 for all terms
  923. // in leading diagonal and zero in other terms
  924. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  925. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  926. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  927. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  928. // this singularity is identity matrix so angle = 0
  929. this.set( 1, 0, 0, 0 );
  930. return this; // zero angle, arbitrary axis
  931. }
  932. // otherwise this singularity is angle = 180
  933. angle = Math.PI;
  934. var xx = ( m11 + 1 ) / 2;
  935. var yy = ( m22 + 1 ) / 2;
  936. var zz = ( m33 + 1 ) / 2;
  937. var xy = ( m12 + m21 ) / 4;
  938. var xz = ( m13 + m31 ) / 4;
  939. var yz = ( m23 + m32 ) / 4;
  940. if ( ( xx > yy ) && ( xx > zz ) ) {
  941. // m11 is the largest diagonal term
  942. if ( xx < epsilon ) {
  943. x = 0;
  944. y = 0.707106781;
  945. z = 0.707106781;
  946. } else {
  947. x = Math.sqrt( xx );
  948. y = xy / x;
  949. z = xz / x;
  950. }
  951. } else if ( yy > zz ) {
  952. // m22 is the largest diagonal term
  953. if ( yy < epsilon ) {
  954. x = 0.707106781;
  955. y = 0;
  956. z = 0.707106781;
  957. } else {
  958. y = Math.sqrt( yy );
  959. x = xy / y;
  960. z = yz / y;
  961. }
  962. } else {
  963. // m33 is the largest diagonal term so base result on this
  964. if ( zz < epsilon ) {
  965. x = 0.707106781;
  966. y = 0.707106781;
  967. z = 0;
  968. } else {
  969. z = Math.sqrt( zz );
  970. x = xz / z;
  971. y = yz / z;
  972. }
  973. }
  974. this.set( x, y, z, angle );
  975. return this; // return 180 deg rotation
  976. }
  977. // as we have reached here there are no singularities so we can handle normally
  978. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  979. ( m13 - m31 ) * ( m13 - m31 ) +
  980. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  981. if ( Math.abs( s ) < 0.001 ) s = 1;
  982. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  983. // caught by singularity test above, but I've left it in just in case
  984. this.x = ( m32 - m23 ) / s;
  985. this.y = ( m13 - m31 ) / s;
  986. this.z = ( m21 - m12 ) / s;
  987. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  988. return this;
  989. },
  990. min: function ( v ) {
  991. this.x = Math.min( this.x, v.x );
  992. this.y = Math.min( this.y, v.y );
  993. this.z = Math.min( this.z, v.z );
  994. this.w = Math.min( this.w, v.w );
  995. return this;
  996. },
  997. max: function ( v ) {
  998. this.x = Math.max( this.x, v.x );
  999. this.y = Math.max( this.y, v.y );
  1000. this.z = Math.max( this.z, v.z );
  1001. this.w = Math.max( this.w, v.w );
  1002. return this;
  1003. },
  1004. clamp: function ( min, max ) {
  1005. // assumes min < max, componentwise
  1006. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1007. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1008. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1009. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1010. return this;
  1011. },
  1012. clampScalar: function () {
  1013. var min, max;
  1014. return function clampScalar( minVal, maxVal ) {
  1015. if ( min === undefined ) {
  1016. min = new Vector4();
  1017. max = new Vector4();
  1018. }
  1019. min.set( minVal, minVal, minVal, minVal );
  1020. max.set( maxVal, maxVal, maxVal, maxVal );
  1021. return this.clamp( min, max );
  1022. };
  1023. }(),
  1024. clampLength: function ( min, max ) {
  1025. var length = this.length();
  1026. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1027. },
  1028. floor: function () {
  1029. this.x = Math.floor( this.x );
  1030. this.y = Math.floor( this.y );
  1031. this.z = Math.floor( this.z );
  1032. this.w = Math.floor( this.w );
  1033. return this;
  1034. },
  1035. ceil: function () {
  1036. this.x = Math.ceil( this.x );
  1037. this.y = Math.ceil( this.y );
  1038. this.z = Math.ceil( this.z );
  1039. this.w = Math.ceil( this.w );
  1040. return this;
  1041. },
  1042. round: function () {
  1043. this.x = Math.round( this.x );
  1044. this.y = Math.round( this.y );
  1045. this.z = Math.round( this.z );
  1046. this.w = Math.round( this.w );
  1047. return this;
  1048. },
  1049. roundToZero: function () {
  1050. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1051. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1052. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1053. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1054. return this;
  1055. },
  1056. negate: function () {
  1057. this.x = - this.x;
  1058. this.y = - this.y;
  1059. this.z = - this.z;
  1060. this.w = - this.w;
  1061. return this;
  1062. },
  1063. dot: function ( v ) {
  1064. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1065. },
  1066. lengthSq: function () {
  1067. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1068. },
  1069. length: function () {
  1070. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1071. },
  1072. lengthManhattan: function () {
  1073. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1074. },
  1075. normalize: function () {
  1076. return this.divideScalar( this.length() || 1 );
  1077. },
  1078. setLength: function ( length ) {
  1079. return this.normalize().multiplyScalar( length );
  1080. },
  1081. lerp: function ( v, alpha ) {
  1082. this.x += ( v.x - this.x ) * alpha;
  1083. this.y += ( v.y - this.y ) * alpha;
  1084. this.z += ( v.z - this.z ) * alpha;
  1085. this.w += ( v.w - this.w ) * alpha;
  1086. return this;
  1087. },
  1088. lerpVectors: function ( v1, v2, alpha ) {
  1089. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1090. },
  1091. equals: function ( v ) {
  1092. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1093. },
  1094. fromArray: function ( array, offset ) {
  1095. if ( offset === undefined ) offset = 0;
  1096. this.x = array[ offset ];
  1097. this.y = array[ offset + 1 ];
  1098. this.z = array[ offset + 2 ];
  1099. this.w = array[ offset + 3 ];
  1100. return this;
  1101. },
  1102. toArray: function ( array, offset ) {
  1103. if ( array === undefined ) array = [];
  1104. if ( offset === undefined ) offset = 0;
  1105. array[ offset ] = this.x;
  1106. array[ offset + 1 ] = this.y;
  1107. array[ offset + 2 ] = this.z;
  1108. array[ offset + 3 ] = this.w;
  1109. return array;
  1110. },
  1111. fromBufferAttribute: function ( attribute, index, offset ) {
  1112. if ( offset !== undefined ) {
  1113. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1114. }
  1115. this.x = attribute.getX( index );
  1116. this.y = attribute.getY( index );
  1117. this.z = attribute.getZ( index );
  1118. this.w = attribute.getW( index );
  1119. return this;
  1120. }
  1121. } );
  1122. /**
  1123. * @author szimek / https://github.com/szimek/
  1124. * @author alteredq / http://alteredqualia.com/
  1125. * @author Marius Kintel / https://github.com/kintel
  1126. */
  1127. /*
  1128. In options, we can specify:
  1129. * Texture parameters for an auto-generated target texture
  1130. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1131. */
  1132. function WebGLRenderTarget( width, height, options ) {
  1133. this.uuid = _Math.generateUUID();
  1134. this.width = width;
  1135. this.height = height;
  1136. this.scissor = new Vector4( 0, 0, width, height );
  1137. this.scissorTest = false;
  1138. this.viewport = new Vector4( 0, 0, width, height );
  1139. options = options || {};
  1140. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1141. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1142. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1143. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1144. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1145. }
  1146. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1147. isWebGLRenderTarget: true,
  1148. setSize: function ( width, height ) {
  1149. if ( this.width !== width || this.height !== height ) {
  1150. this.width = width;
  1151. this.height = height;
  1152. this.dispose();
  1153. }
  1154. this.viewport.set( 0, 0, width, height );
  1155. this.scissor.set( 0, 0, width, height );
  1156. },
  1157. clone: function () {
  1158. return new this.constructor().copy( this );
  1159. },
  1160. copy: function ( source ) {
  1161. this.width = source.width;
  1162. this.height = source.height;
  1163. this.viewport.copy( source.viewport );
  1164. this.texture = source.texture.clone();
  1165. this.depthBuffer = source.depthBuffer;
  1166. this.stencilBuffer = source.stencilBuffer;
  1167. this.depthTexture = source.depthTexture;
  1168. return this;
  1169. },
  1170. dispose: function () {
  1171. this.dispatchEvent( { type: 'dispose' } );
  1172. }
  1173. } );
  1174. /**
  1175. * @author alteredq / http://alteredqualia.com
  1176. */
  1177. function WebGLRenderTargetCube( width, height, options ) {
  1178. WebGLRenderTarget.call( this, width, height, options );
  1179. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1180. this.activeMipMapLevel = 0;
  1181. }
  1182. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1183. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1184. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1185. /**
  1186. * @author mikael emtinger / http://gomo.se/
  1187. * @author alteredq / http://alteredqualia.com/
  1188. * @author WestLangley / http://github.com/WestLangley
  1189. * @author bhouston / http://clara.io
  1190. */
  1191. function Quaternion( x, y, z, w ) {
  1192. this._x = x || 0;
  1193. this._y = y || 0;
  1194. this._z = z || 0;
  1195. this._w = ( w !== undefined ) ? w : 1;
  1196. }
  1197. Object.assign( Quaternion, {
  1198. slerp: function ( qa, qb, qm, t ) {
  1199. return qm.copy( qa ).slerp( qb, t );
  1200. },
  1201. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1202. // fuzz-free, array-based Quaternion SLERP operation
  1203. var x0 = src0[ srcOffset0 + 0 ],
  1204. y0 = src0[ srcOffset0 + 1 ],
  1205. z0 = src0[ srcOffset0 + 2 ],
  1206. w0 = src0[ srcOffset0 + 3 ],
  1207. x1 = src1[ srcOffset1 + 0 ],
  1208. y1 = src1[ srcOffset1 + 1 ],
  1209. z1 = src1[ srcOffset1 + 2 ],
  1210. w1 = src1[ srcOffset1 + 3 ];
  1211. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1212. var s = 1 - t,
  1213. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1214. dir = ( cos >= 0 ? 1 : - 1 ),
  1215. sqrSin = 1 - cos * cos;
  1216. // Skip the Slerp for tiny steps to avoid numeric problems:
  1217. if ( sqrSin > Number.EPSILON ) {
  1218. var sin = Math.sqrt( sqrSin ),
  1219. len = Math.atan2( sin, cos * dir );
  1220. s = Math.sin( s * len ) / sin;
  1221. t = Math.sin( t * len ) / sin;
  1222. }
  1223. var tDir = t * dir;
  1224. x0 = x0 * s + x1 * tDir;
  1225. y0 = y0 * s + y1 * tDir;
  1226. z0 = z0 * s + z1 * tDir;
  1227. w0 = w0 * s + w1 * tDir;
  1228. // Normalize in case we just did a lerp:
  1229. if ( s === 1 - t ) {
  1230. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1231. x0 *= f;
  1232. y0 *= f;
  1233. z0 *= f;
  1234. w0 *= f;
  1235. }
  1236. }
  1237. dst[ dstOffset ] = x0;
  1238. dst[ dstOffset + 1 ] = y0;
  1239. dst[ dstOffset + 2 ] = z0;
  1240. dst[ dstOffset + 3 ] = w0;
  1241. }
  1242. } );
  1243. Object.defineProperties( Quaternion.prototype, {
  1244. x: {
  1245. get: function () {
  1246. return this._x;
  1247. },
  1248. set: function ( value ) {
  1249. this._x = value;
  1250. this.onChangeCallback();
  1251. }
  1252. },
  1253. y: {
  1254. get: function () {
  1255. return this._y;
  1256. },
  1257. set: function ( value ) {
  1258. this._y = value;
  1259. this.onChangeCallback();
  1260. }
  1261. },
  1262. z: {
  1263. get: function () {
  1264. return this._z;
  1265. },
  1266. set: function ( value ) {
  1267. this._z = value;
  1268. this.onChangeCallback();
  1269. }
  1270. },
  1271. w: {
  1272. get: function () {
  1273. return this._w;
  1274. },
  1275. set: function ( value ) {
  1276. this._w = value;
  1277. this.onChangeCallback();
  1278. }
  1279. }
  1280. } );
  1281. Object.assign( Quaternion.prototype, {
  1282. set: function ( x, y, z, w ) {
  1283. this._x = x;
  1284. this._y = y;
  1285. this._z = z;
  1286. this._w = w;
  1287. this.onChangeCallback();
  1288. return this;
  1289. },
  1290. clone: function () {
  1291. return new this.constructor( this._x, this._y, this._z, this._w );
  1292. },
  1293. copy: function ( quaternion ) {
  1294. this._x = quaternion.x;
  1295. this._y = quaternion.y;
  1296. this._z = quaternion.z;
  1297. this._w = quaternion.w;
  1298. this.onChangeCallback();
  1299. return this;
  1300. },
  1301. setFromEuler: function ( euler, update ) {
  1302. if ( ! ( euler && euler.isEuler ) ) {
  1303. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1304. }
  1305. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1306. // http://www.mathworks.com/matlabcentral/fileexchange/
  1307. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1308. // content/SpinCalc.m
  1309. var cos = Math.cos;
  1310. var sin = Math.sin;
  1311. var c1 = cos( x / 2 );
  1312. var c2 = cos( y / 2 );
  1313. var c3 = cos( z / 2 );
  1314. var s1 = sin( x / 2 );
  1315. var s2 = sin( y / 2 );
  1316. var s3 = sin( z / 2 );
  1317. if ( order === 'XYZ' ) {
  1318. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1319. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1320. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1321. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1322. } else if ( order === 'YXZ' ) {
  1323. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1324. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1325. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1326. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1327. } else if ( order === 'ZXY' ) {
  1328. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1329. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1330. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1331. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1332. } else if ( order === 'ZYX' ) {
  1333. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1334. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1335. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1336. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1337. } else if ( order === 'YZX' ) {
  1338. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1339. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1340. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1341. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1342. } else if ( order === 'XZY' ) {
  1343. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1344. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1345. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1346. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1347. }
  1348. if ( update !== false ) this.onChangeCallback();
  1349. return this;
  1350. },
  1351. setFromAxisAngle: function ( axis, angle ) {
  1352. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1353. // assumes axis is normalized
  1354. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1355. this._x = axis.x * s;
  1356. this._y = axis.y * s;
  1357. this._z = axis.z * s;
  1358. this._w = Math.cos( halfAngle );
  1359. this.onChangeCallback();
  1360. return this;
  1361. },
  1362. setFromRotationMatrix: function ( m ) {
  1363. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1364. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1365. var te = m.elements,
  1366. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1367. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1368. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1369. trace = m11 + m22 + m33,
  1370. s;
  1371. if ( trace > 0 ) {
  1372. s = 0.5 / Math.sqrt( trace + 1.0 );
  1373. this._w = 0.25 / s;
  1374. this._x = ( m32 - m23 ) * s;
  1375. this._y = ( m13 - m31 ) * s;
  1376. this._z = ( m21 - m12 ) * s;
  1377. } else if ( m11 > m22 && m11 > m33 ) {
  1378. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1379. this._w = ( m32 - m23 ) / s;
  1380. this._x = 0.25 * s;
  1381. this._y = ( m12 + m21 ) / s;
  1382. this._z = ( m13 + m31 ) / s;
  1383. } else if ( m22 > m33 ) {
  1384. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1385. this._w = ( m13 - m31 ) / s;
  1386. this._x = ( m12 + m21 ) / s;
  1387. this._y = 0.25 * s;
  1388. this._z = ( m23 + m32 ) / s;
  1389. } else {
  1390. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1391. this._w = ( m21 - m12 ) / s;
  1392. this._x = ( m13 + m31 ) / s;
  1393. this._y = ( m23 + m32 ) / s;
  1394. this._z = 0.25 * s;
  1395. }
  1396. this.onChangeCallback();
  1397. return this;
  1398. },
  1399. setFromUnitVectors: function () {
  1400. // assumes direction vectors vFrom and vTo are normalized
  1401. var v1 = new Vector3();
  1402. var r;
  1403. var EPS = 0.000001;
  1404. return function setFromUnitVectors( vFrom, vTo ) {
  1405. if ( v1 === undefined ) v1 = new Vector3();
  1406. r = vFrom.dot( vTo ) + 1;
  1407. if ( r < EPS ) {
  1408. r = 0;
  1409. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1410. v1.set( - vFrom.y, vFrom.x, 0 );
  1411. } else {
  1412. v1.set( 0, - vFrom.z, vFrom.y );
  1413. }
  1414. } else {
  1415. v1.crossVectors( vFrom, vTo );
  1416. }
  1417. this._x = v1.x;
  1418. this._y = v1.y;
  1419. this._z = v1.z;
  1420. this._w = r;
  1421. return this.normalize();
  1422. };
  1423. }(),
  1424. inverse: function () {
  1425. return this.conjugate().normalize();
  1426. },
  1427. conjugate: function () {
  1428. this._x *= - 1;
  1429. this._y *= - 1;
  1430. this._z *= - 1;
  1431. this.onChangeCallback();
  1432. return this;
  1433. },
  1434. dot: function ( v ) {
  1435. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1436. },
  1437. lengthSq: function () {
  1438. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1439. },
  1440. length: function () {
  1441. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1442. },
  1443. normalize: function () {
  1444. var l = this.length();
  1445. if ( l === 0 ) {
  1446. this._x = 0;
  1447. this._y = 0;
  1448. this._z = 0;
  1449. this._w = 1;
  1450. } else {
  1451. l = 1 / l;
  1452. this._x = this._x * l;
  1453. this._y = this._y * l;
  1454. this._z = this._z * l;
  1455. this._w = this._w * l;
  1456. }
  1457. this.onChangeCallback();
  1458. return this;
  1459. },
  1460. multiply: function ( q, p ) {
  1461. if ( p !== undefined ) {
  1462. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1463. return this.multiplyQuaternions( q, p );
  1464. }
  1465. return this.multiplyQuaternions( this, q );
  1466. },
  1467. premultiply: function ( q ) {
  1468. return this.multiplyQuaternions( q, this );
  1469. },
  1470. multiplyQuaternions: function ( a, b ) {
  1471. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1472. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1473. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1474. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1475. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1476. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1477. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1478. this.onChangeCallback();
  1479. return this;
  1480. },
  1481. slerp: function ( qb, t ) {
  1482. if ( t === 0 ) return this;
  1483. if ( t === 1 ) return this.copy( qb );
  1484. var x = this._x, y = this._y, z = this._z, w = this._w;
  1485. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1486. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1487. if ( cosHalfTheta < 0 ) {
  1488. this._w = - qb._w;
  1489. this._x = - qb._x;
  1490. this._y = - qb._y;
  1491. this._z = - qb._z;
  1492. cosHalfTheta = - cosHalfTheta;
  1493. } else {
  1494. this.copy( qb );
  1495. }
  1496. if ( cosHalfTheta >= 1.0 ) {
  1497. this._w = w;
  1498. this._x = x;
  1499. this._y = y;
  1500. this._z = z;
  1501. return this;
  1502. }
  1503. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1504. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1505. this._w = 0.5 * ( w + this._w );
  1506. this._x = 0.5 * ( x + this._x );
  1507. this._y = 0.5 * ( y + this._y );
  1508. this._z = 0.5 * ( z + this._z );
  1509. return this;
  1510. }
  1511. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1512. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1513. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1514. this._w = ( w * ratioA + this._w * ratioB );
  1515. this._x = ( x * ratioA + this._x * ratioB );
  1516. this._y = ( y * ratioA + this._y * ratioB );
  1517. this._z = ( z * ratioA + this._z * ratioB );
  1518. this.onChangeCallback();
  1519. return this;
  1520. },
  1521. equals: function ( quaternion ) {
  1522. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1523. },
  1524. fromArray: function ( array, offset ) {
  1525. if ( offset === undefined ) offset = 0;
  1526. this._x = array[ offset ];
  1527. this._y = array[ offset + 1 ];
  1528. this._z = array[ offset + 2 ];
  1529. this._w = array[ offset + 3 ];
  1530. this.onChangeCallback();
  1531. return this;
  1532. },
  1533. toArray: function ( array, offset ) {
  1534. if ( array === undefined ) array = [];
  1535. if ( offset === undefined ) offset = 0;
  1536. array[ offset ] = this._x;
  1537. array[ offset + 1 ] = this._y;
  1538. array[ offset + 2 ] = this._z;
  1539. array[ offset + 3 ] = this._w;
  1540. return array;
  1541. },
  1542. onChange: function ( callback ) {
  1543. this.onChangeCallback = callback;
  1544. return this;
  1545. },
  1546. onChangeCallback: function () {}
  1547. } );
  1548. /**
  1549. * @author mrdoob / http://mrdoob.com/
  1550. * @author kile / http://kile.stravaganza.org/
  1551. * @author philogb / http://blog.thejit.org/
  1552. * @author mikael emtinger / http://gomo.se/
  1553. * @author egraether / http://egraether.com/
  1554. * @author WestLangley / http://github.com/WestLangley
  1555. */
  1556. function Vector3( x, y, z ) {
  1557. this.x = x || 0;
  1558. this.y = y || 0;
  1559. this.z = z || 0;
  1560. }
  1561. Object.assign( Vector3.prototype, {
  1562. isVector3: true,
  1563. set: function ( x, y, z ) {
  1564. this.x = x;
  1565. this.y = y;
  1566. this.z = z;
  1567. return this;
  1568. },
  1569. setScalar: function ( scalar ) {
  1570. this.x = scalar;
  1571. this.y = scalar;
  1572. this.z = scalar;
  1573. return this;
  1574. },
  1575. setX: function ( x ) {
  1576. this.x = x;
  1577. return this;
  1578. },
  1579. setY: function ( y ) {
  1580. this.y = y;
  1581. return this;
  1582. },
  1583. setZ: function ( z ) {
  1584. this.z = z;
  1585. return this;
  1586. },
  1587. setComponent: function ( index, value ) {
  1588. switch ( index ) {
  1589. case 0: this.x = value; break;
  1590. case 1: this.y = value; break;
  1591. case 2: this.z = value; break;
  1592. default: throw new Error( 'index is out of range: ' + index );
  1593. }
  1594. return this;
  1595. },
  1596. getComponent: function ( index ) {
  1597. switch ( index ) {
  1598. case 0: return this.x;
  1599. case 1: return this.y;
  1600. case 2: return this.z;
  1601. default: throw new Error( 'index is out of range: ' + index );
  1602. }
  1603. },
  1604. clone: function () {
  1605. return new this.constructor( this.x, this.y, this.z );
  1606. },
  1607. copy: function ( v ) {
  1608. this.x = v.x;
  1609. this.y = v.y;
  1610. this.z = v.z;
  1611. return this;
  1612. },
  1613. add: function ( v, w ) {
  1614. if ( w !== undefined ) {
  1615. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1616. return this.addVectors( v, w );
  1617. }
  1618. this.x += v.x;
  1619. this.y += v.y;
  1620. this.z += v.z;
  1621. return this;
  1622. },
  1623. addScalar: function ( s ) {
  1624. this.x += s;
  1625. this.y += s;
  1626. this.z += s;
  1627. return this;
  1628. },
  1629. addVectors: function ( a, b ) {
  1630. this.x = a.x + b.x;
  1631. this.y = a.y + b.y;
  1632. this.z = a.z + b.z;
  1633. return this;
  1634. },
  1635. addScaledVector: function ( v, s ) {
  1636. this.x += v.x * s;
  1637. this.y += v.y * s;
  1638. this.z += v.z * s;
  1639. return this;
  1640. },
  1641. sub: function ( v, w ) {
  1642. if ( w !== undefined ) {
  1643. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1644. return this.subVectors( v, w );
  1645. }
  1646. this.x -= v.x;
  1647. this.y -= v.y;
  1648. this.z -= v.z;
  1649. return this;
  1650. },
  1651. subScalar: function ( s ) {
  1652. this.x -= s;
  1653. this.y -= s;
  1654. this.z -= s;
  1655. return this;
  1656. },
  1657. subVectors: function ( a, b ) {
  1658. this.x = a.x - b.x;
  1659. this.y = a.y - b.y;
  1660. this.z = a.z - b.z;
  1661. return this;
  1662. },
  1663. multiply: function ( v, w ) {
  1664. if ( w !== undefined ) {
  1665. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1666. return this.multiplyVectors( v, w );
  1667. }
  1668. this.x *= v.x;
  1669. this.y *= v.y;
  1670. this.z *= v.z;
  1671. return this;
  1672. },
  1673. multiplyScalar: function ( scalar ) {
  1674. this.x *= scalar;
  1675. this.y *= scalar;
  1676. this.z *= scalar;
  1677. return this;
  1678. },
  1679. multiplyVectors: function ( a, b ) {
  1680. this.x = a.x * b.x;
  1681. this.y = a.y * b.y;
  1682. this.z = a.z * b.z;
  1683. return this;
  1684. },
  1685. applyEuler: function () {
  1686. var quaternion = new Quaternion();
  1687. return function applyEuler( euler ) {
  1688. if ( ! ( euler && euler.isEuler ) ) {
  1689. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1690. }
  1691. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1692. };
  1693. }(),
  1694. applyAxisAngle: function () {
  1695. var quaternion = new Quaternion();
  1696. return function applyAxisAngle( axis, angle ) {
  1697. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1698. };
  1699. }(),
  1700. applyMatrix3: function ( m ) {
  1701. var x = this.x, y = this.y, z = this.z;
  1702. var e = m.elements;
  1703. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1704. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1705. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1706. return this;
  1707. },
  1708. applyMatrix4: function ( m ) {
  1709. var x = this.x, y = this.y, z = this.z;
  1710. var e = m.elements;
  1711. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1712. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1713. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1714. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1715. return this;
  1716. },
  1717. applyQuaternion: function ( q ) {
  1718. var x = this.x, y = this.y, z = this.z;
  1719. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1720. // calculate quat * vector
  1721. var ix = qw * x + qy * z - qz * y;
  1722. var iy = qw * y + qz * x - qx * z;
  1723. var iz = qw * z + qx * y - qy * x;
  1724. var iw = - qx * x - qy * y - qz * z;
  1725. // calculate result * inverse quat
  1726. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1727. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1728. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1729. return this;
  1730. },
  1731. project: function () {
  1732. var matrix = new Matrix4();
  1733. return function project( camera ) {
  1734. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1735. return this.applyMatrix4( matrix );
  1736. };
  1737. }(),
  1738. unproject: function () {
  1739. var matrix = new Matrix4();
  1740. return function unproject( camera ) {
  1741. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1742. return this.applyMatrix4( matrix );
  1743. };
  1744. }(),
  1745. transformDirection: function ( m ) {
  1746. // input: THREE.Matrix4 affine matrix
  1747. // vector interpreted as a direction
  1748. var x = this.x, y = this.y, z = this.z;
  1749. var e = m.elements;
  1750. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1751. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1752. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1753. return this.normalize();
  1754. },
  1755. divide: function ( v ) {
  1756. this.x /= v.x;
  1757. this.y /= v.y;
  1758. this.z /= v.z;
  1759. return this;
  1760. },
  1761. divideScalar: function ( scalar ) {
  1762. return this.multiplyScalar( 1 / scalar );
  1763. },
  1764. min: function ( v ) {
  1765. this.x = Math.min( this.x, v.x );
  1766. this.y = Math.min( this.y, v.y );
  1767. this.z = Math.min( this.z, v.z );
  1768. return this;
  1769. },
  1770. max: function ( v ) {
  1771. this.x = Math.max( this.x, v.x );
  1772. this.y = Math.max( this.y, v.y );
  1773. this.z = Math.max( this.z, v.z );
  1774. return this;
  1775. },
  1776. clamp: function ( min, max ) {
  1777. // assumes min < max, componentwise
  1778. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1779. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1780. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1781. return this;
  1782. },
  1783. clampScalar: function () {
  1784. var min = new Vector3();
  1785. var max = new Vector3();
  1786. return function clampScalar( minVal, maxVal ) {
  1787. min.set( minVal, minVal, minVal );
  1788. max.set( maxVal, maxVal, maxVal );
  1789. return this.clamp( min, max );
  1790. };
  1791. }(),
  1792. clampLength: function ( min, max ) {
  1793. var length = this.length();
  1794. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1795. },
  1796. floor: function () {
  1797. this.x = Math.floor( this.x );
  1798. this.y = Math.floor( this.y );
  1799. this.z = Math.floor( this.z );
  1800. return this;
  1801. },
  1802. ceil: function () {
  1803. this.x = Math.ceil( this.x );
  1804. this.y = Math.ceil( this.y );
  1805. this.z = Math.ceil( this.z );
  1806. return this;
  1807. },
  1808. round: function () {
  1809. this.x = Math.round( this.x );
  1810. this.y = Math.round( this.y );
  1811. this.z = Math.round( this.z );
  1812. return this;
  1813. },
  1814. roundToZero: function () {
  1815. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1816. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1817. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1818. return this;
  1819. },
  1820. negate: function () {
  1821. this.x = - this.x;
  1822. this.y = - this.y;
  1823. this.z = - this.z;
  1824. return this;
  1825. },
  1826. dot: function ( v ) {
  1827. return this.x * v.x + this.y * v.y + this.z * v.z;
  1828. },
  1829. // TODO lengthSquared?
  1830. lengthSq: function () {
  1831. return this.x * this.x + this.y * this.y + this.z * this.z;
  1832. },
  1833. length: function () {
  1834. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1835. },
  1836. lengthManhattan: function () {
  1837. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1838. },
  1839. normalize: function () {
  1840. return this.divideScalar( this.length() || 1 );
  1841. },
  1842. setLength: function ( length ) {
  1843. return this.normalize().multiplyScalar( length );
  1844. },
  1845. lerp: function ( v, alpha ) {
  1846. this.x += ( v.x - this.x ) * alpha;
  1847. this.y += ( v.y - this.y ) * alpha;
  1848. this.z += ( v.z - this.z ) * alpha;
  1849. return this;
  1850. },
  1851. lerpVectors: function ( v1, v2, alpha ) {
  1852. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1853. },
  1854. cross: function ( v, w ) {
  1855. if ( w !== undefined ) {
  1856. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1857. return this.crossVectors( v, w );
  1858. }
  1859. var x = this.x, y = this.y, z = this.z;
  1860. this.x = y * v.z - z * v.y;
  1861. this.y = z * v.x - x * v.z;
  1862. this.z = x * v.y - y * v.x;
  1863. return this;
  1864. },
  1865. crossVectors: function ( a, b ) {
  1866. var ax = a.x, ay = a.y, az = a.z;
  1867. var bx = b.x, by = b.y, bz = b.z;
  1868. this.x = ay * bz - az * by;
  1869. this.y = az * bx - ax * bz;
  1870. this.z = ax * by - ay * bx;
  1871. return this;
  1872. },
  1873. projectOnVector: function ( vector ) {
  1874. var scalar = vector.dot( this ) / vector.lengthSq();
  1875. return this.copy( vector ).multiplyScalar( scalar );
  1876. },
  1877. projectOnPlane: function () {
  1878. var v1 = new Vector3();
  1879. return function projectOnPlane( planeNormal ) {
  1880. v1.copy( this ).projectOnVector( planeNormal );
  1881. return this.sub( v1 );
  1882. };
  1883. }(),
  1884. reflect: function () {
  1885. // reflect incident vector off plane orthogonal to normal
  1886. // normal is assumed to have unit length
  1887. var v1 = new Vector3();
  1888. return function reflect( normal ) {
  1889. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1890. };
  1891. }(),
  1892. angleTo: function ( v ) {
  1893. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1894. // clamp, to handle numerical problems
  1895. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1896. },
  1897. distanceTo: function ( v ) {
  1898. return Math.sqrt( this.distanceToSquared( v ) );
  1899. },
  1900. distanceToSquared: function ( v ) {
  1901. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1902. return dx * dx + dy * dy + dz * dz;
  1903. },
  1904. distanceToManhattan: function ( v ) {
  1905. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1906. },
  1907. setFromSpherical: function ( s ) {
  1908. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1909. this.x = sinPhiRadius * Math.sin( s.theta );
  1910. this.y = Math.cos( s.phi ) * s.radius;
  1911. this.z = sinPhiRadius * Math.cos( s.theta );
  1912. return this;
  1913. },
  1914. setFromCylindrical: function ( c ) {
  1915. this.x = c.radius * Math.sin( c.theta );
  1916. this.y = c.y;
  1917. this.z = c.radius * Math.cos( c.theta );
  1918. return this;
  1919. },
  1920. setFromMatrixPosition: function ( m ) {
  1921. var e = m.elements;
  1922. this.x = e[ 12 ];
  1923. this.y = e[ 13 ];
  1924. this.z = e[ 14 ];
  1925. return this;
  1926. },
  1927. setFromMatrixScale: function ( m ) {
  1928. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1929. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1930. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1931. this.x = sx;
  1932. this.y = sy;
  1933. this.z = sz;
  1934. return this;
  1935. },
  1936. setFromMatrixColumn: function ( m, index ) {
  1937. return this.fromArray( m.elements, index * 4 );
  1938. },
  1939. equals: function ( v ) {
  1940. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1941. },
  1942. fromArray: function ( array, offset ) {
  1943. if ( offset === undefined ) offset = 0;
  1944. this.x = array[ offset ];
  1945. this.y = array[ offset + 1 ];
  1946. this.z = array[ offset + 2 ];
  1947. return this;
  1948. },
  1949. toArray: function ( array, offset ) {
  1950. if ( array === undefined ) array = [];
  1951. if ( offset === undefined ) offset = 0;
  1952. array[ offset ] = this.x;
  1953. array[ offset + 1 ] = this.y;
  1954. array[ offset + 2 ] = this.z;
  1955. return array;
  1956. },
  1957. fromBufferAttribute: function ( attribute, index, offset ) {
  1958. if ( offset !== undefined ) {
  1959. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1960. }
  1961. this.x = attribute.getX( index );
  1962. this.y = attribute.getY( index );
  1963. this.z = attribute.getZ( index );
  1964. return this;
  1965. }
  1966. } );
  1967. /**
  1968. * @author mrdoob / http://mrdoob.com/
  1969. * @author supereggbert / http://www.paulbrunt.co.uk/
  1970. * @author philogb / http://blog.thejit.org/
  1971. * @author jordi_ros / http://plattsoft.com
  1972. * @author D1plo1d / http://github.com/D1plo1d
  1973. * @author alteredq / http://alteredqualia.com/
  1974. * @author mikael emtinger / http://gomo.se/
  1975. * @author timknip / http://www.floorplanner.com/
  1976. * @author bhouston / http://clara.io
  1977. * @author WestLangley / http://github.com/WestLangley
  1978. */
  1979. function Matrix4() {
  1980. this.elements = [
  1981. 1, 0, 0, 0,
  1982. 0, 1, 0, 0,
  1983. 0, 0, 1, 0,
  1984. 0, 0, 0, 1
  1985. ];
  1986. if ( arguments.length > 0 ) {
  1987. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  1988. }
  1989. }
  1990. Object.assign( Matrix4.prototype, {
  1991. isMatrix4: true,
  1992. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1993. var te = this.elements;
  1994. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  1995. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  1996. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  1997. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  1998. return this;
  1999. },
  2000. identity: function () {
  2001. this.set(
  2002. 1, 0, 0, 0,
  2003. 0, 1, 0, 0,
  2004. 0, 0, 1, 0,
  2005. 0, 0, 0, 1
  2006. );
  2007. return this;
  2008. },
  2009. clone: function () {
  2010. return new Matrix4().fromArray( this.elements );
  2011. },
  2012. copy: function ( m ) {
  2013. var te = this.elements;
  2014. var me = m.elements;
  2015. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  2016. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  2017. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  2018. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  2019. return this;
  2020. },
  2021. copyPosition: function ( m ) {
  2022. var te = this.elements, me = m.elements;
  2023. te[ 12 ] = me[ 12 ];
  2024. te[ 13 ] = me[ 13 ];
  2025. te[ 14 ] = me[ 14 ];
  2026. return this;
  2027. },
  2028. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2029. xAxis.setFromMatrixColumn( this, 0 );
  2030. yAxis.setFromMatrixColumn( this, 1 );
  2031. zAxis.setFromMatrixColumn( this, 2 );
  2032. return this;
  2033. },
  2034. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2035. this.set(
  2036. xAxis.x, yAxis.x, zAxis.x, 0,
  2037. xAxis.y, yAxis.y, zAxis.y, 0,
  2038. xAxis.z, yAxis.z, zAxis.z, 0,
  2039. 0, 0, 0, 1
  2040. );
  2041. return this;
  2042. },
  2043. extractRotation: function () {
  2044. var v1 = new Vector3();
  2045. return function extractRotation( m ) {
  2046. var te = this.elements;
  2047. var me = m.elements;
  2048. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2049. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2050. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2051. te[ 0 ] = me[ 0 ] * scaleX;
  2052. te[ 1 ] = me[ 1 ] * scaleX;
  2053. te[ 2 ] = me[ 2 ] * scaleX;
  2054. te[ 4 ] = me[ 4 ] * scaleY;
  2055. te[ 5 ] = me[ 5 ] * scaleY;
  2056. te[ 6 ] = me[ 6 ] * scaleY;
  2057. te[ 8 ] = me[ 8 ] * scaleZ;
  2058. te[ 9 ] = me[ 9 ] * scaleZ;
  2059. te[ 10 ] = me[ 10 ] * scaleZ;
  2060. return this;
  2061. };
  2062. }(),
  2063. makeRotationFromEuler: function ( euler ) {
  2064. if ( ! ( euler && euler.isEuler ) ) {
  2065. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2066. }
  2067. var te = this.elements;
  2068. var x = euler.x, y = euler.y, z = euler.z;
  2069. var a = Math.cos( x ), b = Math.sin( x );
  2070. var c = Math.cos( y ), d = Math.sin( y );
  2071. var e = Math.cos( z ), f = Math.sin( z );
  2072. if ( euler.order === 'XYZ' ) {
  2073. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2074. te[ 0 ] = c * e;
  2075. te[ 4 ] = - c * f;
  2076. te[ 8 ] = d;
  2077. te[ 1 ] = af + be * d;
  2078. te[ 5 ] = ae - bf * d;
  2079. te[ 9 ] = - b * c;
  2080. te[ 2 ] = bf - ae * d;
  2081. te[ 6 ] = be + af * d;
  2082. te[ 10 ] = a * c;
  2083. } else if ( euler.order === 'YXZ' ) {
  2084. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2085. te[ 0 ] = ce + df * b;
  2086. te[ 4 ] = de * b - cf;
  2087. te[ 8 ] = a * d;
  2088. te[ 1 ] = a * f;
  2089. te[ 5 ] = a * e;
  2090. te[ 9 ] = - b;
  2091. te[ 2 ] = cf * b - de;
  2092. te[ 6 ] = df + ce * b;
  2093. te[ 10 ] = a * c;
  2094. } else if ( euler.order === 'ZXY' ) {
  2095. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2096. te[ 0 ] = ce - df * b;
  2097. te[ 4 ] = - a * f;
  2098. te[ 8 ] = de + cf * b;
  2099. te[ 1 ] = cf + de * b;
  2100. te[ 5 ] = a * e;
  2101. te[ 9 ] = df - ce * b;
  2102. te[ 2 ] = - a * d;
  2103. te[ 6 ] = b;
  2104. te[ 10 ] = a * c;
  2105. } else if ( euler.order === 'ZYX' ) {
  2106. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2107. te[ 0 ] = c * e;
  2108. te[ 4 ] = be * d - af;
  2109. te[ 8 ] = ae * d + bf;
  2110. te[ 1 ] = c * f;
  2111. te[ 5 ] = bf * d + ae;
  2112. te[ 9 ] = af * d - be;
  2113. te[ 2 ] = - d;
  2114. te[ 6 ] = b * c;
  2115. te[ 10 ] = a * c;
  2116. } else if ( euler.order === 'YZX' ) {
  2117. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2118. te[ 0 ] = c * e;
  2119. te[ 4 ] = bd - ac * f;
  2120. te[ 8 ] = bc * f + ad;
  2121. te[ 1 ] = f;
  2122. te[ 5 ] = a * e;
  2123. te[ 9 ] = - b * e;
  2124. te[ 2 ] = - d * e;
  2125. te[ 6 ] = ad * f + bc;
  2126. te[ 10 ] = ac - bd * f;
  2127. } else if ( euler.order === 'XZY' ) {
  2128. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2129. te[ 0 ] = c * e;
  2130. te[ 4 ] = - f;
  2131. te[ 8 ] = d * e;
  2132. te[ 1 ] = ac * f + bd;
  2133. te[ 5 ] = a * e;
  2134. te[ 9 ] = ad * f - bc;
  2135. te[ 2 ] = bc * f - ad;
  2136. te[ 6 ] = b * e;
  2137. te[ 10 ] = bd * f + ac;
  2138. }
  2139. // last column
  2140. te[ 3 ] = 0;
  2141. te[ 7 ] = 0;
  2142. te[ 11 ] = 0;
  2143. // bottom row
  2144. te[ 12 ] = 0;
  2145. te[ 13 ] = 0;
  2146. te[ 14 ] = 0;
  2147. te[ 15 ] = 1;
  2148. return this;
  2149. },
  2150. makeRotationFromQuaternion: function ( q ) {
  2151. var te = this.elements;
  2152. var x = q._x, y = q._y, z = q._z, w = q._w;
  2153. var x2 = x + x, y2 = y + y, z2 = z + z;
  2154. var xx = x * x2, xy = x * y2, xz = x * z2;
  2155. var yy = y * y2, yz = y * z2, zz = z * z2;
  2156. var wx = w * x2, wy = w * y2, wz = w * z2;
  2157. te[ 0 ] = 1 - ( yy + zz );
  2158. te[ 4 ] = xy - wz;
  2159. te[ 8 ] = xz + wy;
  2160. te[ 1 ] = xy + wz;
  2161. te[ 5 ] = 1 - ( xx + zz );
  2162. te[ 9 ] = yz - wx;
  2163. te[ 2 ] = xz - wy;
  2164. te[ 6 ] = yz + wx;
  2165. te[ 10 ] = 1 - ( xx + yy );
  2166. // last column
  2167. te[ 3 ] = 0;
  2168. te[ 7 ] = 0;
  2169. te[ 11 ] = 0;
  2170. // bottom row
  2171. te[ 12 ] = 0;
  2172. te[ 13 ] = 0;
  2173. te[ 14 ] = 0;
  2174. te[ 15 ] = 1;
  2175. return this;
  2176. },
  2177. lookAt: function () {
  2178. var x = new Vector3();
  2179. var y = new Vector3();
  2180. var z = new Vector3();
  2181. return function lookAt( eye, target, up ) {
  2182. var te = this.elements;
  2183. z.subVectors( eye, target );
  2184. if ( z.lengthSq() === 0 ) {
  2185. // eye and target are in the same position
  2186. z.z = 1;
  2187. }
  2188. z.normalize();
  2189. x.crossVectors( up, z );
  2190. if ( x.lengthSq() === 0 ) {
  2191. // up and z are parallel
  2192. if ( Math.abs( up.z ) === 1 ) {
  2193. z.x += 0.0001;
  2194. } else {
  2195. z.z += 0.0001;
  2196. }
  2197. z.normalize();
  2198. x.crossVectors( up, z );
  2199. }
  2200. x.normalize();
  2201. y.crossVectors( z, x );
  2202. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2203. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2204. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2205. return this;
  2206. };
  2207. }(),
  2208. multiply: function ( m, n ) {
  2209. if ( n !== undefined ) {
  2210. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2211. return this.multiplyMatrices( m, n );
  2212. }
  2213. return this.multiplyMatrices( this, m );
  2214. },
  2215. premultiply: function ( m ) {
  2216. return this.multiplyMatrices( m, this );
  2217. },
  2218. multiplyMatrices: function ( a, b ) {
  2219. var ae = a.elements;
  2220. var be = b.elements;
  2221. var te = this.elements;
  2222. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2223. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2224. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2225. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2226. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2227. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2228. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2229. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2230. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2231. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2232. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2233. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2234. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2235. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2236. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2237. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2238. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2239. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2240. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2241. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2242. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2243. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2244. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2245. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2246. return this;
  2247. },
  2248. multiplyScalar: function ( s ) {
  2249. var te = this.elements;
  2250. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2251. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2252. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2253. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2254. return this;
  2255. },
  2256. applyToBufferAttribute: function () {
  2257. var v1 = new Vector3();
  2258. return function applyToBufferAttribute( attribute ) {
  2259. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2260. v1.x = attribute.getX( i );
  2261. v1.y = attribute.getY( i );
  2262. v1.z = attribute.getZ( i );
  2263. v1.applyMatrix4( this );
  2264. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2265. }
  2266. return attribute;
  2267. };
  2268. }(),
  2269. determinant: function () {
  2270. var te = this.elements;
  2271. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2272. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2273. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2274. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2275. //TODO: make this more efficient
  2276. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2277. return (
  2278. n41 * (
  2279. + n14 * n23 * n32
  2280. - n13 * n24 * n32
  2281. - n14 * n22 * n33
  2282. + n12 * n24 * n33
  2283. + n13 * n22 * n34
  2284. - n12 * n23 * n34
  2285. ) +
  2286. n42 * (
  2287. + n11 * n23 * n34
  2288. - n11 * n24 * n33
  2289. + n14 * n21 * n33
  2290. - n13 * n21 * n34
  2291. + n13 * n24 * n31
  2292. - n14 * n23 * n31
  2293. ) +
  2294. n43 * (
  2295. + n11 * n24 * n32
  2296. - n11 * n22 * n34
  2297. - n14 * n21 * n32
  2298. + n12 * n21 * n34
  2299. + n14 * n22 * n31
  2300. - n12 * n24 * n31
  2301. ) +
  2302. n44 * (
  2303. - n13 * n22 * n31
  2304. - n11 * n23 * n32
  2305. + n11 * n22 * n33
  2306. + n13 * n21 * n32
  2307. - n12 * n21 * n33
  2308. + n12 * n23 * n31
  2309. )
  2310. );
  2311. },
  2312. transpose: function () {
  2313. var te = this.elements;
  2314. var tmp;
  2315. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2316. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2317. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2318. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2319. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2320. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2321. return this;
  2322. },
  2323. setPosition: function ( v ) {
  2324. var te = this.elements;
  2325. te[ 12 ] = v.x;
  2326. te[ 13 ] = v.y;
  2327. te[ 14 ] = v.z;
  2328. return this;
  2329. },
  2330. getInverse: function ( m, throwOnDegenerate ) {
  2331. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2332. var te = this.elements,
  2333. me = m.elements,
  2334. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2335. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2336. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2337. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2338. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2339. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2340. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2341. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2342. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2343. if ( det === 0 ) {
  2344. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  2345. if ( throwOnDegenerate === true ) {
  2346. throw new Error( msg );
  2347. } else {
  2348. console.warn( msg );
  2349. }
  2350. return this.identity();
  2351. }
  2352. var detInv = 1 / det;
  2353. te[ 0 ] = t11 * detInv;
  2354. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2355. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2356. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2357. te[ 4 ] = t12 * detInv;
  2358. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2359. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2360. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2361. te[ 8 ] = t13 * detInv;
  2362. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2363. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2364. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2365. te[ 12 ] = t14 * detInv;
  2366. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2367. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2368. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2369. return this;
  2370. },
  2371. scale: function ( v ) {
  2372. var te = this.elements;
  2373. var x = v.x, y = v.y, z = v.z;
  2374. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2375. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2376. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2377. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2378. return this;
  2379. },
  2380. getMaxScaleOnAxis: function () {
  2381. var te = this.elements;
  2382. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2383. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2384. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2385. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2386. },
  2387. makeTranslation: function ( x, y, z ) {
  2388. this.set(
  2389. 1, 0, 0, x,
  2390. 0, 1, 0, y,
  2391. 0, 0, 1, z,
  2392. 0, 0, 0, 1
  2393. );
  2394. return this;
  2395. },
  2396. makeRotationX: function ( theta ) {
  2397. var c = Math.cos( theta ), s = Math.sin( theta );
  2398. this.set(
  2399. 1, 0, 0, 0,
  2400. 0, c, - s, 0,
  2401. 0, s, c, 0,
  2402. 0, 0, 0, 1
  2403. );
  2404. return this;
  2405. },
  2406. makeRotationY: function ( theta ) {
  2407. var c = Math.cos( theta ), s = Math.sin( theta );
  2408. this.set(
  2409. c, 0, s, 0,
  2410. 0, 1, 0, 0,
  2411. - s, 0, c, 0,
  2412. 0, 0, 0, 1
  2413. );
  2414. return this;
  2415. },
  2416. makeRotationZ: function ( theta ) {
  2417. var c = Math.cos( theta ), s = Math.sin( theta );
  2418. this.set(
  2419. c, - s, 0, 0,
  2420. s, c, 0, 0,
  2421. 0, 0, 1, 0,
  2422. 0, 0, 0, 1
  2423. );
  2424. return this;
  2425. },
  2426. makeRotationAxis: function ( axis, angle ) {
  2427. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2428. var c = Math.cos( angle );
  2429. var s = Math.sin( angle );
  2430. var t = 1 - c;
  2431. var x = axis.x, y = axis.y, z = axis.z;
  2432. var tx = t * x, ty = t * y;
  2433. this.set(
  2434. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2435. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2436. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2437. 0, 0, 0, 1
  2438. );
  2439. return this;
  2440. },
  2441. makeScale: function ( x, y, z ) {
  2442. this.set(
  2443. x, 0, 0, 0,
  2444. 0, y, 0, 0,
  2445. 0, 0, z, 0,
  2446. 0, 0, 0, 1
  2447. );
  2448. return this;
  2449. },
  2450. makeShear: function ( x, y, z ) {
  2451. this.set(
  2452. 1, y, z, 0,
  2453. x, 1, z, 0,
  2454. x, y, 1, 0,
  2455. 0, 0, 0, 1
  2456. );
  2457. return this;
  2458. },
  2459. compose: function ( position, quaternion, scale ) {
  2460. this.makeRotationFromQuaternion( quaternion );
  2461. this.scale( scale );
  2462. this.setPosition( position );
  2463. return this;
  2464. },
  2465. decompose: function () {
  2466. var vector = new Vector3();
  2467. var matrix = new Matrix4();
  2468. return function decompose( position, quaternion, scale ) {
  2469. var te = this.elements;
  2470. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2471. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2472. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2473. // if determine is negative, we need to invert one scale
  2474. var det = this.determinant();
  2475. if ( det < 0 ) sx = - sx;
  2476. position.x = te[ 12 ];
  2477. position.y = te[ 13 ];
  2478. position.z = te[ 14 ];
  2479. // scale the rotation part
  2480. matrix.copy( this );
  2481. var invSX = 1 / sx;
  2482. var invSY = 1 / sy;
  2483. var invSZ = 1 / sz;
  2484. matrix.elements[ 0 ] *= invSX;
  2485. matrix.elements[ 1 ] *= invSX;
  2486. matrix.elements[ 2 ] *= invSX;
  2487. matrix.elements[ 4 ] *= invSY;
  2488. matrix.elements[ 5 ] *= invSY;
  2489. matrix.elements[ 6 ] *= invSY;
  2490. matrix.elements[ 8 ] *= invSZ;
  2491. matrix.elements[ 9 ] *= invSZ;
  2492. matrix.elements[ 10 ] *= invSZ;
  2493. quaternion.setFromRotationMatrix( matrix );
  2494. scale.x = sx;
  2495. scale.y = sy;
  2496. scale.z = sz;
  2497. return this;
  2498. };
  2499. }(),
  2500. makePerspective: function ( left, right, top, bottom, near, far ) {
  2501. if ( far === undefined ) {
  2502. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2503. }
  2504. var te = this.elements;
  2505. var x = 2 * near / ( right - left );
  2506. var y = 2 * near / ( top - bottom );
  2507. var a = ( right + left ) / ( right - left );
  2508. var b = ( top + bottom ) / ( top - bottom );
  2509. var c = - ( far + near ) / ( far - near );
  2510. var d = - 2 * far * near / ( far - near );
  2511. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2512. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2513. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2514. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2515. return this;
  2516. },
  2517. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2518. var te = this.elements;
  2519. var w = 1.0 / ( right - left );
  2520. var h = 1.0 / ( top - bottom );
  2521. var p = 1.0 / ( far - near );
  2522. var x = ( right + left ) * w;
  2523. var y = ( top + bottom ) * h;
  2524. var z = ( far + near ) * p;
  2525. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2526. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2527. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2528. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2529. return this;
  2530. },
  2531. equals: function ( matrix ) {
  2532. var te = this.elements;
  2533. var me = matrix.elements;
  2534. for ( var i = 0; i < 16; i ++ ) {
  2535. if ( te[ i ] !== me[ i ] ) return false;
  2536. }
  2537. return true;
  2538. },
  2539. fromArray: function ( array, offset ) {
  2540. if ( offset === undefined ) offset = 0;
  2541. for ( var i = 0; i < 16; i ++ ) {
  2542. this.elements[ i ] = array[ i + offset ];
  2543. }
  2544. return this;
  2545. },
  2546. toArray: function ( array, offset ) {
  2547. if ( array === undefined ) array = [];
  2548. if ( offset === undefined ) offset = 0;
  2549. var te = this.elements;
  2550. array[ offset ] = te[ 0 ];
  2551. array[ offset + 1 ] = te[ 1 ];
  2552. array[ offset + 2 ] = te[ 2 ];
  2553. array[ offset + 3 ] = te[ 3 ];
  2554. array[ offset + 4 ] = te[ 4 ];
  2555. array[ offset + 5 ] = te[ 5 ];
  2556. array[ offset + 6 ] = te[ 6 ];
  2557. array[ offset + 7 ] = te[ 7 ];
  2558. array[ offset + 8 ] = te[ 8 ];
  2559. array[ offset + 9 ] = te[ 9 ];
  2560. array[ offset + 10 ] = te[ 10 ];
  2561. array[ offset + 11 ] = te[ 11 ];
  2562. array[ offset + 12 ] = te[ 12 ];
  2563. array[ offset + 13 ] = te[ 13 ];
  2564. array[ offset + 14 ] = te[ 14 ];
  2565. array[ offset + 15 ] = te[ 15 ];
  2566. return array;
  2567. }
  2568. } );
  2569. /**
  2570. * @author alteredq / http://alteredqualia.com/
  2571. */
  2572. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2573. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2574. this.image = { data: data, width: width, height: height };
  2575. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2576. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2577. this.generateMipmaps = false;
  2578. this.flipY = false;
  2579. this.unpackAlignment = 1;
  2580. }
  2581. DataTexture.prototype = Object.create( Texture.prototype );
  2582. DataTexture.prototype.constructor = DataTexture;
  2583. DataTexture.prototype.isDataTexture = true;
  2584. /**
  2585. * @author mrdoob / http://mrdoob.com/
  2586. */
  2587. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2588. images = images !== undefined ? images : [];
  2589. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2590. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2591. this.flipY = false;
  2592. }
  2593. CubeTexture.prototype = Object.create( Texture.prototype );
  2594. CubeTexture.prototype.constructor = CubeTexture;
  2595. CubeTexture.prototype.isCubeTexture = true;
  2596. Object.defineProperty( CubeTexture.prototype, 'images', {
  2597. get: function () {
  2598. return this.image;
  2599. },
  2600. set: function ( value ) {
  2601. this.image = value;
  2602. }
  2603. } );
  2604. /**
  2605. * @author tschw
  2606. *
  2607. * Uniforms of a program.
  2608. * Those form a tree structure with a special top-level container for the root,
  2609. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2610. *
  2611. *
  2612. * Properties of inner nodes including the top-level container:
  2613. *
  2614. * .seq - array of nested uniforms
  2615. * .map - nested uniforms by name
  2616. *
  2617. *
  2618. * Methods of all nodes except the top-level container:
  2619. *
  2620. * .setValue( gl, value, [renderer] )
  2621. *
  2622. * uploads a uniform value(s)
  2623. * the 'renderer' parameter is needed for sampler uniforms
  2624. *
  2625. *
  2626. * Static methods of the top-level container (renderer factorizations):
  2627. *
  2628. * .upload( gl, seq, values, renderer )
  2629. *
  2630. * sets uniforms in 'seq' to 'values[id].value'
  2631. *
  2632. * .seqWithValue( seq, values ) : filteredSeq
  2633. *
  2634. * filters 'seq' entries with corresponding entry in values
  2635. *
  2636. *
  2637. * Methods of the top-level container (renderer factorizations):
  2638. *
  2639. * .setValue( gl, name, value )
  2640. *
  2641. * sets uniform with name 'name' to 'value'
  2642. *
  2643. * .set( gl, obj, prop )
  2644. *
  2645. * sets uniform from object and property with same name than uniform
  2646. *
  2647. * .setOptional( gl, obj, prop )
  2648. *
  2649. * like .set for an optional property of the object
  2650. *
  2651. */
  2652. var emptyTexture = new Texture();
  2653. var emptyCubeTexture = new CubeTexture();
  2654. // --- Base for inner nodes (including the root) ---
  2655. function UniformContainer() {
  2656. this.seq = [];
  2657. this.map = {};
  2658. }
  2659. // --- Utilities ---
  2660. // Array Caches (provide typed arrays for temporary by size)
  2661. var arrayCacheF32 = [];
  2662. var arrayCacheI32 = [];
  2663. // Float32Array caches used for uploading Matrix uniforms
  2664. var mat4array = new Float32Array( 16 );
  2665. var mat3array = new Float32Array( 9 );
  2666. // Flattening for arrays of vectors and matrices
  2667. function flatten( array, nBlocks, blockSize ) {
  2668. var firstElem = array[ 0 ];
  2669. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2670. // unoptimized: ! isNaN( firstElem )
  2671. // see http://jacksondunstan.com/articles/983
  2672. var n = nBlocks * blockSize,
  2673. r = arrayCacheF32[ n ];
  2674. if ( r === undefined ) {
  2675. r = new Float32Array( n );
  2676. arrayCacheF32[ n ] = r;
  2677. }
  2678. if ( nBlocks !== 0 ) {
  2679. firstElem.toArray( r, 0 );
  2680. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2681. offset += blockSize;
  2682. array[ i ].toArray( r, offset );
  2683. }
  2684. }
  2685. return r;
  2686. }
  2687. // Texture unit allocation
  2688. function allocTexUnits( renderer, n ) {
  2689. var r = arrayCacheI32[ n ];
  2690. if ( r === undefined ) {
  2691. r = new Int32Array( n );
  2692. arrayCacheI32[ n ] = r;
  2693. }
  2694. for ( var i = 0; i !== n; ++ i )
  2695. r[ i ] = renderer.allocTextureUnit();
  2696. return r;
  2697. }
  2698. // --- Setters ---
  2699. // Note: Defining these methods externally, because they come in a bunch
  2700. // and this way their names minify.
  2701. // Single scalar
  2702. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2703. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2704. // Single float vector (from flat array or THREE.VectorN)
  2705. function setValue2fv( gl, v ) {
  2706. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2707. else gl.uniform2f( this.addr, v.x, v.y );
  2708. }
  2709. function setValue3fv( gl, v ) {
  2710. if ( v.x !== undefined )
  2711. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2712. else if ( v.r !== undefined )
  2713. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2714. else
  2715. gl.uniform3fv( this.addr, v );
  2716. }
  2717. function setValue4fv( gl, v ) {
  2718. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2719. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2720. }
  2721. // Single matrix (from flat array or MatrixN)
  2722. function setValue2fm( gl, v ) {
  2723. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2724. }
  2725. function setValue3fm( gl, v ) {
  2726. if ( v.elements === undefined ) {
  2727. gl.uniformMatrix3fv( this.addr, false, v );
  2728. } else {
  2729. mat3array.set( v.elements );
  2730. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2731. }
  2732. }
  2733. function setValue4fm( gl, v ) {
  2734. if ( v.elements === undefined ) {
  2735. gl.uniformMatrix4fv( this.addr, false, v );
  2736. } else {
  2737. mat4array.set( v.elements );
  2738. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2739. }
  2740. }
  2741. // Single texture (2D / Cube)
  2742. function setValueT1( gl, v, renderer ) {
  2743. var unit = renderer.allocTextureUnit();
  2744. gl.uniform1i( this.addr, unit );
  2745. renderer.setTexture2D( v || emptyTexture, unit );
  2746. }
  2747. function setValueT6( gl, v, renderer ) {
  2748. var unit = renderer.allocTextureUnit();
  2749. gl.uniform1i( this.addr, unit );
  2750. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2751. }
  2752. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2753. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2754. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2755. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2756. // Helper to pick the right setter for the singular case
  2757. function getSingularSetter( type ) {
  2758. switch ( type ) {
  2759. case 0x1406: return setValue1f; // FLOAT
  2760. case 0x8b50: return setValue2fv; // _VEC2
  2761. case 0x8b51: return setValue3fv; // _VEC3
  2762. case 0x8b52: return setValue4fv; // _VEC4
  2763. case 0x8b5a: return setValue2fm; // _MAT2
  2764. case 0x8b5b: return setValue3fm; // _MAT3
  2765. case 0x8b5c: return setValue4fm; // _MAT4
  2766. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  2767. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2768. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2769. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2770. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2771. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2772. }
  2773. }
  2774. // Array of scalars
  2775. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2776. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2777. // Array of vectors (flat or from THREE classes)
  2778. function setValueV2a( gl, v ) {
  2779. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2780. }
  2781. function setValueV3a( gl, v ) {
  2782. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2783. }
  2784. function setValueV4a( gl, v ) {
  2785. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2786. }
  2787. // Array of matrices (flat or from THREE clases)
  2788. function setValueM2a( gl, v ) {
  2789. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2790. }
  2791. function setValueM3a( gl, v ) {
  2792. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2793. }
  2794. function setValueM4a( gl, v ) {
  2795. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2796. }
  2797. // Array of textures (2D / Cube)
  2798. function setValueT1a( gl, v, renderer ) {
  2799. var n = v.length,
  2800. units = allocTexUnits( renderer, n );
  2801. gl.uniform1iv( this.addr, units );
  2802. for ( var i = 0; i !== n; ++ i ) {
  2803. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2804. }
  2805. }
  2806. function setValueT6a( gl, v, renderer ) {
  2807. var n = v.length,
  2808. units = allocTexUnits( renderer, n );
  2809. gl.uniform1iv( this.addr, units );
  2810. for ( var i = 0; i !== n; ++ i ) {
  2811. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2812. }
  2813. }
  2814. // Helper to pick the right setter for a pure (bottom-level) array
  2815. function getPureArraySetter( type ) {
  2816. switch ( type ) {
  2817. case 0x1406: return setValue1fv; // FLOAT
  2818. case 0x8b50: return setValueV2a; // _VEC2
  2819. case 0x8b51: return setValueV3a; // _VEC3
  2820. case 0x8b52: return setValueV4a; // _VEC4
  2821. case 0x8b5a: return setValueM2a; // _MAT2
  2822. case 0x8b5b: return setValueM3a; // _MAT3
  2823. case 0x8b5c: return setValueM4a; // _MAT4
  2824. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2825. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2826. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2827. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2828. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2829. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2830. }
  2831. }
  2832. // --- Uniform Classes ---
  2833. function SingleUniform( id, activeInfo, addr ) {
  2834. this.id = id;
  2835. this.addr = addr;
  2836. this.setValue = getSingularSetter( activeInfo.type );
  2837. // this.path = activeInfo.name; // DEBUG
  2838. }
  2839. function PureArrayUniform( id, activeInfo, addr ) {
  2840. this.id = id;
  2841. this.addr = addr;
  2842. this.size = activeInfo.size;
  2843. this.setValue = getPureArraySetter( activeInfo.type );
  2844. // this.path = activeInfo.name; // DEBUG
  2845. }
  2846. function StructuredUniform( id ) {
  2847. this.id = id;
  2848. UniformContainer.call( this ); // mix-in
  2849. }
  2850. StructuredUniform.prototype.setValue = function ( gl, value ) {
  2851. // Note: Don't need an extra 'renderer' parameter, since samplers
  2852. // are not allowed in structured uniforms.
  2853. var seq = this.seq;
  2854. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2855. var u = seq[ i ];
  2856. u.setValue( gl, value[ u.id ] );
  2857. }
  2858. };
  2859. // --- Top-level ---
  2860. // Parser - builds up the property tree from the path strings
  2861. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2862. // extracts
  2863. // - the identifier (member name or array index)
  2864. // - followed by an optional right bracket (found when array index)
  2865. // - followed by an optional left bracket or dot (type of subscript)
  2866. //
  2867. // Note: These portions can be read in a non-overlapping fashion and
  2868. // allow straightforward parsing of the hierarchy that WebGL encodes
  2869. // in the uniform names.
  2870. function addUniform( container, uniformObject ) {
  2871. container.seq.push( uniformObject );
  2872. container.map[ uniformObject.id ] = uniformObject;
  2873. }
  2874. function parseUniform( activeInfo, addr, container ) {
  2875. var path = activeInfo.name,
  2876. pathLength = path.length;
  2877. // reset RegExp object, because of the early exit of a previous run
  2878. RePathPart.lastIndex = 0;
  2879. for ( ; ; ) {
  2880. var match = RePathPart.exec( path ),
  2881. matchEnd = RePathPart.lastIndex,
  2882. id = match[ 1 ],
  2883. idIsIndex = match[ 2 ] === ']',
  2884. subscript = match[ 3 ];
  2885. if ( idIsIndex ) id = id | 0; // convert to integer
  2886. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  2887. // bare name or "pure" bottom-level array "[0]" suffix
  2888. addUniform( container, subscript === undefined ?
  2889. new SingleUniform( id, activeInfo, addr ) :
  2890. new PureArrayUniform( id, activeInfo, addr ) );
  2891. break;
  2892. } else {
  2893. // step into inner node / create it in case it doesn't exist
  2894. var map = container.map, next = map[ id ];
  2895. if ( next === undefined ) {
  2896. next = new StructuredUniform( id );
  2897. addUniform( container, next );
  2898. }
  2899. container = next;
  2900. }
  2901. }
  2902. }
  2903. // Root Container
  2904. function WebGLUniforms( gl, program, renderer ) {
  2905. UniformContainer.call( this );
  2906. this.renderer = renderer;
  2907. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2908. for ( var i = 0; i < n; ++ i ) {
  2909. var info = gl.getActiveUniform( program, i ),
  2910. path = info.name,
  2911. addr = gl.getUniformLocation( program, path );
  2912. parseUniform( info, addr, this );
  2913. }
  2914. }
  2915. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  2916. var u = this.map[ name ];
  2917. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2918. };
  2919. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  2920. var v = object[ name ];
  2921. if ( v !== undefined ) this.setValue( gl, name, v );
  2922. };
  2923. // Static interface
  2924. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  2925. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2926. var u = seq[ i ],
  2927. v = values[ u.id ];
  2928. if ( v.needsUpdate !== false ) {
  2929. // note: always updating when .needsUpdate is undefined
  2930. u.setValue( gl, v.value, renderer );
  2931. }
  2932. }
  2933. };
  2934. WebGLUniforms.seqWithValue = function ( seq, values ) {
  2935. var r = [];
  2936. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2937. var u = seq[ i ];
  2938. if ( u.id in values ) r.push( u );
  2939. }
  2940. return r;
  2941. };
  2942. /**
  2943. * @author mrdoob / http://mrdoob.com/
  2944. */
  2945. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  2946. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  2947. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  2948. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  2949. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  2950. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  2951. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  2952. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  2953. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  2954. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  2955. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  2956. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  2957. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  2958. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  2959. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  2960. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  2961. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  2962. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  2963. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  2964. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  2965. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  2966. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  2967. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  2968. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  2969. function Color( r, g, b ) {
  2970. if ( g === undefined && b === undefined ) {
  2971. // r is THREE.Color, hex or string
  2972. return this.set( r );
  2973. }
  2974. return this.setRGB( r, g, b );
  2975. }
  2976. Object.assign( Color.prototype, {
  2977. isColor: true,
  2978. r: 1, g: 1, b: 1,
  2979. set: function ( value ) {
  2980. if ( value && value.isColor ) {
  2981. this.copy( value );
  2982. } else if ( typeof value === 'number' ) {
  2983. this.setHex( value );
  2984. } else if ( typeof value === 'string' ) {
  2985. this.setStyle( value );
  2986. }
  2987. return this;
  2988. },
  2989. setScalar: function ( scalar ) {
  2990. this.r = scalar;
  2991. this.g = scalar;
  2992. this.b = scalar;
  2993. return this;
  2994. },
  2995. setHex: function ( hex ) {
  2996. hex = Math.floor( hex );
  2997. this.r = ( hex >> 16 & 255 ) / 255;
  2998. this.g = ( hex >> 8 & 255 ) / 255;
  2999. this.b = ( hex & 255 ) / 255;
  3000. return this;
  3001. },
  3002. setRGB: function ( r, g, b ) {
  3003. this.r = r;
  3004. this.g = g;
  3005. this.b = b;
  3006. return this;
  3007. },
  3008. setHSL: function () {
  3009. function hue2rgb( p, q, t ) {
  3010. if ( t < 0 ) t += 1;
  3011. if ( t > 1 ) t -= 1;
  3012. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3013. if ( t < 1 / 2 ) return q;
  3014. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3015. return p;
  3016. }
  3017. return function setHSL( h, s, l ) {
  3018. // h,s,l ranges are in 0.0 - 1.0
  3019. h = _Math.euclideanModulo( h, 1 );
  3020. s = _Math.clamp( s, 0, 1 );
  3021. l = _Math.clamp( l, 0, 1 );
  3022. if ( s === 0 ) {
  3023. this.r = this.g = this.b = l;
  3024. } else {
  3025. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3026. var q = ( 2 * l ) - p;
  3027. this.r = hue2rgb( q, p, h + 1 / 3 );
  3028. this.g = hue2rgb( q, p, h );
  3029. this.b = hue2rgb( q, p, h - 1 / 3 );
  3030. }
  3031. return this;
  3032. };
  3033. }(),
  3034. setStyle: function ( style ) {
  3035. function handleAlpha( string ) {
  3036. if ( string === undefined ) return;
  3037. if ( parseFloat( string ) < 1 ) {
  3038. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3039. }
  3040. }
  3041. var m;
  3042. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3043. // rgb / hsl
  3044. var color;
  3045. var name = m[ 1 ];
  3046. var components = m[ 2 ];
  3047. switch ( name ) {
  3048. case 'rgb':
  3049. case 'rgba':
  3050. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3051. // rgb(255,0,0) rgba(255,0,0,0.5)
  3052. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3053. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3054. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3055. handleAlpha( color[ 5 ] );
  3056. return this;
  3057. }
  3058. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3059. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3060. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3061. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3062. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3063. handleAlpha( color[ 5 ] );
  3064. return this;
  3065. }
  3066. break;
  3067. case 'hsl':
  3068. case 'hsla':
  3069. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3070. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3071. var h = parseFloat( color[ 1 ] ) / 360;
  3072. var s = parseInt( color[ 2 ], 10 ) / 100;
  3073. var l = parseInt( color[ 3 ], 10 ) / 100;
  3074. handleAlpha( color[ 5 ] );
  3075. return this.setHSL( h, s, l );
  3076. }
  3077. break;
  3078. }
  3079. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3080. // hex color
  3081. var hex = m[ 1 ];
  3082. var size = hex.length;
  3083. if ( size === 3 ) {
  3084. // #ff0
  3085. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3086. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3087. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3088. return this;
  3089. } else if ( size === 6 ) {
  3090. // #ff0000
  3091. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3092. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3093. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3094. return this;
  3095. }
  3096. }
  3097. if ( style && style.length > 0 ) {
  3098. // color keywords
  3099. var hex = ColorKeywords[ style ];
  3100. if ( hex !== undefined ) {
  3101. // red
  3102. this.setHex( hex );
  3103. } else {
  3104. // unknown color
  3105. console.warn( 'THREE.Color: Unknown color ' + style );
  3106. }
  3107. }
  3108. return this;
  3109. },
  3110. clone: function () {
  3111. return new this.constructor( this.r, this.g, this.b );
  3112. },
  3113. copy: function ( color ) {
  3114. this.r = color.r;
  3115. this.g = color.g;
  3116. this.b = color.b;
  3117. return this;
  3118. },
  3119. copyGammaToLinear: function ( color, gammaFactor ) {
  3120. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3121. this.r = Math.pow( color.r, gammaFactor );
  3122. this.g = Math.pow( color.g, gammaFactor );
  3123. this.b = Math.pow( color.b, gammaFactor );
  3124. return this;
  3125. },
  3126. copyLinearToGamma: function ( color, gammaFactor ) {
  3127. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3128. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3129. this.r = Math.pow( color.r, safeInverse );
  3130. this.g = Math.pow( color.g, safeInverse );
  3131. this.b = Math.pow( color.b, safeInverse );
  3132. return this;
  3133. },
  3134. convertGammaToLinear: function () {
  3135. var r = this.r, g = this.g, b = this.b;
  3136. this.r = r * r;
  3137. this.g = g * g;
  3138. this.b = b * b;
  3139. return this;
  3140. },
  3141. convertLinearToGamma: function () {
  3142. this.r = Math.sqrt( this.r );
  3143. this.g = Math.sqrt( this.g );
  3144. this.b = Math.sqrt( this.b );
  3145. return this;
  3146. },
  3147. getHex: function () {
  3148. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3149. },
  3150. getHexString: function () {
  3151. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3152. },
  3153. getHSL: function ( optionalTarget ) {
  3154. // h,s,l ranges are in 0.0 - 1.0
  3155. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3156. var r = this.r, g = this.g, b = this.b;
  3157. var max = Math.max( r, g, b );
  3158. var min = Math.min( r, g, b );
  3159. var hue, saturation;
  3160. var lightness = ( min + max ) / 2.0;
  3161. if ( min === max ) {
  3162. hue = 0;
  3163. saturation = 0;
  3164. } else {
  3165. var delta = max - min;
  3166. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3167. switch ( max ) {
  3168. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3169. case g: hue = ( b - r ) / delta + 2; break;
  3170. case b: hue = ( r - g ) / delta + 4; break;
  3171. }
  3172. hue /= 6;
  3173. }
  3174. hsl.h = hue;
  3175. hsl.s = saturation;
  3176. hsl.l = lightness;
  3177. return hsl;
  3178. },
  3179. getStyle: function () {
  3180. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3181. },
  3182. offsetHSL: function ( h, s, l ) {
  3183. var hsl = this.getHSL();
  3184. hsl.h += h; hsl.s += s; hsl.l += l;
  3185. this.setHSL( hsl.h, hsl.s, hsl.l );
  3186. return this;
  3187. },
  3188. add: function ( color ) {
  3189. this.r += color.r;
  3190. this.g += color.g;
  3191. this.b += color.b;
  3192. return this;
  3193. },
  3194. addColors: function ( color1, color2 ) {
  3195. this.r = color1.r + color2.r;
  3196. this.g = color1.g + color2.g;
  3197. this.b = color1.b + color2.b;
  3198. return this;
  3199. },
  3200. addScalar: function ( s ) {
  3201. this.r += s;
  3202. this.g += s;
  3203. this.b += s;
  3204. return this;
  3205. },
  3206. sub: function( color ) {
  3207. this.r = Math.max( 0, this.r - color.r );
  3208. this.g = Math.max( 0, this.g - color.g );
  3209. this.b = Math.max( 0, this.b - color.b );
  3210. return this;
  3211. },
  3212. multiply: function ( color ) {
  3213. this.r *= color.r;
  3214. this.g *= color.g;
  3215. this.b *= color.b;
  3216. return this;
  3217. },
  3218. multiplyScalar: function ( s ) {
  3219. this.r *= s;
  3220. this.g *= s;
  3221. this.b *= s;
  3222. return this;
  3223. },
  3224. lerp: function ( color, alpha ) {
  3225. this.r += ( color.r - this.r ) * alpha;
  3226. this.g += ( color.g - this.g ) * alpha;
  3227. this.b += ( color.b - this.b ) * alpha;
  3228. return this;
  3229. },
  3230. equals: function ( c ) {
  3231. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3232. },
  3233. fromArray: function ( array, offset ) {
  3234. if ( offset === undefined ) offset = 0;
  3235. this.r = array[ offset ];
  3236. this.g = array[ offset + 1 ];
  3237. this.b = array[ offset + 2 ];
  3238. return this;
  3239. },
  3240. toArray: function ( array, offset ) {
  3241. if ( array === undefined ) array = [];
  3242. if ( offset === undefined ) offset = 0;
  3243. array[ offset ] = this.r;
  3244. array[ offset + 1 ] = this.g;
  3245. array[ offset + 2 ] = this.b;
  3246. return array;
  3247. },
  3248. toJSON: function () {
  3249. return this.getHex();
  3250. }
  3251. } );
  3252. /**
  3253. * Uniforms library for shared webgl shaders
  3254. */
  3255. var UniformsLib = {
  3256. common: {
  3257. diffuse: { value: new Color( 0xeeeeee ) },
  3258. opacity: { value: 1.0 },
  3259. map: { value: null },
  3260. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3261. specularMap: { value: null },
  3262. alphaMap: { value: null },
  3263. envMap: { value: null },
  3264. flipEnvMap: { value: - 1 },
  3265. reflectivity: { value: 1.0 },
  3266. refractionRatio: { value: 0.98 }
  3267. },
  3268. aomap: {
  3269. aoMap: { value: null },
  3270. aoMapIntensity: { value: 1 }
  3271. },
  3272. lightmap: {
  3273. lightMap: { value: null },
  3274. lightMapIntensity: { value: 1 }
  3275. },
  3276. emissivemap: {
  3277. emissiveMap: { value: null }
  3278. },
  3279. bumpmap: {
  3280. bumpMap: { value: null },
  3281. bumpScale: { value: 1 }
  3282. },
  3283. normalmap: {
  3284. normalMap: { value: null },
  3285. normalScale: { value: new Vector2( 1, 1 ) }
  3286. },
  3287. displacementmap: {
  3288. displacementMap: { value: null },
  3289. displacementScale: { value: 1 },
  3290. displacementBias: { value: 0 }
  3291. },
  3292. roughnessmap: {
  3293. roughnessMap: { value: null }
  3294. },
  3295. metalnessmap: {
  3296. metalnessMap: { value: null }
  3297. },
  3298. gradientmap: {
  3299. gradientMap: { value: null }
  3300. },
  3301. fog: {
  3302. fogDensity: { value: 0.00025 },
  3303. fogNear: { value: 1 },
  3304. fogFar: { value: 2000 },
  3305. fogColor: { value: new Color( 0xffffff ) }
  3306. },
  3307. lights: {
  3308. ambientLightColor: { value: [] },
  3309. directionalLights: { value: [], properties: {
  3310. direction: {},
  3311. color: {},
  3312. shadow: {},
  3313. shadowBias: {},
  3314. shadowRadius: {},
  3315. shadowMapSize: {}
  3316. } },
  3317. directionalShadowMap: { value: [] },
  3318. directionalShadowMatrix: { value: [] },
  3319. spotLights: { value: [], properties: {
  3320. color: {},
  3321. position: {},
  3322. direction: {},
  3323. distance: {},
  3324. coneCos: {},
  3325. penumbraCos: {},
  3326. decay: {},
  3327. shadow: {},
  3328. shadowBias: {},
  3329. shadowRadius: {},
  3330. shadowMapSize: {}
  3331. } },
  3332. spotShadowMap: { value: [] },
  3333. spotShadowMatrix: { value: [] },
  3334. pointLights: { value: [], properties: {
  3335. color: {},
  3336. position: {},
  3337. decay: {},
  3338. distance: {},
  3339. shadow: {},
  3340. shadowBias: {},
  3341. shadowRadius: {},
  3342. shadowMapSize: {},
  3343. shadowCameraNear: {},
  3344. shadowCameraFar: {}
  3345. } },
  3346. pointShadowMap: { value: [] },
  3347. pointShadowMatrix: { value: [] },
  3348. hemisphereLights: { value: [], properties: {
  3349. direction: {},
  3350. skyColor: {},
  3351. groundColor: {}
  3352. } },
  3353. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3354. rectAreaLights: { value: [], properties: {
  3355. color: {},
  3356. position: {},
  3357. width: {},
  3358. height: {}
  3359. } }
  3360. },
  3361. points: {
  3362. diffuse: { value: new Color( 0xeeeeee ) },
  3363. opacity: { value: 1.0 },
  3364. size: { value: 1.0 },
  3365. scale: { value: 1.0 },
  3366. map: { value: null },
  3367. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3368. }
  3369. };
  3370. /**
  3371. * Uniform Utilities
  3372. */
  3373. var UniformsUtils = {
  3374. merge: function ( uniforms ) {
  3375. var merged = {};
  3376. for ( var u = 0; u < uniforms.length; u ++ ) {
  3377. var tmp = this.clone( uniforms[ u ] );
  3378. for ( var p in tmp ) {
  3379. merged[ p ] = tmp[ p ];
  3380. }
  3381. }
  3382. return merged;
  3383. },
  3384. clone: function ( uniforms_src ) {
  3385. var uniforms_dst = {};
  3386. for ( var u in uniforms_src ) {
  3387. uniforms_dst[ u ] = {};
  3388. for ( var p in uniforms_src[ u ] ) {
  3389. var parameter_src = uniforms_src[ u ][ p ];
  3390. if ( parameter_src && ( parameter_src.isColor ||
  3391. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3392. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3393. parameter_src.isTexture ) ) {
  3394. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3395. } else if ( Array.isArray( parameter_src ) ) {
  3396. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3397. } else {
  3398. uniforms_dst[ u ][ p ] = parameter_src;
  3399. }
  3400. }
  3401. }
  3402. return uniforms_dst;
  3403. }
  3404. };
  3405. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3406. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3407. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3408. 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";
  3409. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3410. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3411. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3412. 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";
  3413. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  3414. 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";
  3415. 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";
  3416. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3417. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3418. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3419. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3420. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3421. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3422. 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";
  3423. 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";
  3424. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  3425. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3426. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3427. 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";
  3428. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3429. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3430. 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";
  3431. 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, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = 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";
  3432. 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";
  3433. 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";
  3434. 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";
  3435. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3436. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3437. 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";
  3438. 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";
  3439. 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";
  3440. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3441. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3442. 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";
  3443. 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\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\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 = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 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";
  3444. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3445. 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";
  3446. 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";
  3447. 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";
  3448. 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 ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 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";
  3449. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3450. 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";
  3451. 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";
  3452. 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";
  3453. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3454. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3455. 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";
  3456. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3457. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3458. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3459. 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";
  3460. 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";
  3461. 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";
  3462. 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 );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\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";
  3463. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3464. 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";
  3465. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3466. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  3467. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3468. 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";
  3469. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3470. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3471. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\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";
  3472. 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";
  3473. 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";
  3474. 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 ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3475. 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";
  3476. 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";
  3477. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n";
  3478. 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";
  3479. 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";
  3480. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3481. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3482. 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";
  3483. 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";
  3484. 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";
  3485. 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";
  3486. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3487. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3488. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3489. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  3490. 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";
  3491. 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";
  3492. 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";
  3493. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3494. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n";
  3495. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n";
  3496. 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";
  3497. 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";
  3498. 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";
  3499. 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";
  3500. 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 <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";
  3501. 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";
  3502. 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 <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";
  3503. 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";
  3504. 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_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";
  3505. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3506. 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_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";
  3507. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3508. 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_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  3509. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3510. 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";
  3511. 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";
  3512. 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";
  3513. 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";
  3514. var ShaderChunk = {
  3515. alphamap_fragment: alphamap_fragment,
  3516. alphamap_pars_fragment: alphamap_pars_fragment,
  3517. alphatest_fragment: alphatest_fragment,
  3518. aomap_fragment: aomap_fragment,
  3519. aomap_pars_fragment: aomap_pars_fragment,
  3520. begin_vertex: begin_vertex,
  3521. beginnormal_vertex: beginnormal_vertex,
  3522. bsdfs: bsdfs,
  3523. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3524. clipping_planes_fragment: clipping_planes_fragment,
  3525. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3526. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3527. clipping_planes_vertex: clipping_planes_vertex,
  3528. color_fragment: color_fragment,
  3529. color_pars_fragment: color_pars_fragment,
  3530. color_pars_vertex: color_pars_vertex,
  3531. color_vertex: color_vertex,
  3532. common: common,
  3533. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3534. defaultnormal_vertex: defaultnormal_vertex,
  3535. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3536. displacementmap_vertex: displacementmap_vertex,
  3537. emissivemap_fragment: emissivemap_fragment,
  3538. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3539. encodings_fragment: encodings_fragment,
  3540. encodings_pars_fragment: encodings_pars_fragment,
  3541. envmap_fragment: envmap_fragment,
  3542. envmap_pars_fragment: envmap_pars_fragment,
  3543. envmap_pars_vertex: envmap_pars_vertex,
  3544. envmap_vertex: envmap_vertex,
  3545. fog_vertex: fog_vertex,
  3546. fog_pars_vertex: fog_pars_vertex,
  3547. fog_fragment: fog_fragment,
  3548. fog_pars_fragment: fog_pars_fragment,
  3549. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3550. lightmap_fragment: lightmap_fragment,
  3551. lightmap_pars_fragment: lightmap_pars_fragment,
  3552. lights_lambert_vertex: lights_lambert_vertex,
  3553. lights_pars: lights_pars,
  3554. lights_phong_fragment: lights_phong_fragment,
  3555. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3556. lights_physical_fragment: lights_physical_fragment,
  3557. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3558. lights_template: lights_template,
  3559. logdepthbuf_fragment: logdepthbuf_fragment,
  3560. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3561. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3562. logdepthbuf_vertex: logdepthbuf_vertex,
  3563. map_fragment: map_fragment,
  3564. map_pars_fragment: map_pars_fragment,
  3565. map_particle_fragment: map_particle_fragment,
  3566. map_particle_pars_fragment: map_particle_pars_fragment,
  3567. metalnessmap_fragment: metalnessmap_fragment,
  3568. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3569. morphnormal_vertex: morphnormal_vertex,
  3570. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3571. morphtarget_vertex: morphtarget_vertex,
  3572. normal_fragment: normal_fragment,
  3573. normalmap_pars_fragment: normalmap_pars_fragment,
  3574. packing: packing,
  3575. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3576. project_vertex: project_vertex,
  3577. dithering_fragment: dithering_fragment,
  3578. dithering_pars_fragment: dithering_pars_fragment,
  3579. roughnessmap_fragment: roughnessmap_fragment,
  3580. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3581. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3582. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3583. shadowmap_vertex: shadowmap_vertex,
  3584. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3585. skinbase_vertex: skinbase_vertex,
  3586. skinning_pars_vertex: skinning_pars_vertex,
  3587. skinning_vertex: skinning_vertex,
  3588. skinnormal_vertex: skinnormal_vertex,
  3589. specularmap_fragment: specularmap_fragment,
  3590. specularmap_pars_fragment: specularmap_pars_fragment,
  3591. tonemapping_fragment: tonemapping_fragment,
  3592. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3593. uv_pars_fragment: uv_pars_fragment,
  3594. uv_pars_vertex: uv_pars_vertex,
  3595. uv_vertex: uv_vertex,
  3596. uv2_pars_fragment: uv2_pars_fragment,
  3597. uv2_pars_vertex: uv2_pars_vertex,
  3598. uv2_vertex: uv2_vertex,
  3599. worldpos_vertex: worldpos_vertex,
  3600. cube_frag: cube_frag,
  3601. cube_vert: cube_vert,
  3602. depth_frag: depth_frag,
  3603. depth_vert: depth_vert,
  3604. distanceRGBA_frag: distanceRGBA_frag,
  3605. distanceRGBA_vert: distanceRGBA_vert,
  3606. equirect_frag: equirect_frag,
  3607. equirect_vert: equirect_vert,
  3608. linedashed_frag: linedashed_frag,
  3609. linedashed_vert: linedashed_vert,
  3610. meshbasic_frag: meshbasic_frag,
  3611. meshbasic_vert: meshbasic_vert,
  3612. meshlambert_frag: meshlambert_frag,
  3613. meshlambert_vert: meshlambert_vert,
  3614. meshphong_frag: meshphong_frag,
  3615. meshphong_vert: meshphong_vert,
  3616. meshphysical_frag: meshphysical_frag,
  3617. meshphysical_vert: meshphysical_vert,
  3618. normal_frag: normal_frag,
  3619. normal_vert: normal_vert,
  3620. points_frag: points_frag,
  3621. points_vert: points_vert,
  3622. shadow_frag: shadow_frag,
  3623. shadow_vert: shadow_vert
  3624. };
  3625. /**
  3626. * @author alteredq / http://alteredqualia.com/
  3627. * @author mrdoob / http://mrdoob.com/
  3628. * @author mikael emtinger / http://gomo.se/
  3629. */
  3630. var ShaderLib = {
  3631. basic: {
  3632. uniforms: UniformsUtils.merge( [
  3633. UniformsLib.common,
  3634. UniformsLib.aomap,
  3635. UniformsLib.lightmap,
  3636. UniformsLib.fog
  3637. ] ),
  3638. vertexShader: ShaderChunk.meshbasic_vert,
  3639. fragmentShader: ShaderChunk.meshbasic_frag
  3640. },
  3641. lambert: {
  3642. uniforms: UniformsUtils.merge( [
  3643. UniformsLib.common,
  3644. UniformsLib.aomap,
  3645. UniformsLib.lightmap,
  3646. UniformsLib.emissivemap,
  3647. UniformsLib.fog,
  3648. UniformsLib.lights,
  3649. {
  3650. emissive: { value: new Color( 0x000000 ) }
  3651. }
  3652. ] ),
  3653. vertexShader: ShaderChunk.meshlambert_vert,
  3654. fragmentShader: ShaderChunk.meshlambert_frag
  3655. },
  3656. phong: {
  3657. uniforms: UniformsUtils.merge( [
  3658. UniformsLib.common,
  3659. UniformsLib.aomap,
  3660. UniformsLib.lightmap,
  3661. UniformsLib.emissivemap,
  3662. UniformsLib.bumpmap,
  3663. UniformsLib.normalmap,
  3664. UniformsLib.displacementmap,
  3665. UniformsLib.gradientmap,
  3666. UniformsLib.fog,
  3667. UniformsLib.lights,
  3668. {
  3669. emissive: { value: new Color( 0x000000 ) },
  3670. specular: { value: new Color( 0x111111 ) },
  3671. shininess: { value: 30 }
  3672. }
  3673. ] ),
  3674. vertexShader: ShaderChunk.meshphong_vert,
  3675. fragmentShader: ShaderChunk.meshphong_frag
  3676. },
  3677. standard: {
  3678. uniforms: UniformsUtils.merge( [
  3679. UniformsLib.common,
  3680. UniformsLib.aomap,
  3681. UniformsLib.lightmap,
  3682. UniformsLib.emissivemap,
  3683. UniformsLib.bumpmap,
  3684. UniformsLib.normalmap,
  3685. UniformsLib.displacementmap,
  3686. UniformsLib.roughnessmap,
  3687. UniformsLib.metalnessmap,
  3688. UniformsLib.fog,
  3689. UniformsLib.lights,
  3690. {
  3691. emissive: { value: new Color( 0x000000 ) },
  3692. roughness: { value: 0.5 },
  3693. metalness: { value: 0.5 },
  3694. envMapIntensity: { value: 1 } // temporary
  3695. }
  3696. ] ),
  3697. vertexShader: ShaderChunk.meshphysical_vert,
  3698. fragmentShader: ShaderChunk.meshphysical_frag
  3699. },
  3700. points: {
  3701. uniforms: UniformsUtils.merge( [
  3702. UniformsLib.points,
  3703. UniformsLib.fog
  3704. ] ),
  3705. vertexShader: ShaderChunk.points_vert,
  3706. fragmentShader: ShaderChunk.points_frag
  3707. },
  3708. dashed: {
  3709. uniforms: UniformsUtils.merge( [
  3710. UniformsLib.common,
  3711. UniformsLib.fog,
  3712. {
  3713. scale: { value: 1 },
  3714. dashSize: { value: 1 },
  3715. totalSize: { value: 2 }
  3716. }
  3717. ] ),
  3718. vertexShader: ShaderChunk.linedashed_vert,
  3719. fragmentShader: ShaderChunk.linedashed_frag
  3720. },
  3721. depth: {
  3722. uniforms: UniformsUtils.merge( [
  3723. UniformsLib.common,
  3724. UniformsLib.displacementmap
  3725. ] ),
  3726. vertexShader: ShaderChunk.depth_vert,
  3727. fragmentShader: ShaderChunk.depth_frag
  3728. },
  3729. normal: {
  3730. uniforms: UniformsUtils.merge( [
  3731. UniformsLib.common,
  3732. UniformsLib.bumpmap,
  3733. UniformsLib.normalmap,
  3734. UniformsLib.displacementmap,
  3735. {
  3736. opacity: { value: 1.0 }
  3737. }
  3738. ] ),
  3739. vertexShader: ShaderChunk.normal_vert,
  3740. fragmentShader: ShaderChunk.normal_frag
  3741. },
  3742. /* -------------------------------------------------------------------------
  3743. // Cube map shader
  3744. ------------------------------------------------------------------------- */
  3745. cube: {
  3746. uniforms: {
  3747. tCube: { value: null },
  3748. tFlip: { value: - 1 },
  3749. opacity: { value: 1.0 }
  3750. },
  3751. vertexShader: ShaderChunk.cube_vert,
  3752. fragmentShader: ShaderChunk.cube_frag
  3753. },
  3754. /* -------------------------------------------------------------------------
  3755. // Cube map shader
  3756. ------------------------------------------------------------------------- */
  3757. equirect: {
  3758. uniforms: {
  3759. tEquirect: { value: null },
  3760. tFlip: { value: - 1 }
  3761. },
  3762. vertexShader: ShaderChunk.equirect_vert,
  3763. fragmentShader: ShaderChunk.equirect_frag
  3764. },
  3765. distanceRGBA: {
  3766. uniforms: UniformsUtils.merge( [
  3767. UniformsLib.common,
  3768. UniformsLib.displacementmap,
  3769. {
  3770. referencePosition: { value: new Vector3() },
  3771. nearDistance: { value: 1 },
  3772. farDistance: { value: 1000 }
  3773. }
  3774. ] ),
  3775. vertexShader: ShaderChunk.distanceRGBA_vert,
  3776. fragmentShader: ShaderChunk.distanceRGBA_frag
  3777. }
  3778. };
  3779. ShaderLib.physical = {
  3780. uniforms: UniformsUtils.merge( [
  3781. ShaderLib.standard.uniforms,
  3782. {
  3783. clearCoat: { value: 0 },
  3784. clearCoatRoughness: { value: 0 }
  3785. }
  3786. ] ),
  3787. vertexShader: ShaderChunk.meshphysical_vert,
  3788. fragmentShader: ShaderChunk.meshphysical_frag
  3789. };
  3790. /**
  3791. * @author bhouston / http://clara.io
  3792. */
  3793. function Box2( min, max ) {
  3794. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3795. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3796. }
  3797. Object.assign( Box2.prototype, {
  3798. set: function ( min, max ) {
  3799. this.min.copy( min );
  3800. this.max.copy( max );
  3801. return this;
  3802. },
  3803. setFromPoints: function ( points ) {
  3804. this.makeEmpty();
  3805. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3806. this.expandByPoint( points[ i ] );
  3807. }
  3808. return this;
  3809. },
  3810. setFromCenterAndSize: function () {
  3811. var v1 = new Vector2();
  3812. return function setFromCenterAndSize( center, size ) {
  3813. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3814. this.min.copy( center ).sub( halfSize );
  3815. this.max.copy( center ).add( halfSize );
  3816. return this;
  3817. };
  3818. }(),
  3819. clone: function () {
  3820. return new this.constructor().copy( this );
  3821. },
  3822. copy: function ( box ) {
  3823. this.min.copy( box.min );
  3824. this.max.copy( box.max );
  3825. return this;
  3826. },
  3827. makeEmpty: function () {
  3828. this.min.x = this.min.y = + Infinity;
  3829. this.max.x = this.max.y = - Infinity;
  3830. return this;
  3831. },
  3832. isEmpty: function () {
  3833. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3834. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3835. },
  3836. getCenter: function ( optionalTarget ) {
  3837. var result = optionalTarget || new Vector2();
  3838. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3839. },
  3840. getSize: function ( optionalTarget ) {
  3841. var result = optionalTarget || new Vector2();
  3842. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3843. },
  3844. expandByPoint: function ( point ) {
  3845. this.min.min( point );
  3846. this.max.max( point );
  3847. return this;
  3848. },
  3849. expandByVector: function ( vector ) {
  3850. this.min.sub( vector );
  3851. this.max.add( vector );
  3852. return this;
  3853. },
  3854. expandByScalar: function ( scalar ) {
  3855. this.min.addScalar( - scalar );
  3856. this.max.addScalar( scalar );
  3857. return this;
  3858. },
  3859. containsPoint: function ( point ) {
  3860. return point.x < this.min.x || point.x > this.max.x ||
  3861. point.y < this.min.y || point.y > this.max.y ? false : true;
  3862. },
  3863. containsBox: function ( box ) {
  3864. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3865. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3866. },
  3867. getParameter: function ( point, optionalTarget ) {
  3868. // This can potentially have a divide by zero if the box
  3869. // has a size dimension of 0.
  3870. var result = optionalTarget || new Vector2();
  3871. return result.set(
  3872. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3873. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3874. );
  3875. },
  3876. intersectsBox: function ( box ) {
  3877. // using 4 splitting planes to rule out intersections
  3878. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3879. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3880. },
  3881. clampPoint: function ( point, optionalTarget ) {
  3882. var result = optionalTarget || new Vector2();
  3883. return result.copy( point ).clamp( this.min, this.max );
  3884. },
  3885. distanceToPoint: function () {
  3886. var v1 = new Vector2();
  3887. return function distanceToPoint( point ) {
  3888. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3889. return clampedPoint.sub( point ).length();
  3890. };
  3891. }(),
  3892. intersect: function ( box ) {
  3893. this.min.max( box.min );
  3894. this.max.min( box.max );
  3895. return this;
  3896. },
  3897. union: function ( box ) {
  3898. this.min.min( box.min );
  3899. this.max.max( box.max );
  3900. return this;
  3901. },
  3902. translate: function ( offset ) {
  3903. this.min.add( offset );
  3904. this.max.add( offset );
  3905. return this;
  3906. },
  3907. equals: function ( box ) {
  3908. return box.min.equals( this.min ) && box.max.equals( this.max );
  3909. }
  3910. } );
  3911. /**
  3912. * @author mikael emtinger / http://gomo.se/
  3913. * @author alteredq / http://alteredqualia.com/
  3914. */
  3915. function WebGLFlareRenderer( renderer, gl, state, capabilities ) {
  3916. var vertexBuffer, elementBuffer;
  3917. var shader, program, attributes, uniforms;
  3918. var tempTexture, occlusionTexture;
  3919. function init() {
  3920. var vertices = new Float32Array( [
  3921. - 1, - 1, 0, 0,
  3922. 1, - 1, 1, 0,
  3923. 1, 1, 1, 1,
  3924. - 1, 1, 0, 1
  3925. ] );
  3926. var faces = new Uint16Array( [
  3927. 0, 1, 2,
  3928. 0, 2, 3
  3929. ] );
  3930. // buffers
  3931. vertexBuffer = gl.createBuffer();
  3932. elementBuffer = gl.createBuffer();
  3933. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3934. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3935. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3936. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3937. // textures
  3938. tempTexture = gl.createTexture();
  3939. occlusionTexture = gl.createTexture();
  3940. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3941. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3942. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3943. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3944. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3945. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3946. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3947. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3948. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3949. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3950. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3951. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3952. shader = {
  3953. vertexShader: [
  3954. "uniform lowp int renderType;",
  3955. "uniform vec3 screenPosition;",
  3956. "uniform vec2 scale;",
  3957. "uniform float rotation;",
  3958. "uniform sampler2D occlusionMap;",
  3959. "attribute vec2 position;",
  3960. "attribute vec2 uv;",
  3961. "varying vec2 vUV;",
  3962. "varying float vVisibility;",
  3963. "void main() {",
  3964. "vUV = uv;",
  3965. "vec2 pos = position;",
  3966. "if ( renderType == 2 ) {",
  3967. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3968. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3969. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3970. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3971. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3972. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3973. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3974. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3975. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3976. "vVisibility = visibility.r / 9.0;",
  3977. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3978. "vVisibility *= visibility.b / 9.0;",
  3979. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3980. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3981. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3982. "}",
  3983. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3984. "}"
  3985. ].join( "\n" ),
  3986. fragmentShader: [
  3987. "uniform lowp int renderType;",
  3988. "uniform sampler2D map;",
  3989. "uniform float opacity;",
  3990. "uniform vec3 color;",
  3991. "varying vec2 vUV;",
  3992. "varying float vVisibility;",
  3993. "void main() {",
  3994. // pink square
  3995. "if ( renderType == 0 ) {",
  3996. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  3997. // restore
  3998. "} else if ( renderType == 1 ) {",
  3999. "gl_FragColor = texture2D( map, vUV );",
  4000. // flare
  4001. "} else {",
  4002. "vec4 texture = texture2D( map, vUV );",
  4003. "texture.a *= opacity * vVisibility;",
  4004. "gl_FragColor = texture;",
  4005. "gl_FragColor.rgb *= color;",
  4006. "}",
  4007. "}"
  4008. ].join( "\n" )
  4009. };
  4010. program = createProgram( shader );
  4011. attributes = {
  4012. vertex: gl.getAttribLocation ( program, "position" ),
  4013. uv: gl.getAttribLocation ( program, "uv" )
  4014. };
  4015. uniforms = {
  4016. renderType: gl.getUniformLocation( program, "renderType" ),
  4017. map: gl.getUniformLocation( program, "map" ),
  4018. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4019. opacity: gl.getUniformLocation( program, "opacity" ),
  4020. color: gl.getUniformLocation( program, "color" ),
  4021. scale: gl.getUniformLocation( program, "scale" ),
  4022. rotation: gl.getUniformLocation( program, "rotation" ),
  4023. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4024. };
  4025. }
  4026. /*
  4027. * Render lens flares
  4028. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4029. * reads these back and calculates occlusion.
  4030. */
  4031. this.render = function ( flares, scene, camera, viewport ) {
  4032. if ( flares.length === 0 ) return;
  4033. var tempPosition = new Vector3();
  4034. var invAspect = viewport.w / viewport.z,
  4035. halfViewportWidth = viewport.z * 0.5,
  4036. halfViewportHeight = viewport.w * 0.5;
  4037. var size = 16 / viewport.w,
  4038. scale = new Vector2( size * invAspect, size );
  4039. var screenPosition = new Vector3( 1, 1, 0 ),
  4040. screenPositionPixels = new Vector2( 1, 1 );
  4041. var validArea = new Box2();
  4042. validArea.min.set( viewport.x, viewport.y );
  4043. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4044. if ( program === undefined ) {
  4045. init();
  4046. }
  4047. state.useProgram( program );
  4048. state.initAttributes();
  4049. state.enableAttribute( attributes.vertex );
  4050. state.enableAttribute( attributes.uv );
  4051. state.disableUnusedAttributes();
  4052. // loop through all lens flares to update their occlusion and positions
  4053. // setup gl and common used attribs/uniforms
  4054. gl.uniform1i( uniforms.occlusionMap, 0 );
  4055. gl.uniform1i( uniforms.map, 1 );
  4056. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4057. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4058. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4059. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4060. state.disable( gl.CULL_FACE );
  4061. state.buffers.depth.setMask( false );
  4062. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4063. size = 16 / viewport.w;
  4064. scale.set( size * invAspect, size );
  4065. // calc object screen position
  4066. var flare = flares[ i ];
  4067. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4068. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4069. tempPosition.applyMatrix4( camera.projectionMatrix );
  4070. // setup arrays for gl programs
  4071. screenPosition.copy( tempPosition );
  4072. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4073. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4074. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4075. // screen cull
  4076. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4077. // save current RGB to temp texture
  4078. state.activeTexture( gl.TEXTURE0 );
  4079. state.bindTexture( gl.TEXTURE_2D, null );
  4080. state.activeTexture( gl.TEXTURE1 );
  4081. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4082. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4083. // render pink quad
  4084. gl.uniform1i( uniforms.renderType, 0 );
  4085. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4086. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4087. state.disable( gl.BLEND );
  4088. state.enable( gl.DEPTH_TEST );
  4089. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4090. // copy result to occlusionMap
  4091. state.activeTexture( gl.TEXTURE0 );
  4092. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4093. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4094. // restore graphics
  4095. gl.uniform1i( uniforms.renderType, 1 );
  4096. state.disable( gl.DEPTH_TEST );
  4097. state.activeTexture( gl.TEXTURE1 );
  4098. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4099. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4100. // update object positions
  4101. flare.positionScreen.copy( screenPosition );
  4102. if ( flare.customUpdateCallback ) {
  4103. flare.customUpdateCallback( flare );
  4104. } else {
  4105. flare.updateLensFlares();
  4106. }
  4107. // render flares
  4108. gl.uniform1i( uniforms.renderType, 2 );
  4109. state.enable( gl.BLEND );
  4110. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4111. var sprite = flare.lensFlares[ j ];
  4112. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4113. screenPosition.x = sprite.x;
  4114. screenPosition.y = sprite.y;
  4115. screenPosition.z = sprite.z;
  4116. size = sprite.size * sprite.scale / viewport.w;
  4117. scale.x = size * invAspect;
  4118. scale.y = size;
  4119. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4120. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4121. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4122. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4123. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4124. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4125. renderer.setTexture2D( sprite.texture, 1 );
  4126. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4127. }
  4128. }
  4129. }
  4130. }
  4131. // restore gl
  4132. state.enable( gl.CULL_FACE );
  4133. state.enable( gl.DEPTH_TEST );
  4134. state.buffers.depth.setMask( true );
  4135. state.reset();
  4136. };
  4137. function createProgram( shader ) {
  4138. var program = gl.createProgram();
  4139. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4140. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4141. var prefix = "precision " + capabilities.precision + " float;\n";
  4142. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4143. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4144. gl.compileShader( fragmentShader );
  4145. gl.compileShader( vertexShader );
  4146. gl.attachShader( program, fragmentShader );
  4147. gl.attachShader( program, vertexShader );
  4148. gl.linkProgram( program );
  4149. return program;
  4150. }
  4151. }
  4152. /**
  4153. * @author mrdoob / http://mrdoob.com/
  4154. */
  4155. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  4156. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  4157. this.needsUpdate = true;
  4158. }
  4159. CanvasTexture.prototype = Object.create( Texture.prototype );
  4160. CanvasTexture.prototype.constructor = CanvasTexture;
  4161. /**
  4162. * @author mikael emtinger / http://gomo.se/
  4163. * @author alteredq / http://alteredqualia.com/
  4164. */
  4165. function WebGLSpriteRenderer( renderer, gl, state, capabilities ) {
  4166. var vertexBuffer, elementBuffer;
  4167. var program, attributes, uniforms;
  4168. var texture;
  4169. // decompose matrixWorld
  4170. var spritePosition = new Vector3();
  4171. var spriteRotation = new Quaternion();
  4172. var spriteScale = new Vector3();
  4173. function init() {
  4174. var vertices = new Float32Array( [
  4175. - 0.5, - 0.5, 0, 0,
  4176. 0.5, - 0.5, 1, 0,
  4177. 0.5, 0.5, 1, 1,
  4178. - 0.5, 0.5, 0, 1
  4179. ] );
  4180. var faces = new Uint16Array( [
  4181. 0, 1, 2,
  4182. 0, 2, 3
  4183. ] );
  4184. vertexBuffer = gl.createBuffer();
  4185. elementBuffer = gl.createBuffer();
  4186. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4187. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4188. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4189. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4190. program = createProgram();
  4191. attributes = {
  4192. position: gl.getAttribLocation ( program, 'position' ),
  4193. uv: gl.getAttribLocation ( program, 'uv' )
  4194. };
  4195. uniforms = {
  4196. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4197. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4198. rotation: gl.getUniformLocation( program, 'rotation' ),
  4199. scale: gl.getUniformLocation( program, 'scale' ),
  4200. color: gl.getUniformLocation( program, 'color' ),
  4201. map: gl.getUniformLocation( program, 'map' ),
  4202. opacity: gl.getUniformLocation( program, 'opacity' ),
  4203. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4204. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4205. fogType: gl.getUniformLocation( program, 'fogType' ),
  4206. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4207. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4208. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4209. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4210. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4211. };
  4212. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4213. canvas.width = 8;
  4214. canvas.height = 8;
  4215. var context = canvas.getContext( '2d' );
  4216. context.fillStyle = 'white';
  4217. context.fillRect( 0, 0, 8, 8 );
  4218. texture = new CanvasTexture( canvas );
  4219. }
  4220. this.render = function ( sprites, scene, camera ) {
  4221. if ( sprites.length === 0 ) return;
  4222. // setup gl
  4223. if ( program === undefined ) {
  4224. init();
  4225. }
  4226. state.useProgram( program );
  4227. state.initAttributes();
  4228. state.enableAttribute( attributes.position );
  4229. state.enableAttribute( attributes.uv );
  4230. state.disableUnusedAttributes();
  4231. state.disable( gl.CULL_FACE );
  4232. state.enable( gl.BLEND );
  4233. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4234. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4235. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4236. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4237. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4238. state.activeTexture( gl.TEXTURE0 );
  4239. gl.uniform1i( uniforms.map, 0 );
  4240. var oldFogType = 0;
  4241. var sceneFogType = 0;
  4242. var fog = scene.fog;
  4243. if ( fog ) {
  4244. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4245. if ( fog.isFog ) {
  4246. gl.uniform1f( uniforms.fogNear, fog.near );
  4247. gl.uniform1f( uniforms.fogFar, fog.far );
  4248. gl.uniform1i( uniforms.fogType, 1 );
  4249. oldFogType = 1;
  4250. sceneFogType = 1;
  4251. } else if ( fog.isFogExp2 ) {
  4252. gl.uniform1f( uniforms.fogDensity, fog.density );
  4253. gl.uniform1i( uniforms.fogType, 2 );
  4254. oldFogType = 2;
  4255. sceneFogType = 2;
  4256. }
  4257. } else {
  4258. gl.uniform1i( uniforms.fogType, 0 );
  4259. oldFogType = 0;
  4260. sceneFogType = 0;
  4261. }
  4262. // update positions and sort
  4263. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4264. var sprite = sprites[ i ];
  4265. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4266. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4267. }
  4268. sprites.sort( painterSortStable );
  4269. // render all sprites
  4270. var scale = [];
  4271. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4272. var sprite = sprites[ i ];
  4273. var material = sprite.material;
  4274. if ( material.visible === false ) continue;
  4275. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  4276. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4277. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4278. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4279. scale[ 0 ] = spriteScale.x;
  4280. scale[ 1 ] = spriteScale.y;
  4281. var fogType = 0;
  4282. if ( scene.fog && material.fog ) {
  4283. fogType = sceneFogType;
  4284. }
  4285. if ( oldFogType !== fogType ) {
  4286. gl.uniform1i( uniforms.fogType, fogType );
  4287. oldFogType = fogType;
  4288. }
  4289. if ( material.map !== null ) {
  4290. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4291. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4292. } else {
  4293. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4294. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4295. }
  4296. gl.uniform1f( uniforms.opacity, material.opacity );
  4297. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4298. gl.uniform1f( uniforms.rotation, material.rotation );
  4299. gl.uniform2fv( uniforms.scale, scale );
  4300. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  4301. state.buffers.depth.setTest( material.depthTest );
  4302. state.buffers.depth.setMask( material.depthWrite );
  4303. if ( material.map ) {
  4304. renderer.setTexture2D( material.map, 0 );
  4305. } else {
  4306. renderer.setTexture2D( texture, 0 );
  4307. }
  4308. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4309. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  4310. }
  4311. // restore gl
  4312. state.enable( gl.CULL_FACE );
  4313. state.reset();
  4314. };
  4315. function createProgram() {
  4316. var program = gl.createProgram();
  4317. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4318. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4319. gl.shaderSource( vertexShader, [
  4320. 'precision ' + capabilities.precision + ' float;',
  4321. '#define SHADER_NAME ' + 'SpriteMaterial',
  4322. 'uniform mat4 modelViewMatrix;',
  4323. 'uniform mat4 projectionMatrix;',
  4324. 'uniform float rotation;',
  4325. 'uniform vec2 scale;',
  4326. 'uniform vec2 uvOffset;',
  4327. 'uniform vec2 uvScale;',
  4328. 'attribute vec2 position;',
  4329. 'attribute vec2 uv;',
  4330. 'varying vec2 vUV;',
  4331. 'void main() {',
  4332. 'vUV = uvOffset + uv * uvScale;',
  4333. 'vec2 alignedPosition = position * scale;',
  4334. 'vec2 rotatedPosition;',
  4335. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4336. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4337. 'vec4 finalPosition;',
  4338. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4339. 'finalPosition.xy += rotatedPosition;',
  4340. 'finalPosition = projectionMatrix * finalPosition;',
  4341. 'gl_Position = finalPosition;',
  4342. '}'
  4343. ].join( '\n' ) );
  4344. gl.shaderSource( fragmentShader, [
  4345. 'precision ' + capabilities.precision + ' float;',
  4346. '#define SHADER_NAME ' + 'SpriteMaterial',
  4347. 'uniform vec3 color;',
  4348. 'uniform sampler2D map;',
  4349. 'uniform float opacity;',
  4350. 'uniform int fogType;',
  4351. 'uniform vec3 fogColor;',
  4352. 'uniform float fogDensity;',
  4353. 'uniform float fogNear;',
  4354. 'uniform float fogFar;',
  4355. 'uniform float alphaTest;',
  4356. 'varying vec2 vUV;',
  4357. 'void main() {',
  4358. 'vec4 texture = texture2D( map, vUV );',
  4359. 'if ( texture.a < alphaTest ) discard;',
  4360. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4361. 'if ( fogType > 0 ) {',
  4362. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4363. 'float fogFactor = 0.0;',
  4364. 'if ( fogType == 1 ) {',
  4365. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4366. '} else {',
  4367. 'const float LOG2 = 1.442695;',
  4368. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4369. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4370. '}',
  4371. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4372. '}',
  4373. '}'
  4374. ].join( '\n' ) );
  4375. gl.compileShader( vertexShader );
  4376. gl.compileShader( fragmentShader );
  4377. gl.attachShader( program, vertexShader );
  4378. gl.attachShader( program, fragmentShader );
  4379. gl.linkProgram( program );
  4380. return program;
  4381. }
  4382. function painterSortStable( a, b ) {
  4383. if ( a.renderOrder !== b.renderOrder ) {
  4384. return a.renderOrder - b.renderOrder;
  4385. } else if ( a.z !== b.z ) {
  4386. return b.z - a.z;
  4387. } else {
  4388. return b.id - a.id;
  4389. }
  4390. }
  4391. }
  4392. /**
  4393. * @author mrdoob / http://mrdoob.com/
  4394. * @author alteredq / http://alteredqualia.com/
  4395. */
  4396. var materialId = 0;
  4397. function Material() {
  4398. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4399. this.uuid = _Math.generateUUID();
  4400. this.name = '';
  4401. this.type = 'Material';
  4402. this.fog = true;
  4403. this.lights = true;
  4404. this.blending = NormalBlending;
  4405. this.side = FrontSide;
  4406. this.flatShading = false;
  4407. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4408. this.opacity = 1;
  4409. this.transparent = false;
  4410. this.blendSrc = SrcAlphaFactor;
  4411. this.blendDst = OneMinusSrcAlphaFactor;
  4412. this.blendEquation = AddEquation;
  4413. this.blendSrcAlpha = null;
  4414. this.blendDstAlpha = null;
  4415. this.blendEquationAlpha = null;
  4416. this.depthFunc = LessEqualDepth;
  4417. this.depthTest = true;
  4418. this.depthWrite = true;
  4419. this.clippingPlanes = null;
  4420. this.clipIntersection = false;
  4421. this.clipShadows = false;
  4422. this.colorWrite = true;
  4423. this.precision = null; // override the renderer's default precision for this material
  4424. this.polygonOffset = false;
  4425. this.polygonOffsetFactor = 0;
  4426. this.polygonOffsetUnits = 0;
  4427. this.dithering = false;
  4428. this.alphaTest = 0;
  4429. this.premultipliedAlpha = false;
  4430. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4431. this.visible = true;
  4432. this.needsUpdate = true;
  4433. }
  4434. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4435. isMaterial: true,
  4436. onBeforeCompile: function () {},
  4437. setValues: function ( values ) {
  4438. if ( values === undefined ) return;
  4439. for ( var key in values ) {
  4440. var newValue = values[ key ];
  4441. if ( newValue === undefined ) {
  4442. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4443. continue;
  4444. }
  4445. // for backward compatability if shading is set in the constructor
  4446. if ( key === 'shading' ) {
  4447. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4448. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4449. continue;
  4450. }
  4451. var currentValue = this[ key ];
  4452. if ( currentValue === undefined ) {
  4453. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4454. continue;
  4455. }
  4456. if ( currentValue && currentValue.isColor ) {
  4457. currentValue.set( newValue );
  4458. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4459. currentValue.copy( newValue );
  4460. } else if ( key === 'overdraw' ) {
  4461. // ensure overdraw is backwards-compatible with legacy boolean type
  4462. this[ key ] = Number( newValue );
  4463. } else {
  4464. this[ key ] = newValue;
  4465. }
  4466. }
  4467. },
  4468. toJSON: function ( meta ) {
  4469. var isRoot = meta === undefined;
  4470. if ( isRoot ) {
  4471. meta = {
  4472. textures: {},
  4473. images: {}
  4474. };
  4475. }
  4476. var data = {
  4477. metadata: {
  4478. version: 4.5,
  4479. type: 'Material',
  4480. generator: 'Material.toJSON'
  4481. }
  4482. };
  4483. // standard Material serialization
  4484. data.uuid = this.uuid;
  4485. data.type = this.type;
  4486. if ( this.name !== '' ) data.name = this.name;
  4487. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4488. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4489. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4490. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4491. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4492. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4493. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4494. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4495. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4496. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4497. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4498. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4499. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4500. data.bumpScale = this.bumpScale;
  4501. }
  4502. if ( this.normalMap && this.normalMap.isTexture ) {
  4503. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4504. data.normalScale = this.normalScale.toArray();
  4505. }
  4506. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4507. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4508. data.displacementScale = this.displacementScale;
  4509. data.displacementBias = this.displacementBias;
  4510. }
  4511. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4512. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4513. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4514. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4515. if ( this.envMap && this.envMap.isTexture ) {
  4516. data.envMap = this.envMap.toJSON( meta ).uuid;
  4517. data.reflectivity = this.reflectivity; // Scale behind envMap
  4518. }
  4519. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4520. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4521. }
  4522. if ( this.size !== undefined ) data.size = this.size;
  4523. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4524. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4525. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4526. if ( this.side !== FrontSide ) data.side = this.side;
  4527. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4528. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4529. if ( this.transparent === true ) data.transparent = this.transparent;
  4530. data.depthFunc = this.depthFunc;
  4531. data.depthTest = this.depthTest;
  4532. data.depthWrite = this.depthWrite;
  4533. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4534. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4535. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4536. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4537. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4538. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4539. data.skinning = this.skinning;
  4540. data.morphTargets = this.morphTargets;
  4541. data.dithering = this.dithering;
  4542. // TODO: Copied from Object3D.toJSON
  4543. function extractFromCache( cache ) {
  4544. var values = [];
  4545. for ( var key in cache ) {
  4546. var data = cache[ key ];
  4547. delete data.metadata;
  4548. values.push( data );
  4549. }
  4550. return values;
  4551. }
  4552. if ( isRoot ) {
  4553. var textures = extractFromCache( meta.textures );
  4554. var images = extractFromCache( meta.images );
  4555. if ( textures.length > 0 ) data.textures = textures;
  4556. if ( images.length > 0 ) data.images = images;
  4557. }
  4558. return data;
  4559. },
  4560. clone: function () {
  4561. return new this.constructor().copy( this );
  4562. },
  4563. copy: function ( source ) {
  4564. this.name = source.name;
  4565. this.fog = source.fog;
  4566. this.lights = source.lights;
  4567. this.blending = source.blending;
  4568. this.side = source.side;
  4569. this.flatShading = source.flatShading;
  4570. this.vertexColors = source.vertexColors;
  4571. this.opacity = source.opacity;
  4572. this.transparent = source.transparent;
  4573. this.blendSrc = source.blendSrc;
  4574. this.blendDst = source.blendDst;
  4575. this.blendEquation = source.blendEquation;
  4576. this.blendSrcAlpha = source.blendSrcAlpha;
  4577. this.blendDstAlpha = source.blendDstAlpha;
  4578. this.blendEquationAlpha = source.blendEquationAlpha;
  4579. this.depthFunc = source.depthFunc;
  4580. this.depthTest = source.depthTest;
  4581. this.depthWrite = source.depthWrite;
  4582. this.colorWrite = source.colorWrite;
  4583. this.precision = source.precision;
  4584. this.polygonOffset = source.polygonOffset;
  4585. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4586. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4587. this.dithering = source.dithering;
  4588. this.alphaTest = source.alphaTest;
  4589. this.premultipliedAlpha = source.premultipliedAlpha;
  4590. this.overdraw = source.overdraw;
  4591. this.visible = source.visible;
  4592. this.clipShadows = source.clipShadows;
  4593. this.clipIntersection = source.clipIntersection;
  4594. var srcPlanes = source.clippingPlanes,
  4595. dstPlanes = null;
  4596. if ( srcPlanes !== null ) {
  4597. var n = srcPlanes.length;
  4598. dstPlanes = new Array( n );
  4599. for ( var i = 0; i !== n; ++ i )
  4600. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4601. }
  4602. this.clippingPlanes = dstPlanes;
  4603. return this;
  4604. },
  4605. dispose: function () {
  4606. this.dispatchEvent( { type: 'dispose' } );
  4607. }
  4608. } );
  4609. /**
  4610. * @author alteredq / http://alteredqualia.com/
  4611. *
  4612. * parameters = {
  4613. * defines: { "label" : "value" },
  4614. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4615. *
  4616. * fragmentShader: <string>,
  4617. * vertexShader: <string>,
  4618. *
  4619. * wireframe: <boolean>,
  4620. * wireframeLinewidth: <float>,
  4621. *
  4622. * lights: <bool>,
  4623. *
  4624. * skinning: <bool>,
  4625. * morphTargets: <bool>,
  4626. * morphNormals: <bool>
  4627. * }
  4628. */
  4629. function ShaderMaterial( parameters ) {
  4630. Material.call( this );
  4631. this.type = 'ShaderMaterial';
  4632. this.defines = {};
  4633. this.uniforms = {};
  4634. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4635. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4636. this.linewidth = 1;
  4637. this.wireframe = false;
  4638. this.wireframeLinewidth = 1;
  4639. this.fog = false; // set to use scene fog
  4640. this.lights = false; // set to use scene lights
  4641. this.clipping = false; // set to use user-defined clipping planes
  4642. this.skinning = false; // set to use skinning attribute streams
  4643. this.morphTargets = false; // set to use morph targets
  4644. this.morphNormals = false; // set to use morph normals
  4645. this.extensions = {
  4646. derivatives: false, // set to use derivatives
  4647. fragDepth: false, // set to use fragment depth values
  4648. drawBuffers: false, // set to use draw buffers
  4649. shaderTextureLOD: false // set to use shader texture LOD
  4650. };
  4651. // When rendered geometry doesn't include these attributes but the material does,
  4652. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4653. this.defaultAttributeValues = {
  4654. 'color': [ 1, 1, 1 ],
  4655. 'uv': [ 0, 0 ],
  4656. 'uv2': [ 0, 0 ]
  4657. };
  4658. this.index0AttributeName = undefined;
  4659. if ( parameters !== undefined ) {
  4660. if ( parameters.attributes !== undefined ) {
  4661. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4662. }
  4663. this.setValues( parameters );
  4664. }
  4665. }
  4666. ShaderMaterial.prototype = Object.create( Material.prototype );
  4667. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4668. ShaderMaterial.prototype.isShaderMaterial = true;
  4669. ShaderMaterial.prototype.copy = function ( source ) {
  4670. Material.prototype.copy.call( this, source );
  4671. this.fragmentShader = source.fragmentShader;
  4672. this.vertexShader = source.vertexShader;
  4673. this.uniforms = UniformsUtils.clone( source.uniforms );
  4674. this.defines = source.defines;
  4675. this.wireframe = source.wireframe;
  4676. this.wireframeLinewidth = source.wireframeLinewidth;
  4677. this.lights = source.lights;
  4678. this.clipping = source.clipping;
  4679. this.skinning = source.skinning;
  4680. this.morphTargets = source.morphTargets;
  4681. this.morphNormals = source.morphNormals;
  4682. this.extensions = source.extensions;
  4683. return this;
  4684. };
  4685. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4686. var data = Material.prototype.toJSON.call( this, meta );
  4687. data.uniforms = this.uniforms;
  4688. data.vertexShader = this.vertexShader;
  4689. data.fragmentShader = this.fragmentShader;
  4690. return data;
  4691. };
  4692. /**
  4693. * @author mrdoob / http://mrdoob.com/
  4694. * @author alteredq / http://alteredqualia.com/
  4695. * @author bhouston / https://clara.io
  4696. * @author WestLangley / http://github.com/WestLangley
  4697. *
  4698. * parameters = {
  4699. *
  4700. * opacity: <float>,
  4701. *
  4702. * map: new THREE.Texture( <Image> ),
  4703. *
  4704. * alphaMap: new THREE.Texture( <Image> ),
  4705. *
  4706. * displacementMap: new THREE.Texture( <Image> ),
  4707. * displacementScale: <float>,
  4708. * displacementBias: <float>,
  4709. *
  4710. * wireframe: <boolean>,
  4711. * wireframeLinewidth: <float>
  4712. * }
  4713. */
  4714. function MeshDepthMaterial( parameters ) {
  4715. Material.call( this );
  4716. this.type = 'MeshDepthMaterial';
  4717. this.depthPacking = BasicDepthPacking;
  4718. this.skinning = false;
  4719. this.morphTargets = false;
  4720. this.map = null;
  4721. this.alphaMap = null;
  4722. this.displacementMap = null;
  4723. this.displacementScale = 1;
  4724. this.displacementBias = 0;
  4725. this.wireframe = false;
  4726. this.wireframeLinewidth = 1;
  4727. this.fog = false;
  4728. this.lights = false;
  4729. this.setValues( parameters );
  4730. }
  4731. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4732. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4733. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4734. MeshDepthMaterial.prototype.copy = function ( source ) {
  4735. Material.prototype.copy.call( this, source );
  4736. this.depthPacking = source.depthPacking;
  4737. this.skinning = source.skinning;
  4738. this.morphTargets = source.morphTargets;
  4739. this.map = source.map;
  4740. this.alphaMap = source.alphaMap;
  4741. this.displacementMap = source.displacementMap;
  4742. this.displacementScale = source.displacementScale;
  4743. this.displacementBias = source.displacementBias;
  4744. this.wireframe = source.wireframe;
  4745. this.wireframeLinewidth = source.wireframeLinewidth;
  4746. return this;
  4747. };
  4748. /**
  4749. * @author WestLangley / http://github.com/WestLangley
  4750. *
  4751. * parameters = {
  4752. *
  4753. * referencePosition: <float>,
  4754. * nearDistance: <float>,
  4755. * farDistance: <float>,
  4756. *
  4757. * skinning: <bool>,
  4758. * morphTargets: <bool>,
  4759. *
  4760. * map: new THREE.Texture( <Image> ),
  4761. *
  4762. * alphaMap: new THREE.Texture( <Image> ),
  4763. *
  4764. * displacementMap: new THREE.Texture( <Image> ),
  4765. * displacementScale: <float>,
  4766. * displacementBias: <float>
  4767. *
  4768. * }
  4769. */
  4770. function MeshDistanceMaterial( parameters ) {
  4771. Material.call( this );
  4772. this.type = 'MeshDistanceMaterial';
  4773. this.referencePosition = new THREE.Vector3();
  4774. this.nearDistance = 1;
  4775. this.farDistance = 1000;
  4776. this.skinning = false;
  4777. this.morphTargets = false;
  4778. this.map = null;
  4779. this.alphaMap = null;
  4780. this.displacementMap = null;
  4781. this.displacementScale = 1;
  4782. this.displacementBias = 0;
  4783. this.fog = false;
  4784. this.lights = false;
  4785. this.setValues( parameters );
  4786. }
  4787. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  4788. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  4789. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  4790. MeshDistanceMaterial.prototype.copy = function ( source ) {
  4791. Material.prototype.copy.call( this, source );
  4792. this.referencePosition.copy( source.referencePosition );
  4793. this.nearDistance = source.nearDistance;
  4794. this.farDistance = source.farDistance;
  4795. this.skinning = source.skinning;
  4796. this.morphTargets = source.morphTargets;
  4797. this.map = source.map;
  4798. this.alphaMap = source.alphaMap;
  4799. this.displacementMap = source.displacementMap;
  4800. this.displacementScale = source.displacementScale;
  4801. this.displacementBias = source.displacementBias;
  4802. return this;
  4803. };
  4804. /**
  4805. * @author bhouston / http://clara.io
  4806. * @author WestLangley / http://github.com/WestLangley
  4807. */
  4808. function Box3( min, max ) {
  4809. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4810. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4811. }
  4812. Object.assign( Box3.prototype, {
  4813. isBox3: true,
  4814. set: function ( min, max ) {
  4815. this.min.copy( min );
  4816. this.max.copy( max );
  4817. return this;
  4818. },
  4819. setFromArray: function ( array ) {
  4820. var minX = + Infinity;
  4821. var minY = + Infinity;
  4822. var minZ = + Infinity;
  4823. var maxX = - Infinity;
  4824. var maxY = - Infinity;
  4825. var maxZ = - Infinity;
  4826. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4827. var x = array[ i ];
  4828. var y = array[ i + 1 ];
  4829. var z = array[ i + 2 ];
  4830. if ( x < minX ) minX = x;
  4831. if ( y < minY ) minY = y;
  4832. if ( z < minZ ) minZ = z;
  4833. if ( x > maxX ) maxX = x;
  4834. if ( y > maxY ) maxY = y;
  4835. if ( z > maxZ ) maxZ = z;
  4836. }
  4837. this.min.set( minX, minY, minZ );
  4838. this.max.set( maxX, maxY, maxZ );
  4839. return this;
  4840. },
  4841. setFromBufferAttribute: function ( attribute ) {
  4842. var minX = + Infinity;
  4843. var minY = + Infinity;
  4844. var minZ = + Infinity;
  4845. var maxX = - Infinity;
  4846. var maxY = - Infinity;
  4847. var maxZ = - Infinity;
  4848. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4849. var x = attribute.getX( i );
  4850. var y = attribute.getY( i );
  4851. var z = attribute.getZ( i );
  4852. if ( x < minX ) minX = x;
  4853. if ( y < minY ) minY = y;
  4854. if ( z < minZ ) minZ = z;
  4855. if ( x > maxX ) maxX = x;
  4856. if ( y > maxY ) maxY = y;
  4857. if ( z > maxZ ) maxZ = z;
  4858. }
  4859. this.min.set( minX, minY, minZ );
  4860. this.max.set( maxX, maxY, maxZ );
  4861. return this;
  4862. },
  4863. setFromPoints: function ( points ) {
  4864. this.makeEmpty();
  4865. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4866. this.expandByPoint( points[ i ] );
  4867. }
  4868. return this;
  4869. },
  4870. setFromCenterAndSize: function () {
  4871. var v1 = new Vector3();
  4872. return function setFromCenterAndSize( center, size ) {
  4873. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4874. this.min.copy( center ).sub( halfSize );
  4875. this.max.copy( center ).add( halfSize );
  4876. return this;
  4877. };
  4878. }(),
  4879. setFromObject: function ( object ) {
  4880. this.makeEmpty();
  4881. return this.expandByObject( object );
  4882. },
  4883. clone: function () {
  4884. return new this.constructor().copy( this );
  4885. },
  4886. copy: function ( box ) {
  4887. this.min.copy( box.min );
  4888. this.max.copy( box.max );
  4889. return this;
  4890. },
  4891. makeEmpty: function () {
  4892. this.min.x = this.min.y = this.min.z = + Infinity;
  4893. this.max.x = this.max.y = this.max.z = - Infinity;
  4894. return this;
  4895. },
  4896. isEmpty: function () {
  4897. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4898. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4899. },
  4900. getCenter: function ( optionalTarget ) {
  4901. var result = optionalTarget || new Vector3();
  4902. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4903. },
  4904. getSize: function ( optionalTarget ) {
  4905. var result = optionalTarget || new Vector3();
  4906. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4907. },
  4908. expandByPoint: function ( point ) {
  4909. this.min.min( point );
  4910. this.max.max( point );
  4911. return this;
  4912. },
  4913. expandByVector: function ( vector ) {
  4914. this.min.sub( vector );
  4915. this.max.add( vector );
  4916. return this;
  4917. },
  4918. expandByScalar: function ( scalar ) {
  4919. this.min.addScalar( - scalar );
  4920. this.max.addScalar( scalar );
  4921. return this;
  4922. },
  4923. expandByObject: function () {
  4924. // Computes the world-axis-aligned bounding box of an object (including its children),
  4925. // accounting for both the object's, and children's, world transforms
  4926. var v1 = new Vector3();
  4927. return function expandByObject( object ) {
  4928. var scope = this;
  4929. object.updateMatrixWorld( true );
  4930. object.traverse( function ( node ) {
  4931. var i, l;
  4932. var geometry = node.geometry;
  4933. if ( geometry !== undefined ) {
  4934. if ( geometry.isGeometry ) {
  4935. var vertices = geometry.vertices;
  4936. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4937. v1.copy( vertices[ i ] );
  4938. v1.applyMatrix4( node.matrixWorld );
  4939. scope.expandByPoint( v1 );
  4940. }
  4941. } else if ( geometry.isBufferGeometry ) {
  4942. var attribute = geometry.attributes.position;
  4943. if ( attribute !== undefined ) {
  4944. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4945. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4946. scope.expandByPoint( v1 );
  4947. }
  4948. }
  4949. }
  4950. }
  4951. } );
  4952. return this;
  4953. };
  4954. }(),
  4955. containsPoint: function ( point ) {
  4956. return point.x < this.min.x || point.x > this.max.x ||
  4957. point.y < this.min.y || point.y > this.max.y ||
  4958. point.z < this.min.z || point.z > this.max.z ? false : true;
  4959. },
  4960. containsBox: function ( box ) {
  4961. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4962. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4963. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4964. },
  4965. getParameter: function ( point, optionalTarget ) {
  4966. // This can potentially have a divide by zero if the box
  4967. // has a size dimension of 0.
  4968. var result = optionalTarget || new Vector3();
  4969. return result.set(
  4970. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4971. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4972. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4973. );
  4974. },
  4975. intersectsBox: function ( box ) {
  4976. // using 6 splitting planes to rule out intersections.
  4977. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4978. box.max.y < this.min.y || box.min.y > this.max.y ||
  4979. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4980. },
  4981. intersectsSphere: ( function () {
  4982. var closestPoint = new Vector3();
  4983. return function intersectsSphere( sphere ) {
  4984. // Find the point on the AABB closest to the sphere center.
  4985. this.clampPoint( sphere.center, closestPoint );
  4986. // If that point is inside the sphere, the AABB and sphere intersect.
  4987. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4988. };
  4989. } )(),
  4990. intersectsPlane: function ( plane ) {
  4991. // We compute the minimum and maximum dot product values. If those values
  4992. // are on the same side (back or front) of the plane, then there is no intersection.
  4993. var min, max;
  4994. if ( plane.normal.x > 0 ) {
  4995. min = plane.normal.x * this.min.x;
  4996. max = plane.normal.x * this.max.x;
  4997. } else {
  4998. min = plane.normal.x * this.max.x;
  4999. max = plane.normal.x * this.min.x;
  5000. }
  5001. if ( plane.normal.y > 0 ) {
  5002. min += plane.normal.y * this.min.y;
  5003. max += plane.normal.y * this.max.y;
  5004. } else {
  5005. min += plane.normal.y * this.max.y;
  5006. max += plane.normal.y * this.min.y;
  5007. }
  5008. if ( plane.normal.z > 0 ) {
  5009. min += plane.normal.z * this.min.z;
  5010. max += plane.normal.z * this.max.z;
  5011. } else {
  5012. min += plane.normal.z * this.max.z;
  5013. max += plane.normal.z * this.min.z;
  5014. }
  5015. return ( min <= plane.constant && max >= plane.constant );
  5016. },
  5017. clampPoint: function ( point, optionalTarget ) {
  5018. var result = optionalTarget || new Vector3();
  5019. return result.copy( point ).clamp( this.min, this.max );
  5020. },
  5021. distanceToPoint: function () {
  5022. var v1 = new Vector3();
  5023. return function distanceToPoint( point ) {
  5024. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5025. return clampedPoint.sub( point ).length();
  5026. };
  5027. }(),
  5028. getBoundingSphere: function () {
  5029. var v1 = new Vector3();
  5030. return function getBoundingSphere( optionalTarget ) {
  5031. var result = optionalTarget || new Sphere();
  5032. this.getCenter( result.center );
  5033. result.radius = this.getSize( v1 ).length() * 0.5;
  5034. return result;
  5035. };
  5036. }(),
  5037. intersect: function ( box ) {
  5038. this.min.max( box.min );
  5039. this.max.min( box.max );
  5040. // 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.
  5041. if( this.isEmpty() ) this.makeEmpty();
  5042. return this;
  5043. },
  5044. union: function ( box ) {
  5045. this.min.min( box.min );
  5046. this.max.max( box.max );
  5047. return this;
  5048. },
  5049. applyMatrix4: function () {
  5050. var points = [
  5051. new Vector3(),
  5052. new Vector3(),
  5053. new Vector3(),
  5054. new Vector3(),
  5055. new Vector3(),
  5056. new Vector3(),
  5057. new Vector3(),
  5058. new Vector3()
  5059. ];
  5060. return function applyMatrix4( matrix ) {
  5061. // transform of empty box is an empty box.
  5062. if( this.isEmpty() ) return this;
  5063. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5064. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5065. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5066. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5067. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5068. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5069. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5070. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5071. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5072. this.setFromPoints( points );
  5073. return this;
  5074. };
  5075. }(),
  5076. translate: function ( offset ) {
  5077. this.min.add( offset );
  5078. this.max.add( offset );
  5079. return this;
  5080. },
  5081. equals: function ( box ) {
  5082. return box.min.equals( this.min ) && box.max.equals( this.max );
  5083. }
  5084. } );
  5085. /**
  5086. * @author bhouston / http://clara.io
  5087. * @author mrdoob / http://mrdoob.com/
  5088. */
  5089. function Sphere( center, radius ) {
  5090. this.center = ( center !== undefined ) ? center : new Vector3();
  5091. this.radius = ( radius !== undefined ) ? radius : 0;
  5092. }
  5093. Object.assign( Sphere.prototype, {
  5094. set: function ( center, radius ) {
  5095. this.center.copy( center );
  5096. this.radius = radius;
  5097. return this;
  5098. },
  5099. setFromPoints: function () {
  5100. var box = new Box3();
  5101. return function setFromPoints( points, optionalCenter ) {
  5102. var center = this.center;
  5103. if ( optionalCenter !== undefined ) {
  5104. center.copy( optionalCenter );
  5105. } else {
  5106. box.setFromPoints( points ).getCenter( center );
  5107. }
  5108. var maxRadiusSq = 0;
  5109. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5110. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5111. }
  5112. this.radius = Math.sqrt( maxRadiusSq );
  5113. return this;
  5114. };
  5115. }(),
  5116. clone: function () {
  5117. return new this.constructor().copy( this );
  5118. },
  5119. copy: function ( sphere ) {
  5120. this.center.copy( sphere.center );
  5121. this.radius = sphere.radius;
  5122. return this;
  5123. },
  5124. empty: function () {
  5125. return ( this.radius <= 0 );
  5126. },
  5127. containsPoint: function ( point ) {
  5128. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5129. },
  5130. distanceToPoint: function ( point ) {
  5131. return ( point.distanceTo( this.center ) - this.radius );
  5132. },
  5133. intersectsSphere: function ( sphere ) {
  5134. var radiusSum = this.radius + sphere.radius;
  5135. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5136. },
  5137. intersectsBox: function ( box ) {
  5138. return box.intersectsSphere( this );
  5139. },
  5140. intersectsPlane: function ( plane ) {
  5141. // We use the following equation to compute the signed distance from
  5142. // the center of the sphere to the plane.
  5143. //
  5144. // distance = q * n - d
  5145. //
  5146. // If this distance is greater than the radius of the sphere,
  5147. // then there is no intersection.
  5148. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5149. },
  5150. clampPoint: function ( point, optionalTarget ) {
  5151. var deltaLengthSq = this.center.distanceToSquared( point );
  5152. var result = optionalTarget || new Vector3();
  5153. result.copy( point );
  5154. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5155. result.sub( this.center ).normalize();
  5156. result.multiplyScalar( this.radius ).add( this.center );
  5157. }
  5158. return result;
  5159. },
  5160. getBoundingBox: function ( optionalTarget ) {
  5161. var box = optionalTarget || new Box3();
  5162. box.set( this.center, this.center );
  5163. box.expandByScalar( this.radius );
  5164. return box;
  5165. },
  5166. applyMatrix4: function ( matrix ) {
  5167. this.center.applyMatrix4( matrix );
  5168. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5169. return this;
  5170. },
  5171. translate: function ( offset ) {
  5172. this.center.add( offset );
  5173. return this;
  5174. },
  5175. equals: function ( sphere ) {
  5176. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5177. }
  5178. } );
  5179. /**
  5180. * @author alteredq / http://alteredqualia.com/
  5181. * @author WestLangley / http://github.com/WestLangley
  5182. * @author bhouston / http://clara.io
  5183. * @author tschw
  5184. */
  5185. function Matrix3() {
  5186. this.elements = [
  5187. 1, 0, 0,
  5188. 0, 1, 0,
  5189. 0, 0, 1
  5190. ];
  5191. if ( arguments.length > 0 ) {
  5192. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5193. }
  5194. }
  5195. Object.assign( Matrix3.prototype, {
  5196. isMatrix3: true,
  5197. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5198. var te = this.elements;
  5199. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5200. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5201. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5202. return this;
  5203. },
  5204. identity: function () {
  5205. this.set(
  5206. 1, 0, 0,
  5207. 0, 1, 0,
  5208. 0, 0, 1
  5209. );
  5210. return this;
  5211. },
  5212. clone: function () {
  5213. return new this.constructor().fromArray( this.elements );
  5214. },
  5215. copy: function ( m ) {
  5216. var te = this.elements;
  5217. var me = m.elements;
  5218. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5219. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5220. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5221. return this;
  5222. },
  5223. setFromMatrix4: function ( m ) {
  5224. var me = m.elements;
  5225. this.set(
  5226. me[ 0 ], me[ 4 ], me[ 8 ],
  5227. me[ 1 ], me[ 5 ], me[ 9 ],
  5228. me[ 2 ], me[ 6 ], me[ 10 ]
  5229. );
  5230. return this;
  5231. },
  5232. applyToBufferAttribute: function () {
  5233. var v1 = new Vector3();
  5234. return function applyToBufferAttribute( attribute ) {
  5235. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5236. v1.x = attribute.getX( i );
  5237. v1.y = attribute.getY( i );
  5238. v1.z = attribute.getZ( i );
  5239. v1.applyMatrix3( this );
  5240. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5241. }
  5242. return attribute;
  5243. };
  5244. }(),
  5245. multiply: function ( m ) {
  5246. return this.multiplyMatrices( this, m );
  5247. },
  5248. premultiply: function ( m ) {
  5249. return this.multiplyMatrices( m, this );
  5250. },
  5251. multiplyMatrices: function ( a, b ) {
  5252. var ae = a.elements;
  5253. var be = b.elements;
  5254. var te = this.elements;
  5255. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5256. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5257. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5258. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5259. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5260. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5261. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5262. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5263. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5264. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5265. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5266. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5267. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5268. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5269. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5270. return this;
  5271. },
  5272. multiplyScalar: function ( s ) {
  5273. var te = this.elements;
  5274. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5275. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5276. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5277. return this;
  5278. },
  5279. determinant: function () {
  5280. var te = this.elements;
  5281. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5282. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5283. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5284. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5285. },
  5286. getInverse: function ( matrix, throwOnDegenerate ) {
  5287. if ( matrix && matrix.isMatrix4 ) {
  5288. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  5289. }
  5290. var me = matrix.elements,
  5291. te = this.elements,
  5292. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5293. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5294. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5295. t11 = n33 * n22 - n32 * n23,
  5296. t12 = n32 * n13 - n33 * n12,
  5297. t13 = n23 * n12 - n22 * n13,
  5298. det = n11 * t11 + n21 * t12 + n31 * t13;
  5299. if ( det === 0 ) {
  5300. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  5301. if ( throwOnDegenerate === true ) {
  5302. throw new Error( msg );
  5303. } else {
  5304. console.warn( msg );
  5305. }
  5306. return this.identity();
  5307. }
  5308. var detInv = 1 / det;
  5309. te[ 0 ] = t11 * detInv;
  5310. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5311. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5312. te[ 3 ] = t12 * detInv;
  5313. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5314. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5315. te[ 6 ] = t13 * detInv;
  5316. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5317. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5318. return this;
  5319. },
  5320. transpose: function () {
  5321. var tmp, m = this.elements;
  5322. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5323. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5324. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5325. return this;
  5326. },
  5327. getNormalMatrix: function ( matrix4 ) {
  5328. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5329. },
  5330. transposeIntoArray: function ( r ) {
  5331. var m = this.elements;
  5332. r[ 0 ] = m[ 0 ];
  5333. r[ 1 ] = m[ 3 ];
  5334. r[ 2 ] = m[ 6 ];
  5335. r[ 3 ] = m[ 1 ];
  5336. r[ 4 ] = m[ 4 ];
  5337. r[ 5 ] = m[ 7 ];
  5338. r[ 6 ] = m[ 2 ];
  5339. r[ 7 ] = m[ 5 ];
  5340. r[ 8 ] = m[ 8 ];
  5341. return this;
  5342. },
  5343. equals: function ( matrix ) {
  5344. var te = this.elements;
  5345. var me = matrix.elements;
  5346. for ( var i = 0; i < 9; i ++ ) {
  5347. if ( te[ i ] !== me[ i ] ) return false;
  5348. }
  5349. return true;
  5350. },
  5351. fromArray: function ( array, offset ) {
  5352. if ( offset === undefined ) offset = 0;
  5353. for ( var i = 0; i < 9; i ++ ) {
  5354. this.elements[ i ] = array[ i + offset ];
  5355. }
  5356. return this;
  5357. },
  5358. toArray: function ( array, offset ) {
  5359. if ( array === undefined ) array = [];
  5360. if ( offset === undefined ) offset = 0;
  5361. var te = this.elements;
  5362. array[ offset ] = te[ 0 ];
  5363. array[ offset + 1 ] = te[ 1 ];
  5364. array[ offset + 2 ] = te[ 2 ];
  5365. array[ offset + 3 ] = te[ 3 ];
  5366. array[ offset + 4 ] = te[ 4 ];
  5367. array[ offset + 5 ] = te[ 5 ];
  5368. array[ offset + 6 ] = te[ 6 ];
  5369. array[ offset + 7 ] = te[ 7 ];
  5370. array[ offset + 8 ] = te[ 8 ];
  5371. return array;
  5372. }
  5373. } );
  5374. /**
  5375. * @author bhouston / http://clara.io
  5376. */
  5377. function Plane( normal, constant ) {
  5378. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5379. this.constant = ( constant !== undefined ) ? constant : 0;
  5380. }
  5381. Object.assign( Plane.prototype, {
  5382. set: function ( normal, constant ) {
  5383. this.normal.copy( normal );
  5384. this.constant = constant;
  5385. return this;
  5386. },
  5387. setComponents: function ( x, y, z, w ) {
  5388. this.normal.set( x, y, z );
  5389. this.constant = w;
  5390. return this;
  5391. },
  5392. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5393. this.normal.copy( normal );
  5394. this.constant = - point.dot( this.normal );
  5395. return this;
  5396. },
  5397. setFromCoplanarPoints: function () {
  5398. var v1 = new Vector3();
  5399. var v2 = new Vector3();
  5400. return function setFromCoplanarPoints( a, b, c ) {
  5401. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5402. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5403. this.setFromNormalAndCoplanarPoint( normal, a );
  5404. return this;
  5405. };
  5406. }(),
  5407. clone: function () {
  5408. return new this.constructor().copy( this );
  5409. },
  5410. copy: function ( plane ) {
  5411. this.normal.copy( plane.normal );
  5412. this.constant = plane.constant;
  5413. return this;
  5414. },
  5415. normalize: function () {
  5416. // Note: will lead to a divide by zero if the plane is invalid.
  5417. var inverseNormalLength = 1.0 / this.normal.length();
  5418. this.normal.multiplyScalar( inverseNormalLength );
  5419. this.constant *= inverseNormalLength;
  5420. return this;
  5421. },
  5422. negate: function () {
  5423. this.constant *= - 1;
  5424. this.normal.negate();
  5425. return this;
  5426. },
  5427. distanceToPoint: function ( point ) {
  5428. return this.normal.dot( point ) + this.constant;
  5429. },
  5430. distanceToSphere: function ( sphere ) {
  5431. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5432. },
  5433. projectPoint: function ( point, optionalTarget ) {
  5434. var result = optionalTarget || new Vector3();
  5435. return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5436. },
  5437. intersectLine: function () {
  5438. var v1 = new Vector3();
  5439. return function intersectLine( line, optionalTarget ) {
  5440. var result = optionalTarget || new Vector3();
  5441. var direction = line.delta( v1 );
  5442. var denominator = this.normal.dot( direction );
  5443. if ( denominator === 0 ) {
  5444. // line is coplanar, return origin
  5445. if ( this.distanceToPoint( line.start ) === 0 ) {
  5446. return result.copy( line.start );
  5447. }
  5448. // Unsure if this is the correct method to handle this case.
  5449. return undefined;
  5450. }
  5451. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5452. if ( t < 0 || t > 1 ) {
  5453. return undefined;
  5454. }
  5455. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5456. };
  5457. }(),
  5458. intersectsLine: function ( line ) {
  5459. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5460. var startSign = this.distanceToPoint( line.start );
  5461. var endSign = this.distanceToPoint( line.end );
  5462. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5463. },
  5464. intersectsBox: function ( box ) {
  5465. return box.intersectsPlane( this );
  5466. },
  5467. intersectsSphere: function ( sphere ) {
  5468. return sphere.intersectsPlane( this );
  5469. },
  5470. coplanarPoint: function ( optionalTarget ) {
  5471. var result = optionalTarget || new Vector3();
  5472. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5473. },
  5474. applyMatrix4: function () {
  5475. var v1 = new Vector3();
  5476. var m1 = new Matrix3();
  5477. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5478. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5479. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5480. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5481. this.constant = - referencePoint.dot( normal );
  5482. return this;
  5483. };
  5484. }(),
  5485. translate: function ( offset ) {
  5486. this.constant -= offset.dot( this.normal );
  5487. return this;
  5488. },
  5489. equals: function ( plane ) {
  5490. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5491. }
  5492. } );
  5493. /**
  5494. * @author mrdoob / http://mrdoob.com/
  5495. * @author alteredq / http://alteredqualia.com/
  5496. * @author bhouston / http://clara.io
  5497. */
  5498. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5499. this.planes = [
  5500. ( p0 !== undefined ) ? p0 : new Plane(),
  5501. ( p1 !== undefined ) ? p1 : new Plane(),
  5502. ( p2 !== undefined ) ? p2 : new Plane(),
  5503. ( p3 !== undefined ) ? p3 : new Plane(),
  5504. ( p4 !== undefined ) ? p4 : new Plane(),
  5505. ( p5 !== undefined ) ? p5 : new Plane()
  5506. ];
  5507. }
  5508. Object.assign( Frustum.prototype, {
  5509. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5510. var planes = this.planes;
  5511. planes[ 0 ].copy( p0 );
  5512. planes[ 1 ].copy( p1 );
  5513. planes[ 2 ].copy( p2 );
  5514. planes[ 3 ].copy( p3 );
  5515. planes[ 4 ].copy( p4 );
  5516. planes[ 5 ].copy( p5 );
  5517. return this;
  5518. },
  5519. clone: function () {
  5520. return new this.constructor().copy( this );
  5521. },
  5522. copy: function ( frustum ) {
  5523. var planes = this.planes;
  5524. for ( var i = 0; i < 6; i ++ ) {
  5525. planes[ i ].copy( frustum.planes[ i ] );
  5526. }
  5527. return this;
  5528. },
  5529. setFromMatrix: function ( m ) {
  5530. var planes = this.planes;
  5531. var me = m.elements;
  5532. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5533. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5534. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5535. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5536. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5537. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5538. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5539. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5540. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5541. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5542. return this;
  5543. },
  5544. intersectsObject: function () {
  5545. var sphere = new Sphere();
  5546. return function intersectsObject( object ) {
  5547. var geometry = object.geometry;
  5548. if ( geometry.boundingSphere === null )
  5549. geometry.computeBoundingSphere();
  5550. sphere.copy( geometry.boundingSphere )
  5551. .applyMatrix4( object.matrixWorld );
  5552. return this.intersectsSphere( sphere );
  5553. };
  5554. }(),
  5555. intersectsSprite: function () {
  5556. var sphere = new Sphere();
  5557. return function intersectsSprite( sprite ) {
  5558. sphere.center.set( 0, 0, 0 );
  5559. sphere.radius = 0.7071067811865476;
  5560. sphere.applyMatrix4( sprite.matrixWorld );
  5561. return this.intersectsSphere( sphere );
  5562. };
  5563. }(),
  5564. intersectsSphere: function ( sphere ) {
  5565. var planes = this.planes;
  5566. var center = sphere.center;
  5567. var negRadius = - sphere.radius;
  5568. for ( var i = 0; i < 6; i ++ ) {
  5569. var distance = planes[ i ].distanceToPoint( center );
  5570. if ( distance < negRadius ) {
  5571. return false;
  5572. }
  5573. }
  5574. return true;
  5575. },
  5576. intersectsBox: function () {
  5577. var p1 = new Vector3(),
  5578. p2 = new Vector3();
  5579. return function intersectsBox( box ) {
  5580. var planes = this.planes;
  5581. for ( var i = 0; i < 6; i ++ ) {
  5582. var plane = planes[ i ];
  5583. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5584. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5585. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5586. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5587. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5588. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5589. var d1 = plane.distanceToPoint( p1 );
  5590. var d2 = plane.distanceToPoint( p2 );
  5591. // if both outside plane, no intersection
  5592. if ( d1 < 0 && d2 < 0 ) {
  5593. return false;
  5594. }
  5595. }
  5596. return true;
  5597. };
  5598. }(),
  5599. containsPoint: function ( point ) {
  5600. var planes = this.planes;
  5601. for ( var i = 0; i < 6; i ++ ) {
  5602. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5603. return false;
  5604. }
  5605. }
  5606. return true;
  5607. }
  5608. } );
  5609. /**
  5610. * @author alteredq / http://alteredqualia.com/
  5611. * @author mrdoob / http://mrdoob.com/
  5612. */
  5613. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  5614. var _frustum = new Frustum(),
  5615. _projScreenMatrix = new Matrix4(),
  5616. _shadowMapSize = new Vector2(),
  5617. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  5618. _lookTarget = new Vector3(),
  5619. _lightPositionWorld = new Vector3(),
  5620. _MorphingFlag = 1,
  5621. _SkinningFlag = 2,
  5622. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5623. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5624. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5625. _materialCache = {};
  5626. var cubeDirections = [
  5627. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5628. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5629. ];
  5630. var cubeUps = [
  5631. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5632. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5633. ];
  5634. var cube2DViewPorts = [
  5635. new Vector4(), new Vector4(), new Vector4(),
  5636. new Vector4(), new Vector4(), new Vector4()
  5637. ];
  5638. // init
  5639. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5640. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5641. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5642. var depthMaterial = new MeshDepthMaterial( {
  5643. depthPacking: RGBADepthPacking,
  5644. morphTargets: useMorphing,
  5645. skinning: useSkinning
  5646. } );
  5647. _depthMaterials[ i ] = depthMaterial;
  5648. //
  5649. var distanceMaterial = new MeshDistanceMaterial( {
  5650. morphTargets: useMorphing,
  5651. skinning: useSkinning
  5652. } );
  5653. _distanceMaterials[ i ] = distanceMaterial;
  5654. }
  5655. //
  5656. var scope = this;
  5657. this.enabled = false;
  5658. this.autoUpdate = true;
  5659. this.needsUpdate = false;
  5660. this.type = PCFShadowMap;
  5661. this.renderReverseSided = true;
  5662. this.renderSingleSided = true;
  5663. this.render = function ( lights, scene, camera ) {
  5664. if ( scope.enabled === false ) return;
  5665. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5666. if ( lights.length === 0 ) return;
  5667. // TODO Clean up (needed in case of contextlost)
  5668. var _gl = _renderer.context;
  5669. var _state = _renderer.state;
  5670. // Set GL state for depth map.
  5671. _state.disable( _gl.BLEND );
  5672. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5673. _state.buffers.depth.setTest( true );
  5674. _state.setScissorTest( false );
  5675. // render depth map
  5676. var faceCount;
  5677. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  5678. var light = lights[ i ];
  5679. var shadow = light.shadow;
  5680. var isPointLight = light && light.isPointLight;
  5681. if ( shadow === undefined ) {
  5682. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5683. continue;
  5684. }
  5685. var shadowCamera = shadow.camera;
  5686. _shadowMapSize.copy( shadow.mapSize );
  5687. _shadowMapSize.min( _maxShadowMapSize );
  5688. if ( isPointLight ) {
  5689. var vpWidth = _shadowMapSize.x;
  5690. var vpHeight = _shadowMapSize.y;
  5691. // These viewports map a cube-map onto a 2D texture with the
  5692. // following orientation:
  5693. //
  5694. // xzXZ
  5695. // y Y
  5696. //
  5697. // X - Positive x direction
  5698. // x - Negative x direction
  5699. // Y - Positive y direction
  5700. // y - Negative y direction
  5701. // Z - Positive z direction
  5702. // z - Negative z direction
  5703. // positive X
  5704. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5705. // negative X
  5706. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5707. // positive Z
  5708. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5709. // negative Z
  5710. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5711. // positive Y
  5712. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5713. // negative Y
  5714. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5715. _shadowMapSize.x *= 4.0;
  5716. _shadowMapSize.y *= 2.0;
  5717. }
  5718. if ( shadow.map === null ) {
  5719. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5720. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5721. shadow.map.texture.name = light.name + ".shadowMap";
  5722. shadowCamera.updateProjectionMatrix();
  5723. }
  5724. if ( shadow.isSpotLightShadow ) {
  5725. shadow.update( light );
  5726. }
  5727. var shadowMap = shadow.map;
  5728. var shadowMatrix = shadow.matrix;
  5729. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5730. shadowCamera.position.copy( _lightPositionWorld );
  5731. if ( isPointLight ) {
  5732. faceCount = 6;
  5733. // for point lights we set the shadow matrix to be a translation-only matrix
  5734. // equal to inverse of the light's position
  5735. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5736. } else {
  5737. faceCount = 1;
  5738. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5739. shadowCamera.lookAt( _lookTarget );
  5740. shadowCamera.updateMatrixWorld();
  5741. // compute shadow matrix
  5742. shadowMatrix.set(
  5743. 0.5, 0.0, 0.0, 0.5,
  5744. 0.0, 0.5, 0.0, 0.5,
  5745. 0.0, 0.0, 0.5, 0.5,
  5746. 0.0, 0.0, 0.0, 1.0
  5747. );
  5748. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5749. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5750. }
  5751. _renderer.setRenderTarget( shadowMap );
  5752. _renderer.clear();
  5753. // render shadow map for each cube face (if omni-directional) or
  5754. // run a single pass if not
  5755. for ( var face = 0; face < faceCount; face ++ ) {
  5756. if ( isPointLight ) {
  5757. _lookTarget.copy( shadowCamera.position );
  5758. _lookTarget.add( cubeDirections[ face ] );
  5759. shadowCamera.up.copy( cubeUps[ face ] );
  5760. shadowCamera.lookAt( _lookTarget );
  5761. shadowCamera.updateMatrixWorld();
  5762. var vpDimensions = cube2DViewPorts[ face ];
  5763. _state.viewport( vpDimensions );
  5764. }
  5765. // update camera matrices and frustum
  5766. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5767. _frustum.setFromMatrix( _projScreenMatrix );
  5768. // set object matrices & frustum culling
  5769. renderObject( scene, camera, shadowCamera, isPointLight );
  5770. }
  5771. }
  5772. scope.needsUpdate = false;
  5773. };
  5774. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  5775. var geometry = object.geometry;
  5776. var result = null;
  5777. var materialVariants = _depthMaterials;
  5778. var customMaterial = object.customDepthMaterial;
  5779. if ( isPointLight ) {
  5780. materialVariants = _distanceMaterials;
  5781. customMaterial = object.customDistanceMaterial;
  5782. }
  5783. if ( ! customMaterial ) {
  5784. var useMorphing = false;
  5785. if ( material.morphTargets ) {
  5786. if ( geometry && geometry.isBufferGeometry ) {
  5787. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5788. } else if ( geometry && geometry.isGeometry ) {
  5789. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5790. }
  5791. }
  5792. if ( object.isSkinnedMesh && material.skinning === false ) {
  5793. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5794. }
  5795. var useSkinning = object.isSkinnedMesh && material.skinning;
  5796. var variantIndex = 0;
  5797. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5798. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5799. result = materialVariants[ variantIndex ];
  5800. } else {
  5801. result = customMaterial;
  5802. }
  5803. if ( _renderer.localClippingEnabled &&
  5804. material.clipShadows === true &&
  5805. material.clippingPlanes.length !== 0 ) {
  5806. // in this case we need a unique material instance reflecting the
  5807. // appropriate state
  5808. var keyA = result.uuid, keyB = material.uuid;
  5809. var materialsForVariant = _materialCache[ keyA ];
  5810. if ( materialsForVariant === undefined ) {
  5811. materialsForVariant = {};
  5812. _materialCache[ keyA ] = materialsForVariant;
  5813. }
  5814. var cachedMaterial = materialsForVariant[ keyB ];
  5815. if ( cachedMaterial === undefined ) {
  5816. cachedMaterial = result.clone();
  5817. materialsForVariant[ keyB ] = cachedMaterial;
  5818. }
  5819. result = cachedMaterial;
  5820. }
  5821. result.visible = material.visible;
  5822. result.wireframe = material.wireframe;
  5823. var side = material.side;
  5824. if ( scope.renderSingleSided && side == DoubleSide ) {
  5825. side = FrontSide;
  5826. }
  5827. if ( scope.renderReverseSided ) {
  5828. if ( side === FrontSide ) side = BackSide;
  5829. else if ( side === BackSide ) side = FrontSide;
  5830. }
  5831. result.side = side;
  5832. result.clipShadows = material.clipShadows;
  5833. result.clippingPlanes = material.clippingPlanes;
  5834. result.clipIntersection = material.clipIntersection;
  5835. result.wireframeLinewidth = material.wireframeLinewidth;
  5836. result.linewidth = material.linewidth;
  5837. if ( isPointLight && result.isMeshDistanceMaterial ) {
  5838. result.referencePosition.copy( lightPositionWorld );
  5839. result.nearDistance = shadowCameraNear;
  5840. result.farDistance = shadowCameraFar;
  5841. }
  5842. return result;
  5843. }
  5844. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5845. if ( object.visible === false ) return;
  5846. var visible = object.layers.test( camera.layers );
  5847. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5848. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5849. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5850. var geometry = _objects.update( object );
  5851. var material = object.material;
  5852. if ( Array.isArray( material ) ) {
  5853. var groups = geometry.groups;
  5854. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5855. var group = groups[ k ];
  5856. var groupMaterial = material[ group.materialIndex ];
  5857. if ( groupMaterial && groupMaterial.visible ) {
  5858. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5859. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5860. }
  5861. }
  5862. } else if ( material.visible ) {
  5863. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  5864. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5865. }
  5866. }
  5867. }
  5868. var children = object.children;
  5869. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5870. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5871. }
  5872. }
  5873. }
  5874. /**
  5875. * @author mrdoob / http://mrdoob.com/
  5876. */
  5877. function WebGLAttributes( gl ) {
  5878. var buffers = {};
  5879. function createBuffer( attribute, bufferType ) {
  5880. var array = attribute.array;
  5881. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  5882. var buffer = gl.createBuffer();
  5883. gl.bindBuffer( bufferType, buffer );
  5884. gl.bufferData( bufferType, array, usage );
  5885. attribute.onUploadCallback();
  5886. var type = gl.FLOAT;
  5887. if ( array instanceof Float32Array ) {
  5888. type = gl.FLOAT;
  5889. } else if ( array instanceof Float64Array ) {
  5890. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  5891. } else if ( array instanceof Uint16Array ) {
  5892. type = gl.UNSIGNED_SHORT;
  5893. } else if ( array instanceof Int16Array ) {
  5894. type = gl.SHORT;
  5895. } else if ( array instanceof Uint32Array ) {
  5896. type = gl.UNSIGNED_INT;
  5897. } else if ( array instanceof Int32Array ) {
  5898. type = gl.INT;
  5899. } else if ( array instanceof Int8Array ) {
  5900. type = gl.BYTE;
  5901. } else if ( array instanceof Uint8Array ) {
  5902. type = gl.UNSIGNED_BYTE;
  5903. }
  5904. return {
  5905. buffer: buffer,
  5906. type: type,
  5907. bytesPerElement: array.BYTES_PER_ELEMENT,
  5908. version: attribute.version
  5909. };
  5910. }
  5911. function updateBuffer( buffer, attribute, bufferType ) {
  5912. var array = attribute.array;
  5913. var updateRange = attribute.updateRange;
  5914. gl.bindBuffer( bufferType, buffer );
  5915. if ( attribute.dynamic === false ) {
  5916. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  5917. } else if ( updateRange.count === - 1 ) {
  5918. // Not using update ranges
  5919. gl.bufferSubData( bufferType, 0, array );
  5920. } else if ( updateRange.count === 0 ) {
  5921. 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.' );
  5922. } else {
  5923. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  5924. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  5925. updateRange.count = -1; // reset range
  5926. }
  5927. }
  5928. //
  5929. function get( attribute ) {
  5930. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5931. return buffers[ attribute.uuid ];
  5932. }
  5933. function remove( attribute ) {
  5934. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5935. var data = buffers[ attribute.uuid ];
  5936. if ( data ) {
  5937. gl.deleteBuffer( data.buffer );
  5938. delete buffers[ attribute.uuid ];
  5939. }
  5940. }
  5941. function update( attribute, bufferType ) {
  5942. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  5943. var data = buffers[ attribute.uuid ];
  5944. if ( data === undefined ) {
  5945. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  5946. } else if ( data.version < attribute.version ) {
  5947. updateBuffer( data.buffer, attribute, bufferType );
  5948. data.version = attribute.version;
  5949. }
  5950. }
  5951. return {
  5952. get: get,
  5953. remove: remove,
  5954. update: update
  5955. };
  5956. }
  5957. /**
  5958. * @author mrdoob / http://mrdoob.com/
  5959. * @author WestLangley / http://github.com/WestLangley
  5960. * @author bhouston / http://clara.io
  5961. */
  5962. function Euler( x, y, z, order ) {
  5963. this._x = x || 0;
  5964. this._y = y || 0;
  5965. this._z = z || 0;
  5966. this._order = order || Euler.DefaultOrder;
  5967. }
  5968. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  5969. Euler.DefaultOrder = 'XYZ';
  5970. Object.defineProperties( Euler.prototype, {
  5971. x: {
  5972. get: function () {
  5973. return this._x;
  5974. },
  5975. set: function ( value ) {
  5976. this._x = value;
  5977. this.onChangeCallback();
  5978. }
  5979. },
  5980. y: {
  5981. get: function () {
  5982. return this._y;
  5983. },
  5984. set: function ( value ) {
  5985. this._y = value;
  5986. this.onChangeCallback();
  5987. }
  5988. },
  5989. z: {
  5990. get: function () {
  5991. return this._z;
  5992. },
  5993. set: function ( value ) {
  5994. this._z = value;
  5995. this.onChangeCallback();
  5996. }
  5997. },
  5998. order: {
  5999. get: function () {
  6000. return this._order;
  6001. },
  6002. set: function ( value ) {
  6003. this._order = value;
  6004. this.onChangeCallback();
  6005. }
  6006. }
  6007. } );
  6008. Object.assign( Euler.prototype, {
  6009. isEuler: true,
  6010. set: function ( x, y, z, order ) {
  6011. this._x = x;
  6012. this._y = y;
  6013. this._z = z;
  6014. this._order = order || this._order;
  6015. this.onChangeCallback();
  6016. return this;
  6017. },
  6018. clone: function () {
  6019. return new this.constructor( this._x, this._y, this._z, this._order );
  6020. },
  6021. copy: function ( euler ) {
  6022. this._x = euler._x;
  6023. this._y = euler._y;
  6024. this._z = euler._z;
  6025. this._order = euler._order;
  6026. this.onChangeCallback();
  6027. return this;
  6028. },
  6029. setFromRotationMatrix: function ( m, order, update ) {
  6030. var clamp = _Math.clamp;
  6031. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6032. var te = m.elements;
  6033. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6034. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6035. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6036. order = order || this._order;
  6037. if ( order === 'XYZ' ) {
  6038. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6039. if ( Math.abs( m13 ) < 0.99999 ) {
  6040. this._x = Math.atan2( - m23, m33 );
  6041. this._z = Math.atan2( - m12, m11 );
  6042. } else {
  6043. this._x = Math.atan2( m32, m22 );
  6044. this._z = 0;
  6045. }
  6046. } else if ( order === 'YXZ' ) {
  6047. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6048. if ( Math.abs( m23 ) < 0.99999 ) {
  6049. this._y = Math.atan2( m13, m33 );
  6050. this._z = Math.atan2( m21, m22 );
  6051. } else {
  6052. this._y = Math.atan2( - m31, m11 );
  6053. this._z = 0;
  6054. }
  6055. } else if ( order === 'ZXY' ) {
  6056. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6057. if ( Math.abs( m32 ) < 0.99999 ) {
  6058. this._y = Math.atan2( - m31, m33 );
  6059. this._z = Math.atan2( - m12, m22 );
  6060. } else {
  6061. this._y = 0;
  6062. this._z = Math.atan2( m21, m11 );
  6063. }
  6064. } else if ( order === 'ZYX' ) {
  6065. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6066. if ( Math.abs( m31 ) < 0.99999 ) {
  6067. this._x = Math.atan2( m32, m33 );
  6068. this._z = Math.atan2( m21, m11 );
  6069. } else {
  6070. this._x = 0;
  6071. this._z = Math.atan2( - m12, m22 );
  6072. }
  6073. } else if ( order === 'YZX' ) {
  6074. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6075. if ( Math.abs( m21 ) < 0.99999 ) {
  6076. this._x = Math.atan2( - m23, m22 );
  6077. this._y = Math.atan2( - m31, m11 );
  6078. } else {
  6079. this._x = 0;
  6080. this._y = Math.atan2( m13, m33 );
  6081. }
  6082. } else if ( order === 'XZY' ) {
  6083. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6084. if ( Math.abs( m12 ) < 0.99999 ) {
  6085. this._x = Math.atan2( m32, m22 );
  6086. this._y = Math.atan2( m13, m11 );
  6087. } else {
  6088. this._x = Math.atan2( - m23, m33 );
  6089. this._y = 0;
  6090. }
  6091. } else {
  6092. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6093. }
  6094. this._order = order;
  6095. if ( update !== false ) this.onChangeCallback();
  6096. return this;
  6097. },
  6098. setFromQuaternion: function () {
  6099. var matrix = new Matrix4();
  6100. return function setFromQuaternion( q, order, update ) {
  6101. matrix.makeRotationFromQuaternion( q );
  6102. return this.setFromRotationMatrix( matrix, order, update );
  6103. };
  6104. }(),
  6105. setFromVector3: function ( v, order ) {
  6106. return this.set( v.x, v.y, v.z, order || this._order );
  6107. },
  6108. reorder: function () {
  6109. // WARNING: this discards revolution information -bhouston
  6110. var q = new Quaternion();
  6111. return function reorder( newOrder ) {
  6112. q.setFromEuler( this );
  6113. return this.setFromQuaternion( q, newOrder );
  6114. };
  6115. }(),
  6116. equals: function ( euler ) {
  6117. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6118. },
  6119. fromArray: function ( array ) {
  6120. this._x = array[ 0 ];
  6121. this._y = array[ 1 ];
  6122. this._z = array[ 2 ];
  6123. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6124. this.onChangeCallback();
  6125. return this;
  6126. },
  6127. toArray: function ( array, offset ) {
  6128. if ( array === undefined ) array = [];
  6129. if ( offset === undefined ) offset = 0;
  6130. array[ offset ] = this._x;
  6131. array[ offset + 1 ] = this._y;
  6132. array[ offset + 2 ] = this._z;
  6133. array[ offset + 3 ] = this._order;
  6134. return array;
  6135. },
  6136. toVector3: function ( optionalResult ) {
  6137. if ( optionalResult ) {
  6138. return optionalResult.set( this._x, this._y, this._z );
  6139. } else {
  6140. return new Vector3( this._x, this._y, this._z );
  6141. }
  6142. },
  6143. onChange: function ( callback ) {
  6144. this.onChangeCallback = callback;
  6145. return this;
  6146. },
  6147. onChangeCallback: function () {}
  6148. } );
  6149. /**
  6150. * @author mrdoob / http://mrdoob.com/
  6151. */
  6152. function Layers() {
  6153. this.mask = 1 | 0;
  6154. }
  6155. Object.assign( Layers.prototype, {
  6156. set: function ( channel ) {
  6157. this.mask = 1 << channel | 0;
  6158. },
  6159. enable: function ( channel ) {
  6160. this.mask |= 1 << channel | 0;
  6161. },
  6162. toggle: function ( channel ) {
  6163. this.mask ^= 1 << channel | 0;
  6164. },
  6165. disable: function ( channel ) {
  6166. this.mask &= ~ ( 1 << channel | 0 );
  6167. },
  6168. test: function ( layers ) {
  6169. return ( this.mask & layers.mask ) !== 0;
  6170. }
  6171. } );
  6172. /**
  6173. * @author mrdoob / http://mrdoob.com/
  6174. * @author mikael emtinger / http://gomo.se/
  6175. * @author alteredq / http://alteredqualia.com/
  6176. * @author WestLangley / http://github.com/WestLangley
  6177. * @author elephantatwork / www.elephantatwork.ch
  6178. */
  6179. var object3DId = 0;
  6180. function Object3D() {
  6181. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6182. this.uuid = _Math.generateUUID();
  6183. this.name = '';
  6184. this.type = 'Object3D';
  6185. this.parent = null;
  6186. this.children = [];
  6187. this.up = Object3D.DefaultUp.clone();
  6188. var position = new Vector3();
  6189. var rotation = new Euler();
  6190. var quaternion = new Quaternion();
  6191. var scale = new Vector3( 1, 1, 1 );
  6192. function onRotationChange() {
  6193. quaternion.setFromEuler( rotation, false );
  6194. }
  6195. function onQuaternionChange() {
  6196. rotation.setFromQuaternion( quaternion, undefined, false );
  6197. }
  6198. rotation.onChange( onRotationChange );
  6199. quaternion.onChange( onQuaternionChange );
  6200. Object.defineProperties( this, {
  6201. position: {
  6202. enumerable: true,
  6203. value: position
  6204. },
  6205. rotation: {
  6206. enumerable: true,
  6207. value: rotation
  6208. },
  6209. quaternion: {
  6210. enumerable: true,
  6211. value: quaternion
  6212. },
  6213. scale: {
  6214. enumerable: true,
  6215. value: scale
  6216. },
  6217. modelViewMatrix: {
  6218. value: new Matrix4()
  6219. },
  6220. normalMatrix: {
  6221. value: new Matrix3()
  6222. }
  6223. } );
  6224. this.matrix = new Matrix4();
  6225. this.matrixWorld = new Matrix4();
  6226. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6227. this.matrixWorldNeedsUpdate = false;
  6228. this.layers = new Layers();
  6229. this.visible = true;
  6230. this.castShadow = false;
  6231. this.receiveShadow = false;
  6232. this.frustumCulled = true;
  6233. this.renderOrder = 0;
  6234. this.userData = {};
  6235. }
  6236. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6237. Object3D.DefaultMatrixAutoUpdate = true;
  6238. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6239. isObject3D: true,
  6240. onBeforeRender: function () {},
  6241. onAfterRender: function () {},
  6242. applyMatrix: function ( matrix ) {
  6243. this.matrix.multiplyMatrices( matrix, this.matrix );
  6244. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6245. },
  6246. applyQuaternion: function ( q ) {
  6247. this.quaternion.premultiply( q );
  6248. return this;
  6249. },
  6250. setRotationFromAxisAngle: function ( axis, angle ) {
  6251. // assumes axis is normalized
  6252. this.quaternion.setFromAxisAngle( axis, angle );
  6253. },
  6254. setRotationFromEuler: function ( euler ) {
  6255. this.quaternion.setFromEuler( euler, true );
  6256. },
  6257. setRotationFromMatrix: function ( m ) {
  6258. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6259. this.quaternion.setFromRotationMatrix( m );
  6260. },
  6261. setRotationFromQuaternion: function ( q ) {
  6262. // assumes q is normalized
  6263. this.quaternion.copy( q );
  6264. },
  6265. rotateOnAxis: function () {
  6266. // rotate object on axis in object space
  6267. // axis is assumed to be normalized
  6268. var q1 = new Quaternion();
  6269. return function rotateOnAxis( axis, angle ) {
  6270. q1.setFromAxisAngle( axis, angle );
  6271. this.quaternion.multiply( q1 );
  6272. return this;
  6273. };
  6274. }(),
  6275. rotateX: function () {
  6276. var v1 = new Vector3( 1, 0, 0 );
  6277. return function rotateX( angle ) {
  6278. return this.rotateOnAxis( v1, angle );
  6279. };
  6280. }(),
  6281. rotateY: function () {
  6282. var v1 = new Vector3( 0, 1, 0 );
  6283. return function rotateY( angle ) {
  6284. return this.rotateOnAxis( v1, angle );
  6285. };
  6286. }(),
  6287. rotateZ: function () {
  6288. var v1 = new Vector3( 0, 0, 1 );
  6289. return function rotateZ( angle ) {
  6290. return this.rotateOnAxis( v1, angle );
  6291. };
  6292. }(),
  6293. translateOnAxis: function () {
  6294. // translate object by distance along axis in object space
  6295. // axis is assumed to be normalized
  6296. var v1 = new Vector3();
  6297. return function translateOnAxis( axis, distance ) {
  6298. v1.copy( axis ).applyQuaternion( this.quaternion );
  6299. this.position.add( v1.multiplyScalar( distance ) );
  6300. return this;
  6301. };
  6302. }(),
  6303. translateX: function () {
  6304. var v1 = new Vector3( 1, 0, 0 );
  6305. return function translateX( distance ) {
  6306. return this.translateOnAxis( v1, distance );
  6307. };
  6308. }(),
  6309. translateY: function () {
  6310. var v1 = new Vector3( 0, 1, 0 );
  6311. return function translateY( distance ) {
  6312. return this.translateOnAxis( v1, distance );
  6313. };
  6314. }(),
  6315. translateZ: function () {
  6316. var v1 = new Vector3( 0, 0, 1 );
  6317. return function translateZ( distance ) {
  6318. return this.translateOnAxis( v1, distance );
  6319. };
  6320. }(),
  6321. localToWorld: function ( vector ) {
  6322. return vector.applyMatrix4( this.matrixWorld );
  6323. },
  6324. worldToLocal: function () {
  6325. var m1 = new Matrix4();
  6326. return function worldToLocal( vector ) {
  6327. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6328. };
  6329. }(),
  6330. lookAt: function () {
  6331. // This method does not support objects with rotated and/or translated parent(s)
  6332. var m1 = new Matrix4();
  6333. return function lookAt( vector ) {
  6334. if ( this.isCamera ) {
  6335. m1.lookAt( this.position, vector, this.up );
  6336. } else {
  6337. m1.lookAt( vector, this.position, this.up );
  6338. }
  6339. this.quaternion.setFromRotationMatrix( m1 );
  6340. };
  6341. }(),
  6342. add: function ( object ) {
  6343. if ( arguments.length > 1 ) {
  6344. for ( var i = 0; i < arguments.length; i ++ ) {
  6345. this.add( arguments[ i ] );
  6346. }
  6347. return this;
  6348. }
  6349. if ( object === this ) {
  6350. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6351. return this;
  6352. }
  6353. if ( ( object && object.isObject3D ) ) {
  6354. if ( object.parent !== null ) {
  6355. object.parent.remove( object );
  6356. }
  6357. object.parent = this;
  6358. object.dispatchEvent( { type: 'added' } );
  6359. this.children.push( object );
  6360. } else {
  6361. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6362. }
  6363. return this;
  6364. },
  6365. remove: function ( object ) {
  6366. if ( arguments.length > 1 ) {
  6367. for ( var i = 0; i < arguments.length; i ++ ) {
  6368. this.remove( arguments[ i ] );
  6369. }
  6370. return this;
  6371. }
  6372. var index = this.children.indexOf( object );
  6373. if ( index !== - 1 ) {
  6374. object.parent = null;
  6375. object.dispatchEvent( { type: 'removed' } );
  6376. this.children.splice( index, 1 );
  6377. }
  6378. return this;
  6379. },
  6380. getObjectById: function ( id ) {
  6381. return this.getObjectByProperty( 'id', id );
  6382. },
  6383. getObjectByName: function ( name ) {
  6384. return this.getObjectByProperty( 'name', name );
  6385. },
  6386. getObjectByProperty: function ( name, value ) {
  6387. if ( this[ name ] === value ) return this;
  6388. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6389. var child = this.children[ i ];
  6390. var object = child.getObjectByProperty( name, value );
  6391. if ( object !== undefined ) {
  6392. return object;
  6393. }
  6394. }
  6395. return undefined;
  6396. },
  6397. getWorldPosition: function ( optionalTarget ) {
  6398. var result = optionalTarget || new Vector3();
  6399. this.updateMatrixWorld( true );
  6400. return result.setFromMatrixPosition( this.matrixWorld );
  6401. },
  6402. getWorldQuaternion: function () {
  6403. var position = new Vector3();
  6404. var scale = new Vector3();
  6405. return function getWorldQuaternion( optionalTarget ) {
  6406. var result = optionalTarget || new Quaternion();
  6407. this.updateMatrixWorld( true );
  6408. this.matrixWorld.decompose( position, result, scale );
  6409. return result;
  6410. };
  6411. }(),
  6412. getWorldRotation: function () {
  6413. var quaternion = new Quaternion();
  6414. return function getWorldRotation( optionalTarget ) {
  6415. var result = optionalTarget || new Euler();
  6416. this.getWorldQuaternion( quaternion );
  6417. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6418. };
  6419. }(),
  6420. getWorldScale: function () {
  6421. var position = new Vector3();
  6422. var quaternion = new Quaternion();
  6423. return function getWorldScale( optionalTarget ) {
  6424. var result = optionalTarget || new Vector3();
  6425. this.updateMatrixWorld( true );
  6426. this.matrixWorld.decompose( position, quaternion, result );
  6427. return result;
  6428. };
  6429. }(),
  6430. getWorldDirection: function () {
  6431. var quaternion = new Quaternion();
  6432. return function getWorldDirection( optionalTarget ) {
  6433. var result = optionalTarget || new Vector3();
  6434. this.getWorldQuaternion( quaternion );
  6435. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6436. };
  6437. }(),
  6438. raycast: function () {},
  6439. traverse: function ( callback ) {
  6440. callback( this );
  6441. var children = this.children;
  6442. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6443. children[ i ].traverse( callback );
  6444. }
  6445. },
  6446. traverseVisible: function ( callback ) {
  6447. if ( this.visible === false ) return;
  6448. callback( this );
  6449. var children = this.children;
  6450. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6451. children[ i ].traverseVisible( callback );
  6452. }
  6453. },
  6454. traverseAncestors: function ( callback ) {
  6455. var parent = this.parent;
  6456. if ( parent !== null ) {
  6457. callback( parent );
  6458. parent.traverseAncestors( callback );
  6459. }
  6460. },
  6461. updateMatrix: function () {
  6462. this.matrix.compose( this.position, this.quaternion, this.scale );
  6463. this.matrixWorldNeedsUpdate = true;
  6464. },
  6465. updateMatrixWorld: function ( force ) {
  6466. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6467. if ( this.matrixWorldNeedsUpdate || force ) {
  6468. if ( this.parent === null ) {
  6469. this.matrixWorld.copy( this.matrix );
  6470. } else {
  6471. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6472. }
  6473. this.matrixWorldNeedsUpdate = false;
  6474. force = true;
  6475. }
  6476. // update children
  6477. var children = this.children;
  6478. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6479. children[ i ].updateMatrixWorld( force );
  6480. }
  6481. },
  6482. toJSON: function ( meta ) {
  6483. // meta is '' when called from JSON.stringify
  6484. var isRootObject = ( meta === undefined || meta === '' );
  6485. var output = {};
  6486. // meta is a hash used to collect geometries, materials.
  6487. // not providing it implies that this is the root object
  6488. // being serialized.
  6489. if ( isRootObject ) {
  6490. // initialize meta obj
  6491. meta = {
  6492. geometries: {},
  6493. materials: {},
  6494. textures: {},
  6495. images: {}
  6496. };
  6497. output.metadata = {
  6498. version: 4.5,
  6499. type: 'Object',
  6500. generator: 'Object3D.toJSON'
  6501. };
  6502. }
  6503. // standard Object3D serialization
  6504. var object = {};
  6505. object.uuid = this.uuid;
  6506. object.type = this.type;
  6507. if ( this.name !== '' ) object.name = this.name;
  6508. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6509. if ( this.castShadow === true ) object.castShadow = true;
  6510. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6511. if ( this.visible === false ) object.visible = false;
  6512. object.matrix = this.matrix.toArray();
  6513. //
  6514. function serialize( library, element ) {
  6515. if ( library[ element.uuid ] === undefined ) {
  6516. library[ element.uuid ] = element.toJSON( meta );
  6517. }
  6518. return element.uuid;
  6519. }
  6520. if ( this.geometry !== undefined ) {
  6521. object.geometry = serialize( meta.geometries, this.geometry );
  6522. }
  6523. if ( this.material !== undefined ) {
  6524. if ( Array.isArray( this.material ) ) {
  6525. var uuids = [];
  6526. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6527. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6528. }
  6529. object.material = uuids;
  6530. } else {
  6531. object.material = serialize( meta.materials, this.material );
  6532. }
  6533. }
  6534. //
  6535. if ( this.children.length > 0 ) {
  6536. object.children = [];
  6537. for ( var i = 0; i < this.children.length; i ++ ) {
  6538. object.children.push( this.children[ i ].toJSON( meta ).object );
  6539. }
  6540. }
  6541. if ( isRootObject ) {
  6542. var geometries = extractFromCache( meta.geometries );
  6543. var materials = extractFromCache( meta.materials );
  6544. var textures = extractFromCache( meta.textures );
  6545. var images = extractFromCache( meta.images );
  6546. if ( geometries.length > 0 ) output.geometries = geometries;
  6547. if ( materials.length > 0 ) output.materials = materials;
  6548. if ( textures.length > 0 ) output.textures = textures;
  6549. if ( images.length > 0 ) output.images = images;
  6550. }
  6551. output.object = object;
  6552. return output;
  6553. // extract data from the cache hash
  6554. // remove metadata on each item
  6555. // and return as array
  6556. function extractFromCache( cache ) {
  6557. var values = [];
  6558. for ( var key in cache ) {
  6559. var data = cache[ key ];
  6560. delete data.metadata;
  6561. values.push( data );
  6562. }
  6563. return values;
  6564. }
  6565. },
  6566. clone: function ( recursive ) {
  6567. return new this.constructor().copy( this, recursive );
  6568. },
  6569. copy: function ( source, recursive ) {
  6570. if ( recursive === undefined ) recursive = true;
  6571. this.name = source.name;
  6572. this.up.copy( source.up );
  6573. this.position.copy( source.position );
  6574. this.quaternion.copy( source.quaternion );
  6575. this.scale.copy( source.scale );
  6576. this.matrix.copy( source.matrix );
  6577. this.matrixWorld.copy( source.matrixWorld );
  6578. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6579. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6580. this.layers.mask = source.layers.mask;
  6581. this.visible = source.visible;
  6582. this.castShadow = source.castShadow;
  6583. this.receiveShadow = source.receiveShadow;
  6584. this.frustumCulled = source.frustumCulled;
  6585. this.renderOrder = source.renderOrder;
  6586. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6587. if ( recursive === true ) {
  6588. for ( var i = 0; i < source.children.length; i ++ ) {
  6589. var child = source.children[ i ];
  6590. this.add( child.clone() );
  6591. }
  6592. }
  6593. return this;
  6594. }
  6595. } );
  6596. /**
  6597. * @author mrdoob / http://mrdoob.com/
  6598. * @author mikael emtinger / http://gomo.se/
  6599. * @author WestLangley / http://github.com/WestLangley
  6600. */
  6601. function Camera() {
  6602. Object3D.call( this );
  6603. this.type = 'Camera';
  6604. this.matrixWorldInverse = new Matrix4();
  6605. this.projectionMatrix = new Matrix4();
  6606. }
  6607. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6608. constructor: Camera,
  6609. isCamera: true,
  6610. copy: function ( source, recursive ) {
  6611. Object3D.prototype.copy.call( this, source, recursive );
  6612. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6613. this.projectionMatrix.copy( source.projectionMatrix );
  6614. return this;
  6615. },
  6616. getWorldDirection: function () {
  6617. var quaternion = new Quaternion();
  6618. return function getWorldDirection( optionalTarget ) {
  6619. var result = optionalTarget || new Vector3();
  6620. this.getWorldQuaternion( quaternion );
  6621. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6622. };
  6623. }(),
  6624. updateMatrixWorld: function ( force ) {
  6625. Object3D.prototype.updateMatrixWorld.call( this, force );
  6626. this.matrixWorldInverse.getInverse( this.matrixWorld );
  6627. },
  6628. clone: function () {
  6629. return new this.constructor().copy( this );
  6630. }
  6631. } );
  6632. /**
  6633. * @author alteredq / http://alteredqualia.com/
  6634. * @author arose / http://github.com/arose
  6635. */
  6636. function OrthographicCamera( left, right, top, bottom, near, far ) {
  6637. Camera.call( this );
  6638. this.type = 'OrthographicCamera';
  6639. this.zoom = 1;
  6640. this.view = null;
  6641. this.left = left;
  6642. this.right = right;
  6643. this.top = top;
  6644. this.bottom = bottom;
  6645. this.near = ( near !== undefined ) ? near : 0.1;
  6646. this.far = ( far !== undefined ) ? far : 2000;
  6647. this.updateProjectionMatrix();
  6648. }
  6649. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6650. constructor: OrthographicCamera,
  6651. isOrthographicCamera: true,
  6652. copy: function ( source, recursive ) {
  6653. Camera.prototype.copy.call( this, source, recursive );
  6654. this.left = source.left;
  6655. this.right = source.right;
  6656. this.top = source.top;
  6657. this.bottom = source.bottom;
  6658. this.near = source.near;
  6659. this.far = source.far;
  6660. this.zoom = source.zoom;
  6661. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6662. return this;
  6663. },
  6664. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  6665. this.view = {
  6666. fullWidth: fullWidth,
  6667. fullHeight: fullHeight,
  6668. offsetX: x,
  6669. offsetY: y,
  6670. width: width,
  6671. height: height
  6672. };
  6673. this.updateProjectionMatrix();
  6674. },
  6675. clearViewOffset: function() {
  6676. this.view = null;
  6677. this.updateProjectionMatrix();
  6678. },
  6679. updateProjectionMatrix: function () {
  6680. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6681. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6682. var cx = ( this.right + this.left ) / 2;
  6683. var cy = ( this.top + this.bottom ) / 2;
  6684. var left = cx - dx;
  6685. var right = cx + dx;
  6686. var top = cy + dy;
  6687. var bottom = cy - dy;
  6688. if ( this.view !== null ) {
  6689. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  6690. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  6691. var scaleW = ( this.right - this.left ) / this.view.width;
  6692. var scaleH = ( this.top - this.bottom ) / this.view.height;
  6693. left += scaleW * ( this.view.offsetX / zoomW );
  6694. right = left + scaleW * ( this.view.width / zoomW );
  6695. top -= scaleH * ( this.view.offsetY / zoomH );
  6696. bottom = top - scaleH * ( this.view.height / zoomH );
  6697. }
  6698. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  6699. },
  6700. toJSON: function ( meta ) {
  6701. var data = Object3D.prototype.toJSON.call( this, meta );
  6702. data.object.zoom = this.zoom;
  6703. data.object.left = this.left;
  6704. data.object.right = this.right;
  6705. data.object.top = this.top;
  6706. data.object.bottom = this.bottom;
  6707. data.object.near = this.near;
  6708. data.object.far = this.far;
  6709. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6710. return data;
  6711. }
  6712. } );
  6713. /**
  6714. * @author mrdoob / http://mrdoob.com/
  6715. * @author greggman / http://games.greggman.com/
  6716. * @author zz85 / http://www.lab4games.net/zz85/blog
  6717. * @author tschw
  6718. */
  6719. function PerspectiveCamera( fov, aspect, near, far ) {
  6720. Camera.call( this );
  6721. this.type = 'PerspectiveCamera';
  6722. this.fov = fov !== undefined ? fov : 50;
  6723. this.zoom = 1;
  6724. this.near = near !== undefined ? near : 0.1;
  6725. this.far = far !== undefined ? far : 2000;
  6726. this.focus = 10;
  6727. this.aspect = aspect !== undefined ? aspect : 1;
  6728. this.view = null;
  6729. this.filmGauge = 35; // width of the film (default in millimeters)
  6730. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6731. this.updateProjectionMatrix();
  6732. }
  6733. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6734. constructor: PerspectiveCamera,
  6735. isPerspectiveCamera: true,
  6736. copy: function ( source, recursive ) {
  6737. Camera.prototype.copy.call( this, source, recursive );
  6738. this.fov = source.fov;
  6739. this.zoom = source.zoom;
  6740. this.near = source.near;
  6741. this.far = source.far;
  6742. this.focus = source.focus;
  6743. this.aspect = source.aspect;
  6744. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6745. this.filmGauge = source.filmGauge;
  6746. this.filmOffset = source.filmOffset;
  6747. return this;
  6748. },
  6749. /**
  6750. * Sets the FOV by focal length in respect to the current .filmGauge.
  6751. *
  6752. * The default film gauge is 35, so that the focal length can be specified for
  6753. * a 35mm (full frame) camera.
  6754. *
  6755. * Values for focal length and film gauge must have the same unit.
  6756. */
  6757. setFocalLength: function ( focalLength ) {
  6758. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  6759. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6760. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  6761. this.updateProjectionMatrix();
  6762. },
  6763. /**
  6764. * Calculates the focal length from the current .fov and .filmGauge.
  6765. */
  6766. getFocalLength: function () {
  6767. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  6768. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6769. },
  6770. getEffectiveFOV: function () {
  6771. return _Math.RAD2DEG * 2 * Math.atan(
  6772. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6773. },
  6774. getFilmWidth: function () {
  6775. // film not completely covered in portrait format (aspect < 1)
  6776. return this.filmGauge * Math.min( this.aspect, 1 );
  6777. },
  6778. getFilmHeight: function () {
  6779. // film not completely covered in landscape format (aspect > 1)
  6780. return this.filmGauge / Math.max( this.aspect, 1 );
  6781. },
  6782. /**
  6783. * Sets an offset in a larger frustum. This is useful for multi-window or
  6784. * multi-monitor/multi-machine setups.
  6785. *
  6786. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6787. * the monitors are in grid like this
  6788. *
  6789. * +---+---+---+
  6790. * | A | B | C |
  6791. * +---+---+---+
  6792. * | D | E | F |
  6793. * +---+---+---+
  6794. *
  6795. * then for each monitor you would call it like this
  6796. *
  6797. * var w = 1920;
  6798. * var h = 1080;
  6799. * var fullWidth = w * 3;
  6800. * var fullHeight = h * 2;
  6801. *
  6802. * --A--
  6803. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6804. * --B--
  6805. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6806. * --C--
  6807. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6808. * --D--
  6809. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6810. * --E--
  6811. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6812. * --F--
  6813. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6814. *
  6815. * Note there is no reason monitors have to be the same size or in a grid.
  6816. */
  6817. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  6818. this.aspect = fullWidth / fullHeight;
  6819. this.view = {
  6820. fullWidth: fullWidth,
  6821. fullHeight: fullHeight,
  6822. offsetX: x,
  6823. offsetY: y,
  6824. width: width,
  6825. height: height
  6826. };
  6827. this.updateProjectionMatrix();
  6828. },
  6829. clearViewOffset: function () {
  6830. this.view = null;
  6831. this.updateProjectionMatrix();
  6832. },
  6833. updateProjectionMatrix: function () {
  6834. var near = this.near,
  6835. top = near * Math.tan(
  6836. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  6837. height = 2 * top,
  6838. width = this.aspect * height,
  6839. left = - 0.5 * width,
  6840. view = this.view;
  6841. if ( view !== null ) {
  6842. var fullWidth = view.fullWidth,
  6843. fullHeight = view.fullHeight;
  6844. left += view.offsetX * width / fullWidth;
  6845. top -= view.offsetY * height / fullHeight;
  6846. width *= view.width / fullWidth;
  6847. height *= view.height / fullHeight;
  6848. }
  6849. var skew = this.filmOffset;
  6850. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6851. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6852. },
  6853. toJSON: function ( meta ) {
  6854. var data = Object3D.prototype.toJSON.call( this, meta );
  6855. data.object.fov = this.fov;
  6856. data.object.zoom = this.zoom;
  6857. data.object.near = this.near;
  6858. data.object.far = this.far;
  6859. data.object.focus = this.focus;
  6860. data.object.aspect = this.aspect;
  6861. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6862. data.object.filmGauge = this.filmGauge;
  6863. data.object.filmOffset = this.filmOffset;
  6864. return data;
  6865. }
  6866. } );
  6867. /**
  6868. * @author mrdoob / http://mrdoob.com/
  6869. * @author alteredq / http://alteredqualia.com/
  6870. */
  6871. function Face3( a, b, c, normal, color, materialIndex ) {
  6872. this.a = a;
  6873. this.b = b;
  6874. this.c = c;
  6875. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6876. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6877. this.color = ( color && color.isColor ) ? color : new Color();
  6878. this.vertexColors = Array.isArray( color ) ? color : [];
  6879. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6880. }
  6881. Object.assign( Face3.prototype, {
  6882. clone: function () {
  6883. return new this.constructor().copy( this );
  6884. },
  6885. copy: function ( source ) {
  6886. this.a = source.a;
  6887. this.b = source.b;
  6888. this.c = source.c;
  6889. this.normal.copy( source.normal );
  6890. this.color.copy( source.color );
  6891. this.materialIndex = source.materialIndex;
  6892. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6893. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6894. }
  6895. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6896. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6897. }
  6898. return this;
  6899. }
  6900. } );
  6901. /**
  6902. * @author mrdoob / http://mrdoob.com/
  6903. * @author kile / http://kile.stravaganza.org/
  6904. * @author alteredq / http://alteredqualia.com/
  6905. * @author mikael emtinger / http://gomo.se/
  6906. * @author zz85 / http://www.lab4games.net/zz85/blog
  6907. * @author bhouston / http://clara.io
  6908. */
  6909. var count = 0;
  6910. function GeometryIdCount() { return count++; }
  6911. function Geometry() {
  6912. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  6913. this.uuid = _Math.generateUUID();
  6914. this.name = '';
  6915. this.type = 'Geometry';
  6916. this.vertices = [];
  6917. this.colors = [];
  6918. this.faces = [];
  6919. this.faceVertexUvs = [[]];
  6920. this.morphTargets = [];
  6921. this.morphNormals = [];
  6922. this.skinWeights = [];
  6923. this.skinIndices = [];
  6924. this.lineDistances = [];
  6925. this.boundingBox = null;
  6926. this.boundingSphere = null;
  6927. // update flags
  6928. this.elementsNeedUpdate = false;
  6929. this.verticesNeedUpdate = false;
  6930. this.uvsNeedUpdate = false;
  6931. this.normalsNeedUpdate = false;
  6932. this.colorsNeedUpdate = false;
  6933. this.lineDistancesNeedUpdate = false;
  6934. this.groupsNeedUpdate = false;
  6935. }
  6936. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  6937. isGeometry: true,
  6938. applyMatrix: function ( matrix ) {
  6939. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6940. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  6941. var vertex = this.vertices[ i ];
  6942. vertex.applyMatrix4( matrix );
  6943. }
  6944. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  6945. var face = this.faces[ i ];
  6946. face.normal.applyMatrix3( normalMatrix ).normalize();
  6947. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  6948. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  6949. }
  6950. }
  6951. if ( this.boundingBox !== null ) {
  6952. this.computeBoundingBox();
  6953. }
  6954. if ( this.boundingSphere !== null ) {
  6955. this.computeBoundingSphere();
  6956. }
  6957. this.verticesNeedUpdate = true;
  6958. this.normalsNeedUpdate = true;
  6959. return this;
  6960. },
  6961. rotateX: function () {
  6962. // rotate geometry around world x-axis
  6963. var m1 = new Matrix4();
  6964. return function rotateX( angle ) {
  6965. m1.makeRotationX( angle );
  6966. this.applyMatrix( m1 );
  6967. return this;
  6968. };
  6969. }(),
  6970. rotateY: function () {
  6971. // rotate geometry around world y-axis
  6972. var m1 = new Matrix4();
  6973. return function rotateY( angle ) {
  6974. m1.makeRotationY( angle );
  6975. this.applyMatrix( m1 );
  6976. return this;
  6977. };
  6978. }(),
  6979. rotateZ: function () {
  6980. // rotate geometry around world z-axis
  6981. var m1 = new Matrix4();
  6982. return function rotateZ( angle ) {
  6983. m1.makeRotationZ( angle );
  6984. this.applyMatrix( m1 );
  6985. return this;
  6986. };
  6987. }(),
  6988. translate: function () {
  6989. // translate geometry
  6990. var m1 = new Matrix4();
  6991. return function translate( x, y, z ) {
  6992. m1.makeTranslation( x, y, z );
  6993. this.applyMatrix( m1 );
  6994. return this;
  6995. };
  6996. }(),
  6997. scale: function () {
  6998. // scale geometry
  6999. var m1 = new Matrix4();
  7000. return function scale( x, y, z ) {
  7001. m1.makeScale( x, y, z );
  7002. this.applyMatrix( m1 );
  7003. return this;
  7004. };
  7005. }(),
  7006. lookAt: function () {
  7007. var obj = new Object3D();
  7008. return function lookAt( vector ) {
  7009. obj.lookAt( vector );
  7010. obj.updateMatrix();
  7011. this.applyMatrix( obj.matrix );
  7012. };
  7013. }(),
  7014. fromBufferGeometry: function ( geometry ) {
  7015. var scope = this;
  7016. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7017. var attributes = geometry.attributes;
  7018. var positions = attributes.position.array;
  7019. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7020. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7021. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7022. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7023. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7024. var tempNormals = [];
  7025. var tempUVs = [];
  7026. var tempUVs2 = [];
  7027. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7028. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7029. if ( normals !== undefined ) {
  7030. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7031. }
  7032. if ( colors !== undefined ) {
  7033. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7034. }
  7035. if ( uvs !== undefined ) {
  7036. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7037. }
  7038. if ( uvs2 !== undefined ) {
  7039. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7040. }
  7041. }
  7042. function addFace( a, b, c, materialIndex ) {
  7043. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7044. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7045. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7046. scope.faces.push( face );
  7047. if ( uvs !== undefined ) {
  7048. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7049. }
  7050. if ( uvs2 !== undefined ) {
  7051. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7052. }
  7053. }
  7054. var groups = geometry.groups;
  7055. if ( groups.length > 0 ) {
  7056. for ( var i = 0; i < groups.length; i ++ ) {
  7057. var group = groups[ i ];
  7058. var start = group.start;
  7059. var count = group.count;
  7060. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7061. if ( indices !== undefined ) {
  7062. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7063. } else {
  7064. addFace( j, j + 1, j + 2, group.materialIndex );
  7065. }
  7066. }
  7067. }
  7068. } else {
  7069. if ( indices !== undefined ) {
  7070. for ( var i = 0; i < indices.length; i += 3 ) {
  7071. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7072. }
  7073. } else {
  7074. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7075. addFace( i, i + 1, i + 2 );
  7076. }
  7077. }
  7078. }
  7079. this.computeFaceNormals();
  7080. if ( geometry.boundingBox !== null ) {
  7081. this.boundingBox = geometry.boundingBox.clone();
  7082. }
  7083. if ( geometry.boundingSphere !== null ) {
  7084. this.boundingSphere = geometry.boundingSphere.clone();
  7085. }
  7086. return this;
  7087. },
  7088. center: function () {
  7089. this.computeBoundingBox();
  7090. var offset = this.boundingBox.getCenter().negate();
  7091. this.translate( offset.x, offset.y, offset.z );
  7092. return offset;
  7093. },
  7094. normalize: function () {
  7095. this.computeBoundingSphere();
  7096. var center = this.boundingSphere.center;
  7097. var radius = this.boundingSphere.radius;
  7098. var s = radius === 0 ? 1 : 1.0 / radius;
  7099. var matrix = new Matrix4();
  7100. matrix.set(
  7101. s, 0, 0, - s * center.x,
  7102. 0, s, 0, - s * center.y,
  7103. 0, 0, s, - s * center.z,
  7104. 0, 0, 0, 1
  7105. );
  7106. this.applyMatrix( matrix );
  7107. return this;
  7108. },
  7109. computeFaceNormals: function () {
  7110. var cb = new Vector3(), ab = new Vector3();
  7111. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7112. var face = this.faces[ f ];
  7113. var vA = this.vertices[ face.a ];
  7114. var vB = this.vertices[ face.b ];
  7115. var vC = this.vertices[ face.c ];
  7116. cb.subVectors( vC, vB );
  7117. ab.subVectors( vA, vB );
  7118. cb.cross( ab );
  7119. cb.normalize();
  7120. face.normal.copy( cb );
  7121. }
  7122. },
  7123. computeVertexNormals: function ( areaWeighted ) {
  7124. if ( areaWeighted === undefined ) areaWeighted = true;
  7125. var v, vl, f, fl, face, vertices;
  7126. vertices = new Array( this.vertices.length );
  7127. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7128. vertices[ v ] = new Vector3();
  7129. }
  7130. if ( areaWeighted ) {
  7131. // vertex normals weighted by triangle areas
  7132. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7133. var vA, vB, vC;
  7134. var cb = new Vector3(), ab = new Vector3();
  7135. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7136. face = this.faces[ f ];
  7137. vA = this.vertices[ face.a ];
  7138. vB = this.vertices[ face.b ];
  7139. vC = this.vertices[ face.c ];
  7140. cb.subVectors( vC, vB );
  7141. ab.subVectors( vA, vB );
  7142. cb.cross( ab );
  7143. vertices[ face.a ].add( cb );
  7144. vertices[ face.b ].add( cb );
  7145. vertices[ face.c ].add( cb );
  7146. }
  7147. } else {
  7148. this.computeFaceNormals();
  7149. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7150. face = this.faces[ f ];
  7151. vertices[ face.a ].add( face.normal );
  7152. vertices[ face.b ].add( face.normal );
  7153. vertices[ face.c ].add( face.normal );
  7154. }
  7155. }
  7156. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7157. vertices[ v ].normalize();
  7158. }
  7159. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7160. face = this.faces[ f ];
  7161. var vertexNormals = face.vertexNormals;
  7162. if ( vertexNormals.length === 3 ) {
  7163. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7164. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7165. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7166. } else {
  7167. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7168. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7169. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7170. }
  7171. }
  7172. if ( this.faces.length > 0 ) {
  7173. this.normalsNeedUpdate = true;
  7174. }
  7175. },
  7176. computeFlatVertexNormals: function () {
  7177. var f, fl, face;
  7178. this.computeFaceNormals();
  7179. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7180. face = this.faces[ f ];
  7181. var vertexNormals = face.vertexNormals;
  7182. if ( vertexNormals.length === 3 ) {
  7183. vertexNormals[ 0 ].copy( face.normal );
  7184. vertexNormals[ 1 ].copy( face.normal );
  7185. vertexNormals[ 2 ].copy( face.normal );
  7186. } else {
  7187. vertexNormals[ 0 ] = face.normal.clone();
  7188. vertexNormals[ 1 ] = face.normal.clone();
  7189. vertexNormals[ 2 ] = face.normal.clone();
  7190. }
  7191. }
  7192. if ( this.faces.length > 0 ) {
  7193. this.normalsNeedUpdate = true;
  7194. }
  7195. },
  7196. computeMorphNormals: function () {
  7197. var i, il, f, fl, face;
  7198. // save original normals
  7199. // - create temp variables on first access
  7200. // otherwise just copy (for faster repeated calls)
  7201. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7202. face = this.faces[ f ];
  7203. if ( ! face.__originalFaceNormal ) {
  7204. face.__originalFaceNormal = face.normal.clone();
  7205. } else {
  7206. face.__originalFaceNormal.copy( face.normal );
  7207. }
  7208. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7209. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7210. if ( ! face.__originalVertexNormals[ i ] ) {
  7211. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7212. } else {
  7213. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7214. }
  7215. }
  7216. }
  7217. // use temp geometry to compute face and vertex normals for each morph
  7218. var tmpGeo = new Geometry();
  7219. tmpGeo.faces = this.faces;
  7220. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7221. // create on first access
  7222. if ( ! this.morphNormals[ i ] ) {
  7223. this.morphNormals[ i ] = {};
  7224. this.morphNormals[ i ].faceNormals = [];
  7225. this.morphNormals[ i ].vertexNormals = [];
  7226. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7227. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7228. var faceNormal, vertexNormals;
  7229. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7230. faceNormal = new Vector3();
  7231. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7232. dstNormalsFace.push( faceNormal );
  7233. dstNormalsVertex.push( vertexNormals );
  7234. }
  7235. }
  7236. var morphNormals = this.morphNormals[ i ];
  7237. // set vertices to morph target
  7238. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7239. // compute morph normals
  7240. tmpGeo.computeFaceNormals();
  7241. tmpGeo.computeVertexNormals();
  7242. // store morph normals
  7243. var faceNormal, vertexNormals;
  7244. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7245. face = this.faces[ f ];
  7246. faceNormal = morphNormals.faceNormals[ f ];
  7247. vertexNormals = morphNormals.vertexNormals[ f ];
  7248. faceNormal.copy( face.normal );
  7249. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7250. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7251. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7252. }
  7253. }
  7254. // restore original normals
  7255. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7256. face = this.faces[ f ];
  7257. face.normal = face.__originalFaceNormal;
  7258. face.vertexNormals = face.__originalVertexNormals;
  7259. }
  7260. },
  7261. computeLineDistances: function () {
  7262. var d = 0;
  7263. var vertices = this.vertices;
  7264. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7265. if ( i > 0 ) {
  7266. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7267. }
  7268. this.lineDistances[ i ] = d;
  7269. }
  7270. },
  7271. computeBoundingBox: function () {
  7272. if ( this.boundingBox === null ) {
  7273. this.boundingBox = new Box3();
  7274. }
  7275. this.boundingBox.setFromPoints( this.vertices );
  7276. },
  7277. computeBoundingSphere: function () {
  7278. if ( this.boundingSphere === null ) {
  7279. this.boundingSphere = new Sphere();
  7280. }
  7281. this.boundingSphere.setFromPoints( this.vertices );
  7282. },
  7283. merge: function ( geometry, matrix, materialIndexOffset ) {
  7284. if ( ! ( geometry && geometry.isGeometry ) ) {
  7285. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7286. return;
  7287. }
  7288. var normalMatrix,
  7289. vertexOffset = this.vertices.length,
  7290. vertices1 = this.vertices,
  7291. vertices2 = geometry.vertices,
  7292. faces1 = this.faces,
  7293. faces2 = geometry.faces,
  7294. uvs1 = this.faceVertexUvs[ 0 ],
  7295. uvs2 = geometry.faceVertexUvs[ 0 ],
  7296. colors1 = this.colors,
  7297. colors2 = geometry.colors;
  7298. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7299. if ( matrix !== undefined ) {
  7300. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7301. }
  7302. // vertices
  7303. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7304. var vertex = vertices2[ i ];
  7305. var vertexCopy = vertex.clone();
  7306. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7307. vertices1.push( vertexCopy );
  7308. }
  7309. // colors
  7310. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7311. colors1.push( colors2[ i ].clone() );
  7312. }
  7313. // faces
  7314. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7315. var face = faces2[ i ], faceCopy, normal, color,
  7316. faceVertexNormals = face.vertexNormals,
  7317. faceVertexColors = face.vertexColors;
  7318. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7319. faceCopy.normal.copy( face.normal );
  7320. if ( normalMatrix !== undefined ) {
  7321. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7322. }
  7323. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7324. normal = faceVertexNormals[ j ].clone();
  7325. if ( normalMatrix !== undefined ) {
  7326. normal.applyMatrix3( normalMatrix ).normalize();
  7327. }
  7328. faceCopy.vertexNormals.push( normal );
  7329. }
  7330. faceCopy.color.copy( face.color );
  7331. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7332. color = faceVertexColors[ j ];
  7333. faceCopy.vertexColors.push( color.clone() );
  7334. }
  7335. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7336. faces1.push( faceCopy );
  7337. }
  7338. // uvs
  7339. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7340. var uv = uvs2[ i ], uvCopy = [];
  7341. if ( uv === undefined ) {
  7342. continue;
  7343. }
  7344. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7345. uvCopy.push( uv[ j ].clone() );
  7346. }
  7347. uvs1.push( uvCopy );
  7348. }
  7349. },
  7350. mergeMesh: function ( mesh ) {
  7351. if ( ! ( mesh && mesh.isMesh ) ) {
  7352. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7353. return;
  7354. }
  7355. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7356. this.merge( mesh.geometry, mesh.matrix );
  7357. },
  7358. /*
  7359. * Checks for duplicate vertices with hashmap.
  7360. * Duplicated vertices are removed
  7361. * and faces' vertices are updated.
  7362. */
  7363. mergeVertices: function () {
  7364. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7365. var unique = [], changes = [];
  7366. var v, key;
  7367. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7368. var precision = Math.pow( 10, precisionPoints );
  7369. var i, il, face;
  7370. var indices, j, jl;
  7371. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7372. v = this.vertices[ i ];
  7373. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7374. if ( verticesMap[ key ] === undefined ) {
  7375. verticesMap[ key ] = i;
  7376. unique.push( this.vertices[ i ] );
  7377. changes[ i ] = unique.length - 1;
  7378. } else {
  7379. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7380. changes[ i ] = changes[ verticesMap[ key ] ];
  7381. }
  7382. }
  7383. // if faces are completely degenerate after merging vertices, we
  7384. // have to remove them from the geometry.
  7385. var faceIndicesToRemove = [];
  7386. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7387. face = this.faces[ i ];
  7388. face.a = changes[ face.a ];
  7389. face.b = changes[ face.b ];
  7390. face.c = changes[ face.c ];
  7391. indices = [ face.a, face.b, face.c ];
  7392. // if any duplicate vertices are found in a Face3
  7393. // we have to remove the face as nothing can be saved
  7394. for ( var n = 0; n < 3; n ++ ) {
  7395. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7396. faceIndicesToRemove.push( i );
  7397. break;
  7398. }
  7399. }
  7400. }
  7401. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7402. var idx = faceIndicesToRemove[ i ];
  7403. this.faces.splice( idx, 1 );
  7404. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7405. this.faceVertexUvs[ j ].splice( idx, 1 );
  7406. }
  7407. }
  7408. // Use unique set of vertices
  7409. var diff = this.vertices.length - unique.length;
  7410. this.vertices = unique;
  7411. return diff;
  7412. },
  7413. sortFacesByMaterialIndex: function () {
  7414. var faces = this.faces;
  7415. var length = faces.length;
  7416. // tag faces
  7417. for ( var i = 0; i < length; i ++ ) {
  7418. faces[ i ]._id = i;
  7419. }
  7420. // sort faces
  7421. function materialIndexSort( a, b ) {
  7422. return a.materialIndex - b.materialIndex;
  7423. }
  7424. faces.sort( materialIndexSort );
  7425. // sort uvs
  7426. var uvs1 = this.faceVertexUvs[ 0 ];
  7427. var uvs2 = this.faceVertexUvs[ 1 ];
  7428. var newUvs1, newUvs2;
  7429. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7430. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7431. for ( var i = 0; i < length; i ++ ) {
  7432. var id = faces[ i ]._id;
  7433. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7434. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7435. }
  7436. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7437. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7438. },
  7439. toJSON: function () {
  7440. var data = {
  7441. metadata: {
  7442. version: 4.5,
  7443. type: 'Geometry',
  7444. generator: 'Geometry.toJSON'
  7445. }
  7446. };
  7447. // standard Geometry serialization
  7448. data.uuid = this.uuid;
  7449. data.type = this.type;
  7450. if ( this.name !== '' ) data.name = this.name;
  7451. if ( this.parameters !== undefined ) {
  7452. var parameters = this.parameters;
  7453. for ( var key in parameters ) {
  7454. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7455. }
  7456. return data;
  7457. }
  7458. var vertices = [];
  7459. for ( var i = 0; i < this.vertices.length; i ++ ) {
  7460. var vertex = this.vertices[ i ];
  7461. vertices.push( vertex.x, vertex.y, vertex.z );
  7462. }
  7463. var faces = [];
  7464. var normals = [];
  7465. var normalsHash = {};
  7466. var colors = [];
  7467. var colorsHash = {};
  7468. var uvs = [];
  7469. var uvsHash = {};
  7470. for ( var i = 0; i < this.faces.length; i ++ ) {
  7471. var face = this.faces[ i ];
  7472. var hasMaterial = true;
  7473. var hasFaceUv = false; // deprecated
  7474. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  7475. var hasFaceNormal = face.normal.length() > 0;
  7476. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  7477. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  7478. var hasFaceVertexColor = face.vertexColors.length > 0;
  7479. var faceType = 0;
  7480. faceType = setBit( faceType, 0, 0 ); // isQuad
  7481. faceType = setBit( faceType, 1, hasMaterial );
  7482. faceType = setBit( faceType, 2, hasFaceUv );
  7483. faceType = setBit( faceType, 3, hasFaceVertexUv );
  7484. faceType = setBit( faceType, 4, hasFaceNormal );
  7485. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  7486. faceType = setBit( faceType, 6, hasFaceColor );
  7487. faceType = setBit( faceType, 7, hasFaceVertexColor );
  7488. faces.push( faceType );
  7489. faces.push( face.a, face.b, face.c );
  7490. faces.push( face.materialIndex );
  7491. if ( hasFaceVertexUv ) {
  7492. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  7493. faces.push(
  7494. getUvIndex( faceVertexUvs[ 0 ] ),
  7495. getUvIndex( faceVertexUvs[ 1 ] ),
  7496. getUvIndex( faceVertexUvs[ 2 ] )
  7497. );
  7498. }
  7499. if ( hasFaceNormal ) {
  7500. faces.push( getNormalIndex( face.normal ) );
  7501. }
  7502. if ( hasFaceVertexNormal ) {
  7503. var vertexNormals = face.vertexNormals;
  7504. faces.push(
  7505. getNormalIndex( vertexNormals[ 0 ] ),
  7506. getNormalIndex( vertexNormals[ 1 ] ),
  7507. getNormalIndex( vertexNormals[ 2 ] )
  7508. );
  7509. }
  7510. if ( hasFaceColor ) {
  7511. faces.push( getColorIndex( face.color ) );
  7512. }
  7513. if ( hasFaceVertexColor ) {
  7514. var vertexColors = face.vertexColors;
  7515. faces.push(
  7516. getColorIndex( vertexColors[ 0 ] ),
  7517. getColorIndex( vertexColors[ 1 ] ),
  7518. getColorIndex( vertexColors[ 2 ] )
  7519. );
  7520. }
  7521. }
  7522. function setBit( value, position, enabled ) {
  7523. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  7524. }
  7525. function getNormalIndex( normal ) {
  7526. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  7527. if ( normalsHash[ hash ] !== undefined ) {
  7528. return normalsHash[ hash ];
  7529. }
  7530. normalsHash[ hash ] = normals.length / 3;
  7531. normals.push( normal.x, normal.y, normal.z );
  7532. return normalsHash[ hash ];
  7533. }
  7534. function getColorIndex( color ) {
  7535. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  7536. if ( colorsHash[ hash ] !== undefined ) {
  7537. return colorsHash[ hash ];
  7538. }
  7539. colorsHash[ hash ] = colors.length;
  7540. colors.push( color.getHex() );
  7541. return colorsHash[ hash ];
  7542. }
  7543. function getUvIndex( uv ) {
  7544. var hash = uv.x.toString() + uv.y.toString();
  7545. if ( uvsHash[ hash ] !== undefined ) {
  7546. return uvsHash[ hash ];
  7547. }
  7548. uvsHash[ hash ] = uvs.length / 2;
  7549. uvs.push( uv.x, uv.y );
  7550. return uvsHash[ hash ];
  7551. }
  7552. data.data = {};
  7553. data.data.vertices = vertices;
  7554. data.data.normals = normals;
  7555. if ( colors.length > 0 ) data.data.colors = colors;
  7556. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  7557. data.data.faces = faces;
  7558. return data;
  7559. },
  7560. clone: function () {
  7561. /*
  7562. // Handle primitives
  7563. var parameters = this.parameters;
  7564. if ( parameters !== undefined ) {
  7565. var values = [];
  7566. for ( var key in parameters ) {
  7567. values.push( parameters[ key ] );
  7568. }
  7569. var geometry = Object.create( this.constructor.prototype );
  7570. this.constructor.apply( geometry, values );
  7571. return geometry;
  7572. }
  7573. return new this.constructor().copy( this );
  7574. */
  7575. return new Geometry().copy( this );
  7576. },
  7577. copy: function ( source ) {
  7578. var i, il, j, jl, k, kl;
  7579. // reset
  7580. this.vertices = [];
  7581. this.colors = [];
  7582. this.faces = [];
  7583. this.faceVertexUvs = [[]];
  7584. this.morphTargets = [];
  7585. this.morphNormals = [];
  7586. this.skinWeights = [];
  7587. this.skinIndices = [];
  7588. this.lineDistances = [];
  7589. this.boundingBox = null;
  7590. this.boundingSphere = null;
  7591. // name
  7592. this.name = source.name;
  7593. // vertices
  7594. var vertices = source.vertices;
  7595. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  7596. this.vertices.push( vertices[ i ].clone() );
  7597. }
  7598. // colors
  7599. var colors = source.colors;
  7600. for ( i = 0, il = colors.length; i < il; i ++ ) {
  7601. this.colors.push( colors[ i ].clone() );
  7602. }
  7603. // faces
  7604. var faces = source.faces;
  7605. for ( i = 0, il = faces.length; i < il; i ++ ) {
  7606. this.faces.push( faces[ i ].clone() );
  7607. }
  7608. // face vertex uvs
  7609. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  7610. var faceVertexUvs = source.faceVertexUvs[ i ];
  7611. if ( this.faceVertexUvs[ i ] === undefined ) {
  7612. this.faceVertexUvs[ i ] = [];
  7613. }
  7614. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  7615. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  7616. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  7617. var uv = uvs[ k ];
  7618. uvsCopy.push( uv.clone() );
  7619. }
  7620. this.faceVertexUvs[ i ].push( uvsCopy );
  7621. }
  7622. }
  7623. // morph targets
  7624. var morphTargets = source.morphTargets;
  7625. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  7626. var morphTarget = {};
  7627. morphTarget.name = morphTargets[ i ].name;
  7628. // vertices
  7629. if ( morphTargets[ i ].vertices !== undefined ) {
  7630. morphTarget.vertices = [];
  7631. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  7632. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  7633. }
  7634. }
  7635. // normals
  7636. if ( morphTargets[ i ].normals !== undefined ) {
  7637. morphTarget.normals = [];
  7638. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  7639. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  7640. }
  7641. }
  7642. this.morphTargets.push( morphTarget );
  7643. }
  7644. // morph normals
  7645. var morphNormals = source.morphNormals;
  7646. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  7647. var morphNormal = {};
  7648. // vertex normals
  7649. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  7650. morphNormal.vertexNormals = [];
  7651. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  7652. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  7653. var destVertexNormal = {};
  7654. destVertexNormal.a = srcVertexNormal.a.clone();
  7655. destVertexNormal.b = srcVertexNormal.b.clone();
  7656. destVertexNormal.c = srcVertexNormal.c.clone();
  7657. morphNormal.vertexNormals.push( destVertexNormal );
  7658. }
  7659. }
  7660. // face normals
  7661. if ( morphNormals[ i ].faceNormals !== undefined ) {
  7662. morphNormal.faceNormals = [];
  7663. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  7664. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  7665. }
  7666. }
  7667. this.morphNormals.push( morphNormal );
  7668. }
  7669. // skin weights
  7670. var skinWeights = source.skinWeights;
  7671. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  7672. this.skinWeights.push( skinWeights[ i ].clone() );
  7673. }
  7674. // skin indices
  7675. var skinIndices = source.skinIndices;
  7676. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  7677. this.skinIndices.push( skinIndices[ i ].clone() );
  7678. }
  7679. // line distances
  7680. var lineDistances = source.lineDistances;
  7681. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  7682. this.lineDistances.push( lineDistances[ i ] );
  7683. }
  7684. // bounding box
  7685. var boundingBox = source.boundingBox;
  7686. if ( boundingBox !== null ) {
  7687. this.boundingBox = boundingBox.clone();
  7688. }
  7689. // bounding sphere
  7690. var boundingSphere = source.boundingSphere;
  7691. if ( boundingSphere !== null ) {
  7692. this.boundingSphere = boundingSphere.clone();
  7693. }
  7694. // update flags
  7695. this.elementsNeedUpdate = source.elementsNeedUpdate;
  7696. this.verticesNeedUpdate = source.verticesNeedUpdate;
  7697. this.uvsNeedUpdate = source.uvsNeedUpdate;
  7698. this.normalsNeedUpdate = source.normalsNeedUpdate;
  7699. this.colorsNeedUpdate = source.colorsNeedUpdate;
  7700. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  7701. this.groupsNeedUpdate = source.groupsNeedUpdate;
  7702. return this;
  7703. },
  7704. dispose: function () {
  7705. this.dispatchEvent( { type: 'dispose' } );
  7706. }
  7707. } );
  7708. /**
  7709. * @author mrdoob / http://mrdoob.com/
  7710. */
  7711. function BufferAttribute( array, itemSize, normalized ) {
  7712. if ( Array.isArray( array ) ) {
  7713. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7714. }
  7715. this.uuid = _Math.generateUUID();
  7716. this.name = '';
  7717. this.array = array;
  7718. this.itemSize = itemSize;
  7719. this.count = array !== undefined ? array.length / itemSize : 0;
  7720. this.normalized = normalized === true;
  7721. this.dynamic = false;
  7722. this.updateRange = { offset: 0, count: - 1 };
  7723. this.onUploadCallback = function () {};
  7724. this.version = 0;
  7725. }
  7726. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7727. set: function ( value ) {
  7728. if ( value === true ) this.version ++;
  7729. }
  7730. } );
  7731. Object.assign( BufferAttribute.prototype, {
  7732. isBufferAttribute: true,
  7733. setArray: function ( array ) {
  7734. if ( Array.isArray( array ) ) {
  7735. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7736. }
  7737. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7738. this.array = array;
  7739. },
  7740. setDynamic: function ( value ) {
  7741. this.dynamic = value;
  7742. return this;
  7743. },
  7744. copy: function ( source ) {
  7745. this.array = new source.array.constructor( source.array );
  7746. this.itemSize = source.itemSize;
  7747. this.count = source.count;
  7748. this.normalized = source.normalized;
  7749. this.dynamic = source.dynamic;
  7750. return this;
  7751. },
  7752. copyAt: function ( index1, attribute, index2 ) {
  7753. index1 *= this.itemSize;
  7754. index2 *= attribute.itemSize;
  7755. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7756. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7757. }
  7758. return this;
  7759. },
  7760. copyArray: function ( array ) {
  7761. this.array.set( array );
  7762. return this;
  7763. },
  7764. copyColorsArray: function ( colors ) {
  7765. var array = this.array, offset = 0;
  7766. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7767. var color = colors[ i ];
  7768. if ( color === undefined ) {
  7769. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7770. color = new Color();
  7771. }
  7772. array[ offset ++ ] = color.r;
  7773. array[ offset ++ ] = color.g;
  7774. array[ offset ++ ] = color.b;
  7775. }
  7776. return this;
  7777. },
  7778. copyIndicesArray: function ( indices ) {
  7779. var array = this.array, offset = 0;
  7780. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7781. var index = indices[ i ];
  7782. array[ offset ++ ] = index.a;
  7783. array[ offset ++ ] = index.b;
  7784. array[ offset ++ ] = index.c;
  7785. }
  7786. return this;
  7787. },
  7788. copyVector2sArray: function ( vectors ) {
  7789. var array = this.array, offset = 0;
  7790. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7791. var vector = vectors[ i ];
  7792. if ( vector === undefined ) {
  7793. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7794. vector = new Vector2();
  7795. }
  7796. array[ offset ++ ] = vector.x;
  7797. array[ offset ++ ] = vector.y;
  7798. }
  7799. return this;
  7800. },
  7801. copyVector3sArray: function ( vectors ) {
  7802. var array = this.array, offset = 0;
  7803. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7804. var vector = vectors[ i ];
  7805. if ( vector === undefined ) {
  7806. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7807. vector = new Vector3();
  7808. }
  7809. array[ offset ++ ] = vector.x;
  7810. array[ offset ++ ] = vector.y;
  7811. array[ offset ++ ] = vector.z;
  7812. }
  7813. return this;
  7814. },
  7815. copyVector4sArray: function ( vectors ) {
  7816. var array = this.array, offset = 0;
  7817. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7818. var vector = vectors[ i ];
  7819. if ( vector === undefined ) {
  7820. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7821. vector = new Vector4();
  7822. }
  7823. array[ offset ++ ] = vector.x;
  7824. array[ offset ++ ] = vector.y;
  7825. array[ offset ++ ] = vector.z;
  7826. array[ offset ++ ] = vector.w;
  7827. }
  7828. return this;
  7829. },
  7830. set: function ( value, offset ) {
  7831. if ( offset === undefined ) offset = 0;
  7832. this.array.set( value, offset );
  7833. return this;
  7834. },
  7835. getX: function ( index ) {
  7836. return this.array[ index * this.itemSize ];
  7837. },
  7838. setX: function ( index, x ) {
  7839. this.array[ index * this.itemSize ] = x;
  7840. return this;
  7841. },
  7842. getY: function ( index ) {
  7843. return this.array[ index * this.itemSize + 1 ];
  7844. },
  7845. setY: function ( index, y ) {
  7846. this.array[ index * this.itemSize + 1 ] = y;
  7847. return this;
  7848. },
  7849. getZ: function ( index ) {
  7850. return this.array[ index * this.itemSize + 2 ];
  7851. },
  7852. setZ: function ( index, z ) {
  7853. this.array[ index * this.itemSize + 2 ] = z;
  7854. return this;
  7855. },
  7856. getW: function ( index ) {
  7857. return this.array[ index * this.itemSize + 3 ];
  7858. },
  7859. setW: function ( index, w ) {
  7860. this.array[ index * this.itemSize + 3 ] = w;
  7861. return this;
  7862. },
  7863. setXY: function ( index, x, y ) {
  7864. index *= this.itemSize;
  7865. this.array[ index + 0 ] = x;
  7866. this.array[ index + 1 ] = y;
  7867. return this;
  7868. },
  7869. setXYZ: function ( index, x, y, z ) {
  7870. index *= this.itemSize;
  7871. this.array[ index + 0 ] = x;
  7872. this.array[ index + 1 ] = y;
  7873. this.array[ index + 2 ] = z;
  7874. return this;
  7875. },
  7876. setXYZW: function ( index, x, y, z, w ) {
  7877. index *= this.itemSize;
  7878. this.array[ index + 0 ] = x;
  7879. this.array[ index + 1 ] = y;
  7880. this.array[ index + 2 ] = z;
  7881. this.array[ index + 3 ] = w;
  7882. return this;
  7883. },
  7884. onUpload: function ( callback ) {
  7885. this.onUploadCallback = callback;
  7886. return this;
  7887. },
  7888. clone: function () {
  7889. return new this.constructor( this.array, this.itemSize ).copy( this );
  7890. }
  7891. } );
  7892. //
  7893. function Int8BufferAttribute( array, itemSize ) {
  7894. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7895. }
  7896. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7897. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7898. function Uint8BufferAttribute( array, itemSize ) {
  7899. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7900. }
  7901. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7902. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7903. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7904. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7905. }
  7906. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7907. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7908. function Int16BufferAttribute( array, itemSize ) {
  7909. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7910. }
  7911. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7912. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7913. function Uint16BufferAttribute( array, itemSize ) {
  7914. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7915. }
  7916. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7917. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7918. function Int32BufferAttribute( array, itemSize ) {
  7919. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7920. }
  7921. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7922. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7923. function Uint32BufferAttribute( array, itemSize ) {
  7924. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7925. }
  7926. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7927. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7928. function Float32BufferAttribute( array, itemSize ) {
  7929. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7930. }
  7931. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7932. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7933. function Float64BufferAttribute( array, itemSize ) {
  7934. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7935. }
  7936. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7937. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7938. /**
  7939. * @author mrdoob / http://mrdoob.com/
  7940. */
  7941. function DirectGeometry() {
  7942. this.indices = [];
  7943. this.vertices = [];
  7944. this.normals = [];
  7945. this.colors = [];
  7946. this.uvs = [];
  7947. this.uvs2 = [];
  7948. this.groups = [];
  7949. this.morphTargets = {};
  7950. this.skinWeights = [];
  7951. this.skinIndices = [];
  7952. // this.lineDistances = [];
  7953. this.boundingBox = null;
  7954. this.boundingSphere = null;
  7955. // update flags
  7956. this.verticesNeedUpdate = false;
  7957. this.normalsNeedUpdate = false;
  7958. this.colorsNeedUpdate = false;
  7959. this.uvsNeedUpdate = false;
  7960. this.groupsNeedUpdate = false;
  7961. }
  7962. Object.assign( DirectGeometry.prototype, {
  7963. computeGroups: function ( geometry ) {
  7964. var group;
  7965. var groups = [];
  7966. var materialIndex = undefined;
  7967. var faces = geometry.faces;
  7968. for ( var i = 0; i < faces.length; i ++ ) {
  7969. var face = faces[ i ];
  7970. // materials
  7971. if ( face.materialIndex !== materialIndex ) {
  7972. materialIndex = face.materialIndex;
  7973. if ( group !== undefined ) {
  7974. group.count = ( i * 3 ) - group.start;
  7975. groups.push( group );
  7976. }
  7977. group = {
  7978. start: i * 3,
  7979. materialIndex: materialIndex
  7980. };
  7981. }
  7982. }
  7983. if ( group !== undefined ) {
  7984. group.count = ( i * 3 ) - group.start;
  7985. groups.push( group );
  7986. }
  7987. this.groups = groups;
  7988. },
  7989. fromGeometry: function ( geometry ) {
  7990. var faces = geometry.faces;
  7991. var vertices = geometry.vertices;
  7992. var faceVertexUvs = geometry.faceVertexUvs;
  7993. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7994. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7995. // morphs
  7996. var morphTargets = geometry.morphTargets;
  7997. var morphTargetsLength = morphTargets.length;
  7998. var morphTargetsPosition;
  7999. if ( morphTargetsLength > 0 ) {
  8000. morphTargetsPosition = [];
  8001. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  8002. morphTargetsPosition[ i ] = [];
  8003. }
  8004. this.morphTargets.position = morphTargetsPosition;
  8005. }
  8006. var morphNormals = geometry.morphNormals;
  8007. var morphNormalsLength = morphNormals.length;
  8008. var morphTargetsNormal;
  8009. if ( morphNormalsLength > 0 ) {
  8010. morphTargetsNormal = [];
  8011. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  8012. morphTargetsNormal[ i ] = [];
  8013. }
  8014. this.morphTargets.normal = morphTargetsNormal;
  8015. }
  8016. // skins
  8017. var skinIndices = geometry.skinIndices;
  8018. var skinWeights = geometry.skinWeights;
  8019. var hasSkinIndices = skinIndices.length === vertices.length;
  8020. var hasSkinWeights = skinWeights.length === vertices.length;
  8021. //
  8022. for ( var i = 0; i < faces.length; i ++ ) {
  8023. var face = faces[ i ];
  8024. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  8025. var vertexNormals = face.vertexNormals;
  8026. if ( vertexNormals.length === 3 ) {
  8027. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  8028. } else {
  8029. var normal = face.normal;
  8030. this.normals.push( normal, normal, normal );
  8031. }
  8032. var vertexColors = face.vertexColors;
  8033. if ( vertexColors.length === 3 ) {
  8034. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  8035. } else {
  8036. var color = face.color;
  8037. this.colors.push( color, color, color );
  8038. }
  8039. if ( hasFaceVertexUv === true ) {
  8040. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  8041. if ( vertexUvs !== undefined ) {
  8042. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8043. } else {
  8044. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  8045. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  8046. }
  8047. }
  8048. if ( hasFaceVertexUv2 === true ) {
  8049. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  8050. if ( vertexUvs !== undefined ) {
  8051. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  8052. } else {
  8053. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  8054. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  8055. }
  8056. }
  8057. // morphs
  8058. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  8059. var morphTarget = morphTargets[ j ].vertices;
  8060. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  8061. }
  8062. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  8063. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  8064. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  8065. }
  8066. // skins
  8067. if ( hasSkinIndices ) {
  8068. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  8069. }
  8070. if ( hasSkinWeights ) {
  8071. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  8072. }
  8073. }
  8074. this.computeGroups( geometry );
  8075. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8076. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8077. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8078. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8079. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8080. return this;
  8081. }
  8082. } );
  8083. /**
  8084. * @author mrdoob / http://mrdoob.com/
  8085. */
  8086. function arrayMax( array ) {
  8087. if ( array.length === 0 ) return - Infinity;
  8088. var max = array[ 0 ];
  8089. for ( var i = 1, l = array.length; i < l; ++ i ) {
  8090. if ( array[ i ] > max ) max = array[ i ];
  8091. }
  8092. return max;
  8093. }
  8094. /**
  8095. * @author alteredq / http://alteredqualia.com/
  8096. * @author mrdoob / http://mrdoob.com/
  8097. */
  8098. function BufferGeometry() {
  8099. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8100. this.uuid = _Math.generateUUID();
  8101. this.name = '';
  8102. this.type = 'BufferGeometry';
  8103. this.index = null;
  8104. this.attributes = {};
  8105. this.morphAttributes = {};
  8106. this.groups = [];
  8107. this.boundingBox = null;
  8108. this.boundingSphere = null;
  8109. this.drawRange = { start: 0, count: Infinity };
  8110. }
  8111. BufferGeometry.MaxIndex = 65535;
  8112. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8113. isBufferGeometry: true,
  8114. getIndex: function () {
  8115. return this.index;
  8116. },
  8117. setIndex: function ( index ) {
  8118. if ( Array.isArray( index ) ) {
  8119. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8120. } else {
  8121. this.index = index;
  8122. }
  8123. },
  8124. addAttribute: function ( name, attribute ) {
  8125. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  8126. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8127. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8128. return;
  8129. }
  8130. if ( name === 'index' ) {
  8131. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8132. this.setIndex( attribute );
  8133. return;
  8134. }
  8135. this.attributes[ name ] = attribute;
  8136. return this;
  8137. },
  8138. getAttribute: function ( name ) {
  8139. return this.attributes[ name ];
  8140. },
  8141. removeAttribute: function ( name ) {
  8142. delete this.attributes[ name ];
  8143. return this;
  8144. },
  8145. addGroup: function ( start, count, materialIndex ) {
  8146. this.groups.push( {
  8147. start: start,
  8148. count: count,
  8149. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8150. } );
  8151. },
  8152. clearGroups: function () {
  8153. this.groups = [];
  8154. },
  8155. setDrawRange: function ( start, count ) {
  8156. this.drawRange.start = start;
  8157. this.drawRange.count = count;
  8158. },
  8159. applyMatrix: function ( matrix ) {
  8160. var position = this.attributes.position;
  8161. if ( position !== undefined ) {
  8162. matrix.applyToBufferAttribute( position );
  8163. position.needsUpdate = true;
  8164. }
  8165. var normal = this.attributes.normal;
  8166. if ( normal !== undefined ) {
  8167. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8168. normalMatrix.applyToBufferAttribute( normal );
  8169. normal.needsUpdate = true;
  8170. }
  8171. if ( this.boundingBox !== null ) {
  8172. this.computeBoundingBox();
  8173. }
  8174. if ( this.boundingSphere !== null ) {
  8175. this.computeBoundingSphere();
  8176. }
  8177. return this;
  8178. },
  8179. rotateX: function () {
  8180. // rotate geometry around world x-axis
  8181. var m1 = new Matrix4();
  8182. return function rotateX( angle ) {
  8183. m1.makeRotationX( angle );
  8184. this.applyMatrix( m1 );
  8185. return this;
  8186. };
  8187. }(),
  8188. rotateY: function () {
  8189. // rotate geometry around world y-axis
  8190. var m1 = new Matrix4();
  8191. return function rotateY( angle ) {
  8192. m1.makeRotationY( angle );
  8193. this.applyMatrix( m1 );
  8194. return this;
  8195. };
  8196. }(),
  8197. rotateZ: function () {
  8198. // rotate geometry around world z-axis
  8199. var m1 = new Matrix4();
  8200. return function rotateZ( angle ) {
  8201. m1.makeRotationZ( angle );
  8202. this.applyMatrix( m1 );
  8203. return this;
  8204. };
  8205. }(),
  8206. translate: function () {
  8207. // translate geometry
  8208. var m1 = new Matrix4();
  8209. return function translate( x, y, z ) {
  8210. m1.makeTranslation( x, y, z );
  8211. this.applyMatrix( m1 );
  8212. return this;
  8213. };
  8214. }(),
  8215. scale: function () {
  8216. // scale geometry
  8217. var m1 = new Matrix4();
  8218. return function scale( x, y, z ) {
  8219. m1.makeScale( x, y, z );
  8220. this.applyMatrix( m1 );
  8221. return this;
  8222. };
  8223. }(),
  8224. lookAt: function () {
  8225. var obj = new Object3D();
  8226. return function lookAt( vector ) {
  8227. obj.lookAt( vector );
  8228. obj.updateMatrix();
  8229. this.applyMatrix( obj.matrix );
  8230. };
  8231. }(),
  8232. center: function () {
  8233. this.computeBoundingBox();
  8234. var offset = this.boundingBox.getCenter().negate();
  8235. this.translate( offset.x, offset.y, offset.z );
  8236. return offset;
  8237. },
  8238. setFromObject: function ( object ) {
  8239. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8240. var geometry = object.geometry;
  8241. if ( object.isPoints || object.isLine ) {
  8242. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8243. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8244. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8245. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8246. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8247. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8248. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8249. }
  8250. if ( geometry.boundingSphere !== null ) {
  8251. this.boundingSphere = geometry.boundingSphere.clone();
  8252. }
  8253. if ( geometry.boundingBox !== null ) {
  8254. this.boundingBox = geometry.boundingBox.clone();
  8255. }
  8256. } else if ( object.isMesh ) {
  8257. if ( geometry && geometry.isGeometry ) {
  8258. this.fromGeometry( geometry );
  8259. }
  8260. }
  8261. return this;
  8262. },
  8263. updateFromObject: function ( object ) {
  8264. var geometry = object.geometry;
  8265. if ( object.isMesh ) {
  8266. var direct = geometry.__directGeometry;
  8267. if ( geometry.elementsNeedUpdate === true ) {
  8268. direct = undefined;
  8269. geometry.elementsNeedUpdate = false;
  8270. }
  8271. if ( direct === undefined ) {
  8272. return this.fromGeometry( geometry );
  8273. }
  8274. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8275. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8276. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8277. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8278. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8279. geometry.verticesNeedUpdate = false;
  8280. geometry.normalsNeedUpdate = false;
  8281. geometry.colorsNeedUpdate = false;
  8282. geometry.uvsNeedUpdate = false;
  8283. geometry.groupsNeedUpdate = false;
  8284. geometry = direct;
  8285. }
  8286. var attribute;
  8287. if ( geometry.verticesNeedUpdate === true ) {
  8288. attribute = this.attributes.position;
  8289. if ( attribute !== undefined ) {
  8290. attribute.copyVector3sArray( geometry.vertices );
  8291. attribute.needsUpdate = true;
  8292. }
  8293. geometry.verticesNeedUpdate = false;
  8294. }
  8295. if ( geometry.normalsNeedUpdate === true ) {
  8296. attribute = this.attributes.normal;
  8297. if ( attribute !== undefined ) {
  8298. attribute.copyVector3sArray( geometry.normals );
  8299. attribute.needsUpdate = true;
  8300. }
  8301. geometry.normalsNeedUpdate = false;
  8302. }
  8303. if ( geometry.colorsNeedUpdate === true ) {
  8304. attribute = this.attributes.color;
  8305. if ( attribute !== undefined ) {
  8306. attribute.copyColorsArray( geometry.colors );
  8307. attribute.needsUpdate = true;
  8308. }
  8309. geometry.colorsNeedUpdate = false;
  8310. }
  8311. if ( geometry.uvsNeedUpdate ) {
  8312. attribute = this.attributes.uv;
  8313. if ( attribute !== undefined ) {
  8314. attribute.copyVector2sArray( geometry.uvs );
  8315. attribute.needsUpdate = true;
  8316. }
  8317. geometry.uvsNeedUpdate = false;
  8318. }
  8319. if ( geometry.lineDistancesNeedUpdate ) {
  8320. attribute = this.attributes.lineDistance;
  8321. if ( attribute !== undefined ) {
  8322. attribute.copyArray( geometry.lineDistances );
  8323. attribute.needsUpdate = true;
  8324. }
  8325. geometry.lineDistancesNeedUpdate = false;
  8326. }
  8327. if ( geometry.groupsNeedUpdate ) {
  8328. geometry.computeGroups( object.geometry );
  8329. this.groups = geometry.groups;
  8330. geometry.groupsNeedUpdate = false;
  8331. }
  8332. return this;
  8333. },
  8334. fromGeometry: function ( geometry ) {
  8335. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8336. return this.fromDirectGeometry( geometry.__directGeometry );
  8337. },
  8338. fromDirectGeometry: function ( geometry ) {
  8339. var positions = new Float32Array( geometry.vertices.length * 3 );
  8340. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8341. if ( geometry.normals.length > 0 ) {
  8342. var normals = new Float32Array( geometry.normals.length * 3 );
  8343. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8344. }
  8345. if ( geometry.colors.length > 0 ) {
  8346. var colors = new Float32Array( geometry.colors.length * 3 );
  8347. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8348. }
  8349. if ( geometry.uvs.length > 0 ) {
  8350. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8351. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8352. }
  8353. if ( geometry.uvs2.length > 0 ) {
  8354. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8355. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8356. }
  8357. if ( geometry.indices.length > 0 ) {
  8358. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8359. var indices = new TypeArray( geometry.indices.length * 3 );
  8360. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8361. }
  8362. // groups
  8363. this.groups = geometry.groups;
  8364. // morphs
  8365. for ( var name in geometry.morphTargets ) {
  8366. var array = [];
  8367. var morphTargets = geometry.morphTargets[ name ];
  8368. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8369. var morphTarget = morphTargets[ i ];
  8370. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8371. array.push( attribute.copyVector3sArray( morphTarget ) );
  8372. }
  8373. this.morphAttributes[ name ] = array;
  8374. }
  8375. // skinning
  8376. if ( geometry.skinIndices.length > 0 ) {
  8377. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8378. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8379. }
  8380. if ( geometry.skinWeights.length > 0 ) {
  8381. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8382. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8383. }
  8384. //
  8385. if ( geometry.boundingSphere !== null ) {
  8386. this.boundingSphere = geometry.boundingSphere.clone();
  8387. }
  8388. if ( geometry.boundingBox !== null ) {
  8389. this.boundingBox = geometry.boundingBox.clone();
  8390. }
  8391. return this;
  8392. },
  8393. computeBoundingBox: function () {
  8394. if ( this.boundingBox === null ) {
  8395. this.boundingBox = new Box3();
  8396. }
  8397. var position = this.attributes.position;
  8398. if ( position !== undefined ) {
  8399. this.boundingBox.setFromBufferAttribute( position );
  8400. } else {
  8401. this.boundingBox.makeEmpty();
  8402. }
  8403. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8404. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8405. }
  8406. },
  8407. computeBoundingSphere: function () {
  8408. var box = new Box3();
  8409. var vector = new Vector3();
  8410. return function computeBoundingSphere() {
  8411. if ( this.boundingSphere === null ) {
  8412. this.boundingSphere = new Sphere();
  8413. }
  8414. var position = this.attributes.position;
  8415. if ( position ) {
  8416. var center = this.boundingSphere.center;
  8417. box.setFromBufferAttribute( position );
  8418. box.getCenter( center );
  8419. // hoping to find a boundingSphere with a radius smaller than the
  8420. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8421. var maxRadiusSq = 0;
  8422. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8423. vector.x = position.getX( i );
  8424. vector.y = position.getY( i );
  8425. vector.z = position.getZ( i );
  8426. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8427. }
  8428. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8429. if ( isNaN( this.boundingSphere.radius ) ) {
  8430. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8431. }
  8432. }
  8433. };
  8434. }(),
  8435. computeFaceNormals: function () {
  8436. // backwards compatibility
  8437. },
  8438. computeVertexNormals: function () {
  8439. var index = this.index;
  8440. var attributes = this.attributes;
  8441. var groups = this.groups;
  8442. if ( attributes.position ) {
  8443. var positions = attributes.position.array;
  8444. if ( attributes.normal === undefined ) {
  8445. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8446. } else {
  8447. // reset existing normals to zero
  8448. var array = attributes.normal.array;
  8449. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8450. array[ i ] = 0;
  8451. }
  8452. }
  8453. var normals = attributes.normal.array;
  8454. var vA, vB, vC;
  8455. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8456. var cb = new Vector3(), ab = new Vector3();
  8457. // indexed elements
  8458. if ( index ) {
  8459. var indices = index.array;
  8460. if ( groups.length === 0 ) {
  8461. this.addGroup( 0, indices.length );
  8462. }
  8463. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8464. var group = groups[ j ];
  8465. var start = group.start;
  8466. var count = group.count;
  8467. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8468. vA = indices[ i + 0 ] * 3;
  8469. vB = indices[ i + 1 ] * 3;
  8470. vC = indices[ i + 2 ] * 3;
  8471. pA.fromArray( positions, vA );
  8472. pB.fromArray( positions, vB );
  8473. pC.fromArray( positions, vC );
  8474. cb.subVectors( pC, pB );
  8475. ab.subVectors( pA, pB );
  8476. cb.cross( ab );
  8477. normals[ vA ] += cb.x;
  8478. normals[ vA + 1 ] += cb.y;
  8479. normals[ vA + 2 ] += cb.z;
  8480. normals[ vB ] += cb.x;
  8481. normals[ vB + 1 ] += cb.y;
  8482. normals[ vB + 2 ] += cb.z;
  8483. normals[ vC ] += cb.x;
  8484. normals[ vC + 1 ] += cb.y;
  8485. normals[ vC + 2 ] += cb.z;
  8486. }
  8487. }
  8488. } else {
  8489. // non-indexed elements (unconnected triangle soup)
  8490. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8491. pA.fromArray( positions, i );
  8492. pB.fromArray( positions, i + 3 );
  8493. pC.fromArray( positions, i + 6 );
  8494. cb.subVectors( pC, pB );
  8495. ab.subVectors( pA, pB );
  8496. cb.cross( ab );
  8497. normals[ i ] = cb.x;
  8498. normals[ i + 1 ] = cb.y;
  8499. normals[ i + 2 ] = cb.z;
  8500. normals[ i + 3 ] = cb.x;
  8501. normals[ i + 4 ] = cb.y;
  8502. normals[ i + 5 ] = cb.z;
  8503. normals[ i + 6 ] = cb.x;
  8504. normals[ i + 7 ] = cb.y;
  8505. normals[ i + 8 ] = cb.z;
  8506. }
  8507. }
  8508. this.normalizeNormals();
  8509. attributes.normal.needsUpdate = true;
  8510. }
  8511. },
  8512. merge: function ( geometry, offset ) {
  8513. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  8514. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8515. return;
  8516. }
  8517. if ( offset === undefined ) offset = 0;
  8518. var attributes = this.attributes;
  8519. for ( var key in attributes ) {
  8520. if ( geometry.attributes[ key ] === undefined ) continue;
  8521. var attribute1 = attributes[ key ];
  8522. var attributeArray1 = attribute1.array;
  8523. var attribute2 = geometry.attributes[ key ];
  8524. var attributeArray2 = attribute2.array;
  8525. var attributeSize = attribute2.itemSize;
  8526. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8527. attributeArray1[ j ] = attributeArray2[ i ];
  8528. }
  8529. }
  8530. return this;
  8531. },
  8532. normalizeNormals: function () {
  8533. var vector = new Vector3();
  8534. return function normalizeNormals() {
  8535. var normals = this.attributes.normal;
  8536. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8537. vector.x = normals.getX( i );
  8538. vector.y = normals.getY( i );
  8539. vector.z = normals.getZ( i );
  8540. vector.normalize();
  8541. normals.setXYZ( i, vector.x, vector.y, vector.z );
  8542. }
  8543. };
  8544. }(),
  8545. toNonIndexed: function () {
  8546. if ( this.index === null ) {
  8547. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8548. return this;
  8549. }
  8550. var geometry2 = new BufferGeometry();
  8551. var indices = this.index.array;
  8552. var attributes = this.attributes;
  8553. for ( var name in attributes ) {
  8554. var attribute = attributes[ name ];
  8555. var array = attribute.array;
  8556. var itemSize = attribute.itemSize;
  8557. var array2 = new array.constructor( indices.length * itemSize );
  8558. var index = 0, index2 = 0;
  8559. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8560. index = indices[ i ] * itemSize;
  8561. for ( var j = 0; j < itemSize; j ++ ) {
  8562. array2[ index2 ++ ] = array[ index ++ ];
  8563. }
  8564. }
  8565. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8566. }
  8567. return geometry2;
  8568. },
  8569. toJSON: function () {
  8570. var data = {
  8571. metadata: {
  8572. version: 4.5,
  8573. type: 'BufferGeometry',
  8574. generator: 'BufferGeometry.toJSON'
  8575. }
  8576. };
  8577. // standard BufferGeometry serialization
  8578. data.uuid = this.uuid;
  8579. data.type = this.type;
  8580. if ( this.name !== '' ) data.name = this.name;
  8581. if ( this.parameters !== undefined ) {
  8582. var parameters = this.parameters;
  8583. for ( var key in parameters ) {
  8584. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8585. }
  8586. return data;
  8587. }
  8588. data.data = { attributes: {} };
  8589. var index = this.index;
  8590. if ( index !== null ) {
  8591. var array = Array.prototype.slice.call( index.array );
  8592. data.data.index = {
  8593. type: index.array.constructor.name,
  8594. array: array
  8595. };
  8596. }
  8597. var attributes = this.attributes;
  8598. for ( var key in attributes ) {
  8599. var attribute = attributes[ key ];
  8600. var array = Array.prototype.slice.call( attribute.array );
  8601. data.data.attributes[ key ] = {
  8602. itemSize: attribute.itemSize,
  8603. type: attribute.array.constructor.name,
  8604. array: array,
  8605. normalized: attribute.normalized
  8606. };
  8607. }
  8608. var groups = this.groups;
  8609. if ( groups.length > 0 ) {
  8610. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8611. }
  8612. var boundingSphere = this.boundingSphere;
  8613. if ( boundingSphere !== null ) {
  8614. data.data.boundingSphere = {
  8615. center: boundingSphere.center.toArray(),
  8616. radius: boundingSphere.radius
  8617. };
  8618. }
  8619. return data;
  8620. },
  8621. clone: function () {
  8622. /*
  8623. // Handle primitives
  8624. var parameters = this.parameters;
  8625. if ( parameters !== undefined ) {
  8626. var values = [];
  8627. for ( var key in parameters ) {
  8628. values.push( parameters[ key ] );
  8629. }
  8630. var geometry = Object.create( this.constructor.prototype );
  8631. this.constructor.apply( geometry, values );
  8632. return geometry;
  8633. }
  8634. return new this.constructor().copy( this );
  8635. */
  8636. return new BufferGeometry().copy( this );
  8637. },
  8638. copy: function ( source ) {
  8639. var name, i, l;
  8640. // reset
  8641. this.index = null;
  8642. this.attributes = {};
  8643. this.morphAttributes = {};
  8644. this.groups = [];
  8645. this.boundingBox = null;
  8646. this.boundingSphere = null;
  8647. // name
  8648. this.name = source.name;
  8649. // index
  8650. var index = source.index;
  8651. if ( index !== null ) {
  8652. this.setIndex( index.clone() );
  8653. }
  8654. // attributes
  8655. var attributes = source.attributes;
  8656. for ( name in attributes ) {
  8657. var attribute = attributes[ name ];
  8658. this.addAttribute( name, attribute.clone() );
  8659. }
  8660. // morph attributes
  8661. var morphAttributes = source.morphAttributes;
  8662. for ( name in morphAttributes ) {
  8663. var array = [];
  8664. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8665. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8666. array.push( morphAttribute[ i ].clone() );
  8667. }
  8668. this.morphAttributes[ name ] = array;
  8669. }
  8670. // groups
  8671. var groups = source.groups;
  8672. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8673. var group = groups[ i ];
  8674. this.addGroup( group.start, group.count, group.materialIndex );
  8675. }
  8676. // bounding box
  8677. var boundingBox = source.boundingBox;
  8678. if ( boundingBox !== null ) {
  8679. this.boundingBox = boundingBox.clone();
  8680. }
  8681. // bounding sphere
  8682. var boundingSphere = source.boundingSphere;
  8683. if ( boundingSphere !== null ) {
  8684. this.boundingSphere = boundingSphere.clone();
  8685. }
  8686. // draw range
  8687. this.drawRange.start = source.drawRange.start;
  8688. this.drawRange.count = source.drawRange.count;
  8689. return this;
  8690. },
  8691. dispose: function () {
  8692. this.dispatchEvent( { type: 'dispose' } );
  8693. }
  8694. } );
  8695. /**
  8696. * @author mrdoob / http://mrdoob.com/
  8697. * @author Mugen87 / https://github.com/Mugen87
  8698. */
  8699. // BoxGeometry
  8700. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8701. Geometry.call( this );
  8702. this.type = 'BoxGeometry';
  8703. this.parameters = {
  8704. width: width,
  8705. height: height,
  8706. depth: depth,
  8707. widthSegments: widthSegments,
  8708. heightSegments: heightSegments,
  8709. depthSegments: depthSegments
  8710. };
  8711. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  8712. this.mergeVertices();
  8713. }
  8714. BoxGeometry.prototype = Object.create( Geometry.prototype );
  8715. BoxGeometry.prototype.constructor = BoxGeometry;
  8716. // BoxBufferGeometry
  8717. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8718. BufferGeometry.call( this );
  8719. this.type = 'BoxBufferGeometry';
  8720. this.parameters = {
  8721. width: width,
  8722. height: height,
  8723. depth: depth,
  8724. widthSegments: widthSegments,
  8725. heightSegments: heightSegments,
  8726. depthSegments: depthSegments
  8727. };
  8728. var scope = this;
  8729. // segments
  8730. widthSegments = Math.floor( widthSegments ) || 1;
  8731. heightSegments = Math.floor( heightSegments ) || 1;
  8732. depthSegments = Math.floor( depthSegments ) || 1;
  8733. // buffers
  8734. var indices = [];
  8735. var vertices = [];
  8736. var normals = [];
  8737. var uvs = [];
  8738. // helper variables
  8739. var numberOfVertices = 0;
  8740. var groupStart = 0;
  8741. // build each side of the box geometry
  8742. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8743. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8744. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8745. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8746. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8747. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8748. // build geometry
  8749. this.setIndex( indices );
  8750. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8751. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8752. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8753. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8754. var segmentWidth = width / gridX;
  8755. var segmentHeight = height / gridY;
  8756. var widthHalf = width / 2;
  8757. var heightHalf = height / 2;
  8758. var depthHalf = depth / 2;
  8759. var gridX1 = gridX + 1;
  8760. var gridY1 = gridY + 1;
  8761. var vertexCounter = 0;
  8762. var groupCount = 0;
  8763. var ix, iy;
  8764. var vector = new Vector3();
  8765. // generate vertices, normals and uvs
  8766. for ( iy = 0; iy < gridY1; iy ++ ) {
  8767. var y = iy * segmentHeight - heightHalf;
  8768. for ( ix = 0; ix < gridX1; ix ++ ) {
  8769. var x = ix * segmentWidth - widthHalf;
  8770. // set values to correct vector component
  8771. vector[ u ] = x * udir;
  8772. vector[ v ] = y * vdir;
  8773. vector[ w ] = depthHalf;
  8774. // now apply vector to vertex buffer
  8775. vertices.push( vector.x, vector.y, vector.z );
  8776. // set values to correct vector component
  8777. vector[ u ] = 0;
  8778. vector[ v ] = 0;
  8779. vector[ w ] = depth > 0 ? 1 : - 1;
  8780. // now apply vector to normal buffer
  8781. normals.push( vector.x, vector.y, vector.z );
  8782. // uvs
  8783. uvs.push( ix / gridX );
  8784. uvs.push( 1 - ( iy / gridY ) );
  8785. // counters
  8786. vertexCounter += 1;
  8787. }
  8788. }
  8789. // indices
  8790. // 1. you need three indices to draw a single face
  8791. // 2. a single segment consists of two faces
  8792. // 3. so we need to generate six (2*3) indices per segment
  8793. for ( iy = 0; iy < gridY; iy ++ ) {
  8794. for ( ix = 0; ix < gridX; ix ++ ) {
  8795. var a = numberOfVertices + ix + gridX1 * iy;
  8796. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8797. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8798. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8799. // faces
  8800. indices.push( a, b, d );
  8801. indices.push( b, c, d );
  8802. // increase counter
  8803. groupCount += 6;
  8804. }
  8805. }
  8806. // add a group to the geometry. this will ensure multi material support
  8807. scope.addGroup( groupStart, groupCount, materialIndex );
  8808. // calculate new start value for groups
  8809. groupStart += groupCount;
  8810. // update total number of vertices
  8811. numberOfVertices += vertexCounter;
  8812. }
  8813. }
  8814. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8815. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  8816. /**
  8817. * @author mrdoob / http://mrdoob.com/
  8818. * @author Mugen87 / https://github.com/Mugen87
  8819. */
  8820. // PlaneGeometry
  8821. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  8822. Geometry.call( this );
  8823. this.type = 'PlaneGeometry';
  8824. this.parameters = {
  8825. width: width,
  8826. height: height,
  8827. widthSegments: widthSegments,
  8828. heightSegments: heightSegments
  8829. };
  8830. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  8831. this.mergeVertices();
  8832. }
  8833. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  8834. PlaneGeometry.prototype.constructor = PlaneGeometry;
  8835. // PlaneBufferGeometry
  8836. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  8837. BufferGeometry.call( this );
  8838. this.type = 'PlaneBufferGeometry';
  8839. this.parameters = {
  8840. width: width,
  8841. height: height,
  8842. widthSegments: widthSegments,
  8843. heightSegments: heightSegments
  8844. };
  8845. var width_half = width / 2;
  8846. var height_half = height / 2;
  8847. var gridX = Math.floor( widthSegments ) || 1;
  8848. var gridY = Math.floor( heightSegments ) || 1;
  8849. var gridX1 = gridX + 1;
  8850. var gridY1 = gridY + 1;
  8851. var segment_width = width / gridX;
  8852. var segment_height = height / gridY;
  8853. var ix, iy;
  8854. // buffers
  8855. var indices = [];
  8856. var vertices = [];
  8857. var normals = [];
  8858. var uvs = [];
  8859. // generate vertices, normals and uvs
  8860. for ( iy = 0; iy < gridY1; iy ++ ) {
  8861. var y = iy * segment_height - height_half;
  8862. for ( ix = 0; ix < gridX1; ix ++ ) {
  8863. var x = ix * segment_width - width_half;
  8864. vertices.push( x, - y, 0 );
  8865. normals.push( 0, 0, 1 );
  8866. uvs.push( ix / gridX );
  8867. uvs.push( 1 - ( iy / gridY ) );
  8868. }
  8869. }
  8870. // indices
  8871. for ( iy = 0; iy < gridY; iy ++ ) {
  8872. for ( ix = 0; ix < gridX; ix ++ ) {
  8873. var a = ix + gridX1 * iy;
  8874. var b = ix + gridX1 * ( iy + 1 );
  8875. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8876. var d = ( ix + 1 ) + gridX1 * iy;
  8877. // faces
  8878. indices.push( a, b, d );
  8879. indices.push( b, c, d );
  8880. }
  8881. }
  8882. // build geometry
  8883. this.setIndex( indices );
  8884. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8885. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8886. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8887. }
  8888. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8889. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  8890. /**
  8891. * @author mrdoob / http://mrdoob.com/
  8892. * @author alteredq / http://alteredqualia.com/
  8893. *
  8894. * parameters = {
  8895. * color: <hex>,
  8896. * opacity: <float>,
  8897. * map: new THREE.Texture( <Image> ),
  8898. *
  8899. * lightMap: new THREE.Texture( <Image> ),
  8900. * lightMapIntensity: <float>
  8901. *
  8902. * aoMap: new THREE.Texture( <Image> ),
  8903. * aoMapIntensity: <float>
  8904. *
  8905. * specularMap: new THREE.Texture( <Image> ),
  8906. *
  8907. * alphaMap: new THREE.Texture( <Image> ),
  8908. *
  8909. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8910. * combine: THREE.Multiply,
  8911. * reflectivity: <float>,
  8912. * refractionRatio: <float>,
  8913. *
  8914. * depthTest: <bool>,
  8915. * depthWrite: <bool>,
  8916. *
  8917. * wireframe: <boolean>,
  8918. * wireframeLinewidth: <float>,
  8919. *
  8920. * skinning: <bool>,
  8921. * morphTargets: <bool>
  8922. * }
  8923. */
  8924. function MeshBasicMaterial( parameters ) {
  8925. Material.call( this );
  8926. this.type = 'MeshBasicMaterial';
  8927. this.color = new Color( 0xffffff ); // emissive
  8928. this.map = null;
  8929. this.lightMap = null;
  8930. this.lightMapIntensity = 1.0;
  8931. this.aoMap = null;
  8932. this.aoMapIntensity = 1.0;
  8933. this.specularMap = null;
  8934. this.alphaMap = null;
  8935. this.envMap = null;
  8936. this.combine = MultiplyOperation;
  8937. this.reflectivity = 1;
  8938. this.refractionRatio = 0.98;
  8939. this.wireframe = false;
  8940. this.wireframeLinewidth = 1;
  8941. this.wireframeLinecap = 'round';
  8942. this.wireframeLinejoin = 'round';
  8943. this.skinning = false;
  8944. this.morphTargets = false;
  8945. this.lights = false;
  8946. this.setValues( parameters );
  8947. }
  8948. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  8949. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  8950. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  8951. MeshBasicMaterial.prototype.copy = function ( source ) {
  8952. Material.prototype.copy.call( this, source );
  8953. this.color.copy( source.color );
  8954. this.map = source.map;
  8955. this.lightMap = source.lightMap;
  8956. this.lightMapIntensity = source.lightMapIntensity;
  8957. this.aoMap = source.aoMap;
  8958. this.aoMapIntensity = source.aoMapIntensity;
  8959. this.specularMap = source.specularMap;
  8960. this.alphaMap = source.alphaMap;
  8961. this.envMap = source.envMap;
  8962. this.combine = source.combine;
  8963. this.reflectivity = source.reflectivity;
  8964. this.refractionRatio = source.refractionRatio;
  8965. this.wireframe = source.wireframe;
  8966. this.wireframeLinewidth = source.wireframeLinewidth;
  8967. this.wireframeLinecap = source.wireframeLinecap;
  8968. this.wireframeLinejoin = source.wireframeLinejoin;
  8969. this.skinning = source.skinning;
  8970. this.morphTargets = source.morphTargets;
  8971. return this;
  8972. };
  8973. /**
  8974. * @author bhouston / http://clara.io
  8975. */
  8976. function Ray( origin, direction ) {
  8977. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  8978. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  8979. }
  8980. Object.assign( Ray.prototype, {
  8981. set: function ( origin, direction ) {
  8982. this.origin.copy( origin );
  8983. this.direction.copy( direction );
  8984. return this;
  8985. },
  8986. clone: function () {
  8987. return new this.constructor().copy( this );
  8988. },
  8989. copy: function ( ray ) {
  8990. this.origin.copy( ray.origin );
  8991. this.direction.copy( ray.direction );
  8992. return this;
  8993. },
  8994. at: function ( t, optionalTarget ) {
  8995. var result = optionalTarget || new Vector3();
  8996. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  8997. },
  8998. lookAt: function ( v ) {
  8999. this.direction.copy( v ).sub( this.origin ).normalize();
  9000. return this;
  9001. },
  9002. recast: function () {
  9003. var v1 = new Vector3();
  9004. return function recast( t ) {
  9005. this.origin.copy( this.at( t, v1 ) );
  9006. return this;
  9007. };
  9008. }(),
  9009. closestPointToPoint: function ( point, optionalTarget ) {
  9010. var result = optionalTarget || new Vector3();
  9011. result.subVectors( point, this.origin );
  9012. var directionDistance = result.dot( this.direction );
  9013. if ( directionDistance < 0 ) {
  9014. return result.copy( this.origin );
  9015. }
  9016. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9017. },
  9018. distanceToPoint: function ( point ) {
  9019. return Math.sqrt( this.distanceSqToPoint( point ) );
  9020. },
  9021. distanceSqToPoint: function () {
  9022. var v1 = new Vector3();
  9023. return function distanceSqToPoint( point ) {
  9024. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  9025. // point behind the ray
  9026. if ( directionDistance < 0 ) {
  9027. return this.origin.distanceToSquared( point );
  9028. }
  9029. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9030. return v1.distanceToSquared( point );
  9031. };
  9032. }(),
  9033. distanceSqToSegment: function () {
  9034. var segCenter = new Vector3();
  9035. var segDir = new Vector3();
  9036. var diff = new Vector3();
  9037. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9038. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9039. // It returns the min distance between the ray and the segment
  9040. // defined by v0 and v1
  9041. // It can also set two optional targets :
  9042. // - The closest point on the ray
  9043. // - The closest point on the segment
  9044. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9045. segDir.copy( v1 ).sub( v0 ).normalize();
  9046. diff.copy( this.origin ).sub( segCenter );
  9047. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9048. var a01 = - this.direction.dot( segDir );
  9049. var b0 = diff.dot( this.direction );
  9050. var b1 = - diff.dot( segDir );
  9051. var c = diff.lengthSq();
  9052. var det = Math.abs( 1 - a01 * a01 );
  9053. var s0, s1, sqrDist, extDet;
  9054. if ( det > 0 ) {
  9055. // The ray and segment are not parallel.
  9056. s0 = a01 * b1 - b0;
  9057. s1 = a01 * b0 - b1;
  9058. extDet = segExtent * det;
  9059. if ( s0 >= 0 ) {
  9060. if ( s1 >= - extDet ) {
  9061. if ( s1 <= extDet ) {
  9062. // region 0
  9063. // Minimum at interior points of ray and segment.
  9064. var invDet = 1 / det;
  9065. s0 *= invDet;
  9066. s1 *= invDet;
  9067. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9068. } else {
  9069. // region 1
  9070. s1 = segExtent;
  9071. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9072. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9073. }
  9074. } else {
  9075. // region 5
  9076. s1 = - segExtent;
  9077. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9078. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9079. }
  9080. } else {
  9081. if ( s1 <= - extDet ) {
  9082. // region 4
  9083. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9084. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9085. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9086. } else if ( s1 <= extDet ) {
  9087. // region 3
  9088. s0 = 0;
  9089. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9090. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9091. } else {
  9092. // region 2
  9093. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9094. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9095. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9096. }
  9097. }
  9098. } else {
  9099. // Ray and segment are parallel.
  9100. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9101. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9102. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9103. }
  9104. if ( optionalPointOnRay ) {
  9105. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9106. }
  9107. if ( optionalPointOnSegment ) {
  9108. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  9109. }
  9110. return sqrDist;
  9111. };
  9112. }(),
  9113. intersectSphere: function () {
  9114. var v1 = new Vector3();
  9115. return function intersectSphere( sphere, optionalTarget ) {
  9116. v1.subVectors( sphere.center, this.origin );
  9117. var tca = v1.dot( this.direction );
  9118. var d2 = v1.dot( v1 ) - tca * tca;
  9119. var radius2 = sphere.radius * sphere.radius;
  9120. if ( d2 > radius2 ) return null;
  9121. var thc = Math.sqrt( radius2 - d2 );
  9122. // t0 = first intersect point - entrance on front of sphere
  9123. var t0 = tca - thc;
  9124. // t1 = second intersect point - exit point on back of sphere
  9125. var t1 = tca + thc;
  9126. // test to see if both t0 and t1 are behind the ray - if so, return null
  9127. if ( t0 < 0 && t1 < 0 ) return null;
  9128. // test to see if t0 is behind the ray:
  9129. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9130. // in order to always return an intersect point that is in front of the ray.
  9131. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  9132. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9133. return this.at( t0, optionalTarget );
  9134. };
  9135. }(),
  9136. intersectsSphere: function ( sphere ) {
  9137. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  9138. },
  9139. distanceToPlane: function ( plane ) {
  9140. var denominator = plane.normal.dot( this.direction );
  9141. if ( denominator === 0 ) {
  9142. // line is coplanar, return origin
  9143. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9144. return 0;
  9145. }
  9146. // Null is preferable to undefined since undefined means.... it is undefined
  9147. return null;
  9148. }
  9149. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9150. // Return if the ray never intersects the plane
  9151. return t >= 0 ? t : null;
  9152. },
  9153. intersectPlane: function ( plane, optionalTarget ) {
  9154. var t = this.distanceToPlane( plane );
  9155. if ( t === null ) {
  9156. return null;
  9157. }
  9158. return this.at( t, optionalTarget );
  9159. },
  9160. intersectsPlane: function ( plane ) {
  9161. // check if the ray lies on the plane first
  9162. var distToPoint = plane.distanceToPoint( this.origin );
  9163. if ( distToPoint === 0 ) {
  9164. return true;
  9165. }
  9166. var denominator = plane.normal.dot( this.direction );
  9167. if ( denominator * distToPoint < 0 ) {
  9168. return true;
  9169. }
  9170. // ray origin is behind the plane (and is pointing behind it)
  9171. return false;
  9172. },
  9173. intersectBox: function ( box, optionalTarget ) {
  9174. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9175. var invdirx = 1 / this.direction.x,
  9176. invdiry = 1 / this.direction.y,
  9177. invdirz = 1 / this.direction.z;
  9178. var origin = this.origin;
  9179. if ( invdirx >= 0 ) {
  9180. tmin = ( box.min.x - origin.x ) * invdirx;
  9181. tmax = ( box.max.x - origin.x ) * invdirx;
  9182. } else {
  9183. tmin = ( box.max.x - origin.x ) * invdirx;
  9184. tmax = ( box.min.x - origin.x ) * invdirx;
  9185. }
  9186. if ( invdiry >= 0 ) {
  9187. tymin = ( box.min.y - origin.y ) * invdiry;
  9188. tymax = ( box.max.y - origin.y ) * invdiry;
  9189. } else {
  9190. tymin = ( box.max.y - origin.y ) * invdiry;
  9191. tymax = ( box.min.y - origin.y ) * invdiry;
  9192. }
  9193. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  9194. // These lines also handle the case where tmin or tmax is NaN
  9195. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9196. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  9197. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  9198. if ( invdirz >= 0 ) {
  9199. tzmin = ( box.min.z - origin.z ) * invdirz;
  9200. tzmax = ( box.max.z - origin.z ) * invdirz;
  9201. } else {
  9202. tzmin = ( box.max.z - origin.z ) * invdirz;
  9203. tzmax = ( box.min.z - origin.z ) * invdirz;
  9204. }
  9205. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  9206. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  9207. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  9208. //return point closest to the ray (positive side)
  9209. if ( tmax < 0 ) return null;
  9210. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  9211. },
  9212. intersectsBox: ( function () {
  9213. var v = new Vector3();
  9214. return function intersectsBox( box ) {
  9215. return this.intersectBox( box, v ) !== null;
  9216. };
  9217. } )(),
  9218. intersectTriangle: function () {
  9219. // Compute the offset origin, edges, and normal.
  9220. var diff = new Vector3();
  9221. var edge1 = new Vector3();
  9222. var edge2 = new Vector3();
  9223. var normal = new Vector3();
  9224. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  9225. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9226. edge1.subVectors( b, a );
  9227. edge2.subVectors( c, a );
  9228. normal.crossVectors( edge1, edge2 );
  9229. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9230. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9231. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9232. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9233. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9234. var DdN = this.direction.dot( normal );
  9235. var sign;
  9236. if ( DdN > 0 ) {
  9237. if ( backfaceCulling ) return null;
  9238. sign = 1;
  9239. } else if ( DdN < 0 ) {
  9240. sign = - 1;
  9241. DdN = - DdN;
  9242. } else {
  9243. return null;
  9244. }
  9245. diff.subVectors( this.origin, a );
  9246. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  9247. // b1 < 0, no intersection
  9248. if ( DdQxE2 < 0 ) {
  9249. return null;
  9250. }
  9251. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  9252. // b2 < 0, no intersection
  9253. if ( DdE1xQ < 0 ) {
  9254. return null;
  9255. }
  9256. // b1+b2 > 1, no intersection
  9257. if ( DdQxE2 + DdE1xQ > DdN ) {
  9258. return null;
  9259. }
  9260. // Line intersects triangle, check if ray does.
  9261. var QdN = - sign * diff.dot( normal );
  9262. // t < 0, no intersection
  9263. if ( QdN < 0 ) {
  9264. return null;
  9265. }
  9266. // Ray intersects triangle.
  9267. return this.at( QdN / DdN, optionalTarget );
  9268. };
  9269. }(),
  9270. applyMatrix4: function ( matrix4 ) {
  9271. this.origin.applyMatrix4( matrix4 );
  9272. this.direction.transformDirection( matrix4 );
  9273. return this;
  9274. },
  9275. equals: function ( ray ) {
  9276. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  9277. }
  9278. } );
  9279. /**
  9280. * @author bhouston / http://clara.io
  9281. */
  9282. function Line3( start, end ) {
  9283. this.start = ( start !== undefined ) ? start : new Vector3();
  9284. this.end = ( end !== undefined ) ? end : new Vector3();
  9285. }
  9286. Object.assign( Line3.prototype, {
  9287. set: function ( start, end ) {
  9288. this.start.copy( start );
  9289. this.end.copy( end );
  9290. return this;
  9291. },
  9292. clone: function () {
  9293. return new this.constructor().copy( this );
  9294. },
  9295. copy: function ( line ) {
  9296. this.start.copy( line.start );
  9297. this.end.copy( line.end );
  9298. return this;
  9299. },
  9300. getCenter: function ( optionalTarget ) {
  9301. var result = optionalTarget || new Vector3();
  9302. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  9303. },
  9304. delta: function ( optionalTarget ) {
  9305. var result = optionalTarget || new Vector3();
  9306. return result.subVectors( this.end, this.start );
  9307. },
  9308. distanceSq: function () {
  9309. return this.start.distanceToSquared( this.end );
  9310. },
  9311. distance: function () {
  9312. return this.start.distanceTo( this.end );
  9313. },
  9314. at: function ( t, optionalTarget ) {
  9315. var result = optionalTarget || new Vector3();
  9316. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9317. },
  9318. closestPointToPointParameter: function () {
  9319. var startP = new Vector3();
  9320. var startEnd = new Vector3();
  9321. return function closestPointToPointParameter( point, clampToLine ) {
  9322. startP.subVectors( point, this.start );
  9323. startEnd.subVectors( this.end, this.start );
  9324. var startEnd2 = startEnd.dot( startEnd );
  9325. var startEnd_startP = startEnd.dot( startP );
  9326. var t = startEnd_startP / startEnd2;
  9327. if ( clampToLine ) {
  9328. t = _Math.clamp( t, 0, 1 );
  9329. }
  9330. return t;
  9331. };
  9332. }(),
  9333. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  9334. var t = this.closestPointToPointParameter( point, clampToLine );
  9335. var result = optionalTarget || new Vector3();
  9336. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9337. },
  9338. applyMatrix4: function ( matrix ) {
  9339. this.start.applyMatrix4( matrix );
  9340. this.end.applyMatrix4( matrix );
  9341. return this;
  9342. },
  9343. equals: function ( line ) {
  9344. return line.start.equals( this.start ) && line.end.equals( this.end );
  9345. }
  9346. } );
  9347. /**
  9348. * @author bhouston / http://clara.io
  9349. * @author mrdoob / http://mrdoob.com/
  9350. */
  9351. function Triangle( a, b, c ) {
  9352. this.a = ( a !== undefined ) ? a : new Vector3();
  9353. this.b = ( b !== undefined ) ? b : new Vector3();
  9354. this.c = ( c !== undefined ) ? c : new Vector3();
  9355. }
  9356. Object.assign( Triangle, {
  9357. normal: function () {
  9358. var v0 = new Vector3();
  9359. return function normal( a, b, c, optionalTarget ) {
  9360. var result = optionalTarget || new Vector3();
  9361. result.subVectors( c, b );
  9362. v0.subVectors( a, b );
  9363. result.cross( v0 );
  9364. var resultLengthSq = result.lengthSq();
  9365. if ( resultLengthSq > 0 ) {
  9366. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  9367. }
  9368. return result.set( 0, 0, 0 );
  9369. };
  9370. }(),
  9371. // static/instance method to calculate barycentric coordinates
  9372. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9373. barycoordFromPoint: function () {
  9374. var v0 = new Vector3();
  9375. var v1 = new Vector3();
  9376. var v2 = new Vector3();
  9377. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  9378. v0.subVectors( c, a );
  9379. v1.subVectors( b, a );
  9380. v2.subVectors( point, a );
  9381. var dot00 = v0.dot( v0 );
  9382. var dot01 = v0.dot( v1 );
  9383. var dot02 = v0.dot( v2 );
  9384. var dot11 = v1.dot( v1 );
  9385. var dot12 = v1.dot( v2 );
  9386. var denom = ( dot00 * dot11 - dot01 * dot01 );
  9387. var result = optionalTarget || new Vector3();
  9388. // collinear or singular triangle
  9389. if ( denom === 0 ) {
  9390. // arbitrary location outside of triangle?
  9391. // not sure if this is the best idea, maybe should be returning undefined
  9392. return result.set( - 2, - 1, - 1 );
  9393. }
  9394. var invDenom = 1 / denom;
  9395. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9396. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9397. // barycentric coordinates must always sum to 1
  9398. return result.set( 1 - u - v, v, u );
  9399. };
  9400. }(),
  9401. containsPoint: function () {
  9402. var v1 = new Vector3();
  9403. return function containsPoint( point, a, b, c ) {
  9404. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  9405. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  9406. };
  9407. }()
  9408. } );
  9409. Object.assign( Triangle.prototype, {
  9410. set: function ( a, b, c ) {
  9411. this.a.copy( a );
  9412. this.b.copy( b );
  9413. this.c.copy( c );
  9414. return this;
  9415. },
  9416. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  9417. this.a.copy( points[ i0 ] );
  9418. this.b.copy( points[ i1 ] );
  9419. this.c.copy( points[ i2 ] );
  9420. return this;
  9421. },
  9422. clone: function () {
  9423. return new this.constructor().copy( this );
  9424. },
  9425. copy: function ( triangle ) {
  9426. this.a.copy( triangle.a );
  9427. this.b.copy( triangle.b );
  9428. this.c.copy( triangle.c );
  9429. return this;
  9430. },
  9431. area: function () {
  9432. var v0 = new Vector3();
  9433. var v1 = new Vector3();
  9434. return function area() {
  9435. v0.subVectors( this.c, this.b );
  9436. v1.subVectors( this.a, this.b );
  9437. return v0.cross( v1 ).length() * 0.5;
  9438. };
  9439. }(),
  9440. midpoint: function ( optionalTarget ) {
  9441. var result = optionalTarget || new Vector3();
  9442. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9443. },
  9444. normal: function ( optionalTarget ) {
  9445. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  9446. },
  9447. plane: function ( optionalTarget ) {
  9448. var result = optionalTarget || new Plane();
  9449. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  9450. },
  9451. barycoordFromPoint: function ( point, optionalTarget ) {
  9452. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  9453. },
  9454. containsPoint: function ( point ) {
  9455. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9456. },
  9457. closestPointToPoint: function () {
  9458. var plane = new Plane();
  9459. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  9460. var projectedPoint = new Vector3();
  9461. var closestPoint = new Vector3();
  9462. return function closestPointToPoint( point, optionalTarget ) {
  9463. var result = optionalTarget || new Vector3();
  9464. var minDistance = Infinity;
  9465. // project the point onto the plane of the triangle
  9466. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  9467. plane.projectPoint( point, projectedPoint );
  9468. // check if the projection lies within the triangle
  9469. if( this.containsPoint( projectedPoint ) === true ) {
  9470. // if so, this is the closest point
  9471. result.copy( projectedPoint );
  9472. } else {
  9473. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  9474. edgeList[ 0 ].set( this.a, this.b );
  9475. edgeList[ 1 ].set( this.b, this.c );
  9476. edgeList[ 2 ].set( this.c, this.a );
  9477. for( var i = 0; i < edgeList.length; i ++ ) {
  9478. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  9479. var distance = projectedPoint.distanceToSquared( closestPoint );
  9480. if( distance < minDistance ) {
  9481. minDistance = distance;
  9482. result.copy( closestPoint );
  9483. }
  9484. }
  9485. }
  9486. return result;
  9487. };
  9488. }(),
  9489. equals: function ( triangle ) {
  9490. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9491. }
  9492. } );
  9493. /**
  9494. * @author mrdoob / http://mrdoob.com/
  9495. * @author alteredq / http://alteredqualia.com/
  9496. * @author mikael emtinger / http://gomo.se/
  9497. * @author jonobr1 / http://jonobr1.com/
  9498. */
  9499. function Mesh( geometry, material ) {
  9500. Object3D.call( this );
  9501. this.type = 'Mesh';
  9502. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  9503. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9504. this.drawMode = TrianglesDrawMode;
  9505. this.updateMorphTargets();
  9506. }
  9507. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9508. constructor: Mesh,
  9509. isMesh: true,
  9510. setDrawMode: function ( value ) {
  9511. this.drawMode = value;
  9512. },
  9513. copy: function ( source ) {
  9514. Object3D.prototype.copy.call( this, source );
  9515. this.drawMode = source.drawMode;
  9516. return this;
  9517. },
  9518. updateMorphTargets: function () {
  9519. var geometry = this.geometry;
  9520. var m, ml, name;
  9521. if ( geometry.isBufferGeometry ) {
  9522. var morphAttributes = geometry.morphAttributes;
  9523. var keys = Object.keys( morphAttributes );
  9524. if ( keys.length > 0 ) {
  9525. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  9526. if ( morphAttribute !== undefined ) {
  9527. this.morphTargetInfluences = [];
  9528. this.morphTargetDictionary = {};
  9529. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9530. name = morphAttribute[ m ].name || String( m );
  9531. this.morphTargetInfluences.push( 0 );
  9532. this.morphTargetDictionary[ name ] = m;
  9533. }
  9534. }
  9535. }
  9536. } else {
  9537. var morphTargets = geometry.morphTargets;
  9538. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  9539. this.morphTargetInfluences = [];
  9540. this.morphTargetDictionary = {};
  9541. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  9542. name = morphTargets[ m ].name || String( m );
  9543. this.morphTargetInfluences.push( 0 );
  9544. this.morphTargetDictionary[ name ] = m;
  9545. }
  9546. }
  9547. }
  9548. },
  9549. raycast: ( function () {
  9550. var inverseMatrix = new Matrix4();
  9551. var ray = new Ray();
  9552. var sphere = new Sphere();
  9553. var vA = new Vector3();
  9554. var vB = new Vector3();
  9555. var vC = new Vector3();
  9556. var tempA = new Vector3();
  9557. var tempB = new Vector3();
  9558. var tempC = new Vector3();
  9559. var uvA = new Vector2();
  9560. var uvB = new Vector2();
  9561. var uvC = new Vector2();
  9562. var barycoord = new Vector3();
  9563. var intersectionPoint = new Vector3();
  9564. var intersectionPointWorld = new Vector3();
  9565. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  9566. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  9567. uv1.multiplyScalar( barycoord.x );
  9568. uv2.multiplyScalar( barycoord.y );
  9569. uv3.multiplyScalar( barycoord.z );
  9570. uv1.add( uv2 ).add( uv3 );
  9571. return uv1.clone();
  9572. }
  9573. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  9574. var intersect;
  9575. if ( material.side === BackSide ) {
  9576. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  9577. } else {
  9578. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  9579. }
  9580. if ( intersect === null ) return null;
  9581. intersectionPointWorld.copy( point );
  9582. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  9583. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  9584. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  9585. return {
  9586. distance: distance,
  9587. point: intersectionPointWorld.clone(),
  9588. object: object
  9589. };
  9590. }
  9591. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  9592. vA.fromBufferAttribute( position, a );
  9593. vB.fromBufferAttribute( position, b );
  9594. vC.fromBufferAttribute( position, c );
  9595. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  9596. if ( intersection ) {
  9597. if ( uv ) {
  9598. uvA.fromBufferAttribute( uv, a );
  9599. uvB.fromBufferAttribute( uv, b );
  9600. uvC.fromBufferAttribute( uv, c );
  9601. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  9602. }
  9603. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  9604. intersection.faceIndex = a;
  9605. }
  9606. return intersection;
  9607. }
  9608. return function raycast( raycaster, intersects ) {
  9609. var geometry = this.geometry;
  9610. var material = this.material;
  9611. var matrixWorld = this.matrixWorld;
  9612. if ( material === undefined ) return;
  9613. // Checking boundingSphere distance to ray
  9614. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9615. sphere.copy( geometry.boundingSphere );
  9616. sphere.applyMatrix4( matrixWorld );
  9617. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9618. //
  9619. inverseMatrix.getInverse( matrixWorld );
  9620. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9621. // Check boundingBox before continuing
  9622. if ( geometry.boundingBox !== null ) {
  9623. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  9624. }
  9625. var intersection;
  9626. if ( geometry.isBufferGeometry ) {
  9627. var a, b, c;
  9628. var index = geometry.index;
  9629. var position = geometry.attributes.position;
  9630. var uv = geometry.attributes.uv;
  9631. var i, l;
  9632. if ( index !== null ) {
  9633. // indexed buffer geometry
  9634. for ( i = 0, l = index.count; i < l; i += 3 ) {
  9635. a = index.getX( i );
  9636. b = index.getX( i + 1 );
  9637. c = index.getX( i + 2 );
  9638. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9639. if ( intersection ) {
  9640. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  9641. intersects.push( intersection );
  9642. }
  9643. }
  9644. } else {
  9645. // non-indexed buffer geometry
  9646. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9647. a = i;
  9648. b = i + 1;
  9649. c = i + 2;
  9650. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9651. if ( intersection ) {
  9652. intersection.index = a; // triangle number in positions buffer semantics
  9653. intersects.push( intersection );
  9654. }
  9655. }
  9656. }
  9657. } else if ( geometry.isGeometry ) {
  9658. var fvA, fvB, fvC;
  9659. var isMultiMaterial = Array.isArray( material );
  9660. var vertices = geometry.vertices;
  9661. var faces = geometry.faces;
  9662. var uvs;
  9663. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9664. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9665. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9666. var face = faces[ f ];
  9667. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9668. if ( faceMaterial === undefined ) continue;
  9669. fvA = vertices[ face.a ];
  9670. fvB = vertices[ face.b ];
  9671. fvC = vertices[ face.c ];
  9672. if ( faceMaterial.morphTargets === true ) {
  9673. var morphTargets = geometry.morphTargets;
  9674. var morphInfluences = this.morphTargetInfluences;
  9675. vA.set( 0, 0, 0 );
  9676. vB.set( 0, 0, 0 );
  9677. vC.set( 0, 0, 0 );
  9678. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9679. var influence = morphInfluences[ t ];
  9680. if ( influence === 0 ) continue;
  9681. var targets = morphTargets[ t ].vertices;
  9682. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9683. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9684. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9685. }
  9686. vA.add( fvA );
  9687. vB.add( fvB );
  9688. vC.add( fvC );
  9689. fvA = vA;
  9690. fvB = vB;
  9691. fvC = vC;
  9692. }
  9693. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9694. if ( intersection ) {
  9695. if ( uvs && uvs[ f ] ) {
  9696. var uvs_f = uvs[ f ];
  9697. uvA.copy( uvs_f[ 0 ] );
  9698. uvB.copy( uvs_f[ 1 ] );
  9699. uvC.copy( uvs_f[ 2 ] );
  9700. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9701. }
  9702. intersection.face = face;
  9703. intersection.faceIndex = f;
  9704. intersects.push( intersection );
  9705. }
  9706. }
  9707. }
  9708. };
  9709. }() ),
  9710. clone: function () {
  9711. return new this.constructor( this.geometry, this.material ).copy( this );
  9712. }
  9713. } );
  9714. /**
  9715. * @author mrdoob / http://mrdoob.com/
  9716. */
  9717. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  9718. var clearColor = new Color( 0x000000 );
  9719. var clearAlpha = 0;
  9720. var planeCamera, planeMesh;
  9721. var boxCamera, boxMesh;
  9722. function render( scene, camera, forceClear ) {
  9723. var background = scene.background;
  9724. if ( background === null ) {
  9725. setClear( clearColor, clearAlpha );
  9726. } else if ( background && background.isColor ) {
  9727. setClear( background, 1 );
  9728. forceClear = true;
  9729. }
  9730. if ( renderer.autoClear || forceClear ) {
  9731. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9732. }
  9733. if ( background && background.isCubeTexture ) {
  9734. if ( boxCamera === undefined ) {
  9735. boxCamera = new PerspectiveCamera();
  9736. boxMesh = new Mesh(
  9737. new BoxBufferGeometry( 5, 5, 5 ),
  9738. new ShaderMaterial( {
  9739. uniforms: ShaderLib.cube.uniforms,
  9740. vertexShader: ShaderLib.cube.vertexShader,
  9741. fragmentShader: ShaderLib.cube.fragmentShader,
  9742. side: BackSide,
  9743. depthTest: false,
  9744. depthWrite: false,
  9745. fog: false
  9746. } )
  9747. );
  9748. }
  9749. boxCamera.projectionMatrix.copy( camera.projectionMatrix );
  9750. boxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  9751. boxCamera.matrixWorldInverse.getInverse( boxCamera.matrixWorld );
  9752. boxMesh.material.uniforms[ "tCube" ].value = background;
  9753. boxMesh.modelViewMatrix.multiplyMatrices( boxCamera.matrixWorldInverse, boxMesh.matrixWorld );
  9754. objects.update( boxMesh );
  9755. renderer.renderBufferDirect( boxCamera, null, boxMesh.geometry, boxMesh.material, boxMesh, null );
  9756. } else if ( background && background.isTexture ) {
  9757. if ( planeCamera === undefined ) {
  9758. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9759. planeMesh = new Mesh(
  9760. new PlaneBufferGeometry( 2, 2 ),
  9761. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  9762. );
  9763. }
  9764. planeMesh.material.map = background;
  9765. objects.update( planeMesh );
  9766. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  9767. }
  9768. }
  9769. function setClear( color, alpha ) {
  9770. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9771. }
  9772. return {
  9773. getClearColor: function () {
  9774. return clearColor;
  9775. },
  9776. setClearColor: function ( color, alpha ) {
  9777. clearColor.set( color );
  9778. clearAlpha = alpha !== undefined ? alpha : 1;
  9779. setClear( clearColor, clearAlpha );
  9780. },
  9781. getClearAlpha: function () {
  9782. return clearAlpha;
  9783. },
  9784. setClearAlpha: function ( alpha ) {
  9785. clearAlpha = alpha;
  9786. setClear( clearColor, clearAlpha );
  9787. },
  9788. render: render
  9789. };
  9790. }
  9791. /**
  9792. * @author mrdoob / http://mrdoob.com/
  9793. */
  9794. function painterSortStable( a, b ) {
  9795. if ( a.renderOrder !== b.renderOrder ) {
  9796. return a.renderOrder - b.renderOrder;
  9797. } else if ( a.program && b.program && a.program !== b.program ) {
  9798. return a.program.id - b.program.id;
  9799. } else if ( a.material.id !== b.material.id ) {
  9800. return a.material.id - b.material.id;
  9801. } else if ( a.z !== b.z ) {
  9802. return a.z - b.z;
  9803. } else {
  9804. return a.id - b.id;
  9805. }
  9806. }
  9807. function reversePainterSortStable( a, b ) {
  9808. if ( a.renderOrder !== b.renderOrder ) {
  9809. return a.renderOrder - b.renderOrder;
  9810. } if ( a.z !== b.z ) {
  9811. return b.z - a.z;
  9812. } else {
  9813. return a.id - b.id;
  9814. }
  9815. }
  9816. function WebGLRenderList() {
  9817. var opaque = [];
  9818. var opaqueLastIndex = - 1;
  9819. var transparent = [];
  9820. var transparentLastIndex = - 1;
  9821. function init() {
  9822. opaqueLastIndex = - 1;
  9823. transparentLastIndex = - 1;
  9824. }
  9825. function push( object, geometry, material, z, group ) {
  9826. var array, index;
  9827. // allocate the next position in the appropriate array
  9828. if ( material.transparent ) {
  9829. array = transparent;
  9830. index = ++ transparentLastIndex;
  9831. } else {
  9832. array = opaque;
  9833. index = ++ opaqueLastIndex;
  9834. }
  9835. // recycle existing render item or grow the array
  9836. var renderItem = array[ index ];
  9837. if ( renderItem ) {
  9838. renderItem.id = object.id;
  9839. renderItem.object = object;
  9840. renderItem.geometry = geometry;
  9841. renderItem.material = material;
  9842. renderItem.program = material.program;
  9843. renderItem.renderOrder = object.renderOrder;
  9844. renderItem.z = z;
  9845. renderItem.group = group;
  9846. } else {
  9847. renderItem = {
  9848. id: object.id,
  9849. object: object,
  9850. geometry: geometry,
  9851. material: material,
  9852. program: material.program,
  9853. renderOrder: object.renderOrder,
  9854. z: z,
  9855. group: group
  9856. };
  9857. // assert( index === array.length );
  9858. array.push( renderItem );
  9859. }
  9860. }
  9861. function finish() {
  9862. opaque.length = opaqueLastIndex + 1;
  9863. transparent.length = transparentLastIndex + 1;
  9864. }
  9865. function sort() {
  9866. opaque.sort( painterSortStable );
  9867. transparent.sort( reversePainterSortStable );
  9868. }
  9869. return {
  9870. opaque: opaque,
  9871. transparent: transparent,
  9872. init: init,
  9873. push: push,
  9874. finish: finish,
  9875. sort: sort
  9876. };
  9877. }
  9878. function WebGLRenderLists() {
  9879. var lists = {};
  9880. function get( scene, camera ) {
  9881. var hash = scene.id + ',' + camera.id;
  9882. var list = lists[ hash ];
  9883. if ( list === undefined ) {
  9884. // console.log( 'THREE.WebGLRenderLists:', hash );
  9885. list = new WebGLRenderList();
  9886. lists[ hash ] = list;
  9887. }
  9888. return list;
  9889. }
  9890. function dispose() {
  9891. lists = {};
  9892. }
  9893. return {
  9894. get: get,
  9895. dispose: dispose
  9896. };
  9897. }
  9898. /**
  9899. * @author mrdoob / http://mrdoob.com/
  9900. */
  9901. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9902. var mode;
  9903. function setMode( value ) {
  9904. mode = value;
  9905. }
  9906. var type, bytesPerElement;
  9907. function setIndex( value ) {
  9908. type = value.type;
  9909. bytesPerElement = value.bytesPerElement;
  9910. }
  9911. function render( start, count ) {
  9912. gl.drawElements( mode, count, type, start * bytesPerElement );
  9913. infoRender.calls ++;
  9914. infoRender.vertices += count;
  9915. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9916. else if ( mode === gl.POINTS ) infoRender.points += count;
  9917. }
  9918. function renderInstances( geometry, start, count ) {
  9919. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9920. if ( extension === null ) {
  9921. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9922. return;
  9923. }
  9924. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  9925. infoRender.calls ++;
  9926. infoRender.vertices += count * geometry.maxInstancedCount;
  9927. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9928. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  9929. }
  9930. //
  9931. this.setMode = setMode;
  9932. this.setIndex = setIndex;
  9933. this.render = render;
  9934. this.renderInstances = renderInstances;
  9935. }
  9936. /**
  9937. * @author mrdoob / http://mrdoob.com/
  9938. */
  9939. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9940. var mode;
  9941. function setMode( value ) {
  9942. mode = value;
  9943. }
  9944. function render( start, count ) {
  9945. gl.drawArrays( mode, start, count );
  9946. infoRender.calls ++;
  9947. infoRender.vertices += count;
  9948. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9949. else if ( mode === gl.POINTS ) infoRender.points += count;
  9950. }
  9951. function renderInstances( geometry, start, count ) {
  9952. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9953. if ( extension === null ) {
  9954. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9955. return;
  9956. }
  9957. var position = geometry.attributes.position;
  9958. if ( position.isInterleavedBufferAttribute ) {
  9959. count = position.data.count;
  9960. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9961. } else {
  9962. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  9963. }
  9964. infoRender.calls ++;
  9965. infoRender.vertices += count * geometry.maxInstancedCount;
  9966. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9967. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  9968. }
  9969. //
  9970. this.setMode = setMode;
  9971. this.render = render;
  9972. this.renderInstances = renderInstances;
  9973. }
  9974. /**
  9975. * @author mrdoob / http://mrdoob.com/
  9976. */
  9977. function WebGLGeometries( gl, attributes, infoMemory ) {
  9978. var geometries = {};
  9979. var wireframeAttributes = {};
  9980. function onGeometryDispose( event ) {
  9981. var geometry = event.target;
  9982. var buffergeometry = geometries[ geometry.id ];
  9983. if ( buffergeometry.index !== null ) {
  9984. attributes.remove( buffergeometry.index );
  9985. }
  9986. for ( var name in buffergeometry.attributes ) {
  9987. attributes.remove( buffergeometry.attributes[ name ] );
  9988. }
  9989. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9990. delete geometries[ geometry.id ];
  9991. // TODO Remove duplicate code
  9992. var attribute = wireframeAttributes[ geometry.id ];
  9993. if ( attribute ) {
  9994. attributes.remove( attribute );
  9995. delete wireframeAttributes[ geometry.id ];
  9996. }
  9997. attribute = wireframeAttributes[ buffergeometry.id ];
  9998. if ( attribute ) {
  9999. attributes.remove( attribute );
  10000. delete wireframeAttributes[ buffergeometry.id ];
  10001. }
  10002. //
  10003. infoMemory.geometries --;
  10004. }
  10005. function get( object, geometry ) {
  10006. var buffergeometry = geometries[ geometry.id ];
  10007. if ( buffergeometry ) return buffergeometry;
  10008. geometry.addEventListener( 'dispose', onGeometryDispose );
  10009. if ( geometry.isBufferGeometry ) {
  10010. buffergeometry = geometry;
  10011. } else if ( geometry.isGeometry ) {
  10012. if ( geometry._bufferGeometry === undefined ) {
  10013. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10014. }
  10015. buffergeometry = geometry._bufferGeometry;
  10016. }
  10017. geometries[ geometry.id ] = buffergeometry;
  10018. infoMemory.geometries ++;
  10019. return buffergeometry;
  10020. }
  10021. function update( geometry ) {
  10022. var index = geometry.index;
  10023. var geometryAttributes = geometry.attributes;
  10024. if ( index !== null ) {
  10025. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  10026. }
  10027. for ( var name in geometryAttributes ) {
  10028. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10029. }
  10030. // morph targets
  10031. var morphAttributes = geometry.morphAttributes;
  10032. for ( var name in morphAttributes ) {
  10033. var array = morphAttributes[ name ];
  10034. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10035. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10036. }
  10037. }
  10038. }
  10039. function getWireframeAttribute( geometry ) {
  10040. var attribute = wireframeAttributes[ geometry.id ];
  10041. if ( attribute ) return attribute;
  10042. var indices = [];
  10043. var geometryIndex = geometry.index;
  10044. var geometryAttributes = geometry.attributes;
  10045. // console.time( 'wireframe' );
  10046. if ( geometryIndex !== null ) {
  10047. var array = geometryIndex.array;
  10048. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10049. var a = array[ i + 0 ];
  10050. var b = array[ i + 1 ];
  10051. var c = array[ i + 2 ];
  10052. indices.push( a, b, b, c, c, a );
  10053. }
  10054. } else {
  10055. var array = geometryAttributes.position.array;
  10056. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10057. var a = i + 0;
  10058. var b = i + 1;
  10059. var c = i + 2;
  10060. indices.push( a, b, b, c, c, a );
  10061. }
  10062. }
  10063. // console.timeEnd( 'wireframe' );
  10064. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10065. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10066. wireframeAttributes[ geometry.id ] = attribute;
  10067. return attribute;
  10068. }
  10069. return {
  10070. get: get,
  10071. update: update,
  10072. getWireframeAttribute: getWireframeAttribute
  10073. };
  10074. }
  10075. /**
  10076. * @author mrdoob / http://mrdoob.com/
  10077. */
  10078. function UniformsCache() {
  10079. var lights = {};
  10080. return {
  10081. get: function ( light ) {
  10082. if ( lights[ light.id ] !== undefined ) {
  10083. return lights[ light.id ];
  10084. }
  10085. var uniforms;
  10086. switch ( light.type ) {
  10087. case 'DirectionalLight':
  10088. uniforms = {
  10089. direction: new Vector3(),
  10090. color: new Color(),
  10091. shadow: false,
  10092. shadowBias: 0,
  10093. shadowRadius: 1,
  10094. shadowMapSize: new Vector2()
  10095. };
  10096. break;
  10097. case 'SpotLight':
  10098. uniforms = {
  10099. position: new Vector3(),
  10100. direction: new Vector3(),
  10101. color: new Color(),
  10102. distance: 0,
  10103. coneCos: 0,
  10104. penumbraCos: 0,
  10105. decay: 0,
  10106. shadow: false,
  10107. shadowBias: 0,
  10108. shadowRadius: 1,
  10109. shadowMapSize: new Vector2()
  10110. };
  10111. break;
  10112. case 'PointLight':
  10113. uniforms = {
  10114. position: new Vector3(),
  10115. color: new Color(),
  10116. distance: 0,
  10117. decay: 0,
  10118. shadow: false,
  10119. shadowBias: 0,
  10120. shadowRadius: 1,
  10121. shadowMapSize: new Vector2(),
  10122. shadowCameraNear: 1,
  10123. shadowCameraFar: 1000
  10124. };
  10125. break;
  10126. case 'HemisphereLight':
  10127. uniforms = {
  10128. direction: new Vector3(),
  10129. skyColor: new Color(),
  10130. groundColor: new Color()
  10131. };
  10132. break;
  10133. case 'RectAreaLight':
  10134. uniforms = {
  10135. color: new Color(),
  10136. position: new Vector3(),
  10137. halfWidth: new Vector3(),
  10138. halfHeight: new Vector3()
  10139. // TODO (abelnation): set RectAreaLight shadow uniforms
  10140. };
  10141. break;
  10142. }
  10143. lights[ light.id ] = uniforms;
  10144. return uniforms;
  10145. }
  10146. };
  10147. }
  10148. function WebGLLights() {
  10149. var cache = new UniformsCache();
  10150. var state = {
  10151. hash: '',
  10152. ambient: [ 0, 0, 0 ],
  10153. directional: [],
  10154. directionalShadowMap: [],
  10155. directionalShadowMatrix: [],
  10156. spot: [],
  10157. spotShadowMap: [],
  10158. spotShadowMatrix: [],
  10159. rectArea: [],
  10160. point: [],
  10161. pointShadowMap: [],
  10162. pointShadowMatrix: [],
  10163. hemi: []
  10164. };
  10165. var vector3 = new Vector3();
  10166. var matrix4 = new Matrix4();
  10167. var matrix42 = new Matrix4();
  10168. function setup( lights, shadows, camera ) {
  10169. var r = 0, g = 0, b = 0;
  10170. var directionalLength = 0;
  10171. var pointLength = 0;
  10172. var spotLength = 0;
  10173. var rectAreaLength = 0;
  10174. var hemiLength = 0;
  10175. var viewMatrix = camera.matrixWorldInverse;
  10176. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  10177. var light = lights[ i ];
  10178. var color = light.color;
  10179. var intensity = light.intensity;
  10180. var distance = light.distance;
  10181. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  10182. if ( light.isAmbientLight ) {
  10183. r += color.r * intensity;
  10184. g += color.g * intensity;
  10185. b += color.b * intensity;
  10186. } else if ( light.isDirectionalLight ) {
  10187. var uniforms = cache.get( light );
  10188. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10189. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10190. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10191. uniforms.direction.sub( vector3 );
  10192. uniforms.direction.transformDirection( viewMatrix );
  10193. uniforms.shadow = light.castShadow;
  10194. if ( light.castShadow ) {
  10195. var shadow = light.shadow;
  10196. uniforms.shadowBias = shadow.bias;
  10197. uniforms.shadowRadius = shadow.radius;
  10198. uniforms.shadowMapSize = shadow.mapSize;
  10199. }
  10200. state.directionalShadowMap[ directionalLength ] = shadowMap;
  10201. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  10202. state.directional[ directionalLength ] = uniforms;
  10203. directionalLength ++;
  10204. } else if ( light.isSpotLight ) {
  10205. var uniforms = cache.get( light );
  10206. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10207. uniforms.position.applyMatrix4( viewMatrix );
  10208. uniforms.color.copy( color ).multiplyScalar( intensity );
  10209. uniforms.distance = distance;
  10210. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10211. vector3.setFromMatrixPosition( light.target.matrixWorld );
  10212. uniforms.direction.sub( vector3 );
  10213. uniforms.direction.transformDirection( viewMatrix );
  10214. uniforms.coneCos = Math.cos( light.angle );
  10215. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  10216. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10217. uniforms.shadow = light.castShadow;
  10218. if ( light.castShadow ) {
  10219. var shadow = light.shadow;
  10220. uniforms.shadowBias = shadow.bias;
  10221. uniforms.shadowRadius = shadow.radius;
  10222. uniforms.shadowMapSize = shadow.mapSize;
  10223. }
  10224. state.spotShadowMap[ spotLength ] = shadowMap;
  10225. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  10226. state.spot[ spotLength ] = uniforms;
  10227. spotLength ++;
  10228. } else if ( light.isRectAreaLight ) {
  10229. var uniforms = cache.get( light );
  10230. // (a) intensity controls irradiance of entire light
  10231. uniforms.color
  10232. .copy( color )
  10233. .multiplyScalar( intensity / ( light.width * light.height ) );
  10234. // (b) intensity controls the radiance per light area
  10235. // uniforms.color.copy( color ).multiplyScalar( intensity );
  10236. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10237. uniforms.position.applyMatrix4( viewMatrix );
  10238. // extract local rotation of light to derive width/height half vectors
  10239. matrix42.identity();
  10240. matrix4.copy( light.matrixWorld );
  10241. matrix4.premultiply( viewMatrix );
  10242. matrix42.extractRotation( matrix4 );
  10243. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  10244. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  10245. uniforms.halfWidth.applyMatrix4( matrix42 );
  10246. uniforms.halfHeight.applyMatrix4( matrix42 );
  10247. // TODO (abelnation): RectAreaLight distance?
  10248. // uniforms.distance = distance;
  10249. state.rectArea[ rectAreaLength ] = uniforms;
  10250. rectAreaLength ++;
  10251. } else if ( light.isPointLight ) {
  10252. var uniforms = cache.get( light );
  10253. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10254. uniforms.position.applyMatrix4( viewMatrix );
  10255. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10256. uniforms.distance = light.distance;
  10257. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  10258. uniforms.shadow = light.castShadow;
  10259. if ( light.castShadow ) {
  10260. var shadow = light.shadow;
  10261. uniforms.shadowBias = shadow.bias;
  10262. uniforms.shadowRadius = shadow.radius;
  10263. uniforms.shadowMapSize = shadow.mapSize;
  10264. uniforms.shadowCameraNear = shadow.camera.near;
  10265. uniforms.shadowCameraFar = shadow.camera.far;
  10266. }
  10267. state.pointShadowMap[ pointLength ] = shadowMap;
  10268. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  10269. state.point[ pointLength ] = uniforms;
  10270. pointLength ++;
  10271. } else if ( light.isHemisphereLight ) {
  10272. var uniforms = cache.get( light );
  10273. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  10274. uniforms.direction.transformDirection( viewMatrix );
  10275. uniforms.direction.normalize();
  10276. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  10277. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  10278. state.hemi[ hemiLength ] = uniforms;
  10279. hemiLength ++;
  10280. }
  10281. }
  10282. state.ambient[ 0 ] = r;
  10283. state.ambient[ 1 ] = g;
  10284. state.ambient[ 2 ] = b;
  10285. state.directional.length = directionalLength;
  10286. state.spot.length = spotLength;
  10287. state.rectArea.length = rectAreaLength;
  10288. state.point.length = pointLength;
  10289. state.hemi.length = hemiLength;
  10290. // TODO (sam-g-steel) why aren't we using join
  10291. state.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  10292. }
  10293. return {
  10294. setup: setup,
  10295. state: state
  10296. }
  10297. }
  10298. /**
  10299. * @author mrdoob / http://mrdoob.com/
  10300. */
  10301. function WebGLObjects( gl, geometries, infoRender ) {
  10302. var updateList = {};
  10303. function update( object ) {
  10304. var frame = infoRender.frame;
  10305. var geometry = object.geometry;
  10306. var buffergeometry = geometries.get( object, geometry );
  10307. // Update once per frame
  10308. if ( updateList[ buffergeometry.id ] !== frame ) {
  10309. if ( geometry.isGeometry ) {
  10310. buffergeometry.updateFromObject( object );
  10311. }
  10312. geometries.update( buffergeometry );
  10313. updateList[ buffergeometry.id ] = frame;
  10314. }
  10315. return buffergeometry;
  10316. }
  10317. function clear() {
  10318. updateList = {};
  10319. }
  10320. return {
  10321. update: update,
  10322. clear: clear
  10323. };
  10324. }
  10325. /**
  10326. * @author mrdoob / http://mrdoob.com/
  10327. */
  10328. function addLineNumbers( string ) {
  10329. var lines = string.split( '\n' );
  10330. for ( var i = 0; i < lines.length; i ++ ) {
  10331. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10332. }
  10333. return lines.join( '\n' );
  10334. }
  10335. function WebGLShader( gl, type, string ) {
  10336. var shader = gl.createShader( type );
  10337. gl.shaderSource( shader, string );
  10338. gl.compileShader( shader );
  10339. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10340. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10341. }
  10342. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10343. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10344. }
  10345. // --enable-privileged-webgl-extension
  10346. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10347. return shader;
  10348. }
  10349. /**
  10350. * @author mrdoob / http://mrdoob.com/
  10351. */
  10352. var programIdCount = 0;
  10353. function getEncodingComponents( encoding ) {
  10354. switch ( encoding ) {
  10355. case LinearEncoding:
  10356. return [ 'Linear','( value )' ];
  10357. case sRGBEncoding:
  10358. return [ 'sRGB','( value )' ];
  10359. case RGBEEncoding:
  10360. return [ 'RGBE','( value )' ];
  10361. case RGBM7Encoding:
  10362. return [ 'RGBM','( value, 7.0 )' ];
  10363. case RGBM16Encoding:
  10364. return [ 'RGBM','( value, 16.0 )' ];
  10365. case RGBDEncoding:
  10366. return [ 'RGBD','( value, 256.0 )' ];
  10367. case GammaEncoding:
  10368. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10369. default:
  10370. throw new Error( 'unsupported encoding: ' + encoding );
  10371. }
  10372. }
  10373. function getTexelDecodingFunction( functionName, encoding ) {
  10374. var components = getEncodingComponents( encoding );
  10375. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10376. }
  10377. function getTexelEncodingFunction( functionName, encoding ) {
  10378. var components = getEncodingComponents( encoding );
  10379. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10380. }
  10381. function getToneMappingFunction( functionName, toneMapping ) {
  10382. var toneMappingName;
  10383. switch ( toneMapping ) {
  10384. case LinearToneMapping:
  10385. toneMappingName = "Linear";
  10386. break;
  10387. case ReinhardToneMapping:
  10388. toneMappingName = "Reinhard";
  10389. break;
  10390. case Uncharted2ToneMapping:
  10391. toneMappingName = "Uncharted2";
  10392. break;
  10393. case CineonToneMapping:
  10394. toneMappingName = "OptimizedCineon";
  10395. break;
  10396. default:
  10397. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10398. }
  10399. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10400. }
  10401. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10402. extensions = extensions || {};
  10403. var chunks = [
  10404. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10405. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10406. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10407. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10408. ];
  10409. return chunks.filter( filterEmptyLine ).join( '\n' );
  10410. }
  10411. function generateDefines( defines ) {
  10412. var chunks = [];
  10413. for ( var name in defines ) {
  10414. var value = defines[ name ];
  10415. if ( value === false ) continue;
  10416. chunks.push( '#define ' + name + ' ' + value );
  10417. }
  10418. return chunks.join( '\n' );
  10419. }
  10420. function fetchAttributeLocations( gl, program, identifiers ) {
  10421. var attributes = {};
  10422. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10423. for ( var i = 0; i < n; i ++ ) {
  10424. var info = gl.getActiveAttrib( program, i );
  10425. var name = info.name;
  10426. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10427. attributes[ name ] = gl.getAttribLocation( program, name );
  10428. }
  10429. return attributes;
  10430. }
  10431. function filterEmptyLine( string ) {
  10432. return string !== '';
  10433. }
  10434. function replaceLightNums( string, parameters ) {
  10435. return string
  10436. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10437. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10438. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10439. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10440. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10441. }
  10442. function parseIncludes( string ) {
  10443. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10444. function replace( match, include ) {
  10445. var replace = ShaderChunk[ include ];
  10446. if ( replace === undefined ) {
  10447. throw new Error( 'Can not resolve #include <' + include + '>' );
  10448. }
  10449. return parseIncludes( replace );
  10450. }
  10451. return string.replace( pattern, replace );
  10452. }
  10453. function unrollLoops( string ) {
  10454. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10455. function replace( match, start, end, snippet ) {
  10456. var unroll = '';
  10457. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10458. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10459. }
  10460. return unroll;
  10461. }
  10462. return string.replace( pattern, replace );
  10463. }
  10464. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  10465. var gl = renderer.context;
  10466. var defines = material.defines;
  10467. var vertexShader = shader.vertexShader;
  10468. var fragmentShader = shader.fragmentShader;
  10469. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10470. if ( parameters.shadowMapType === PCFShadowMap ) {
  10471. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10472. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10473. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10474. }
  10475. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10476. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10477. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10478. if ( parameters.envMap ) {
  10479. switch ( material.envMap.mapping ) {
  10480. case CubeReflectionMapping:
  10481. case CubeRefractionMapping:
  10482. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10483. break;
  10484. case CubeUVReflectionMapping:
  10485. case CubeUVRefractionMapping:
  10486. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10487. break;
  10488. case EquirectangularReflectionMapping:
  10489. case EquirectangularRefractionMapping:
  10490. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10491. break;
  10492. case SphericalReflectionMapping:
  10493. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10494. break;
  10495. }
  10496. switch ( material.envMap.mapping ) {
  10497. case CubeRefractionMapping:
  10498. case EquirectangularRefractionMapping:
  10499. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10500. break;
  10501. }
  10502. switch ( material.combine ) {
  10503. case MultiplyOperation:
  10504. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10505. break;
  10506. case MixOperation:
  10507. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10508. break;
  10509. case AddOperation:
  10510. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10511. break;
  10512. }
  10513. }
  10514. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10515. // console.log( 'building new program ' );
  10516. //
  10517. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  10518. var customDefines = generateDefines( defines );
  10519. //
  10520. var program = gl.createProgram();
  10521. var prefixVertex, prefixFragment;
  10522. if ( material.isRawShaderMaterial ) {
  10523. prefixVertex = [
  10524. customDefines,
  10525. '\n'
  10526. ].filter( filterEmptyLine ).join( '\n' );
  10527. prefixFragment = [
  10528. customExtensions,
  10529. customDefines,
  10530. '\n'
  10531. ].filter( filterEmptyLine ).join( '\n' );
  10532. } else {
  10533. prefixVertex = [
  10534. 'precision ' + parameters.precision + ' float;',
  10535. 'precision ' + parameters.precision + ' int;',
  10536. '#define SHADER_NAME ' + shader.name,
  10537. customDefines,
  10538. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10539. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10540. '#define MAX_BONES ' + parameters.maxBones,
  10541. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10542. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10543. parameters.map ? '#define USE_MAP' : '',
  10544. parameters.envMap ? '#define USE_ENVMAP' : '',
  10545. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10546. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10547. parameters.aoMap ? '#define USE_AOMAP' : '',
  10548. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10549. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10550. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10551. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10552. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10553. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10554. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10555. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10556. parameters.vertexColors ? '#define USE_COLOR' : '',
  10557. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10558. parameters.skinning ? '#define USE_SKINNING' : '',
  10559. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10560. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10561. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10562. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10563. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10564. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10565. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10566. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10567. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10568. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10569. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10570. 'uniform mat4 modelMatrix;',
  10571. 'uniform mat4 modelViewMatrix;',
  10572. 'uniform mat4 projectionMatrix;',
  10573. 'uniform mat4 viewMatrix;',
  10574. 'uniform mat3 normalMatrix;',
  10575. 'uniform vec3 cameraPosition;',
  10576. 'attribute vec3 position;',
  10577. 'attribute vec3 normal;',
  10578. 'attribute vec2 uv;',
  10579. '#ifdef USE_COLOR',
  10580. ' attribute vec3 color;',
  10581. '#endif',
  10582. '#ifdef USE_MORPHTARGETS',
  10583. ' attribute vec3 morphTarget0;',
  10584. ' attribute vec3 morphTarget1;',
  10585. ' attribute vec3 morphTarget2;',
  10586. ' attribute vec3 morphTarget3;',
  10587. ' #ifdef USE_MORPHNORMALS',
  10588. ' attribute vec3 morphNormal0;',
  10589. ' attribute vec3 morphNormal1;',
  10590. ' attribute vec3 morphNormal2;',
  10591. ' attribute vec3 morphNormal3;',
  10592. ' #else',
  10593. ' attribute vec3 morphTarget4;',
  10594. ' attribute vec3 morphTarget5;',
  10595. ' attribute vec3 morphTarget6;',
  10596. ' attribute vec3 morphTarget7;',
  10597. ' #endif',
  10598. '#endif',
  10599. '#ifdef USE_SKINNING',
  10600. ' attribute vec4 skinIndex;',
  10601. ' attribute vec4 skinWeight;',
  10602. '#endif',
  10603. '\n'
  10604. ].filter( filterEmptyLine ).join( '\n' );
  10605. prefixFragment = [
  10606. customExtensions,
  10607. 'precision ' + parameters.precision + ' float;',
  10608. 'precision ' + parameters.precision + ' int;',
  10609. '#define SHADER_NAME ' + shader.name,
  10610. customDefines,
  10611. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10612. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10613. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10614. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10615. parameters.map ? '#define USE_MAP' : '',
  10616. parameters.envMap ? '#define USE_ENVMAP' : '',
  10617. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10618. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10619. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10620. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10621. parameters.aoMap ? '#define USE_AOMAP' : '',
  10622. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10623. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10624. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10625. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10626. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10627. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10628. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10629. parameters.vertexColors ? '#define USE_COLOR' : '',
  10630. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10631. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10632. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10633. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10634. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10635. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10636. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10637. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10638. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10639. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10640. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10641. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10642. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10643. 'uniform mat4 viewMatrix;',
  10644. 'uniform vec3 cameraPosition;',
  10645. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10646. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10647. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10648. parameters.dithering ? '#define DITHERING' : '',
  10649. ( 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
  10650. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10651. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10652. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10653. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10654. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10655. '\n'
  10656. ].filter( filterEmptyLine ).join( '\n' );
  10657. }
  10658. vertexShader = parseIncludes( vertexShader );
  10659. vertexShader = replaceLightNums( vertexShader, parameters );
  10660. fragmentShader = parseIncludes( fragmentShader );
  10661. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10662. if ( ! material.isShaderMaterial ) {
  10663. vertexShader = unrollLoops( vertexShader );
  10664. fragmentShader = unrollLoops( fragmentShader );
  10665. }
  10666. var vertexGlsl = prefixVertex + vertexShader;
  10667. var fragmentGlsl = prefixFragment + fragmentShader;
  10668. // console.log( '*VERTEX*', vertexGlsl );
  10669. // console.log( '*FRAGMENT*', fragmentGlsl );
  10670. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10671. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10672. gl.attachShader( program, glVertexShader );
  10673. gl.attachShader( program, glFragmentShader );
  10674. // Force a particular attribute to index 0.
  10675. if ( material.index0AttributeName !== undefined ) {
  10676. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10677. } else if ( parameters.morphTargets === true ) {
  10678. // programs with morphTargets displace position out of attribute 0
  10679. gl.bindAttribLocation( program, 0, 'position' );
  10680. }
  10681. gl.linkProgram( program );
  10682. var programLog = gl.getProgramInfoLog( program );
  10683. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10684. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10685. var runnable = true;
  10686. var haveDiagnostics = true;
  10687. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10688. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10689. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10690. runnable = false;
  10691. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10692. } else if ( programLog !== '' ) {
  10693. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10694. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10695. haveDiagnostics = false;
  10696. }
  10697. if ( haveDiagnostics ) {
  10698. this.diagnostics = {
  10699. runnable: runnable,
  10700. material: material,
  10701. programLog: programLog,
  10702. vertexShader: {
  10703. log: vertexLog,
  10704. prefix: prefixVertex
  10705. },
  10706. fragmentShader: {
  10707. log: fragmentLog,
  10708. prefix: prefixFragment
  10709. }
  10710. };
  10711. }
  10712. // clean up
  10713. gl.deleteShader( glVertexShader );
  10714. gl.deleteShader( glFragmentShader );
  10715. // set up caching for uniform locations
  10716. var cachedUniforms;
  10717. this.getUniforms = function () {
  10718. if ( cachedUniforms === undefined ) {
  10719. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  10720. }
  10721. return cachedUniforms;
  10722. };
  10723. // set up caching for attribute locations
  10724. var cachedAttributes;
  10725. this.getAttributes = function () {
  10726. if ( cachedAttributes === undefined ) {
  10727. cachedAttributes = fetchAttributeLocations( gl, program );
  10728. }
  10729. return cachedAttributes;
  10730. };
  10731. // free resource
  10732. this.destroy = function() {
  10733. gl.deleteProgram( program );
  10734. this.program = undefined;
  10735. };
  10736. // DEPRECATED
  10737. Object.defineProperties( this, {
  10738. uniforms: {
  10739. get: function() {
  10740. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10741. return this.getUniforms();
  10742. }
  10743. },
  10744. attributes: {
  10745. get: function() {
  10746. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10747. return this.getAttributes();
  10748. }
  10749. }
  10750. } );
  10751. //
  10752. this.id = programIdCount ++;
  10753. this.code = code;
  10754. this.usedTimes = 1;
  10755. this.program = program;
  10756. this.vertexShader = glVertexShader;
  10757. this.fragmentShader = glFragmentShader;
  10758. return this;
  10759. }
  10760. /**
  10761. * @author mrdoob / http://mrdoob.com/
  10762. */
  10763. function WebGLPrograms( renderer, extensions, capabilities ) {
  10764. var programs = [];
  10765. var shaderIDs = {
  10766. MeshDepthMaterial: 'depth',
  10767. MeshDistanceMaterial: 'distanceRGBA',
  10768. MeshNormalMaterial: 'normal',
  10769. MeshBasicMaterial: 'basic',
  10770. MeshLambertMaterial: 'lambert',
  10771. MeshPhongMaterial: 'phong',
  10772. MeshToonMaterial: 'phong',
  10773. MeshStandardMaterial: 'physical',
  10774. MeshPhysicalMaterial: 'physical',
  10775. LineBasicMaterial: 'basic',
  10776. LineDashedMaterial: 'dashed',
  10777. PointsMaterial: 'points'
  10778. };
  10779. var parameterNames = [
  10780. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10781. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10782. "roughnessMap", "metalnessMap", "gradientMap",
  10783. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10784. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10785. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10786. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10787. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10788. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10789. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10790. ];
  10791. function allocateBones( object ) {
  10792. var skeleton = object.skeleton;
  10793. var bones = skeleton.bones;
  10794. if ( capabilities.floatVertexTextures ) {
  10795. return 1024;
  10796. } else {
  10797. // default for when object is not specified
  10798. // ( for example when prebuilding shader to be used with multiple objects )
  10799. //
  10800. // - leave some extra space for other uniforms
  10801. // - limit here is ANGLE's 254 max uniform vectors
  10802. // (up to 54 should be safe)
  10803. var nVertexUniforms = capabilities.maxVertexUniforms;
  10804. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10805. var maxBones = Math.min( nVertexMatrices, bones.length );
  10806. if ( maxBones < bones.length ) {
  10807. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10808. return 0;
  10809. }
  10810. return maxBones;
  10811. }
  10812. }
  10813. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10814. var encoding;
  10815. if ( ! map ) {
  10816. encoding = LinearEncoding;
  10817. } else if ( map.isTexture ) {
  10818. encoding = map.encoding;
  10819. } else if ( map.isWebGLRenderTarget ) {
  10820. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10821. encoding = map.texture.encoding;
  10822. }
  10823. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10824. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10825. encoding = GammaEncoding;
  10826. }
  10827. return encoding;
  10828. }
  10829. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  10830. var shaderID = shaderIDs[ material.type ];
  10831. // heuristics to create shader parameters according to lights in the scene
  10832. // (not to blow over maxLights budget)
  10833. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10834. var precision = capabilities.precision;
  10835. if ( material.precision !== null ) {
  10836. precision = capabilities.getMaxPrecision( material.precision );
  10837. if ( precision !== material.precision ) {
  10838. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10839. }
  10840. }
  10841. var currentRenderTarget = renderer.getRenderTarget();
  10842. var parameters = {
  10843. shaderID: shaderID,
  10844. precision: precision,
  10845. supportsVertexTextures: capabilities.vertexTextures,
  10846. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10847. map: !! material.map,
  10848. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10849. envMap: !! material.envMap,
  10850. envMapMode: material.envMap && material.envMap.mapping,
  10851. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10852. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10853. lightMap: !! material.lightMap,
  10854. aoMap: !! material.aoMap,
  10855. emissiveMap: !! material.emissiveMap,
  10856. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10857. bumpMap: !! material.bumpMap,
  10858. normalMap: !! material.normalMap,
  10859. displacementMap: !! material.displacementMap,
  10860. roughnessMap: !! material.roughnessMap,
  10861. metalnessMap: !! material.metalnessMap,
  10862. specularMap: !! material.specularMap,
  10863. alphaMap: !! material.alphaMap,
  10864. gradientMap: !! material.gradientMap,
  10865. combine: material.combine,
  10866. vertexColors: material.vertexColors,
  10867. fog: !! fog,
  10868. useFog: material.fog,
  10869. fogExp: ( fog && fog.isFogExp2 ),
  10870. flatShading: material.flatShading,
  10871. sizeAttenuation: material.sizeAttenuation,
  10872. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10873. skinning: material.skinning && maxBones > 0,
  10874. maxBones: maxBones,
  10875. useVertexTexture: capabilities.floatVertexTextures,
  10876. morphTargets: material.morphTargets,
  10877. morphNormals: material.morphNormals,
  10878. maxMorphTargets: renderer.maxMorphTargets,
  10879. maxMorphNormals: renderer.maxMorphNormals,
  10880. numDirLights: lights.directional.length,
  10881. numPointLights: lights.point.length,
  10882. numSpotLights: lights.spot.length,
  10883. numRectAreaLights: lights.rectArea.length,
  10884. numHemiLights: lights.hemi.length,
  10885. numClippingPlanes: nClipPlanes,
  10886. numClipIntersection: nClipIntersection,
  10887. dithering: material.dithering,
  10888. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  10889. shadowMapType: renderer.shadowMap.type,
  10890. toneMapping: renderer.toneMapping,
  10891. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10892. premultipliedAlpha: material.premultipliedAlpha,
  10893. alphaTest: material.alphaTest,
  10894. doubleSided: material.side === DoubleSide,
  10895. flipSided: material.side === BackSide,
  10896. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10897. };
  10898. return parameters;
  10899. };
  10900. this.getProgramCode = function ( material, parameters ) {
  10901. var array = [];
  10902. if ( parameters.shaderID ) {
  10903. array.push( parameters.shaderID );
  10904. } else {
  10905. array.push( material.fragmentShader );
  10906. array.push( material.vertexShader );
  10907. }
  10908. if ( material.defines !== undefined ) {
  10909. for ( var name in material.defines ) {
  10910. array.push( name );
  10911. array.push( material.defines[ name ] );
  10912. }
  10913. }
  10914. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10915. array.push( parameters[ parameterNames[ i ] ] );
  10916. }
  10917. array.push( material.onBeforeCompile.toString() );
  10918. array.push( renderer.gammaOutput );
  10919. return array.join();
  10920. };
  10921. this.acquireProgram = function ( material, shader, parameters, code ) {
  10922. var program;
  10923. // Check if code has been already compiled
  10924. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10925. var programInfo = programs[ p ];
  10926. if ( programInfo.code === code ) {
  10927. program = programInfo;
  10928. ++ program.usedTimes;
  10929. break;
  10930. }
  10931. }
  10932. if ( program === undefined ) {
  10933. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  10934. programs.push( program );
  10935. }
  10936. return program;
  10937. };
  10938. this.releaseProgram = function ( program ) {
  10939. if ( -- program.usedTimes === 0 ) {
  10940. // Remove from unordered set
  10941. var i = programs.indexOf( program );
  10942. programs[ i ] = programs[ programs.length - 1 ];
  10943. programs.pop();
  10944. // Free WebGL resources
  10945. program.destroy();
  10946. }
  10947. };
  10948. // Exposed for resource monitoring & error feedback via renderer.info:
  10949. this.programs = programs;
  10950. }
  10951. /**
  10952. * @author mrdoob / http://mrdoob.com/
  10953. */
  10954. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) {
  10955. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10956. //
  10957. function clampToMaxSize( image, maxSize ) {
  10958. if ( image.width > maxSize || image.height > maxSize ) {
  10959. // Warning: Scaling through the canvas will only work with images that use
  10960. // premultiplied alpha.
  10961. var scale = maxSize / Math.max( image.width, image.height );
  10962. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10963. canvas.width = Math.floor( image.width * scale );
  10964. canvas.height = Math.floor( image.height * scale );
  10965. var context = canvas.getContext( '2d' );
  10966. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10967. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10968. return canvas;
  10969. }
  10970. return image;
  10971. }
  10972. function isPowerOfTwo( image ) {
  10973. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10974. }
  10975. function makePowerOfTwo( image ) {
  10976. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10977. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10978. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10979. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10980. var context = canvas.getContext( '2d' );
  10981. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10982. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10983. return canvas;
  10984. }
  10985. return image;
  10986. }
  10987. function textureNeedsPowerOfTwo( texture ) {
  10988. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10989. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10990. }
  10991. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  10992. return texture.generateMipmaps && isPowerOfTwo &&
  10993. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  10994. }
  10995. // Fallback filters for non-power-of-2 textures
  10996. function filterFallback( f ) {
  10997. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10998. return _gl.NEAREST;
  10999. }
  11000. return _gl.LINEAR;
  11001. }
  11002. //
  11003. function onTextureDispose( event ) {
  11004. var texture = event.target;
  11005. texture.removeEventListener( 'dispose', onTextureDispose );
  11006. deallocateTexture( texture );
  11007. infoMemory.textures --;
  11008. }
  11009. function onRenderTargetDispose( event ) {
  11010. var renderTarget = event.target;
  11011. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11012. deallocateRenderTarget( renderTarget );
  11013. infoMemory.textures --;
  11014. }
  11015. //
  11016. function deallocateTexture( texture ) {
  11017. var textureProperties = properties.get( texture );
  11018. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  11019. // cube texture
  11020. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  11021. } else {
  11022. // 2D texture
  11023. if ( textureProperties.__webglInit === undefined ) return;
  11024. _gl.deleteTexture( textureProperties.__webglTexture );
  11025. }
  11026. // remove all webgl properties
  11027. properties.remove( texture );
  11028. }
  11029. function deallocateRenderTarget( renderTarget ) {
  11030. var renderTargetProperties = properties.get( renderTarget );
  11031. var textureProperties = properties.get( renderTarget.texture );
  11032. if ( ! renderTarget ) return;
  11033. if ( textureProperties.__webglTexture !== undefined ) {
  11034. _gl.deleteTexture( textureProperties.__webglTexture );
  11035. }
  11036. if ( renderTarget.depthTexture ) {
  11037. renderTarget.depthTexture.dispose();
  11038. }
  11039. if ( renderTarget.isWebGLRenderTargetCube ) {
  11040. for ( var i = 0; i < 6; i ++ ) {
  11041. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  11042. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  11043. }
  11044. } else {
  11045. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  11046. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  11047. }
  11048. properties.remove( renderTarget.texture );
  11049. properties.remove( renderTarget );
  11050. }
  11051. //
  11052. function setTexture2D( texture, slot ) {
  11053. var textureProperties = properties.get( texture );
  11054. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11055. var image = texture.image;
  11056. if ( image === undefined ) {
  11057. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  11058. } else if ( image.complete === false ) {
  11059. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  11060. } else {
  11061. uploadTexture( textureProperties, texture, slot );
  11062. return;
  11063. }
  11064. }
  11065. state.activeTexture( _gl.TEXTURE0 + slot );
  11066. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11067. }
  11068. function setTextureCube( texture, slot ) {
  11069. var textureProperties = properties.get( texture );
  11070. if ( texture.image.length === 6 ) {
  11071. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  11072. if ( ! textureProperties.__image__webglTextureCube ) {
  11073. texture.addEventListener( 'dispose', onTextureDispose );
  11074. textureProperties.__image__webglTextureCube = _gl.createTexture();
  11075. infoMemory.textures ++;
  11076. }
  11077. state.activeTexture( _gl.TEXTURE0 + slot );
  11078. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11079. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11080. var isCompressed = ( texture && texture.isCompressedTexture );
  11081. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  11082. var cubeImage = [];
  11083. for ( var i = 0; i < 6; i ++ ) {
  11084. if ( ! isCompressed && ! isDataTexture ) {
  11085. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  11086. } else {
  11087. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  11088. }
  11089. }
  11090. var image = cubeImage[ 0 ],
  11091. isPowerOfTwoImage = isPowerOfTwo( image ),
  11092. glFormat = paramThreeToGL( texture.format ),
  11093. glType = paramThreeToGL( texture.type );
  11094. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  11095. for ( var i = 0; i < 6; i ++ ) {
  11096. if ( ! isCompressed ) {
  11097. if ( isDataTexture ) {
  11098. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  11099. } else {
  11100. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  11101. }
  11102. } else {
  11103. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  11104. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  11105. mipmap = mipmaps[ j ];
  11106. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11107. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11108. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11109. } else {
  11110. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  11111. }
  11112. } else {
  11113. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11114. }
  11115. }
  11116. }
  11117. }
  11118. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  11119. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11120. }
  11121. textureProperties.__version = texture.version;
  11122. if ( texture.onUpdate ) texture.onUpdate( texture );
  11123. } else {
  11124. state.activeTexture( _gl.TEXTURE0 + slot );
  11125. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  11126. }
  11127. }
  11128. }
  11129. function setTextureCubeDynamic( texture, slot ) {
  11130. state.activeTexture( _gl.TEXTURE0 + slot );
  11131. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  11132. }
  11133. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  11134. var extension;
  11135. if ( isPowerOfTwoImage ) {
  11136. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  11137. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  11138. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  11139. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  11140. } else {
  11141. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11142. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11143. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  11144. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  11145. }
  11146. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  11147. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  11148. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  11149. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  11150. }
  11151. }
  11152. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11153. if ( extension ) {
  11154. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  11155. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  11156. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  11157. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  11158. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  11159. }
  11160. }
  11161. }
  11162. function uploadTexture( textureProperties, texture, slot ) {
  11163. if ( textureProperties.__webglInit === undefined ) {
  11164. textureProperties.__webglInit = true;
  11165. texture.addEventListener( 'dispose', onTextureDispose );
  11166. textureProperties.__webglTexture = _gl.createTexture();
  11167. infoMemory.textures ++;
  11168. }
  11169. state.activeTexture( _gl.TEXTURE0 + slot );
  11170. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11171. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  11172. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  11173. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  11174. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  11175. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  11176. image = makePowerOfTwo( image );
  11177. }
  11178. var isPowerOfTwoImage = isPowerOfTwo( image ),
  11179. glFormat = paramThreeToGL( texture.format ),
  11180. glType = paramThreeToGL( texture.type );
  11181. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  11182. var mipmap, mipmaps = texture.mipmaps;
  11183. if ( texture.isDepthTexture ) {
  11184. // populate depth texture with dummy data
  11185. var internalFormat = _gl.DEPTH_COMPONENT;
  11186. if ( texture.type === FloatType ) {
  11187. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  11188. internalFormat = _gl.DEPTH_COMPONENT32F;
  11189. } else if ( _isWebGL2 ) {
  11190. // WebGL 2.0 requires signed internalformat for glTexImage2D
  11191. internalFormat = _gl.DEPTH_COMPONENT16;
  11192. }
  11193. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  11194. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11195. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  11196. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11197. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  11198. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  11199. texture.type = UnsignedShortType;
  11200. glType = paramThreeToGL( texture.type );
  11201. }
  11202. }
  11203. // Depth stencil textures need the DEPTH_STENCIL internal format
  11204. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11205. if ( texture.format === DepthStencilFormat ) {
  11206. internalFormat = _gl.DEPTH_STENCIL;
  11207. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  11208. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  11209. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  11210. if ( texture.type !== UnsignedInt248Type ) {
  11211. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  11212. texture.type = UnsignedInt248Type;
  11213. glType = paramThreeToGL( texture.type );
  11214. }
  11215. }
  11216. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  11217. } else if ( texture.isDataTexture ) {
  11218. // use manually created mipmaps if available
  11219. // if there are no manual mipmaps
  11220. // set 0 level mipmap and then use GL to generate other mipmap levels
  11221. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11222. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11223. mipmap = mipmaps[ i ];
  11224. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11225. }
  11226. texture.generateMipmaps = false;
  11227. } else {
  11228. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  11229. }
  11230. } else if ( texture.isCompressedTexture ) {
  11231. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11232. mipmap = mipmaps[ i ];
  11233. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  11234. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  11235. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  11236. } else {
  11237. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  11238. }
  11239. } else {
  11240. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  11241. }
  11242. }
  11243. } else {
  11244. // regular Texture (image, video, canvas)
  11245. // use manually created mipmaps if available
  11246. // if there are no manual mipmaps
  11247. // set 0 level mipmap and then use GL to generate other mipmap levels
  11248. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  11249. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  11250. mipmap = mipmaps[ i ];
  11251. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  11252. }
  11253. texture.generateMipmaps = false;
  11254. } else {
  11255. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  11256. }
  11257. }
  11258. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11259. textureProperties.__version = texture.version;
  11260. if ( texture.onUpdate ) texture.onUpdate( texture );
  11261. }
  11262. // Render targets
  11263. // Setup storage for target texture and bind it to correct framebuffer
  11264. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  11265. var glFormat = paramThreeToGL( renderTarget.texture.format );
  11266. var glType = paramThreeToGL( renderTarget.texture.type );
  11267. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  11268. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11269. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  11270. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11271. }
  11272. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  11273. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  11274. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  11275. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  11276. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  11277. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11278. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  11279. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  11280. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  11281. } else {
  11282. // FIXME: We don't support !depth !stencil
  11283. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  11284. }
  11285. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  11286. }
  11287. // Setup resources for a Depth Texture for a FBO (needs an extension)
  11288. function setupDepthTexture( framebuffer, renderTarget ) {
  11289. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  11290. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  11291. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11292. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  11293. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  11294. }
  11295. // upload an empty depth texture with framebuffer size
  11296. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  11297. renderTarget.depthTexture.image.width !== renderTarget.width ||
  11298. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  11299. renderTarget.depthTexture.image.width = renderTarget.width;
  11300. renderTarget.depthTexture.image.height = renderTarget.height;
  11301. renderTarget.depthTexture.needsUpdate = true;
  11302. }
  11303. setTexture2D( renderTarget.depthTexture, 0 );
  11304. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  11305. if ( renderTarget.depthTexture.format === DepthFormat ) {
  11306. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11307. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  11308. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  11309. } else {
  11310. throw new Error( 'Unknown depthTexture format' );
  11311. }
  11312. }
  11313. // Setup GL resources for a non-texture depth buffer
  11314. function setupDepthRenderbuffer( renderTarget ) {
  11315. var renderTargetProperties = properties.get( renderTarget );
  11316. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11317. if ( renderTarget.depthTexture ) {
  11318. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  11319. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  11320. } else {
  11321. if ( isCube ) {
  11322. renderTargetProperties.__webglDepthbuffer = [];
  11323. for ( var i = 0; i < 6; i ++ ) {
  11324. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11325. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11326. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11327. }
  11328. } else {
  11329. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11330. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11331. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11332. }
  11333. }
  11334. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11335. }
  11336. // Set up GL resources for the render target
  11337. function setupRenderTarget( renderTarget ) {
  11338. var renderTargetProperties = properties.get( renderTarget );
  11339. var textureProperties = properties.get( renderTarget.texture );
  11340. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11341. textureProperties.__webglTexture = _gl.createTexture();
  11342. infoMemory.textures ++;
  11343. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11344. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11345. // Setup framebuffer
  11346. if ( isCube ) {
  11347. renderTargetProperties.__webglFramebuffer = [];
  11348. for ( var i = 0; i < 6; i ++ ) {
  11349. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11350. }
  11351. } else {
  11352. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11353. }
  11354. // Setup color buffer
  11355. if ( isCube ) {
  11356. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11357. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11358. for ( var i = 0; i < 6; i ++ ) {
  11359. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11360. }
  11361. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11362. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11363. } else {
  11364. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11365. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11366. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11367. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11368. state.bindTexture( _gl.TEXTURE_2D, null );
  11369. }
  11370. // Setup depth and stencil buffers
  11371. if ( renderTarget.depthBuffer ) {
  11372. setupDepthRenderbuffer( renderTarget );
  11373. }
  11374. }
  11375. function updateRenderTargetMipmap( renderTarget ) {
  11376. var texture = renderTarget.texture;
  11377. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11378. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  11379. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11380. var webglTexture = properties.get( texture ).__webglTexture;
  11381. state.bindTexture( target, webglTexture );
  11382. _gl.generateMipmap( target );
  11383. state.bindTexture( target, null );
  11384. }
  11385. }
  11386. this.setTexture2D = setTexture2D;
  11387. this.setTextureCube = setTextureCube;
  11388. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11389. this.setupRenderTarget = setupRenderTarget;
  11390. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11391. }
  11392. /**
  11393. * @author fordacious / fordacious.github.io
  11394. */
  11395. function WebGLProperties() {
  11396. var properties = {};
  11397. function get( object ) {
  11398. var uuid = object.uuid;
  11399. var map = properties[ uuid ];
  11400. if ( map === undefined ) {
  11401. map = {};
  11402. properties[ uuid ] = map;
  11403. }
  11404. return map;
  11405. }
  11406. function remove( object ) {
  11407. delete properties[ object.uuid ];
  11408. }
  11409. function clear() {
  11410. properties = {};
  11411. }
  11412. return {
  11413. get: get,
  11414. remove: remove,
  11415. clear: clear
  11416. };
  11417. }
  11418. /**
  11419. * @author mrdoob / http://mrdoob.com/
  11420. */
  11421. function WebGLState( gl, extensions, paramThreeToGL ) {
  11422. function ColorBuffer() {
  11423. var locked = false;
  11424. var color = new Vector4();
  11425. var currentColorMask = null;
  11426. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  11427. return {
  11428. setMask: function ( colorMask ) {
  11429. if ( currentColorMask !== colorMask && ! locked ) {
  11430. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11431. currentColorMask = colorMask;
  11432. }
  11433. },
  11434. setLocked: function ( lock ) {
  11435. locked = lock;
  11436. },
  11437. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11438. if ( premultipliedAlpha === true ) {
  11439. r *= a; g *= a; b *= a;
  11440. }
  11441. color.set( r, g, b, a );
  11442. if ( currentColorClear.equals( color ) === false ) {
  11443. gl.clearColor( r, g, b, a );
  11444. currentColorClear.copy( color );
  11445. }
  11446. },
  11447. reset: function () {
  11448. locked = false;
  11449. currentColorMask = null;
  11450. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11451. }
  11452. };
  11453. }
  11454. function DepthBuffer() {
  11455. var locked = false;
  11456. var currentDepthMask = null;
  11457. var currentDepthFunc = null;
  11458. var currentDepthClear = null;
  11459. return {
  11460. setTest: function ( depthTest ) {
  11461. if ( depthTest ) {
  11462. enable( gl.DEPTH_TEST );
  11463. } else {
  11464. disable( gl.DEPTH_TEST );
  11465. }
  11466. },
  11467. setMask: function ( depthMask ) {
  11468. if ( currentDepthMask !== depthMask && ! locked ) {
  11469. gl.depthMask( depthMask );
  11470. currentDepthMask = depthMask;
  11471. }
  11472. },
  11473. setFunc: function ( depthFunc ) {
  11474. if ( currentDepthFunc !== depthFunc ) {
  11475. if ( depthFunc ) {
  11476. switch ( depthFunc ) {
  11477. case NeverDepth:
  11478. gl.depthFunc( gl.NEVER );
  11479. break;
  11480. case AlwaysDepth:
  11481. gl.depthFunc( gl.ALWAYS );
  11482. break;
  11483. case LessDepth:
  11484. gl.depthFunc( gl.LESS );
  11485. break;
  11486. case LessEqualDepth:
  11487. gl.depthFunc( gl.LEQUAL );
  11488. break;
  11489. case EqualDepth:
  11490. gl.depthFunc( gl.EQUAL );
  11491. break;
  11492. case GreaterEqualDepth:
  11493. gl.depthFunc( gl.GEQUAL );
  11494. break;
  11495. case GreaterDepth:
  11496. gl.depthFunc( gl.GREATER );
  11497. break;
  11498. case NotEqualDepth:
  11499. gl.depthFunc( gl.NOTEQUAL );
  11500. break;
  11501. default:
  11502. gl.depthFunc( gl.LEQUAL );
  11503. }
  11504. } else {
  11505. gl.depthFunc( gl.LEQUAL );
  11506. }
  11507. currentDepthFunc = depthFunc;
  11508. }
  11509. },
  11510. setLocked: function ( lock ) {
  11511. locked = lock;
  11512. },
  11513. setClear: function ( depth ) {
  11514. if ( currentDepthClear !== depth ) {
  11515. gl.clearDepth( depth );
  11516. currentDepthClear = depth;
  11517. }
  11518. },
  11519. reset: function () {
  11520. locked = false;
  11521. currentDepthMask = null;
  11522. currentDepthFunc = null;
  11523. currentDepthClear = null;
  11524. }
  11525. };
  11526. }
  11527. function StencilBuffer() {
  11528. var locked = false;
  11529. var currentStencilMask = null;
  11530. var currentStencilFunc = null;
  11531. var currentStencilRef = null;
  11532. var currentStencilFuncMask = null;
  11533. var currentStencilFail = null;
  11534. var currentStencilZFail = null;
  11535. var currentStencilZPass = null;
  11536. var currentStencilClear = null;
  11537. return {
  11538. setTest: function ( stencilTest ) {
  11539. if ( stencilTest ) {
  11540. enable( gl.STENCIL_TEST );
  11541. } else {
  11542. disable( gl.STENCIL_TEST );
  11543. }
  11544. },
  11545. setMask: function ( stencilMask ) {
  11546. if ( currentStencilMask !== stencilMask && ! locked ) {
  11547. gl.stencilMask( stencilMask );
  11548. currentStencilMask = stencilMask;
  11549. }
  11550. },
  11551. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11552. if ( currentStencilFunc !== stencilFunc ||
  11553. currentStencilRef !== stencilRef ||
  11554. currentStencilFuncMask !== stencilMask ) {
  11555. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11556. currentStencilFunc = stencilFunc;
  11557. currentStencilRef = stencilRef;
  11558. currentStencilFuncMask = stencilMask;
  11559. }
  11560. },
  11561. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11562. if ( currentStencilFail !== stencilFail ||
  11563. currentStencilZFail !== stencilZFail ||
  11564. currentStencilZPass !== stencilZPass ) {
  11565. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11566. currentStencilFail = stencilFail;
  11567. currentStencilZFail = stencilZFail;
  11568. currentStencilZPass = stencilZPass;
  11569. }
  11570. },
  11571. setLocked: function ( lock ) {
  11572. locked = lock;
  11573. },
  11574. setClear: function ( stencil ) {
  11575. if ( currentStencilClear !== stencil ) {
  11576. gl.clearStencil( stencil );
  11577. currentStencilClear = stencil;
  11578. }
  11579. },
  11580. reset: function () {
  11581. locked = false;
  11582. currentStencilMask = null;
  11583. currentStencilFunc = null;
  11584. currentStencilRef = null;
  11585. currentStencilFuncMask = null;
  11586. currentStencilFail = null;
  11587. currentStencilZFail = null;
  11588. currentStencilZPass = null;
  11589. currentStencilClear = null;
  11590. }
  11591. };
  11592. }
  11593. //
  11594. var colorBuffer = new ColorBuffer();
  11595. var depthBuffer = new DepthBuffer();
  11596. var stencilBuffer = new StencilBuffer();
  11597. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11598. var newAttributes = new Uint8Array( maxVertexAttributes );
  11599. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11600. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11601. var capabilities = {};
  11602. var compressedTextureFormats = null;
  11603. var currentProgram = null;
  11604. var currentBlending = null;
  11605. var currentBlendEquation = null;
  11606. var currentBlendSrc = null;
  11607. var currentBlendDst = null;
  11608. var currentBlendEquationAlpha = null;
  11609. var currentBlendSrcAlpha = null;
  11610. var currentBlendDstAlpha = null;
  11611. var currentPremultipledAlpha = false;
  11612. var currentFlipSided = null;
  11613. var currentCullFace = null;
  11614. var currentLineWidth = null;
  11615. var currentPolygonOffsetFactor = null;
  11616. var currentPolygonOffsetUnits = null;
  11617. var currentScissorTest = null;
  11618. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  11619. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11620. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11621. var currentTextureSlot = null;
  11622. var currentBoundTextures = {};
  11623. var currentScissor = new Vector4();
  11624. var currentViewport = new Vector4();
  11625. function createTexture( type, target, count ) {
  11626. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11627. var texture = gl.createTexture();
  11628. gl.bindTexture( type, texture );
  11629. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11630. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11631. for ( var i = 0; i < count; i ++ ) {
  11632. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11633. }
  11634. return texture;
  11635. }
  11636. var emptyTextures = {};
  11637. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11638. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11639. // init
  11640. colorBuffer.setClear( 0, 0, 0, 1 );
  11641. depthBuffer.setClear( 1 );
  11642. stencilBuffer.setClear( 0 );
  11643. enable( gl.DEPTH_TEST );
  11644. depthBuffer.setFunc( LessEqualDepth );
  11645. setFlipSided( false );
  11646. setCullFace( CullFaceBack );
  11647. enable( gl.CULL_FACE );
  11648. enable( gl.BLEND );
  11649. setBlending( NormalBlending );
  11650. //
  11651. function initAttributes() {
  11652. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11653. newAttributes[ i ] = 0;
  11654. }
  11655. }
  11656. function enableAttribute( attribute ) {
  11657. newAttributes[ attribute ] = 1;
  11658. if ( enabledAttributes[ attribute ] === 0 ) {
  11659. gl.enableVertexAttribArray( attribute );
  11660. enabledAttributes[ attribute ] = 1;
  11661. }
  11662. if ( attributeDivisors[ attribute ] !== 0 ) {
  11663. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11664. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11665. attributeDivisors[ attribute ] = 0;
  11666. }
  11667. }
  11668. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11669. newAttributes[ attribute ] = 1;
  11670. if ( enabledAttributes[ attribute ] === 0 ) {
  11671. gl.enableVertexAttribArray( attribute );
  11672. enabledAttributes[ attribute ] = 1;
  11673. }
  11674. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11675. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11676. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11677. attributeDivisors[ attribute ] = meshPerAttribute;
  11678. }
  11679. }
  11680. function disableUnusedAttributes() {
  11681. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11682. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11683. gl.disableVertexAttribArray( i );
  11684. enabledAttributes[ i ] = 0;
  11685. }
  11686. }
  11687. }
  11688. function enable( id ) {
  11689. if ( capabilities[ id ] !== true ) {
  11690. gl.enable( id );
  11691. capabilities[ id ] = true;
  11692. }
  11693. }
  11694. function disable( id ) {
  11695. if ( capabilities[ id ] !== false ) {
  11696. gl.disable( id );
  11697. capabilities[ id ] = false;
  11698. }
  11699. }
  11700. function getCompressedTextureFormats() {
  11701. if ( compressedTextureFormats === null ) {
  11702. compressedTextureFormats = [];
  11703. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11704. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11705. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11706. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11707. for ( var i = 0; i < formats.length; i ++ ) {
  11708. compressedTextureFormats.push( formats[ i ] );
  11709. }
  11710. }
  11711. }
  11712. return compressedTextureFormats;
  11713. }
  11714. function useProgram( program ) {
  11715. if ( currentProgram !== program ) {
  11716. gl.useProgram( program );
  11717. currentProgram = program;
  11718. return true;
  11719. }
  11720. return false;
  11721. }
  11722. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11723. if ( blending !== NoBlending ) {
  11724. enable( gl.BLEND );
  11725. } else {
  11726. disable( gl.BLEND );
  11727. }
  11728. if ( blending !== CustomBlending ) {
  11729. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11730. switch ( blending ) {
  11731. case AdditiveBlending:
  11732. if ( premultipliedAlpha ) {
  11733. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11734. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11735. } else {
  11736. gl.blendEquation( gl.FUNC_ADD );
  11737. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11738. }
  11739. break;
  11740. case SubtractiveBlending:
  11741. if ( premultipliedAlpha ) {
  11742. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11743. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11744. } else {
  11745. gl.blendEquation( gl.FUNC_ADD );
  11746. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11747. }
  11748. break;
  11749. case MultiplyBlending:
  11750. if ( premultipliedAlpha ) {
  11751. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11752. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11753. } else {
  11754. gl.blendEquation( gl.FUNC_ADD );
  11755. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11756. }
  11757. break;
  11758. default:
  11759. if ( premultipliedAlpha ) {
  11760. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11761. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11762. } else {
  11763. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11764. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11765. }
  11766. }
  11767. }
  11768. currentBlendEquation = null;
  11769. currentBlendSrc = null;
  11770. currentBlendDst = null;
  11771. currentBlendEquationAlpha = null;
  11772. currentBlendSrcAlpha = null;
  11773. currentBlendDstAlpha = null;
  11774. } else {
  11775. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11776. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11777. blendDstAlpha = blendDstAlpha || blendDst;
  11778. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11779. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11780. currentBlendEquation = blendEquation;
  11781. currentBlendEquationAlpha = blendEquationAlpha;
  11782. }
  11783. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11784. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11785. currentBlendSrc = blendSrc;
  11786. currentBlendDst = blendDst;
  11787. currentBlendSrcAlpha = blendSrcAlpha;
  11788. currentBlendDstAlpha = blendDstAlpha;
  11789. }
  11790. }
  11791. currentBlending = blending;
  11792. currentPremultipledAlpha = premultipliedAlpha;
  11793. }
  11794. function setMaterial( material ) {
  11795. material.side === DoubleSide
  11796. ? disable( gl.CULL_FACE )
  11797. : enable( gl.CULL_FACE );
  11798. setFlipSided( material.side === BackSide );
  11799. material.transparent === true
  11800. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11801. : setBlending( NoBlending );
  11802. depthBuffer.setFunc( material.depthFunc );
  11803. depthBuffer.setTest( material.depthTest );
  11804. depthBuffer.setMask( material.depthWrite );
  11805. colorBuffer.setMask( material.colorWrite );
  11806. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11807. }
  11808. //
  11809. function setFlipSided( flipSided ) {
  11810. if ( currentFlipSided !== flipSided ) {
  11811. if ( flipSided ) {
  11812. gl.frontFace( gl.CW );
  11813. } else {
  11814. gl.frontFace( gl.CCW );
  11815. }
  11816. currentFlipSided = flipSided;
  11817. }
  11818. }
  11819. function setCullFace( cullFace ) {
  11820. if ( cullFace !== CullFaceNone ) {
  11821. enable( gl.CULL_FACE );
  11822. if ( cullFace !== currentCullFace ) {
  11823. if ( cullFace === CullFaceBack ) {
  11824. gl.cullFace( gl.BACK );
  11825. } else if ( cullFace === CullFaceFront ) {
  11826. gl.cullFace( gl.FRONT );
  11827. } else {
  11828. gl.cullFace( gl.FRONT_AND_BACK );
  11829. }
  11830. }
  11831. } else {
  11832. disable( gl.CULL_FACE );
  11833. }
  11834. currentCullFace = cullFace;
  11835. }
  11836. function setLineWidth( width ) {
  11837. if ( width !== currentLineWidth ) {
  11838. if ( lineWidthAvailable ) gl.lineWidth( width );
  11839. currentLineWidth = width;
  11840. }
  11841. }
  11842. function setPolygonOffset( polygonOffset, factor, units ) {
  11843. if ( polygonOffset ) {
  11844. enable( gl.POLYGON_OFFSET_FILL );
  11845. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11846. gl.polygonOffset( factor, units );
  11847. currentPolygonOffsetFactor = factor;
  11848. currentPolygonOffsetUnits = units;
  11849. }
  11850. } else {
  11851. disable( gl.POLYGON_OFFSET_FILL );
  11852. }
  11853. }
  11854. function getScissorTest() {
  11855. return currentScissorTest;
  11856. }
  11857. function setScissorTest( scissorTest ) {
  11858. currentScissorTest = scissorTest;
  11859. if ( scissorTest ) {
  11860. enable( gl.SCISSOR_TEST );
  11861. } else {
  11862. disable( gl.SCISSOR_TEST );
  11863. }
  11864. }
  11865. // texture
  11866. function activeTexture( webglSlot ) {
  11867. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11868. if ( currentTextureSlot !== webglSlot ) {
  11869. gl.activeTexture( webglSlot );
  11870. currentTextureSlot = webglSlot;
  11871. }
  11872. }
  11873. function bindTexture( webglType, webglTexture ) {
  11874. if ( currentTextureSlot === null ) {
  11875. activeTexture();
  11876. }
  11877. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11878. if ( boundTexture === undefined ) {
  11879. boundTexture = { type: undefined, texture: undefined };
  11880. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11881. }
  11882. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11883. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11884. boundTexture.type = webglType;
  11885. boundTexture.texture = webglTexture;
  11886. }
  11887. }
  11888. function compressedTexImage2D() {
  11889. try {
  11890. gl.compressedTexImage2D.apply( gl, arguments );
  11891. } catch ( error ) {
  11892. console.error( 'THREE.WebGLState:', error );
  11893. }
  11894. }
  11895. function texImage2D() {
  11896. try {
  11897. gl.texImage2D.apply( gl, arguments );
  11898. } catch ( error ) {
  11899. console.error( 'THREE.WebGLState:', error );
  11900. }
  11901. }
  11902. //
  11903. function scissor( scissor ) {
  11904. if ( currentScissor.equals( scissor ) === false ) {
  11905. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11906. currentScissor.copy( scissor );
  11907. }
  11908. }
  11909. function viewport( viewport ) {
  11910. if ( currentViewport.equals( viewport ) === false ) {
  11911. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11912. currentViewport.copy( viewport );
  11913. }
  11914. }
  11915. //
  11916. function reset() {
  11917. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11918. if ( enabledAttributes[ i ] === 1 ) {
  11919. gl.disableVertexAttribArray( i );
  11920. enabledAttributes[ i ] = 0;
  11921. }
  11922. }
  11923. capabilities = {};
  11924. compressedTextureFormats = null;
  11925. currentTextureSlot = null;
  11926. currentBoundTextures = {};
  11927. currentProgram = null;
  11928. currentBlending = null;
  11929. currentFlipSided = null;
  11930. currentCullFace = null;
  11931. colorBuffer.reset();
  11932. depthBuffer.reset();
  11933. stencilBuffer.reset();
  11934. }
  11935. return {
  11936. buffers: {
  11937. color: colorBuffer,
  11938. depth: depthBuffer,
  11939. stencil: stencilBuffer
  11940. },
  11941. initAttributes: initAttributes,
  11942. enableAttribute: enableAttribute,
  11943. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11944. disableUnusedAttributes: disableUnusedAttributes,
  11945. enable: enable,
  11946. disable: disable,
  11947. getCompressedTextureFormats: getCompressedTextureFormats,
  11948. useProgram: useProgram,
  11949. setBlending: setBlending,
  11950. setMaterial: setMaterial,
  11951. setFlipSided: setFlipSided,
  11952. setCullFace: setCullFace,
  11953. setLineWidth: setLineWidth,
  11954. setPolygonOffset: setPolygonOffset,
  11955. getScissorTest: getScissorTest,
  11956. setScissorTest: setScissorTest,
  11957. activeTexture: activeTexture,
  11958. bindTexture: bindTexture,
  11959. compressedTexImage2D: compressedTexImage2D,
  11960. texImage2D: texImage2D,
  11961. scissor: scissor,
  11962. viewport: viewport,
  11963. reset: reset
  11964. };
  11965. }
  11966. /**
  11967. * @author mrdoob / http://mrdoob.com/
  11968. */
  11969. function WebGLCapabilities( gl, extensions, parameters ) {
  11970. var maxAnisotropy;
  11971. function getMaxAnisotropy() {
  11972. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11973. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11974. if ( extension !== null ) {
  11975. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11976. } else {
  11977. maxAnisotropy = 0;
  11978. }
  11979. return maxAnisotropy;
  11980. }
  11981. function getMaxPrecision( precision ) {
  11982. if ( precision === 'highp' ) {
  11983. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11984. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11985. return 'highp';
  11986. }
  11987. precision = 'mediump';
  11988. }
  11989. if ( precision === 'mediump' ) {
  11990. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11991. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11992. return 'mediump';
  11993. }
  11994. }
  11995. return 'lowp';
  11996. }
  11997. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11998. var maxPrecision = getMaxPrecision( precision );
  11999. if ( maxPrecision !== precision ) {
  12000. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  12001. precision = maxPrecision;
  12002. }
  12003. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  12004. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  12005. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12006. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  12007. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12008. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  12009. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  12010. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  12011. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  12012. var vertexTextures = maxVertexTextures > 0;
  12013. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  12014. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  12015. return {
  12016. getMaxAnisotropy: getMaxAnisotropy,
  12017. getMaxPrecision: getMaxPrecision,
  12018. precision: precision,
  12019. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12020. maxTextures: maxTextures,
  12021. maxVertexTextures: maxVertexTextures,
  12022. maxTextureSize: maxTextureSize,
  12023. maxCubemapSize: maxCubemapSize,
  12024. maxAttributes: maxAttributes,
  12025. maxVertexUniforms: maxVertexUniforms,
  12026. maxVaryings: maxVaryings,
  12027. maxFragmentUniforms: maxFragmentUniforms,
  12028. vertexTextures: vertexTextures,
  12029. floatFragmentTextures: floatFragmentTextures,
  12030. floatVertexTextures: floatVertexTextures
  12031. };
  12032. }
  12033. /**
  12034. * @author mrdoob / http://mrdoob.com/
  12035. */
  12036. function ArrayCamera( array ) {
  12037. PerspectiveCamera.call( this );
  12038. this.cameras = array || [];
  12039. }
  12040. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  12041. constructor: ArrayCamera,
  12042. isArrayCamera: true
  12043. } );
  12044. /**
  12045. * @author mrdoob / http://mrdoob.com/
  12046. */
  12047. function WebVRManager( renderer ) {
  12048. var scope = this;
  12049. var device = null;
  12050. var frameData = null;
  12051. if ( 'VRFrameData' in window ) {
  12052. frameData = new window.VRFrameData();
  12053. }
  12054. var matrixWorldInverse = new Matrix4();
  12055. var standingMatrix = new Matrix4();
  12056. var standingMatrixInverse = new Matrix4();
  12057. var cameraL = new PerspectiveCamera();
  12058. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  12059. cameraL.layers.enable( 1 );
  12060. var cameraR = new PerspectiveCamera();
  12061. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  12062. cameraR.layers.enable( 2 );
  12063. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  12064. cameraVR.layers.enable( 1 );
  12065. cameraVR.layers.enable( 2 );
  12066. //
  12067. var currentSize, currentPixelRatio;
  12068. function onVRDisplayPresentChange() {
  12069. if ( device.isPresenting ) {
  12070. var eyeParameters = device.getEyeParameters( 'left' );
  12071. var renderWidth = eyeParameters.renderWidth;
  12072. var renderHeight = eyeParameters.renderHeight;
  12073. currentPixelRatio = renderer.getPixelRatio();
  12074. currentSize = renderer.getSize();
  12075. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  12076. } else if ( scope.enabled ) {
  12077. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  12078. }
  12079. }
  12080. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  12081. //
  12082. this.enabled = false;
  12083. this.standing = false;
  12084. this.getDevice = function () {
  12085. return device;
  12086. };
  12087. this.setDevice = function ( value ) {
  12088. if ( value !== undefined ) device = value;
  12089. };
  12090. this.getCamera = function ( camera ) {
  12091. if ( device === null ) return camera;
  12092. device.depthNear = camera.near;
  12093. device.depthFar = camera.far;
  12094. device.getFrameData( frameData );
  12095. //
  12096. var pose = frameData.pose;
  12097. if ( pose.position !== null ) {
  12098. camera.position.fromArray( pose.position );
  12099. } else {
  12100. camera.position.set( 0, 0, 0 );
  12101. }
  12102. if ( pose.orientation !== null ) {
  12103. camera.quaternion.fromArray( pose.orientation );
  12104. }
  12105. camera.updateMatrixWorld();
  12106. var stageParameters = device.stageParameters;
  12107. if ( this.standing && stageParameters ) {
  12108. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  12109. standingMatrixInverse.getInverse( standingMatrix );
  12110. camera.matrixWorld.multiply( standingMatrix );
  12111. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  12112. }
  12113. if ( device.isPresenting === false ) return camera;
  12114. //
  12115. cameraVR.matrixWorld.copy( camera.matrixWorld );
  12116. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  12117. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  12118. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  12119. if ( this.standing && stageParameters ) {
  12120. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  12121. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  12122. }
  12123. var parent = camera.parent;
  12124. if ( parent !== null ) {
  12125. matrixWorldInverse.getInverse( parent.matrixWorld );
  12126. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  12127. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  12128. }
  12129. // envMap and Mirror needs camera.matrixWorld
  12130. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  12131. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  12132. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  12133. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  12134. // HACK @mrdoob
  12135. // https://github.com/w3c/webvr/issues/203
  12136. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  12137. //
  12138. var layers = device.getLayers();
  12139. if ( layers.length ) {
  12140. var layer = layers[ 0 ];
  12141. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  12142. cameraL.bounds.fromArray( layer.leftBounds );
  12143. }
  12144. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  12145. cameraR.bounds.fromArray( layer.rightBounds );
  12146. }
  12147. }
  12148. return cameraVR;
  12149. };
  12150. this.getStandingMatrix = function () {
  12151. return standingMatrix;
  12152. };
  12153. this.submitFrame = function () {
  12154. if ( device && device.isPresenting ) device.submitFrame();
  12155. };
  12156. }
  12157. /**
  12158. * @author mrdoob / http://mrdoob.com/
  12159. */
  12160. function WebGLExtensions( gl ) {
  12161. var extensions = {};
  12162. return {
  12163. get: function ( name ) {
  12164. if ( extensions[ name ] !== undefined ) {
  12165. return extensions[ name ];
  12166. }
  12167. var extension;
  12168. switch ( name ) {
  12169. case 'WEBGL_depth_texture':
  12170. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  12171. break;
  12172. case 'EXT_texture_filter_anisotropic':
  12173. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12174. break;
  12175. case 'WEBGL_compressed_texture_s3tc':
  12176. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12177. break;
  12178. case 'WEBGL_compressed_texture_pvrtc':
  12179. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  12180. break;
  12181. case 'WEBGL_compressed_texture_etc1':
  12182. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  12183. break;
  12184. default:
  12185. extension = gl.getExtension( name );
  12186. }
  12187. if ( extension === null ) {
  12188. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  12189. }
  12190. extensions[ name ] = extension;
  12191. return extension;
  12192. }
  12193. };
  12194. }
  12195. /**
  12196. * @author tschw
  12197. */
  12198. function WebGLClipping() {
  12199. var scope = this,
  12200. globalState = null,
  12201. numGlobalPlanes = 0,
  12202. localClippingEnabled = false,
  12203. renderingShadows = false,
  12204. plane = new Plane(),
  12205. viewNormalMatrix = new Matrix3(),
  12206. uniform = { value: null, needsUpdate: false };
  12207. this.uniform = uniform;
  12208. this.numPlanes = 0;
  12209. this.numIntersection = 0;
  12210. this.init = function( planes, enableLocalClipping, camera ) {
  12211. var enabled =
  12212. planes.length !== 0 ||
  12213. enableLocalClipping ||
  12214. // enable state of previous frame - the clipping code has to
  12215. // run another frame in order to reset the state:
  12216. numGlobalPlanes !== 0 ||
  12217. localClippingEnabled;
  12218. localClippingEnabled = enableLocalClipping;
  12219. globalState = projectPlanes( planes, camera, 0 );
  12220. numGlobalPlanes = planes.length;
  12221. return enabled;
  12222. };
  12223. this.beginShadows = function() {
  12224. renderingShadows = true;
  12225. projectPlanes( null );
  12226. };
  12227. this.endShadows = function() {
  12228. renderingShadows = false;
  12229. resetGlobalState();
  12230. };
  12231. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12232. if ( ! localClippingEnabled ||
  12233. planes === null || planes.length === 0 ||
  12234. renderingShadows && ! clipShadows ) {
  12235. // there's no local clipping
  12236. if ( renderingShadows ) {
  12237. // there's no global clipping
  12238. projectPlanes( null );
  12239. } else {
  12240. resetGlobalState();
  12241. }
  12242. } else {
  12243. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12244. lGlobal = nGlobal * 4,
  12245. dstArray = cache.clippingState || null;
  12246. uniform.value = dstArray; // ensure unique state
  12247. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12248. for ( var i = 0; i !== lGlobal; ++ i ) {
  12249. dstArray[ i ] = globalState[ i ];
  12250. }
  12251. cache.clippingState = dstArray;
  12252. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12253. this.numPlanes += nGlobal;
  12254. }
  12255. };
  12256. function resetGlobalState() {
  12257. if ( uniform.value !== globalState ) {
  12258. uniform.value = globalState;
  12259. uniform.needsUpdate = numGlobalPlanes > 0;
  12260. }
  12261. scope.numPlanes = numGlobalPlanes;
  12262. scope.numIntersection = 0;
  12263. }
  12264. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12265. var nPlanes = planes !== null ? planes.length : 0,
  12266. dstArray = null;
  12267. if ( nPlanes !== 0 ) {
  12268. dstArray = uniform.value;
  12269. if ( skipTransform !== true || dstArray === null ) {
  12270. var flatSize = dstOffset + nPlanes * 4,
  12271. viewMatrix = camera.matrixWorldInverse;
  12272. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12273. if ( dstArray === null || dstArray.length < flatSize ) {
  12274. dstArray = new Float32Array( flatSize );
  12275. }
  12276. for ( var i = 0, i4 = dstOffset;
  12277. i !== nPlanes; ++ i, i4 += 4 ) {
  12278. plane.copy( planes[ i ] ).
  12279. applyMatrix4( viewMatrix, viewNormalMatrix );
  12280. plane.normal.toArray( dstArray, i4 );
  12281. dstArray[ i4 + 3 ] = plane.constant;
  12282. }
  12283. }
  12284. uniform.value = dstArray;
  12285. uniform.needsUpdate = true;
  12286. }
  12287. scope.numPlanes = nPlanes;
  12288. return dstArray;
  12289. }
  12290. }
  12291. // import { Sphere } from '../math/Sphere';
  12292. /**
  12293. * @author supereggbert / http://www.paulbrunt.co.uk/
  12294. * @author mrdoob / http://mrdoob.com/
  12295. * @author alteredq / http://alteredqualia.com/
  12296. * @author szimek / https://github.com/szimek/
  12297. * @author tschw
  12298. */
  12299. function WebGLRenderer( parameters ) {
  12300. console.log( 'THREE.WebGLRenderer', REVISION );
  12301. parameters = parameters || {};
  12302. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  12303. _context = parameters.context !== undefined ? parameters.context : null,
  12304. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12305. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12306. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12307. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12308. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12309. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  12310. var lightsArray = [];
  12311. var shadowsArray = [];
  12312. var currentRenderList = null;
  12313. var morphInfluences = new Float32Array( 8 );
  12314. var spritesArray = [];
  12315. var flaresArray = [];
  12316. // public properties
  12317. this.domElement = _canvas;
  12318. this.context = null;
  12319. // clearing
  12320. this.autoClear = true;
  12321. this.autoClearColor = true;
  12322. this.autoClearDepth = true;
  12323. this.autoClearStencil = true;
  12324. // scene graph
  12325. this.sortObjects = true;
  12326. // user-defined clipping
  12327. this.clippingPlanes = [];
  12328. this.localClippingEnabled = false;
  12329. // physically based shading
  12330. this.gammaFactor = 2.0; // for backwards compatibility
  12331. this.gammaInput = false;
  12332. this.gammaOutput = false;
  12333. // physical lights
  12334. this.physicallyCorrectLights = false;
  12335. // tone mapping
  12336. this.toneMapping = LinearToneMapping;
  12337. this.toneMappingExposure = 1.0;
  12338. this.toneMappingWhitePoint = 1.0;
  12339. // morphs
  12340. this.maxMorphTargets = 8;
  12341. this.maxMorphNormals = 4;
  12342. // internal properties
  12343. var _this = this,
  12344. _isContextLost = false,
  12345. // internal state cache
  12346. _currentRenderTarget = null,
  12347. _currentFramebuffer = null,
  12348. _currentMaterialId = - 1,
  12349. _currentGeometryProgram = '',
  12350. _currentCamera = null,
  12351. _currentArrayCamera = null,
  12352. _currentViewport = new Vector4(),
  12353. _currentScissor = new Vector4(),
  12354. _currentScissorTest = null,
  12355. //
  12356. _usedTextureUnits = 0,
  12357. //
  12358. _width = _canvas.width,
  12359. _height = _canvas.height,
  12360. _pixelRatio = 1,
  12361. _viewport = new Vector4( 0, 0, _width, _height ),
  12362. _scissor = new Vector4( 0, 0, _width, _height ),
  12363. _scissorTest = false,
  12364. // frustum
  12365. _frustum = new Frustum(),
  12366. // clipping
  12367. _clipping = new WebGLClipping(),
  12368. _clippingEnabled = false,
  12369. _localClippingEnabled = false,
  12370. // camera matrices cache
  12371. _projScreenMatrix = new Matrix4(),
  12372. _vector3 = new Vector3(),
  12373. // info
  12374. _infoMemory = {
  12375. geometries: 0,
  12376. textures: 0
  12377. },
  12378. _infoRender = {
  12379. frame: 0,
  12380. calls: 0,
  12381. vertices: 0,
  12382. faces: 0,
  12383. points: 0
  12384. };
  12385. this.info = {
  12386. render: _infoRender,
  12387. memory: _infoMemory,
  12388. programs: null
  12389. };
  12390. function getTargetPixelRatio() {
  12391. return _currentRenderTarget === null ? _pixelRatio : 1;
  12392. }
  12393. // initialize
  12394. var _gl;
  12395. try {
  12396. var contextAttributes = {
  12397. alpha: _alpha,
  12398. depth: _depth,
  12399. stencil: _stencil,
  12400. antialias: _antialias,
  12401. premultipliedAlpha: _premultipliedAlpha,
  12402. preserveDrawingBuffer: _preserveDrawingBuffer
  12403. };
  12404. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  12405. if ( _gl === null ) {
  12406. if ( _canvas.getContext( 'webgl' ) !== null ) {
  12407. throw 'Error creating WebGL context with your selected attributes.';
  12408. } else {
  12409. throw 'Error creating WebGL context.';
  12410. }
  12411. }
  12412. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  12413. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12414. _gl.getShaderPrecisionFormat = function () {
  12415. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  12416. };
  12417. }
  12418. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12419. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  12420. } catch ( error ) {
  12421. console.error( 'THREE.WebGLRenderer: ' + error );
  12422. }
  12423. var extensions, capabilities, state;
  12424. var properties, textures, attributes, geometries, objects, lights;
  12425. var programCache, renderLists;
  12426. var background, bufferRenderer, indexedBufferRenderer;
  12427. var flareRenderer, spriteRenderer;
  12428. function initGLContext() {
  12429. extensions = new WebGLExtensions( _gl );
  12430. extensions.get( 'WEBGL_depth_texture' );
  12431. extensions.get( 'OES_texture_float' );
  12432. extensions.get( 'OES_texture_float_linear' );
  12433. extensions.get( 'OES_texture_half_float' );
  12434. extensions.get( 'OES_texture_half_float_linear' );
  12435. extensions.get( 'OES_standard_derivatives' );
  12436. extensions.get( 'ANGLE_instanced_arrays' );
  12437. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12438. BufferGeometry.MaxIndex = 4294967296;
  12439. }
  12440. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  12441. state = new WebGLState( _gl, extensions, paramThreeToGL );
  12442. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12443. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12444. properties = new WebGLProperties();
  12445. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory );
  12446. attributes = new WebGLAttributes( _gl );
  12447. geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  12448. objects = new WebGLObjects( _gl, geometries, _infoRender );
  12449. programCache = new WebGLPrograms( _this, extensions, capabilities );
  12450. lights = new WebGLLights();
  12451. renderLists = new WebGLRenderLists();
  12452. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  12453. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12454. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12455. flareRenderer = new WebGLFlareRenderer( _this, _gl, state, capabilities );
  12456. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, capabilities );
  12457. _this.info.programs = programCache.programs;
  12458. _this.context = _gl;
  12459. _this.capabilities = capabilities;
  12460. _this.extensions = extensions;
  12461. _this.properties = properties;
  12462. _this.renderLists = renderLists;
  12463. _this.state = state;
  12464. }
  12465. initGLContext();
  12466. // vr
  12467. var vr = new WebVRManager( _this );
  12468. this.vr = vr;
  12469. // shadow map
  12470. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  12471. this.shadowMap = shadowMap;
  12472. // API
  12473. this.getContext = function () {
  12474. return _gl;
  12475. };
  12476. this.getContextAttributes = function () {
  12477. return _gl.getContextAttributes();
  12478. };
  12479. this.forceContextLoss = function () {
  12480. var extension = extensions.get( 'WEBGL_lose_context' );
  12481. if ( extension ) extension.loseContext();
  12482. };
  12483. this.forceContextRestore = function () {
  12484. var extension = extensions.get( 'WEBGL_lose_context' );
  12485. if ( extension ) extension.restoreContext();
  12486. };
  12487. this.getPixelRatio = function () {
  12488. return _pixelRatio;
  12489. };
  12490. this.setPixelRatio = function ( value ) {
  12491. if ( value === undefined ) return;
  12492. _pixelRatio = value;
  12493. this.setSize( _width, _height, false );
  12494. };
  12495. this.getSize = function () {
  12496. return {
  12497. width: _width,
  12498. height: _height
  12499. };
  12500. };
  12501. this.setSize = function ( width, height, updateStyle ) {
  12502. var device = vr.getDevice();
  12503. if ( device && device.isPresenting ) {
  12504. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  12505. return;
  12506. }
  12507. _width = width;
  12508. _height = height;
  12509. _canvas.width = width * _pixelRatio;
  12510. _canvas.height = height * _pixelRatio;
  12511. if ( updateStyle !== false ) {
  12512. _canvas.style.width = width + 'px';
  12513. _canvas.style.height = height + 'px';
  12514. }
  12515. this.setViewport( 0, 0, width, height );
  12516. };
  12517. this.getDrawingBufferSize = function () {
  12518. return {
  12519. width: _width * _pixelRatio,
  12520. height: _height * _pixelRatio
  12521. };
  12522. };
  12523. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  12524. _width = width;
  12525. _height = height;
  12526. _pixelRatio = pixelRatio;
  12527. _canvas.width = width * pixelRatio;
  12528. _canvas.height = height * pixelRatio;
  12529. this.setViewport( 0, 0, width, height );
  12530. };
  12531. this.setViewport = function ( x, y, width, height ) {
  12532. _viewport.set( x, _height - y - height, width, height );
  12533. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12534. };
  12535. this.setScissor = function ( x, y, width, height ) {
  12536. _scissor.set( x, _height - y - height, width, height );
  12537. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12538. };
  12539. this.setScissorTest = function ( boolean ) {
  12540. state.setScissorTest( _scissorTest = boolean );
  12541. };
  12542. // Clearing
  12543. this.getClearColor = background.getClearColor;
  12544. this.setClearColor = background.setClearColor;
  12545. this.getClearAlpha = background.getClearAlpha;
  12546. this.setClearAlpha = background.setClearAlpha;
  12547. this.clear = function ( color, depth, stencil ) {
  12548. var bits = 0;
  12549. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12550. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12551. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12552. _gl.clear( bits );
  12553. };
  12554. this.clearColor = function () {
  12555. this.clear( true, false, false );
  12556. };
  12557. this.clearDepth = function () {
  12558. this.clear( false, true, false );
  12559. };
  12560. this.clearStencil = function () {
  12561. this.clear( false, false, true );
  12562. };
  12563. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12564. this.setRenderTarget( renderTarget );
  12565. this.clear( color, depth, stencil );
  12566. };
  12567. //
  12568. this.dispose = function () {
  12569. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12570. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  12571. renderLists.dispose();
  12572. };
  12573. // Events
  12574. function onContextLost( event ) {
  12575. event.preventDefault();
  12576. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  12577. _isContextLost = true;
  12578. }
  12579. function onContextRestore( event ) {
  12580. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  12581. _isContextLost = false;
  12582. initGLContext();
  12583. }
  12584. function onMaterialDispose( event ) {
  12585. var material = event.target;
  12586. material.removeEventListener( 'dispose', onMaterialDispose );
  12587. deallocateMaterial( material );
  12588. }
  12589. // Buffer deallocation
  12590. function deallocateMaterial( material ) {
  12591. releaseMaterialProgramReference( material );
  12592. properties.remove( material );
  12593. }
  12594. function releaseMaterialProgramReference( material ) {
  12595. var programInfo = properties.get( material ).program;
  12596. material.program = undefined;
  12597. if ( programInfo !== undefined ) {
  12598. programCache.releaseProgram( programInfo );
  12599. }
  12600. }
  12601. // Buffer rendering
  12602. function renderObjectImmediate( object, program, material ) {
  12603. object.render( function ( object ) {
  12604. _this.renderBufferImmediate( object, program, material );
  12605. } );
  12606. }
  12607. this.renderBufferImmediate = function ( object, program, material ) {
  12608. state.initAttributes();
  12609. var buffers = properties.get( object );
  12610. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12611. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12612. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12613. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12614. var programAttributes = program.getAttributes();
  12615. if ( object.hasPositions ) {
  12616. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12617. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12618. state.enableAttribute( programAttributes.position );
  12619. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12620. }
  12621. if ( object.hasNormals ) {
  12622. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12623. if ( ! material.isMeshPhongMaterial &&
  12624. ! material.isMeshStandardMaterial &&
  12625. ! material.isMeshNormalMaterial &&
  12626. material.flatShading === true ) {
  12627. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12628. var array = object.normalArray;
  12629. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12630. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12631. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12632. array[ i + 0 ] = nx;
  12633. array[ i + 1 ] = ny;
  12634. array[ i + 2 ] = nz;
  12635. array[ i + 3 ] = nx;
  12636. array[ i + 4 ] = ny;
  12637. array[ i + 5 ] = nz;
  12638. array[ i + 6 ] = nx;
  12639. array[ i + 7 ] = ny;
  12640. array[ i + 8 ] = nz;
  12641. }
  12642. }
  12643. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12644. state.enableAttribute( programAttributes.normal );
  12645. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12646. }
  12647. if ( object.hasUvs && material.map ) {
  12648. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12649. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12650. state.enableAttribute( programAttributes.uv );
  12651. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12652. }
  12653. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12654. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12655. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12656. state.enableAttribute( programAttributes.color );
  12657. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12658. }
  12659. state.disableUnusedAttributes();
  12660. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12661. object.count = 0;
  12662. };
  12663. function absNumericalSort( a, b ) {
  12664. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12665. }
  12666. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12667. state.setMaterial( material );
  12668. var program = setProgram( camera, fog, material, object );
  12669. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12670. var updateBuffers = false;
  12671. if ( geometryProgram !== _currentGeometryProgram ) {
  12672. _currentGeometryProgram = geometryProgram;
  12673. updateBuffers = true;
  12674. }
  12675. // morph targets
  12676. var morphTargetInfluences = object.morphTargetInfluences;
  12677. if ( morphTargetInfluences !== undefined ) {
  12678. // TODO Remove allocations
  12679. var activeInfluences = [];
  12680. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12681. var influence = morphTargetInfluences[ i ];
  12682. activeInfluences.push( [ influence, i ] );
  12683. }
  12684. activeInfluences.sort( absNumericalSort );
  12685. if ( activeInfluences.length > 8 ) {
  12686. activeInfluences.length = 8;
  12687. }
  12688. var morphAttributes = geometry.morphAttributes;
  12689. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12690. var influence = activeInfluences[ i ];
  12691. morphInfluences[ i ] = influence[ 0 ];
  12692. if ( influence[ 0 ] !== 0 ) {
  12693. var index = influence[ 1 ];
  12694. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12695. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12696. } else {
  12697. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12698. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12699. }
  12700. }
  12701. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12702. morphInfluences[ i ] = 0.0;
  12703. }
  12704. program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences );
  12705. updateBuffers = true;
  12706. }
  12707. //
  12708. var index = geometry.index;
  12709. var position = geometry.attributes.position;
  12710. var rangeFactor = 1;
  12711. if ( material.wireframe === true ) {
  12712. index = geometries.getWireframeAttribute( geometry );
  12713. rangeFactor = 2;
  12714. }
  12715. var attribute;
  12716. var renderer = bufferRenderer;
  12717. if ( index !== null ) {
  12718. attribute = attributes.get( index );
  12719. renderer = indexedBufferRenderer;
  12720. renderer.setIndex( attribute );
  12721. }
  12722. if ( updateBuffers ) {
  12723. setupVertexAttributes( material, program, geometry );
  12724. if ( index !== null ) {
  12725. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  12726. }
  12727. }
  12728. //
  12729. var dataCount = 0;
  12730. if ( index !== null ) {
  12731. dataCount = index.count;
  12732. } else if ( position !== undefined ) {
  12733. dataCount = position.count;
  12734. }
  12735. var rangeStart = geometry.drawRange.start * rangeFactor;
  12736. var rangeCount = geometry.drawRange.count * rangeFactor;
  12737. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12738. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12739. var drawStart = Math.max( rangeStart, groupStart );
  12740. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12741. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12742. if ( drawCount === 0 ) return;
  12743. //
  12744. if ( object.isMesh ) {
  12745. if ( material.wireframe === true ) {
  12746. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12747. renderer.setMode( _gl.LINES );
  12748. } else {
  12749. switch ( object.drawMode ) {
  12750. case TrianglesDrawMode:
  12751. renderer.setMode( _gl.TRIANGLES );
  12752. break;
  12753. case TriangleStripDrawMode:
  12754. renderer.setMode( _gl.TRIANGLE_STRIP );
  12755. break;
  12756. case TriangleFanDrawMode:
  12757. renderer.setMode( _gl.TRIANGLE_FAN );
  12758. break;
  12759. }
  12760. }
  12761. } else if ( object.isLine ) {
  12762. var lineWidth = material.linewidth;
  12763. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12764. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12765. if ( object.isLineSegments ) {
  12766. renderer.setMode( _gl.LINES );
  12767. } else if ( object.isLineLoop ) {
  12768. renderer.setMode( _gl.LINE_LOOP );
  12769. } else {
  12770. renderer.setMode( _gl.LINE_STRIP );
  12771. }
  12772. } else if ( object.isPoints ) {
  12773. renderer.setMode( _gl.POINTS );
  12774. }
  12775. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12776. if ( geometry.maxInstancedCount > 0 ) {
  12777. renderer.renderInstances( geometry, drawStart, drawCount );
  12778. }
  12779. } else {
  12780. renderer.render( drawStart, drawCount );
  12781. }
  12782. };
  12783. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12784. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12785. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12786. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12787. return;
  12788. }
  12789. }
  12790. if ( startIndex === undefined ) startIndex = 0;
  12791. state.initAttributes();
  12792. var geometryAttributes = geometry.attributes;
  12793. var programAttributes = program.getAttributes();
  12794. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12795. for ( var name in programAttributes ) {
  12796. var programAttribute = programAttributes[ name ];
  12797. if ( programAttribute >= 0 ) {
  12798. var geometryAttribute = geometryAttributes[ name ];
  12799. if ( geometryAttribute !== undefined ) {
  12800. var normalized = geometryAttribute.normalized;
  12801. var size = geometryAttribute.itemSize;
  12802. var attribute = attributes.get( geometryAttribute );
  12803. // TODO Attribute may not be available on context restore
  12804. if ( attribute === undefined ) continue;
  12805. var buffer = attribute.buffer;
  12806. var type = attribute.type;
  12807. var bytesPerElement = attribute.bytesPerElement;
  12808. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12809. var data = geometryAttribute.data;
  12810. var stride = data.stride;
  12811. var offset = geometryAttribute.offset;
  12812. if ( data && data.isInstancedInterleavedBuffer ) {
  12813. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12814. if ( geometry.maxInstancedCount === undefined ) {
  12815. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12816. }
  12817. } else {
  12818. state.enableAttribute( programAttribute );
  12819. }
  12820. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12821. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12822. } else {
  12823. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12824. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12825. if ( geometry.maxInstancedCount === undefined ) {
  12826. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12827. }
  12828. } else {
  12829. state.enableAttribute( programAttribute );
  12830. }
  12831. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12832. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12833. }
  12834. } else if ( materialDefaultAttributeValues !== undefined ) {
  12835. var value = materialDefaultAttributeValues[ name ];
  12836. if ( value !== undefined ) {
  12837. switch ( value.length ) {
  12838. case 2:
  12839. _gl.vertexAttrib2fv( programAttribute, value );
  12840. break;
  12841. case 3:
  12842. _gl.vertexAttrib3fv( programAttribute, value );
  12843. break;
  12844. case 4:
  12845. _gl.vertexAttrib4fv( programAttribute, value );
  12846. break;
  12847. default:
  12848. _gl.vertexAttrib1fv( programAttribute, value );
  12849. }
  12850. }
  12851. }
  12852. }
  12853. }
  12854. state.disableUnusedAttributes();
  12855. }
  12856. // Compile
  12857. this.compile = function ( scene, camera ) {
  12858. lightsArray.length = 0;
  12859. shadowsArray.length = 0;
  12860. scene.traverse( function ( object ) {
  12861. if ( object.isLight ) {
  12862. lightsArray.push( object );
  12863. if ( object.castShadow ) {
  12864. shadowsArray.push( object );
  12865. }
  12866. }
  12867. } );
  12868. lights.setup( lightsArray, shadowsArray, camera );
  12869. scene.traverse( function ( object ) {
  12870. if ( object.material ) {
  12871. if ( Array.isArray( object.material ) ) {
  12872. for ( var i = 0; i < object.material.length; i ++ ) {
  12873. initMaterial( object.material[ i ], scene.fog, object );
  12874. }
  12875. } else {
  12876. initMaterial( object.material, scene.fog, object );
  12877. }
  12878. }
  12879. } );
  12880. };
  12881. // Rendering
  12882. this.animate = function ( callback ) {
  12883. function onFrame() {
  12884. callback();
  12885. ( vr.getDevice() || window ).requestAnimationFrame( onFrame );
  12886. }
  12887. ( vr.getDevice() || window ).requestAnimationFrame( onFrame );
  12888. };
  12889. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12890. if ( ! ( camera && camera.isCamera ) ) {
  12891. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12892. return;
  12893. }
  12894. if ( _isContextLost ) return;
  12895. // reset caching for this frame
  12896. _currentGeometryProgram = '';
  12897. _currentMaterialId = - 1;
  12898. _currentCamera = null;
  12899. // update scene graph
  12900. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12901. // update camera matrices and frustum
  12902. if ( camera.parent === null ) camera.updateMatrixWorld();
  12903. if ( vr.enabled ) {
  12904. camera = vr.getCamera( camera );
  12905. }
  12906. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12907. _frustum.setFromMatrix( _projScreenMatrix );
  12908. lightsArray.length = 0;
  12909. shadowsArray.length = 0;
  12910. spritesArray.length = 0;
  12911. flaresArray.length = 0;
  12912. _localClippingEnabled = this.localClippingEnabled;
  12913. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12914. currentRenderList = renderLists.get( scene, camera );
  12915. currentRenderList.init();
  12916. projectObject( scene, camera, _this.sortObjects );
  12917. currentRenderList.finish();
  12918. if ( _this.sortObjects === true ) {
  12919. currentRenderList.sort();
  12920. }
  12921. //
  12922. if ( _clippingEnabled ) _clipping.beginShadows();
  12923. shadowMap.render( shadowsArray, scene, camera );
  12924. lights.setup( lightsArray, shadowsArray, camera );
  12925. if ( _clippingEnabled ) _clipping.endShadows();
  12926. //
  12927. _infoRender.frame ++;
  12928. _infoRender.calls = 0;
  12929. _infoRender.vertices = 0;
  12930. _infoRender.faces = 0;
  12931. _infoRender.points = 0;
  12932. if ( renderTarget === undefined ) {
  12933. renderTarget = null;
  12934. }
  12935. this.setRenderTarget( renderTarget );
  12936. //
  12937. background.render( scene, camera, forceClear );
  12938. // render scene
  12939. var opaqueObjects = currentRenderList.opaque;
  12940. var transparentObjects = currentRenderList.transparent;
  12941. if ( scene.overrideMaterial ) {
  12942. var overrideMaterial = scene.overrideMaterial;
  12943. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12944. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12945. } else {
  12946. // opaque pass (front-to-back order)
  12947. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  12948. // transparent pass (back-to-front order)
  12949. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  12950. }
  12951. // custom renderers
  12952. spriteRenderer.render( spritesArray, scene, camera );
  12953. flareRenderer.render( flaresArray, scene, camera, _currentViewport );
  12954. // Generate mipmap if we're using any kind of mipmap filtering
  12955. if ( renderTarget ) {
  12956. textures.updateRenderTargetMipmap( renderTarget );
  12957. }
  12958. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12959. state.buffers.depth.setTest( true );
  12960. state.buffers.depth.setMask( true );
  12961. state.buffers.color.setMask( true );
  12962. if ( vr.enabled ) {
  12963. vr.submitFrame();
  12964. }
  12965. // _gl.finish();
  12966. };
  12967. /*
  12968. // TODO Duplicated code (Frustum)
  12969. var _sphere = new Sphere();
  12970. function isObjectViewable( object ) {
  12971. var geometry = object.geometry;
  12972. if ( geometry.boundingSphere === null )
  12973. geometry.computeBoundingSphere();
  12974. _sphere.copy( geometry.boundingSphere ).
  12975. applyMatrix4( object.matrixWorld );
  12976. return isSphereViewable( _sphere );
  12977. }
  12978. function isSpriteViewable( sprite ) {
  12979. _sphere.center.set( 0, 0, 0 );
  12980. _sphere.radius = 0.7071067811865476;
  12981. _sphere.applyMatrix4( sprite.matrixWorld );
  12982. return isSphereViewable( _sphere );
  12983. }
  12984. function isSphereViewable( sphere ) {
  12985. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12986. var numPlanes = _clipping.numPlanes;
  12987. if ( numPlanes === 0 ) return true;
  12988. var planes = _this.clippingPlanes,
  12989. center = sphere.center,
  12990. negRad = - sphere.radius,
  12991. i = 0;
  12992. do {
  12993. // out when deeper than radius in the negative halfspace
  12994. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12995. } while ( ++ i !== numPlanes );
  12996. return true;
  12997. }
  12998. */
  12999. function projectObject( object, camera, sortObjects ) {
  13000. if ( ! object.visible ) return;
  13001. var visible = object.layers.test( camera.layers );
  13002. if ( visible ) {
  13003. if ( object.isLight ) {
  13004. lightsArray.push( object );
  13005. if ( object.castShadow ) {
  13006. shadowsArray.push( object );
  13007. }
  13008. } else if ( object.isSprite ) {
  13009. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  13010. spritesArray.push( object );
  13011. }
  13012. } else if ( object.isLensFlare ) {
  13013. flaresArray.push( object );
  13014. } else if ( object.isImmediateRenderObject ) {
  13015. if ( sortObjects ) {
  13016. _vector3.setFromMatrixPosition( object.matrixWorld )
  13017. .applyMatrix4( _projScreenMatrix );
  13018. }
  13019. currentRenderList.push( object, null, object.material, _vector3.z, null );
  13020. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  13021. if ( object.isSkinnedMesh ) {
  13022. object.skeleton.update();
  13023. }
  13024. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  13025. if ( sortObjects ) {
  13026. _vector3.setFromMatrixPosition( object.matrixWorld )
  13027. .applyMatrix4( _projScreenMatrix );
  13028. }
  13029. var geometry = objects.update( object );
  13030. var material = object.material;
  13031. if ( Array.isArray( material ) ) {
  13032. var groups = geometry.groups;
  13033. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  13034. var group = groups[ i ];
  13035. var groupMaterial = material[ group.materialIndex ];
  13036. if ( groupMaterial && groupMaterial.visible ) {
  13037. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  13038. }
  13039. }
  13040. } else if ( material.visible ) {
  13041. currentRenderList.push( object, geometry, material, _vector3.z, null );
  13042. }
  13043. }
  13044. }
  13045. }
  13046. var children = object.children;
  13047. for ( var i = 0, l = children.length; i < l; i ++ ) {
  13048. projectObject( children[ i ], camera, sortObjects );
  13049. }
  13050. }
  13051. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  13052. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  13053. var renderItem = renderList[ i ];
  13054. var object = renderItem.object;
  13055. var geometry = renderItem.geometry;
  13056. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  13057. var group = renderItem.group;
  13058. if ( camera.isArrayCamera ) {
  13059. _currentArrayCamera = camera;
  13060. var cameras = camera.cameras;
  13061. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  13062. var camera2 = cameras[ j ];
  13063. if ( object.layers.test( camera2.layers ) ) {
  13064. var bounds = camera2.bounds;
  13065. var x = bounds.x * _width;
  13066. var y = bounds.y * _height;
  13067. var width = bounds.z * _width;
  13068. var height = bounds.w * _height;
  13069. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  13070. state.scissor( _currentScissor.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  13071. state.setScissorTest( true );
  13072. renderObject( object, scene, camera2, geometry, material, group );
  13073. }
  13074. }
  13075. } else {
  13076. _currentArrayCamera = null;
  13077. renderObject( object, scene, camera, geometry, material, group );
  13078. }
  13079. }
  13080. }
  13081. function renderObject( object, scene, camera, geometry, material, group ) {
  13082. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  13083. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13084. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  13085. if ( object.isImmediateRenderObject ) {
  13086. state.setMaterial( material );
  13087. var program = setProgram( camera, scene.fog, material, object );
  13088. _currentGeometryProgram = '';
  13089. renderObjectImmediate( object, program, material );
  13090. } else {
  13091. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  13092. }
  13093. object.onAfterRender( _this, scene, camera, geometry, material, group );
  13094. }
  13095. function initMaterial( material, fog, object ) {
  13096. var materialProperties = properties.get( material );
  13097. var parameters = programCache.getParameters(
  13098. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  13099. var code = programCache.getProgramCode( material, parameters );
  13100. var program = materialProperties.program;
  13101. var programChange = true;
  13102. if ( program === undefined ) {
  13103. // new material
  13104. material.addEventListener( 'dispose', onMaterialDispose );
  13105. } else if ( program.code !== code ) {
  13106. // changed glsl or parameters
  13107. releaseMaterialProgramReference( material );
  13108. } else if ( parameters.shaderID !== undefined ) {
  13109. // same glsl and uniform list
  13110. return;
  13111. } else {
  13112. // only rebuild uniform list
  13113. programChange = false;
  13114. }
  13115. if ( programChange ) {
  13116. if ( parameters.shaderID ) {
  13117. var shader = ShaderLib[ parameters.shaderID ];
  13118. materialProperties.shader = {
  13119. name: material.type,
  13120. uniforms: UniformsUtils.clone( shader.uniforms ),
  13121. vertexShader: shader.vertexShader,
  13122. fragmentShader: shader.fragmentShader
  13123. };
  13124. } else {
  13125. materialProperties.shader = {
  13126. name: material.type,
  13127. uniforms: material.uniforms,
  13128. vertexShader: material.vertexShader,
  13129. fragmentShader: material.fragmentShader
  13130. };
  13131. }
  13132. material.onBeforeCompile( materialProperties.shader );
  13133. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  13134. materialProperties.program = program;
  13135. material.program = program;
  13136. }
  13137. var programAttributes = program.getAttributes();
  13138. if ( material.morphTargets ) {
  13139. material.numSupportedMorphTargets = 0;
  13140. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13141. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  13142. material.numSupportedMorphTargets ++;
  13143. }
  13144. }
  13145. }
  13146. if ( material.morphNormals ) {
  13147. material.numSupportedMorphNormals = 0;
  13148. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  13149. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  13150. material.numSupportedMorphNormals ++;
  13151. }
  13152. }
  13153. }
  13154. var uniforms = materialProperties.shader.uniforms;
  13155. if ( ! material.isShaderMaterial &&
  13156. ! material.isRawShaderMaterial ||
  13157. material.clipping === true ) {
  13158. materialProperties.numClippingPlanes = _clipping.numPlanes;
  13159. materialProperties.numIntersection = _clipping.numIntersection;
  13160. uniforms.clippingPlanes = _clipping.uniform;
  13161. }
  13162. materialProperties.fog = fog;
  13163. // store the light setup it was created for
  13164. materialProperties.lightsHash = lights.state.hash;
  13165. if ( material.lights ) {
  13166. // wire up the material to this renderer's lighting state
  13167. uniforms.ambientLightColor.value = lights.state.ambient;
  13168. uniforms.directionalLights.value = lights.state.directional;
  13169. uniforms.spotLights.value = lights.state.spot;
  13170. uniforms.rectAreaLights.value = lights.state.rectArea;
  13171. uniforms.pointLights.value = lights.state.point;
  13172. uniforms.hemisphereLights.value = lights.state.hemi;
  13173. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  13174. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  13175. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  13176. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  13177. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  13178. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  13179. // TODO (abelnation): add area lights shadow info to uniforms
  13180. }
  13181. var progUniforms = materialProperties.program.getUniforms(),
  13182. uniformsList =
  13183. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  13184. materialProperties.uniformsList = uniformsList;
  13185. }
  13186. function setProgram( camera, fog, material, object ) {
  13187. _usedTextureUnits = 0;
  13188. var materialProperties = properties.get( material );
  13189. if ( _clippingEnabled ) {
  13190. if ( _localClippingEnabled || camera !== _currentCamera ) {
  13191. var useCache =
  13192. camera === _currentCamera &&
  13193. material.id === _currentMaterialId;
  13194. // we might want to call this function with some ClippingGroup
  13195. // object instead of the material, once it becomes feasible
  13196. // (#8465, #8379)
  13197. _clipping.setState(
  13198. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  13199. camera, materialProperties, useCache );
  13200. }
  13201. }
  13202. if ( material.needsUpdate === false ) {
  13203. if ( materialProperties.program === undefined ) {
  13204. material.needsUpdate = true;
  13205. } else if ( material.fog && materialProperties.fog !== fog ) {
  13206. material.needsUpdate = true;
  13207. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  13208. material.needsUpdate = true;
  13209. } else if ( materialProperties.numClippingPlanes !== undefined &&
  13210. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  13211. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  13212. material.needsUpdate = true;
  13213. }
  13214. }
  13215. if ( material.needsUpdate ) {
  13216. initMaterial( material, fog, object );
  13217. material.needsUpdate = false;
  13218. }
  13219. var refreshProgram = false;
  13220. var refreshMaterial = false;
  13221. var refreshLights = false;
  13222. var program = materialProperties.program,
  13223. p_uniforms = program.getUniforms(),
  13224. m_uniforms = materialProperties.shader.uniforms;
  13225. if ( state.useProgram( program.program ) ) {
  13226. refreshProgram = true;
  13227. refreshMaterial = true;
  13228. refreshLights = true;
  13229. }
  13230. if ( material.id !== _currentMaterialId ) {
  13231. _currentMaterialId = material.id;
  13232. refreshMaterial = true;
  13233. }
  13234. if ( refreshProgram || camera !== _currentCamera ) {
  13235. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  13236. if ( capabilities.logarithmicDepthBuffer ) {
  13237. p_uniforms.setValue( _gl, 'logDepthBufFC',
  13238. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13239. }
  13240. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  13241. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  13242. _currentCamera = ( _currentArrayCamera || camera );
  13243. // lighting uniforms depend on the camera so enforce an update
  13244. // now, in case this material supports lights - or later, when
  13245. // the next material that does gets activated:
  13246. refreshMaterial = true; // set to true on material change
  13247. refreshLights = true; // remains set until update done
  13248. }
  13249. // load material specific uniforms
  13250. // (shader material also gets them for the sake of genericity)
  13251. if ( material.isShaderMaterial ||
  13252. material.isMeshPhongMaterial ||
  13253. material.isMeshStandardMaterial ||
  13254. material.envMap ) {
  13255. var uCamPos = p_uniforms.map.cameraPosition;
  13256. if ( uCamPos !== undefined ) {
  13257. uCamPos.setValue( _gl,
  13258. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  13259. }
  13260. }
  13261. if ( material.isMeshPhongMaterial ||
  13262. material.isMeshLambertMaterial ||
  13263. material.isMeshBasicMaterial ||
  13264. material.isMeshStandardMaterial ||
  13265. material.isShaderMaterial ||
  13266. material.skinning ) {
  13267. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  13268. }
  13269. }
  13270. // skinning uniforms must be set even if material didn't change
  13271. // auto-setting of texture unit for bone texture must go before other textures
  13272. // not sure why, but otherwise weird things happen
  13273. if ( material.skinning ) {
  13274. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  13275. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  13276. var skeleton = object.skeleton;
  13277. if ( skeleton ) {
  13278. var bones = skeleton.bones;
  13279. if ( capabilities.floatVertexTextures ) {
  13280. if ( skeleton.boneTexture === undefined ) {
  13281. // layout (1 matrix = 4 pixels)
  13282. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13283. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13284. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13285. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13286. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13287. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  13288. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13289. size = Math.max( size, 4 );
  13290. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  13291. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  13292. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  13293. skeleton.boneMatrices = boneMatrices;
  13294. skeleton.boneTexture = boneTexture;
  13295. skeleton.boneTextureSize = size;
  13296. }
  13297. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  13298. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  13299. } else {
  13300. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  13301. }
  13302. }
  13303. }
  13304. if ( refreshMaterial ) {
  13305. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  13306. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  13307. if ( material.lights ) {
  13308. // the current material requires lighting info
  13309. // note: all lighting uniforms are always set correctly
  13310. // they simply reference the renderer's state for their
  13311. // values
  13312. //
  13313. // use the current material's .needsUpdate flags to set
  13314. // the GL state when required
  13315. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  13316. }
  13317. // refresh uniforms common to several materials
  13318. if ( fog && material.fog ) {
  13319. refreshUniformsFog( m_uniforms, fog );
  13320. }
  13321. if ( material.isMeshBasicMaterial ||
  13322. material.isMeshLambertMaterial ||
  13323. material.isMeshPhongMaterial ||
  13324. material.isMeshStandardMaterial ||
  13325. material.isMeshNormalMaterial ||
  13326. material.isMeshDepthMaterial ||
  13327. material.isMeshDistanceMaterial ) {
  13328. refreshUniformsCommon( m_uniforms, material );
  13329. }
  13330. // refresh single material specific uniforms
  13331. if ( material.isLineBasicMaterial ) {
  13332. refreshUniformsLine( m_uniforms, material );
  13333. } else if ( material.isLineDashedMaterial ) {
  13334. refreshUniformsLine( m_uniforms, material );
  13335. refreshUniformsDash( m_uniforms, material );
  13336. } else if ( material.isPointsMaterial ) {
  13337. refreshUniformsPoints( m_uniforms, material );
  13338. } else if ( material.isMeshLambertMaterial ) {
  13339. refreshUniformsLambert( m_uniforms, material );
  13340. } else if ( material.isMeshToonMaterial ) {
  13341. refreshUniformsToon( m_uniforms, material );
  13342. } else if ( material.isMeshPhongMaterial ) {
  13343. refreshUniformsPhong( m_uniforms, material );
  13344. } else if ( material.isMeshPhysicalMaterial ) {
  13345. refreshUniformsPhysical( m_uniforms, material );
  13346. } else if ( material.isMeshStandardMaterial ) {
  13347. refreshUniformsStandard( m_uniforms, material );
  13348. } else if ( material.isMeshDepthMaterial ) {
  13349. refreshUniformsDepth( m_uniforms, material );
  13350. } else if ( material.isMeshDistanceMaterial ) {
  13351. refreshUniformsDistance( m_uniforms, material );
  13352. } else if ( material.isMeshNormalMaterial ) {
  13353. refreshUniformsNormal( m_uniforms, material );
  13354. }
  13355. // RectAreaLight Texture
  13356. // TODO (mrdoob): Find a nicer implementation
  13357. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  13358. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  13359. WebGLUniforms.upload(
  13360. _gl, materialProperties.uniformsList, m_uniforms, _this );
  13361. }
  13362. // common matrices
  13363. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  13364. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  13365. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  13366. return program;
  13367. }
  13368. // Uniforms (refresh uniforms objects)
  13369. function refreshUniformsCommon( uniforms, material ) {
  13370. uniforms.opacity.value = material.opacity;
  13371. uniforms.diffuse.value = material.color;
  13372. if ( material.emissive ) {
  13373. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13374. }
  13375. uniforms.map.value = material.map;
  13376. uniforms.specularMap.value = material.specularMap;
  13377. uniforms.alphaMap.value = material.alphaMap;
  13378. if ( material.lightMap ) {
  13379. uniforms.lightMap.value = material.lightMap;
  13380. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13381. }
  13382. if ( material.aoMap ) {
  13383. uniforms.aoMap.value = material.aoMap;
  13384. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13385. }
  13386. // uv repeat and offset setting priorities
  13387. // 1. color map
  13388. // 2. specular map
  13389. // 3. normal map
  13390. // 4. bump map
  13391. // 5. alpha map
  13392. // 6. emissive map
  13393. var uvScaleMap;
  13394. if ( material.map ) {
  13395. uvScaleMap = material.map;
  13396. } else if ( material.specularMap ) {
  13397. uvScaleMap = material.specularMap;
  13398. } else if ( material.displacementMap ) {
  13399. uvScaleMap = material.displacementMap;
  13400. } else if ( material.normalMap ) {
  13401. uvScaleMap = material.normalMap;
  13402. } else if ( material.bumpMap ) {
  13403. uvScaleMap = material.bumpMap;
  13404. } else if ( material.roughnessMap ) {
  13405. uvScaleMap = material.roughnessMap;
  13406. } else if ( material.metalnessMap ) {
  13407. uvScaleMap = material.metalnessMap;
  13408. } else if ( material.alphaMap ) {
  13409. uvScaleMap = material.alphaMap;
  13410. } else if ( material.emissiveMap ) {
  13411. uvScaleMap = material.emissiveMap;
  13412. }
  13413. if ( uvScaleMap !== undefined ) {
  13414. // backwards compatibility
  13415. if ( uvScaleMap.isWebGLRenderTarget ) {
  13416. uvScaleMap = uvScaleMap.texture;
  13417. }
  13418. var offset = uvScaleMap.offset;
  13419. var repeat = uvScaleMap.repeat;
  13420. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13421. }
  13422. uniforms.envMap.value = material.envMap;
  13423. // don't flip CubeTexture envMaps, flip everything else:
  13424. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13425. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13426. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13427. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13428. uniforms.reflectivity.value = material.reflectivity;
  13429. uniforms.refractionRatio.value = material.refractionRatio;
  13430. }
  13431. function refreshUniformsLine( uniforms, material ) {
  13432. uniforms.diffuse.value = material.color;
  13433. uniforms.opacity.value = material.opacity;
  13434. }
  13435. function refreshUniformsDash( uniforms, material ) {
  13436. uniforms.dashSize.value = material.dashSize;
  13437. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13438. uniforms.scale.value = material.scale;
  13439. }
  13440. function refreshUniformsPoints( uniforms, material ) {
  13441. uniforms.diffuse.value = material.color;
  13442. uniforms.opacity.value = material.opacity;
  13443. uniforms.size.value = material.size * _pixelRatio;
  13444. uniforms.scale.value = _height * 0.5;
  13445. uniforms.map.value = material.map;
  13446. if ( material.map !== null ) {
  13447. var offset = material.map.offset;
  13448. var repeat = material.map.repeat;
  13449. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13450. }
  13451. }
  13452. function refreshUniformsFog( uniforms, fog ) {
  13453. uniforms.fogColor.value = fog.color;
  13454. if ( fog.isFog ) {
  13455. uniforms.fogNear.value = fog.near;
  13456. uniforms.fogFar.value = fog.far;
  13457. } else if ( fog.isFogExp2 ) {
  13458. uniforms.fogDensity.value = fog.density;
  13459. }
  13460. }
  13461. function refreshUniformsLambert( uniforms, material ) {
  13462. if ( material.emissiveMap ) {
  13463. uniforms.emissiveMap.value = material.emissiveMap;
  13464. }
  13465. }
  13466. function refreshUniformsPhong( uniforms, material ) {
  13467. uniforms.specular.value = material.specular;
  13468. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13469. if ( material.emissiveMap ) {
  13470. uniforms.emissiveMap.value = material.emissiveMap;
  13471. }
  13472. if ( material.bumpMap ) {
  13473. uniforms.bumpMap.value = material.bumpMap;
  13474. uniforms.bumpScale.value = material.bumpScale;
  13475. }
  13476. if ( material.normalMap ) {
  13477. uniforms.normalMap.value = material.normalMap;
  13478. uniforms.normalScale.value.copy( material.normalScale );
  13479. }
  13480. if ( material.displacementMap ) {
  13481. uniforms.displacementMap.value = material.displacementMap;
  13482. uniforms.displacementScale.value = material.displacementScale;
  13483. uniforms.displacementBias.value = material.displacementBias;
  13484. }
  13485. }
  13486. function refreshUniformsToon( uniforms, material ) {
  13487. refreshUniformsPhong( uniforms, material );
  13488. if ( material.gradientMap ) {
  13489. uniforms.gradientMap.value = material.gradientMap;
  13490. }
  13491. }
  13492. function refreshUniformsStandard( uniforms, material ) {
  13493. uniforms.roughness.value = material.roughness;
  13494. uniforms.metalness.value = material.metalness;
  13495. if ( material.roughnessMap ) {
  13496. uniforms.roughnessMap.value = material.roughnessMap;
  13497. }
  13498. if ( material.metalnessMap ) {
  13499. uniforms.metalnessMap.value = material.metalnessMap;
  13500. }
  13501. if ( material.emissiveMap ) {
  13502. uniforms.emissiveMap.value = material.emissiveMap;
  13503. }
  13504. if ( material.bumpMap ) {
  13505. uniforms.bumpMap.value = material.bumpMap;
  13506. uniforms.bumpScale.value = material.bumpScale;
  13507. }
  13508. if ( material.normalMap ) {
  13509. uniforms.normalMap.value = material.normalMap;
  13510. uniforms.normalScale.value.copy( material.normalScale );
  13511. }
  13512. if ( material.displacementMap ) {
  13513. uniforms.displacementMap.value = material.displacementMap;
  13514. uniforms.displacementScale.value = material.displacementScale;
  13515. uniforms.displacementBias.value = material.displacementBias;
  13516. }
  13517. if ( material.envMap ) {
  13518. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13519. uniforms.envMapIntensity.value = material.envMapIntensity;
  13520. }
  13521. }
  13522. function refreshUniformsPhysical( uniforms, material ) {
  13523. uniforms.clearCoat.value = material.clearCoat;
  13524. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13525. refreshUniformsStandard( uniforms, material );
  13526. }
  13527. function refreshUniformsDepth( uniforms, material ) {
  13528. if ( material.displacementMap ) {
  13529. uniforms.displacementMap.value = material.displacementMap;
  13530. uniforms.displacementScale.value = material.displacementScale;
  13531. uniforms.displacementBias.value = material.displacementBias;
  13532. }
  13533. }
  13534. function refreshUniformsDistance( uniforms, material ) {
  13535. if ( material.displacementMap ) {
  13536. uniforms.displacementMap.value = material.displacementMap;
  13537. uniforms.displacementScale.value = material.displacementScale;
  13538. uniforms.displacementBias.value = material.displacementBias;
  13539. }
  13540. uniforms.referencePosition.value.copy( material.referencePosition );
  13541. uniforms.nearDistance.value = material.nearDistance;
  13542. uniforms.farDistance.value = material.farDistance;
  13543. }
  13544. function refreshUniformsNormal( uniforms, material ) {
  13545. if ( material.bumpMap ) {
  13546. uniforms.bumpMap.value = material.bumpMap;
  13547. uniforms.bumpScale.value = material.bumpScale;
  13548. }
  13549. if ( material.normalMap ) {
  13550. uniforms.normalMap.value = material.normalMap;
  13551. uniforms.normalScale.value.copy( material.normalScale );
  13552. }
  13553. if ( material.displacementMap ) {
  13554. uniforms.displacementMap.value = material.displacementMap;
  13555. uniforms.displacementScale.value = material.displacementScale;
  13556. uniforms.displacementBias.value = material.displacementBias;
  13557. }
  13558. }
  13559. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13560. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13561. uniforms.ambientLightColor.needsUpdate = value;
  13562. uniforms.directionalLights.needsUpdate = value;
  13563. uniforms.pointLights.needsUpdate = value;
  13564. uniforms.spotLights.needsUpdate = value;
  13565. uniforms.rectAreaLights.needsUpdate = value;
  13566. uniforms.hemisphereLights.needsUpdate = value;
  13567. }
  13568. // GL state setting
  13569. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13570. state.setCullFace( cullFace );
  13571. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13572. };
  13573. // Textures
  13574. function allocTextureUnit() {
  13575. var textureUnit = _usedTextureUnits;
  13576. if ( textureUnit >= capabilities.maxTextures ) {
  13577. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13578. }
  13579. _usedTextureUnits += 1;
  13580. return textureUnit;
  13581. }
  13582. this.allocTextureUnit = allocTextureUnit;
  13583. // this.setTexture2D = setTexture2D;
  13584. this.setTexture2D = ( function () {
  13585. var warned = false;
  13586. // backwards compatibility: peel texture.texture
  13587. return function setTexture2D( texture, slot ) {
  13588. if ( texture && texture.isWebGLRenderTarget ) {
  13589. if ( ! warned ) {
  13590. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13591. warned = true;
  13592. }
  13593. texture = texture.texture;
  13594. }
  13595. textures.setTexture2D( texture, slot );
  13596. };
  13597. }() );
  13598. this.setTexture = ( function () {
  13599. var warned = false;
  13600. return function setTexture( texture, slot ) {
  13601. if ( ! warned ) {
  13602. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13603. warned = true;
  13604. }
  13605. textures.setTexture2D( texture, slot );
  13606. };
  13607. }() );
  13608. this.setTextureCube = ( function () {
  13609. var warned = false;
  13610. return function setTextureCube( texture, slot ) {
  13611. // backwards compatibility: peel texture.texture
  13612. if ( texture && texture.isWebGLRenderTargetCube ) {
  13613. if ( ! warned ) {
  13614. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13615. warned = true;
  13616. }
  13617. texture = texture.texture;
  13618. }
  13619. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13620. // TODO: unify these code paths
  13621. if ( ( texture && texture.isCubeTexture ) ||
  13622. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13623. // CompressedTexture can have Array in image :/
  13624. // this function alone should take care of cube textures
  13625. textures.setTextureCube( texture, slot );
  13626. } else {
  13627. // assumed: texture property of THREE.WebGLRenderTargetCube
  13628. textures.setTextureCubeDynamic( texture, slot );
  13629. }
  13630. };
  13631. }() );
  13632. this.getRenderTarget = function () {
  13633. return _currentRenderTarget;
  13634. };
  13635. this.setRenderTarget = function ( renderTarget ) {
  13636. _currentRenderTarget = renderTarget;
  13637. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13638. textures.setupRenderTarget( renderTarget );
  13639. }
  13640. var framebuffer = null;
  13641. var isCube = false;
  13642. if ( renderTarget ) {
  13643. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13644. if ( renderTarget.isWebGLRenderTargetCube ) {
  13645. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  13646. isCube = true;
  13647. } else {
  13648. framebuffer = __webglFramebuffer;
  13649. }
  13650. _currentViewport.copy( renderTarget.viewport );
  13651. _currentScissor.copy( renderTarget.scissor );
  13652. _currentScissorTest = renderTarget.scissorTest;
  13653. } else {
  13654. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13655. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13656. _currentScissorTest = _scissorTest;
  13657. }
  13658. if ( _currentFramebuffer !== framebuffer ) {
  13659. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13660. _currentFramebuffer = framebuffer;
  13661. }
  13662. state.viewport( _currentViewport );
  13663. state.scissor( _currentScissor );
  13664. state.setScissorTest( _currentScissorTest );
  13665. if ( isCube ) {
  13666. var textureProperties = properties.get( renderTarget.texture );
  13667. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13668. }
  13669. };
  13670. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13671. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  13672. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13673. return;
  13674. }
  13675. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13676. if ( framebuffer ) {
  13677. var restore = false;
  13678. if ( framebuffer !== _currentFramebuffer ) {
  13679. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13680. restore = true;
  13681. }
  13682. try {
  13683. var texture = renderTarget.texture;
  13684. var textureFormat = texture.format;
  13685. var textureType = texture.type;
  13686. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13687. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13688. return;
  13689. }
  13690. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13691. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13692. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13693. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13694. return;
  13695. }
  13696. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13697. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13698. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13699. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13700. }
  13701. } else {
  13702. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13703. }
  13704. } finally {
  13705. if ( restore ) {
  13706. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13707. }
  13708. }
  13709. }
  13710. };
  13711. // Map three.js constants to WebGL constants
  13712. function paramThreeToGL( p ) {
  13713. var extension;
  13714. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13715. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13716. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13717. if ( p === NearestFilter ) return _gl.NEAREST;
  13718. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13719. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13720. if ( p === LinearFilter ) return _gl.LINEAR;
  13721. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13722. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13723. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13724. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13725. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13726. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13727. if ( p === ByteType ) return _gl.BYTE;
  13728. if ( p === ShortType ) return _gl.SHORT;
  13729. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13730. if ( p === IntType ) return _gl.INT;
  13731. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13732. if ( p === FloatType ) return _gl.FLOAT;
  13733. if ( p === HalfFloatType ) {
  13734. extension = extensions.get( 'OES_texture_half_float' );
  13735. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13736. }
  13737. if ( p === AlphaFormat ) return _gl.ALPHA;
  13738. if ( p === RGBFormat ) return _gl.RGB;
  13739. if ( p === RGBAFormat ) return _gl.RGBA;
  13740. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13741. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13742. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13743. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13744. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13745. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13746. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13747. if ( p === ZeroFactor ) return _gl.ZERO;
  13748. if ( p === OneFactor ) return _gl.ONE;
  13749. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13750. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13751. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13752. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13753. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13754. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13755. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13756. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13757. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13758. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13759. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13760. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13761. if ( extension !== null ) {
  13762. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13763. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13764. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13765. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13766. }
  13767. }
  13768. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13769. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13770. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13771. if ( extension !== null ) {
  13772. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13773. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13774. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13775. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13776. }
  13777. }
  13778. if ( p === RGB_ETC1_Format ) {
  13779. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13780. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13781. }
  13782. if ( p === MinEquation || p === MaxEquation ) {
  13783. extension = extensions.get( 'EXT_blend_minmax' );
  13784. if ( extension !== null ) {
  13785. if ( p === MinEquation ) return extension.MIN_EXT;
  13786. if ( p === MaxEquation ) return extension.MAX_EXT;
  13787. }
  13788. }
  13789. if ( p === UnsignedInt248Type ) {
  13790. extension = extensions.get( 'WEBGL_depth_texture' );
  13791. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13792. }
  13793. return 0;
  13794. }
  13795. }
  13796. /**
  13797. * @author mrdoob / http://mrdoob.com/
  13798. * @author alteredq / http://alteredqualia.com/
  13799. */
  13800. function FogExp2 ( color, density ) {
  13801. this.name = '';
  13802. this.color = new Color( color );
  13803. this.density = ( density !== undefined ) ? density : 0.00025;
  13804. }
  13805. FogExp2.prototype.isFogExp2 = true;
  13806. FogExp2.prototype.clone = function () {
  13807. return new FogExp2( this.color.getHex(), this.density );
  13808. };
  13809. FogExp2.prototype.toJSON = function ( meta ) {
  13810. return {
  13811. type: 'FogExp2',
  13812. color: this.color.getHex(),
  13813. density: this.density
  13814. };
  13815. };
  13816. /**
  13817. * @author mrdoob / http://mrdoob.com/
  13818. * @author alteredq / http://alteredqualia.com/
  13819. */
  13820. function Fog ( color, near, far ) {
  13821. this.name = '';
  13822. this.color = new Color( color );
  13823. this.near = ( near !== undefined ) ? near : 1;
  13824. this.far = ( far !== undefined ) ? far : 1000;
  13825. }
  13826. Fog.prototype.isFog = true;
  13827. Fog.prototype.clone = function () {
  13828. return new Fog( this.color.getHex(), this.near, this.far );
  13829. };
  13830. Fog.prototype.toJSON = function ( meta ) {
  13831. return {
  13832. type: 'Fog',
  13833. color: this.color.getHex(),
  13834. near: this.near,
  13835. far: this.far
  13836. };
  13837. };
  13838. /**
  13839. * @author mrdoob / http://mrdoob.com/
  13840. */
  13841. function Scene () {
  13842. Object3D.call( this );
  13843. this.type = 'Scene';
  13844. this.background = null;
  13845. this.fog = null;
  13846. this.overrideMaterial = null;
  13847. this.autoUpdate = true; // checked by the renderer
  13848. }
  13849. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13850. constructor: Scene,
  13851. copy: function ( source, recursive ) {
  13852. Object3D.prototype.copy.call( this, source, recursive );
  13853. if ( source.background !== null ) this.background = source.background.clone();
  13854. if ( source.fog !== null ) this.fog = source.fog.clone();
  13855. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13856. this.autoUpdate = source.autoUpdate;
  13857. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13858. return this;
  13859. },
  13860. toJSON: function ( meta ) {
  13861. var data = Object3D.prototype.toJSON.call( this, meta );
  13862. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13863. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13864. return data;
  13865. }
  13866. } );
  13867. /**
  13868. * @author mikael emtinger / http://gomo.se/
  13869. * @author alteredq / http://alteredqualia.com/
  13870. */
  13871. function LensFlare( texture, size, distance, blending, color ) {
  13872. Object3D.call( this );
  13873. this.lensFlares = [];
  13874. this.positionScreen = new Vector3();
  13875. this.customUpdateCallback = undefined;
  13876. if ( texture !== undefined ) {
  13877. this.add( texture, size, distance, blending, color );
  13878. }
  13879. }
  13880. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13881. constructor: LensFlare,
  13882. isLensFlare: true,
  13883. copy: function ( source ) {
  13884. Object3D.prototype.copy.call( this, source );
  13885. this.positionScreen.copy( source.positionScreen );
  13886. this.customUpdateCallback = source.customUpdateCallback;
  13887. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13888. this.lensFlares.push( source.lensFlares[ i ] );
  13889. }
  13890. return this;
  13891. },
  13892. add: function ( texture, size, distance, blending, color, opacity ) {
  13893. if ( size === undefined ) size = - 1;
  13894. if ( distance === undefined ) distance = 0;
  13895. if ( opacity === undefined ) opacity = 1;
  13896. if ( color === undefined ) color = new Color( 0xffffff );
  13897. if ( blending === undefined ) blending = NormalBlending;
  13898. distance = Math.min( distance, Math.max( 0, distance ) );
  13899. this.lensFlares.push( {
  13900. texture: texture, // THREE.Texture
  13901. size: size, // size in pixels (-1 = use texture.width)
  13902. distance: distance, // distance (0-1) from light source (0=at light source)
  13903. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13904. scale: 1, // scale
  13905. rotation: 0, // rotation
  13906. opacity: opacity, // opacity
  13907. color: color, // color
  13908. blending: blending // blending
  13909. } );
  13910. },
  13911. /*
  13912. * Update lens flares update positions on all flares based on the screen position
  13913. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13914. */
  13915. updateLensFlares: function () {
  13916. var f, fl = this.lensFlares.length;
  13917. var flare;
  13918. var vecX = - this.positionScreen.x * 2;
  13919. var vecY = - this.positionScreen.y * 2;
  13920. for ( f = 0; f < fl; f ++ ) {
  13921. flare = this.lensFlares[ f ];
  13922. flare.x = this.positionScreen.x + vecX * flare.distance;
  13923. flare.y = this.positionScreen.y + vecY * flare.distance;
  13924. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13925. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13926. }
  13927. }
  13928. } );
  13929. /**
  13930. * @author alteredq / http://alteredqualia.com/
  13931. *
  13932. * parameters = {
  13933. * color: <hex>,
  13934. * opacity: <float>,
  13935. * map: new THREE.Texture( <Image> ),
  13936. *
  13937. * uvOffset: new THREE.Vector2(),
  13938. * uvScale: new THREE.Vector2()
  13939. * }
  13940. */
  13941. function SpriteMaterial( parameters ) {
  13942. Material.call( this );
  13943. this.type = 'SpriteMaterial';
  13944. this.color = new Color( 0xffffff );
  13945. this.map = null;
  13946. this.rotation = 0;
  13947. this.fog = false;
  13948. this.lights = false;
  13949. this.setValues( parameters );
  13950. }
  13951. SpriteMaterial.prototype = Object.create( Material.prototype );
  13952. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13953. SpriteMaterial.prototype.isSpriteMaterial = true;
  13954. SpriteMaterial.prototype.copy = function ( source ) {
  13955. Material.prototype.copy.call( this, source );
  13956. this.color.copy( source.color );
  13957. this.map = source.map;
  13958. this.rotation = source.rotation;
  13959. return this;
  13960. };
  13961. /**
  13962. * @author mikael emtinger / http://gomo.se/
  13963. * @author alteredq / http://alteredqualia.com/
  13964. */
  13965. function Sprite( material ) {
  13966. Object3D.call( this );
  13967. this.type = 'Sprite';
  13968. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13969. }
  13970. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13971. constructor: Sprite,
  13972. isSprite: true,
  13973. raycast: ( function () {
  13974. var intersectPoint = new Vector3();
  13975. var worldPosition = new Vector3();
  13976. var worldScale = new Vector3();
  13977. return function raycast( raycaster, intersects ) {
  13978. worldPosition.setFromMatrixPosition( this.matrixWorld );
  13979. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  13980. worldScale.setFromMatrixScale( this.matrixWorld );
  13981. var guessSizeSq = worldScale.x * worldScale.y / 4;
  13982. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  13983. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13984. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13985. intersects.push( {
  13986. distance: distance,
  13987. point: intersectPoint.clone(),
  13988. face: null,
  13989. object: this
  13990. } );
  13991. };
  13992. }() ),
  13993. clone: function () {
  13994. return new this.constructor( this.material ).copy( this );
  13995. }
  13996. } );
  13997. /**
  13998. * @author mikael emtinger / http://gomo.se/
  13999. * @author alteredq / http://alteredqualia.com/
  14000. * @author mrdoob / http://mrdoob.com/
  14001. */
  14002. function LOD() {
  14003. Object3D.call( this );
  14004. this.type = 'LOD';
  14005. Object.defineProperties( this, {
  14006. levels: {
  14007. enumerable: true,
  14008. value: []
  14009. }
  14010. } );
  14011. }
  14012. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14013. constructor: LOD,
  14014. copy: function ( source ) {
  14015. Object3D.prototype.copy.call( this, source, false );
  14016. var levels = source.levels;
  14017. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14018. var level = levels[ i ];
  14019. this.addLevel( level.object.clone(), level.distance );
  14020. }
  14021. return this;
  14022. },
  14023. addLevel: function ( object, distance ) {
  14024. if ( distance === undefined ) distance = 0;
  14025. distance = Math.abs( distance );
  14026. var levels = this.levels;
  14027. for ( var l = 0; l < levels.length; l ++ ) {
  14028. if ( distance < levels[ l ].distance ) {
  14029. break;
  14030. }
  14031. }
  14032. levels.splice( l, 0, { distance: distance, object: object } );
  14033. this.add( object );
  14034. },
  14035. getObjectForDistance: function ( distance ) {
  14036. var levels = this.levels;
  14037. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14038. if ( distance < levels[ i ].distance ) {
  14039. break;
  14040. }
  14041. }
  14042. return levels[ i - 1 ].object;
  14043. },
  14044. raycast: ( function () {
  14045. var matrixPosition = new Vector3();
  14046. return function raycast( raycaster, intersects ) {
  14047. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  14048. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  14049. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14050. };
  14051. }() ),
  14052. update: function () {
  14053. var v1 = new Vector3();
  14054. var v2 = new Vector3();
  14055. return function update( camera ) {
  14056. var levels = this.levels;
  14057. if ( levels.length > 1 ) {
  14058. v1.setFromMatrixPosition( camera.matrixWorld );
  14059. v2.setFromMatrixPosition( this.matrixWorld );
  14060. var distance = v1.distanceTo( v2 );
  14061. levels[ 0 ].object.visible = true;
  14062. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  14063. if ( distance >= levels[ i ].distance ) {
  14064. levels[ i - 1 ].object.visible = false;
  14065. levels[ i ].object.visible = true;
  14066. } else {
  14067. break;
  14068. }
  14069. }
  14070. for ( ; i < l; i ++ ) {
  14071. levels[ i ].object.visible = false;
  14072. }
  14073. }
  14074. };
  14075. }(),
  14076. toJSON: function ( meta ) {
  14077. var data = Object3D.prototype.toJSON.call( this, meta );
  14078. data.object.levels = [];
  14079. var levels = this.levels;
  14080. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  14081. var level = levels[ i ];
  14082. data.object.levels.push( {
  14083. object: level.object.uuid,
  14084. distance: level.distance
  14085. } );
  14086. }
  14087. return data;
  14088. }
  14089. } );
  14090. /**
  14091. * @author mikael emtinger / http://gomo.se/
  14092. * @author alteredq / http://alteredqualia.com/
  14093. * @author michael guerrero / http://realitymeltdown.com
  14094. * @author ikerr / http://verold.com
  14095. */
  14096. function Skeleton( bones, boneInverses ) {
  14097. // copy the bone array
  14098. bones = bones || [];
  14099. this.bones = bones.slice( 0 );
  14100. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  14101. // use the supplied bone inverses or calculate the inverses
  14102. if ( boneInverses === undefined ) {
  14103. this.calculateInverses();
  14104. } else {
  14105. if ( this.bones.length === boneInverses.length ) {
  14106. this.boneInverses = boneInverses.slice( 0 );
  14107. } else {
  14108. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  14109. this.boneInverses = [];
  14110. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14111. this.boneInverses.push( new Matrix4() );
  14112. }
  14113. }
  14114. }
  14115. }
  14116. Object.assign( Skeleton.prototype, {
  14117. calculateInverses: function () {
  14118. this.boneInverses = [];
  14119. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  14120. var inverse = new Matrix4();
  14121. if ( this.bones[ i ] ) {
  14122. inverse.getInverse( this.bones[ i ].matrixWorld );
  14123. }
  14124. this.boneInverses.push( inverse );
  14125. }
  14126. },
  14127. pose: function () {
  14128. var bone, i, il;
  14129. // recover the bind-time world matrices
  14130. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14131. bone = this.bones[ i ];
  14132. if ( bone ) {
  14133. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  14134. }
  14135. }
  14136. // compute the local matrices, positions, rotations and scales
  14137. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  14138. bone = this.bones[ i ];
  14139. if ( bone ) {
  14140. if ( bone.parent && bone.parent.isBone ) {
  14141. bone.matrix.getInverse( bone.parent.matrixWorld );
  14142. bone.matrix.multiply( bone.matrixWorld );
  14143. } else {
  14144. bone.matrix.copy( bone.matrixWorld );
  14145. }
  14146. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14147. }
  14148. }
  14149. },
  14150. update: ( function () {
  14151. var offsetMatrix = new Matrix4();
  14152. var identityMatrix = new Matrix4();
  14153. return function update() {
  14154. var bones = this.bones;
  14155. var boneInverses = this.boneInverses;
  14156. var boneMatrices = this.boneMatrices;
  14157. var boneTexture = this.boneTexture;
  14158. // flatten bone matrices to array
  14159. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  14160. // compute the offset between the current and the original transform
  14161. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  14162. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14163. offsetMatrix.toArray( boneMatrices, i * 16 );
  14164. }
  14165. if ( boneTexture !== undefined ) {
  14166. boneTexture.needsUpdate = true;
  14167. }
  14168. };
  14169. } )(),
  14170. clone: function () {
  14171. return new Skeleton( this.bones, this.boneInverses );
  14172. }
  14173. } );
  14174. /**
  14175. * @author mikael emtinger / http://gomo.se/
  14176. * @author alteredq / http://alteredqualia.com/
  14177. * @author ikerr / http://verold.com
  14178. */
  14179. function Bone() {
  14180. Object3D.call( this );
  14181. this.type = 'Bone';
  14182. }
  14183. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14184. constructor: Bone,
  14185. isBone: true
  14186. } );
  14187. /**
  14188. * @author mikael emtinger / http://gomo.se/
  14189. * @author alteredq / http://alteredqualia.com/
  14190. * @author ikerr / http://verold.com
  14191. */
  14192. function SkinnedMesh( geometry, material ) {
  14193. Mesh.call( this, geometry, material );
  14194. this.type = 'SkinnedMesh';
  14195. this.bindMode = 'attached';
  14196. this.bindMatrix = new Matrix4();
  14197. this.bindMatrixInverse = new Matrix4();
  14198. var bones = this.initBones();
  14199. var skeleton = new Skeleton( bones );
  14200. this.bind( skeleton, this.matrixWorld );
  14201. this.normalizeSkinWeights();
  14202. }
  14203. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  14204. constructor: SkinnedMesh,
  14205. isSkinnedMesh: true,
  14206. initBones: function () {
  14207. var bones = [], bone, gbone;
  14208. var i, il;
  14209. if ( this.geometry && this.geometry.bones !== undefined ) {
  14210. // first, create array of 'Bone' objects from geometry data
  14211. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14212. gbone = this.geometry.bones[ i ];
  14213. // create new 'Bone' object
  14214. bone = new Bone();
  14215. bones.push( bone );
  14216. // apply values
  14217. bone.name = gbone.name;
  14218. bone.position.fromArray( gbone.pos );
  14219. bone.quaternion.fromArray( gbone.rotq );
  14220. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  14221. }
  14222. // second, create bone hierarchy
  14223. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  14224. gbone = this.geometry.bones[ i ];
  14225. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  14226. // subsequent bones in the hierarchy
  14227. bones[ gbone.parent ].add( bones[ i ] );
  14228. } else {
  14229. // topmost bone, immediate child of the skinned mesh
  14230. this.add( bones[ i ] );
  14231. }
  14232. }
  14233. }
  14234. // now the bones are part of the scene graph and children of the skinned mesh.
  14235. // let's update the corresponding matrices
  14236. this.updateMatrixWorld( true );
  14237. return bones;
  14238. },
  14239. bind: function ( skeleton, bindMatrix ) {
  14240. this.skeleton = skeleton;
  14241. if ( bindMatrix === undefined ) {
  14242. this.updateMatrixWorld( true );
  14243. this.skeleton.calculateInverses();
  14244. bindMatrix = this.matrixWorld;
  14245. }
  14246. this.bindMatrix.copy( bindMatrix );
  14247. this.bindMatrixInverse.getInverse( bindMatrix );
  14248. },
  14249. pose: function () {
  14250. this.skeleton.pose();
  14251. },
  14252. normalizeSkinWeights: function () {
  14253. var scale, i;
  14254. if ( this.geometry && this.geometry.isGeometry ) {
  14255. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  14256. var sw = this.geometry.skinWeights[ i ];
  14257. scale = 1.0 / sw.lengthManhattan();
  14258. if ( scale !== Infinity ) {
  14259. sw.multiplyScalar( scale );
  14260. } else {
  14261. sw.set( 1, 0, 0, 0 ); // do something reasonable
  14262. }
  14263. }
  14264. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  14265. var vec = new Vector4();
  14266. var skinWeight = this.geometry.attributes.skinWeight;
  14267. for ( i = 0; i < skinWeight.count; i ++ ) {
  14268. vec.x = skinWeight.getX( i );
  14269. vec.y = skinWeight.getY( i );
  14270. vec.z = skinWeight.getZ( i );
  14271. vec.w = skinWeight.getW( i );
  14272. scale = 1.0 / vec.lengthManhattan();
  14273. if ( scale !== Infinity ) {
  14274. vec.multiplyScalar( scale );
  14275. } else {
  14276. vec.set( 1, 0, 0, 0 ); // do something reasonable
  14277. }
  14278. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  14279. }
  14280. }
  14281. },
  14282. updateMatrixWorld: function ( force ) {
  14283. Mesh.prototype.updateMatrixWorld.call( this, force );
  14284. if ( this.bindMode === 'attached' ) {
  14285. this.bindMatrixInverse.getInverse( this.matrixWorld );
  14286. } else if ( this.bindMode === 'detached' ) {
  14287. this.bindMatrixInverse.getInverse( this.bindMatrix );
  14288. } else {
  14289. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14290. }
  14291. },
  14292. clone: function () {
  14293. return new this.constructor( this.geometry, this.material ).copy( this );
  14294. }
  14295. } );
  14296. /**
  14297. * @author mrdoob / http://mrdoob.com/
  14298. * @author alteredq / http://alteredqualia.com/
  14299. *
  14300. * parameters = {
  14301. * color: <hex>,
  14302. * opacity: <float>,
  14303. *
  14304. * linewidth: <float>,
  14305. * linecap: "round",
  14306. * linejoin: "round"
  14307. * }
  14308. */
  14309. function LineBasicMaterial( parameters ) {
  14310. Material.call( this );
  14311. this.type = 'LineBasicMaterial';
  14312. this.color = new Color( 0xffffff );
  14313. this.linewidth = 1;
  14314. this.linecap = 'round';
  14315. this.linejoin = 'round';
  14316. this.lights = false;
  14317. this.setValues( parameters );
  14318. }
  14319. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14320. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14321. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14322. LineBasicMaterial.prototype.copy = function ( source ) {
  14323. Material.prototype.copy.call( this, source );
  14324. this.color.copy( source.color );
  14325. this.linewidth = source.linewidth;
  14326. this.linecap = source.linecap;
  14327. this.linejoin = source.linejoin;
  14328. return this;
  14329. };
  14330. /**
  14331. * @author mrdoob / http://mrdoob.com/
  14332. */
  14333. function Line( geometry, material, mode ) {
  14334. if ( mode === 1 ) {
  14335. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14336. return new LineSegments( geometry, material );
  14337. }
  14338. Object3D.call( this );
  14339. this.type = 'Line';
  14340. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14341. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14342. }
  14343. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14344. constructor: Line,
  14345. isLine: true,
  14346. raycast: ( function () {
  14347. var inverseMatrix = new Matrix4();
  14348. var ray = new Ray();
  14349. var sphere = new Sphere();
  14350. return function raycast( raycaster, intersects ) {
  14351. var precision = raycaster.linePrecision;
  14352. var precisionSq = precision * precision;
  14353. var geometry = this.geometry;
  14354. var matrixWorld = this.matrixWorld;
  14355. // Checking boundingSphere distance to ray
  14356. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14357. sphere.copy( geometry.boundingSphere );
  14358. sphere.applyMatrix4( matrixWorld );
  14359. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14360. //
  14361. inverseMatrix.getInverse( matrixWorld );
  14362. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14363. var vStart = new Vector3();
  14364. var vEnd = new Vector3();
  14365. var interSegment = new Vector3();
  14366. var interRay = new Vector3();
  14367. var step = (this && this.isLineSegments) ? 2 : 1;
  14368. if ( geometry.isBufferGeometry ) {
  14369. var index = geometry.index;
  14370. var attributes = geometry.attributes;
  14371. var positions = attributes.position.array;
  14372. if ( index !== null ) {
  14373. var indices = index.array;
  14374. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14375. var a = indices[ i ];
  14376. var b = indices[ i + 1 ];
  14377. vStart.fromArray( positions, a * 3 );
  14378. vEnd.fromArray( positions, b * 3 );
  14379. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14380. if ( distSq > precisionSq ) continue;
  14381. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14382. var distance = raycaster.ray.origin.distanceTo( interRay );
  14383. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14384. intersects.push( {
  14385. distance: distance,
  14386. // What do we want? intersection point on the ray or on the segment??
  14387. // point: raycaster.ray.at( distance ),
  14388. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14389. index: i,
  14390. face: null,
  14391. faceIndex: null,
  14392. object: this
  14393. } );
  14394. }
  14395. } else {
  14396. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14397. vStart.fromArray( positions, 3 * i );
  14398. vEnd.fromArray( positions, 3 * i + 3 );
  14399. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14400. if ( distSq > precisionSq ) continue;
  14401. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14402. var distance = raycaster.ray.origin.distanceTo( interRay );
  14403. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14404. intersects.push( {
  14405. distance: distance,
  14406. // What do we want? intersection point on the ray or on the segment??
  14407. // point: raycaster.ray.at( distance ),
  14408. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14409. index: i,
  14410. face: null,
  14411. faceIndex: null,
  14412. object: this
  14413. } );
  14414. }
  14415. }
  14416. } else if ( geometry.isGeometry ) {
  14417. var vertices = geometry.vertices;
  14418. var nbVertices = vertices.length;
  14419. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14420. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14421. if ( distSq > precisionSq ) continue;
  14422. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14423. var distance = raycaster.ray.origin.distanceTo( interRay );
  14424. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14425. intersects.push( {
  14426. distance: distance,
  14427. // What do we want? intersection point on the ray or on the segment??
  14428. // point: raycaster.ray.at( distance ),
  14429. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14430. index: i,
  14431. face: null,
  14432. faceIndex: null,
  14433. object: this
  14434. } );
  14435. }
  14436. }
  14437. };
  14438. }() ),
  14439. clone: function () {
  14440. return new this.constructor( this.geometry, this.material ).copy( this );
  14441. }
  14442. } );
  14443. /**
  14444. * @author mrdoob / http://mrdoob.com/
  14445. */
  14446. function LineSegments( geometry, material ) {
  14447. Line.call( this, geometry, material );
  14448. this.type = 'LineSegments';
  14449. }
  14450. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14451. constructor: LineSegments,
  14452. isLineSegments: true
  14453. } );
  14454. /**
  14455. * @author mgreter / http://github.com/mgreter
  14456. */
  14457. function LineLoop( geometry, material ) {
  14458. Line.call( this, geometry, material );
  14459. this.type = 'LineLoop';
  14460. }
  14461. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14462. constructor: LineLoop,
  14463. isLineLoop: true,
  14464. } );
  14465. /**
  14466. * @author mrdoob / http://mrdoob.com/
  14467. * @author alteredq / http://alteredqualia.com/
  14468. *
  14469. * parameters = {
  14470. * color: <hex>,
  14471. * opacity: <float>,
  14472. * map: new THREE.Texture( <Image> ),
  14473. *
  14474. * size: <float>,
  14475. * sizeAttenuation: <bool>
  14476. * }
  14477. */
  14478. function PointsMaterial( parameters ) {
  14479. Material.call( this );
  14480. this.type = 'PointsMaterial';
  14481. this.color = new Color( 0xffffff );
  14482. this.map = null;
  14483. this.size = 1;
  14484. this.sizeAttenuation = true;
  14485. this.lights = false;
  14486. this.setValues( parameters );
  14487. }
  14488. PointsMaterial.prototype = Object.create( Material.prototype );
  14489. PointsMaterial.prototype.constructor = PointsMaterial;
  14490. PointsMaterial.prototype.isPointsMaterial = true;
  14491. PointsMaterial.prototype.copy = function ( source ) {
  14492. Material.prototype.copy.call( this, source );
  14493. this.color.copy( source.color );
  14494. this.map = source.map;
  14495. this.size = source.size;
  14496. this.sizeAttenuation = source.sizeAttenuation;
  14497. return this;
  14498. };
  14499. /**
  14500. * @author alteredq / http://alteredqualia.com/
  14501. */
  14502. function Points( geometry, material ) {
  14503. Object3D.call( this );
  14504. this.type = 'Points';
  14505. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14506. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14507. }
  14508. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14509. constructor: Points,
  14510. isPoints: true,
  14511. raycast: ( function () {
  14512. var inverseMatrix = new Matrix4();
  14513. var ray = new Ray();
  14514. var sphere = new Sphere();
  14515. return function raycast( raycaster, intersects ) {
  14516. var object = this;
  14517. var geometry = this.geometry;
  14518. var matrixWorld = this.matrixWorld;
  14519. var threshold = raycaster.params.Points.threshold;
  14520. // Checking boundingSphere distance to ray
  14521. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14522. sphere.copy( geometry.boundingSphere );
  14523. sphere.applyMatrix4( matrixWorld );
  14524. sphere.radius += threshold;
  14525. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14526. //
  14527. inverseMatrix.getInverse( matrixWorld );
  14528. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14529. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14530. var localThresholdSq = localThreshold * localThreshold;
  14531. var position = new Vector3();
  14532. function testPoint( point, index ) {
  14533. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14534. if ( rayPointDistanceSq < localThresholdSq ) {
  14535. var intersectPoint = ray.closestPointToPoint( point );
  14536. intersectPoint.applyMatrix4( matrixWorld );
  14537. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14538. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14539. intersects.push( {
  14540. distance: distance,
  14541. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14542. point: intersectPoint.clone(),
  14543. index: index,
  14544. face: null,
  14545. object: object
  14546. } );
  14547. }
  14548. }
  14549. if ( geometry.isBufferGeometry ) {
  14550. var index = geometry.index;
  14551. var attributes = geometry.attributes;
  14552. var positions = attributes.position.array;
  14553. if ( index !== null ) {
  14554. var indices = index.array;
  14555. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14556. var a = indices[ i ];
  14557. position.fromArray( positions, a * 3 );
  14558. testPoint( position, a );
  14559. }
  14560. } else {
  14561. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14562. position.fromArray( positions, i * 3 );
  14563. testPoint( position, i );
  14564. }
  14565. }
  14566. } else {
  14567. var vertices = geometry.vertices;
  14568. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14569. testPoint( vertices[ i ], i );
  14570. }
  14571. }
  14572. };
  14573. }() ),
  14574. clone: function () {
  14575. return new this.constructor( this.geometry, this.material ).copy( this );
  14576. }
  14577. } );
  14578. /**
  14579. * @author mrdoob / http://mrdoob.com/
  14580. */
  14581. function Group() {
  14582. Object3D.call( this );
  14583. this.type = 'Group';
  14584. }
  14585. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14586. constructor: Group
  14587. } );
  14588. /**
  14589. * @author mrdoob / http://mrdoob.com/
  14590. */
  14591. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14592. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14593. this.generateMipmaps = false;
  14594. var scope = this;
  14595. function update() {
  14596. requestAnimationFrame( update );
  14597. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14598. scope.needsUpdate = true;
  14599. }
  14600. }
  14601. update();
  14602. }
  14603. VideoTexture.prototype = Object.create( Texture.prototype );
  14604. VideoTexture.prototype.constructor = VideoTexture;
  14605. /**
  14606. * @author alteredq / http://alteredqualia.com/
  14607. */
  14608. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14609. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14610. this.image = { width: width, height: height };
  14611. this.mipmaps = mipmaps;
  14612. // no flipping for cube textures
  14613. // (also flipping doesn't work for compressed textures )
  14614. this.flipY = false;
  14615. // can't generate mipmaps for compressed textures
  14616. // mips must be embedded in DDS files
  14617. this.generateMipmaps = false;
  14618. }
  14619. CompressedTexture.prototype = Object.create( Texture.prototype );
  14620. CompressedTexture.prototype.constructor = CompressedTexture;
  14621. CompressedTexture.prototype.isCompressedTexture = true;
  14622. /**
  14623. * @author Matt DesLauriers / @mattdesl
  14624. * @author atix / arthursilber.de
  14625. */
  14626. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14627. format = format !== undefined ? format : DepthFormat;
  14628. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14629. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14630. }
  14631. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14632. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14633. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14634. this.image = { width: width, height: height };
  14635. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14636. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14637. this.flipY = false;
  14638. this.generateMipmaps = false;
  14639. }
  14640. DepthTexture.prototype = Object.create( Texture.prototype );
  14641. DepthTexture.prototype.constructor = DepthTexture;
  14642. DepthTexture.prototype.isDepthTexture = true;
  14643. /**
  14644. * @author mrdoob / http://mrdoob.com/
  14645. * @author Mugen87 / https://github.com/Mugen87
  14646. */
  14647. function WireframeGeometry( geometry ) {
  14648. BufferGeometry.call( this );
  14649. this.type = 'WireframeGeometry';
  14650. // buffer
  14651. var vertices = [];
  14652. // helper variables
  14653. var i, j, l, o, ol;
  14654. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14655. var key, keys = [ 'a', 'b', 'c' ];
  14656. var vertex;
  14657. // different logic for Geometry and BufferGeometry
  14658. if ( geometry && geometry.isGeometry ) {
  14659. // create a data structure that contains all edges without duplicates
  14660. var faces = geometry.faces;
  14661. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14662. var face = faces[ i ];
  14663. for ( j = 0; j < 3; j ++ ) {
  14664. edge1 = face[ keys[ j ] ];
  14665. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14666. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14667. edge[ 1 ] = Math.max( edge1, edge2 );
  14668. key = edge[ 0 ] + ',' + edge[ 1 ];
  14669. if ( edges[ key ] === undefined ) {
  14670. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14671. }
  14672. }
  14673. }
  14674. // generate vertices
  14675. for ( key in edges ) {
  14676. e = edges[ key ];
  14677. vertex = geometry.vertices[ e.index1 ];
  14678. vertices.push( vertex.x, vertex.y, vertex.z );
  14679. vertex = geometry.vertices[ e.index2 ];
  14680. vertices.push( vertex.x, vertex.y, vertex.z );
  14681. }
  14682. } else if ( geometry && geometry.isBufferGeometry ) {
  14683. var position, indices, groups;
  14684. var group, start, count;
  14685. var index1, index2;
  14686. vertex = new Vector3();
  14687. if ( geometry.index !== null ) {
  14688. // indexed BufferGeometry
  14689. position = geometry.attributes.position;
  14690. indices = geometry.index;
  14691. groups = geometry.groups;
  14692. if ( groups.length === 0 ) {
  14693. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14694. }
  14695. // create a data structure that contains all eges without duplicates
  14696. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14697. group = groups[ o ];
  14698. start = group.start;
  14699. count = group.count;
  14700. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14701. for ( j = 0; j < 3; j ++ ) {
  14702. edge1 = indices.getX( i + j );
  14703. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14704. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14705. edge[ 1 ] = Math.max( edge1, edge2 );
  14706. key = edge[ 0 ] + ',' + edge[ 1 ];
  14707. if ( edges[ key ] === undefined ) {
  14708. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14709. }
  14710. }
  14711. }
  14712. }
  14713. // generate vertices
  14714. for ( key in edges ) {
  14715. e = edges[ key ];
  14716. vertex.fromBufferAttribute( position, e.index1 );
  14717. vertices.push( vertex.x, vertex.y, vertex.z );
  14718. vertex.fromBufferAttribute( position, e.index2 );
  14719. vertices.push( vertex.x, vertex.y, vertex.z );
  14720. }
  14721. } else {
  14722. // non-indexed BufferGeometry
  14723. position = geometry.attributes.position;
  14724. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14725. for ( j = 0; j < 3; j ++ ) {
  14726. // three edges per triangle, an edge is represented as (index1, index2)
  14727. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14728. index1 = 3 * i + j;
  14729. vertex.fromBufferAttribute( position, index1 );
  14730. vertices.push( vertex.x, vertex.y, vertex.z );
  14731. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14732. vertex.fromBufferAttribute( position, index2 );
  14733. vertices.push( vertex.x, vertex.y, vertex.z );
  14734. }
  14735. }
  14736. }
  14737. }
  14738. // build geometry
  14739. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14740. }
  14741. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14742. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14743. /**
  14744. * @author zz85 / https://github.com/zz85
  14745. * @author Mugen87 / https://github.com/Mugen87
  14746. *
  14747. * Parametric Surfaces Geometry
  14748. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14749. */
  14750. // ParametricGeometry
  14751. function ParametricGeometry( func, slices, stacks ) {
  14752. Geometry.call( this );
  14753. this.type = 'ParametricGeometry';
  14754. this.parameters = {
  14755. func: func,
  14756. slices: slices,
  14757. stacks: stacks
  14758. };
  14759. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14760. this.mergeVertices();
  14761. }
  14762. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14763. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14764. // ParametricBufferGeometry
  14765. function ParametricBufferGeometry( func, slices, stacks ) {
  14766. BufferGeometry.call( this );
  14767. this.type = 'ParametricBufferGeometry';
  14768. this.parameters = {
  14769. func: func,
  14770. slices: slices,
  14771. stacks: stacks
  14772. };
  14773. // buffers
  14774. var indices = [];
  14775. var vertices = [];
  14776. var normals = [];
  14777. var uvs = [];
  14778. var EPS = 0.00001;
  14779. var normal = new Vector3();
  14780. var p0 = new Vector3(), p1 = new Vector3();
  14781. var pu = new Vector3(), pv = new Vector3();
  14782. var i, j;
  14783. // generate vertices, normals and uvs
  14784. var sliceCount = slices + 1;
  14785. for ( i = 0; i <= stacks; i ++ ) {
  14786. var v = i / stacks;
  14787. for ( j = 0; j <= slices; j ++ ) {
  14788. var u = j / slices;
  14789. // vertex
  14790. p0 = func( u, v, p0 );
  14791. vertices.push( p0.x, p0.y, p0.z );
  14792. // normal
  14793. // approximate tangent vectors via finite differences
  14794. if ( u - EPS >= 0 ) {
  14795. p1 = func( u - EPS, v, p1 );
  14796. pu.subVectors( p0, p1 );
  14797. } else {
  14798. p1 = func( u + EPS, v, p1 );
  14799. pu.subVectors( p1, p0 );
  14800. }
  14801. if ( v - EPS >= 0 ) {
  14802. p1 = func( u, v - EPS, p1 );
  14803. pv.subVectors( p0, p1 );
  14804. } else {
  14805. p1 = func( u, v + EPS, p1 );
  14806. pv.subVectors( p1, p0 );
  14807. }
  14808. // cross product of tangent vectors returns surface normal
  14809. normal.crossVectors( pu, pv ).normalize();
  14810. normals.push( normal.x, normal.y, normal.z );
  14811. // uv
  14812. uvs.push( u, v );
  14813. }
  14814. }
  14815. // generate indices
  14816. for ( i = 0; i < stacks; i ++ ) {
  14817. for ( j = 0; j < slices; j ++ ) {
  14818. var a = i * sliceCount + j;
  14819. var b = i * sliceCount + j + 1;
  14820. var c = ( i + 1 ) * sliceCount + j + 1;
  14821. var d = ( i + 1 ) * sliceCount + j;
  14822. // faces one and two
  14823. indices.push( a, b, d );
  14824. indices.push( b, c, d );
  14825. }
  14826. }
  14827. // build geometry
  14828. this.setIndex( indices );
  14829. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14830. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14831. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14832. }
  14833. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14834. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14835. /**
  14836. * @author clockworkgeek / https://github.com/clockworkgeek
  14837. * @author timothypratley / https://github.com/timothypratley
  14838. * @author WestLangley / http://github.com/WestLangley
  14839. * @author Mugen87 / https://github.com/Mugen87
  14840. */
  14841. // PolyhedronGeometry
  14842. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14843. Geometry.call( this );
  14844. this.type = 'PolyhedronGeometry';
  14845. this.parameters = {
  14846. vertices: vertices,
  14847. indices: indices,
  14848. radius: radius,
  14849. detail: detail
  14850. };
  14851. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14852. this.mergeVertices();
  14853. }
  14854. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14855. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14856. // PolyhedronBufferGeometry
  14857. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14858. BufferGeometry.call( this );
  14859. this.type = 'PolyhedronBufferGeometry';
  14860. this.parameters = {
  14861. vertices: vertices,
  14862. indices: indices,
  14863. radius: radius,
  14864. detail: detail
  14865. };
  14866. radius = radius || 1;
  14867. detail = detail || 0;
  14868. // default buffer data
  14869. var vertexBuffer = [];
  14870. var uvBuffer = [];
  14871. // the subdivision creates the vertex buffer data
  14872. subdivide( detail );
  14873. // all vertices should lie on a conceptual sphere with a given radius
  14874. appplyRadius( radius );
  14875. // finally, create the uv data
  14876. generateUVs();
  14877. // build non-indexed geometry
  14878. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14879. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14880. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14881. if ( detail === 0 ) {
  14882. this.computeVertexNormals(); // flat normals
  14883. } else {
  14884. this.normalizeNormals(); // smooth normals
  14885. }
  14886. // helper functions
  14887. function subdivide( detail ) {
  14888. var a = new Vector3();
  14889. var b = new Vector3();
  14890. var c = new Vector3();
  14891. // iterate over all faces and apply a subdivison with the given detail value
  14892. for ( var i = 0; i < indices.length; i += 3 ) {
  14893. // get the vertices of the face
  14894. getVertexByIndex( indices[ i + 0 ], a );
  14895. getVertexByIndex( indices[ i + 1 ], b );
  14896. getVertexByIndex( indices[ i + 2 ], c );
  14897. // perform subdivision
  14898. subdivideFace( a, b, c, detail );
  14899. }
  14900. }
  14901. function subdivideFace( a, b, c, detail ) {
  14902. var cols = Math.pow( 2, detail );
  14903. // we use this multidimensional array as a data structure for creating the subdivision
  14904. var v = [];
  14905. var i, j;
  14906. // construct all of the vertices for this subdivision
  14907. for ( i = 0; i <= cols; i ++ ) {
  14908. v[ i ] = [];
  14909. var aj = a.clone().lerp( c, i / cols );
  14910. var bj = b.clone().lerp( c, i / cols );
  14911. var rows = cols - i;
  14912. for ( j = 0; j <= rows; j ++ ) {
  14913. if ( j === 0 && i === cols ) {
  14914. v[ i ][ j ] = aj;
  14915. } else {
  14916. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14917. }
  14918. }
  14919. }
  14920. // construct all of the faces
  14921. for ( i = 0; i < cols; i ++ ) {
  14922. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14923. var k = Math.floor( j / 2 );
  14924. if ( j % 2 === 0 ) {
  14925. pushVertex( v[ i ][ k + 1 ] );
  14926. pushVertex( v[ i + 1 ][ k ] );
  14927. pushVertex( v[ i ][ k ] );
  14928. } else {
  14929. pushVertex( v[ i ][ k + 1 ] );
  14930. pushVertex( v[ i + 1 ][ k + 1 ] );
  14931. pushVertex( v[ i + 1 ][ k ] );
  14932. }
  14933. }
  14934. }
  14935. }
  14936. function appplyRadius( radius ) {
  14937. var vertex = new Vector3();
  14938. // iterate over the entire buffer and apply the radius to each vertex
  14939. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14940. vertex.x = vertexBuffer[ i + 0 ];
  14941. vertex.y = vertexBuffer[ i + 1 ];
  14942. vertex.z = vertexBuffer[ i + 2 ];
  14943. vertex.normalize().multiplyScalar( radius );
  14944. vertexBuffer[ i + 0 ] = vertex.x;
  14945. vertexBuffer[ i + 1 ] = vertex.y;
  14946. vertexBuffer[ i + 2 ] = vertex.z;
  14947. }
  14948. }
  14949. function generateUVs() {
  14950. var vertex = new Vector3();
  14951. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14952. vertex.x = vertexBuffer[ i + 0 ];
  14953. vertex.y = vertexBuffer[ i + 1 ];
  14954. vertex.z = vertexBuffer[ i + 2 ];
  14955. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14956. var v = inclination( vertex ) / Math.PI + 0.5;
  14957. uvBuffer.push( u, 1 - v );
  14958. }
  14959. correctUVs();
  14960. correctSeam();
  14961. }
  14962. function correctSeam() {
  14963. // handle case when face straddles the seam, see #3269
  14964. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14965. // uv data of a single face
  14966. var x0 = uvBuffer[ i + 0 ];
  14967. var x1 = uvBuffer[ i + 2 ];
  14968. var x2 = uvBuffer[ i + 4 ];
  14969. var max = Math.max( x0, x1, x2 );
  14970. var min = Math.min( x0, x1, x2 );
  14971. // 0.9 is somewhat arbitrary
  14972. if ( max > 0.9 && min < 0.1 ) {
  14973. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14974. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14975. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14976. }
  14977. }
  14978. }
  14979. function pushVertex( vertex ) {
  14980. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14981. }
  14982. function getVertexByIndex( index, vertex ) {
  14983. var stride = index * 3;
  14984. vertex.x = vertices[ stride + 0 ];
  14985. vertex.y = vertices[ stride + 1 ];
  14986. vertex.z = vertices[ stride + 2 ];
  14987. }
  14988. function correctUVs() {
  14989. var a = new Vector3();
  14990. var b = new Vector3();
  14991. var c = new Vector3();
  14992. var centroid = new Vector3();
  14993. var uvA = new Vector2();
  14994. var uvB = new Vector2();
  14995. var uvC = new Vector2();
  14996. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14997. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14998. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14999. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  15000. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  15001. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  15002. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  15003. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  15004. var azi = azimuth( centroid );
  15005. correctUV( uvA, j + 0, a, azi );
  15006. correctUV( uvB, j + 2, b, azi );
  15007. correctUV( uvC, j + 4, c, azi );
  15008. }
  15009. }
  15010. function correctUV( uv, stride, vector, azimuth ) {
  15011. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  15012. uvBuffer[ stride ] = uv.x - 1;
  15013. }
  15014. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  15015. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  15016. }
  15017. }
  15018. // Angle around the Y axis, counter-clockwise when looking from above.
  15019. function azimuth( vector ) {
  15020. return Math.atan2( vector.z, - vector.x );
  15021. }
  15022. // Angle above the XZ plane.
  15023. function inclination( vector ) {
  15024. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15025. }
  15026. }
  15027. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15028. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  15029. /**
  15030. * @author timothypratley / https://github.com/timothypratley
  15031. * @author Mugen87 / https://github.com/Mugen87
  15032. */
  15033. // TetrahedronGeometry
  15034. function TetrahedronGeometry( radius, detail ) {
  15035. Geometry.call( this );
  15036. this.type = 'TetrahedronGeometry';
  15037. this.parameters = {
  15038. radius: radius,
  15039. detail: detail
  15040. };
  15041. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  15042. this.mergeVertices();
  15043. }
  15044. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  15045. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  15046. // TetrahedronBufferGeometry
  15047. function TetrahedronBufferGeometry( radius, detail ) {
  15048. var vertices = [
  15049. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  15050. ];
  15051. var indices = [
  15052. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  15053. ];
  15054. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15055. this.type = 'TetrahedronBufferGeometry';
  15056. this.parameters = {
  15057. radius: radius,
  15058. detail: detail
  15059. };
  15060. }
  15061. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15062. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  15063. /**
  15064. * @author timothypratley / https://github.com/timothypratley
  15065. * @author Mugen87 / https://github.com/Mugen87
  15066. */
  15067. // OctahedronGeometry
  15068. function OctahedronGeometry( radius, detail ) {
  15069. Geometry.call( this );
  15070. this.type = 'OctahedronGeometry';
  15071. this.parameters = {
  15072. radius: radius,
  15073. detail: detail
  15074. };
  15075. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  15076. this.mergeVertices();
  15077. }
  15078. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  15079. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  15080. // OctahedronBufferGeometry
  15081. function OctahedronBufferGeometry( radius, detail ) {
  15082. var vertices = [
  15083. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  15084. ];
  15085. var indices = [
  15086. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  15087. ];
  15088. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15089. this.type = 'OctahedronBufferGeometry';
  15090. this.parameters = {
  15091. radius: radius,
  15092. detail: detail
  15093. };
  15094. }
  15095. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15096. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  15097. /**
  15098. * @author timothypratley / https://github.com/timothypratley
  15099. * @author Mugen87 / https://github.com/Mugen87
  15100. */
  15101. // IcosahedronGeometry
  15102. function IcosahedronGeometry( radius, detail ) {
  15103. Geometry.call( this );
  15104. this.type = 'IcosahedronGeometry';
  15105. this.parameters = {
  15106. radius: radius,
  15107. detail: detail
  15108. };
  15109. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  15110. this.mergeVertices();
  15111. }
  15112. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  15113. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  15114. // IcosahedronBufferGeometry
  15115. function IcosahedronBufferGeometry( radius, detail ) {
  15116. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15117. var vertices = [
  15118. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  15119. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  15120. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  15121. ];
  15122. var indices = [
  15123. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15124. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15125. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15126. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15127. ];
  15128. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15129. this.type = 'IcosahedronBufferGeometry';
  15130. this.parameters = {
  15131. radius: radius,
  15132. detail: detail
  15133. };
  15134. }
  15135. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15136. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  15137. /**
  15138. * @author Abe Pazos / https://hamoid.com
  15139. * @author Mugen87 / https://github.com/Mugen87
  15140. */
  15141. // DodecahedronGeometry
  15142. function DodecahedronGeometry( radius, detail ) {
  15143. Geometry.call( this );
  15144. this.type = 'DodecahedronGeometry';
  15145. this.parameters = {
  15146. radius: radius,
  15147. detail: detail
  15148. };
  15149. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  15150. this.mergeVertices();
  15151. }
  15152. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  15153. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  15154. // DodecahedronBufferGeometry
  15155. function DodecahedronBufferGeometry( radius, detail ) {
  15156. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15157. var r = 1 / t;
  15158. var vertices = [
  15159. // (±1, ±1, ±1)
  15160. - 1, - 1, - 1, - 1, - 1, 1,
  15161. - 1, 1, - 1, - 1, 1, 1,
  15162. 1, - 1, - 1, 1, - 1, 1,
  15163. 1, 1, - 1, 1, 1, 1,
  15164. // (0, ±1/φ, ±φ)
  15165. 0, - r, - t, 0, - r, t,
  15166. 0, r, - t, 0, r, t,
  15167. // (±1/φ, ±φ, 0)
  15168. - r, - t, 0, - r, t, 0,
  15169. r, - t, 0, r, t, 0,
  15170. // (±φ, 0, ±1/φ)
  15171. - t, 0, - r, t, 0, - r,
  15172. - t, 0, r, t, 0, r
  15173. ];
  15174. var indices = [
  15175. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  15176. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  15177. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  15178. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  15179. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  15180. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  15181. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  15182. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  15183. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  15184. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  15185. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  15186. 1, 12, 14, 1, 14, 5, 1, 5, 9
  15187. ];
  15188. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  15189. this.type = 'DodecahedronBufferGeometry';
  15190. this.parameters = {
  15191. radius: radius,
  15192. detail: detail
  15193. };
  15194. }
  15195. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  15196. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  15197. /**
  15198. * @author oosmoxiecode / https://github.com/oosmoxiecode
  15199. * @author WestLangley / https://github.com/WestLangley
  15200. * @author zz85 / https://github.com/zz85
  15201. * @author miningold / https://github.com/miningold
  15202. * @author jonobr1 / https://github.com/jonobr1
  15203. * @author Mugen87 / https://github.com/Mugen87
  15204. *
  15205. */
  15206. // TubeGeometry
  15207. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  15208. Geometry.call( this );
  15209. this.type = 'TubeGeometry';
  15210. this.parameters = {
  15211. path: path,
  15212. tubularSegments: tubularSegments,
  15213. radius: radius,
  15214. radialSegments: radialSegments,
  15215. closed: closed
  15216. };
  15217. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  15218. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  15219. // expose internals
  15220. this.tangents = bufferGeometry.tangents;
  15221. this.normals = bufferGeometry.normals;
  15222. this.binormals = bufferGeometry.binormals;
  15223. // create geometry
  15224. this.fromBufferGeometry( bufferGeometry );
  15225. this.mergeVertices();
  15226. }
  15227. TubeGeometry.prototype = Object.create( Geometry.prototype );
  15228. TubeGeometry.prototype.constructor = TubeGeometry;
  15229. // TubeBufferGeometry
  15230. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  15231. BufferGeometry.call( this );
  15232. this.type = 'TubeBufferGeometry';
  15233. this.parameters = {
  15234. path: path,
  15235. tubularSegments: tubularSegments,
  15236. radius: radius,
  15237. radialSegments: radialSegments,
  15238. closed: closed
  15239. };
  15240. tubularSegments = tubularSegments || 64;
  15241. radius = radius || 1;
  15242. radialSegments = radialSegments || 8;
  15243. closed = closed || false;
  15244. var frames = path.computeFrenetFrames( tubularSegments, closed );
  15245. // expose internals
  15246. this.tangents = frames.tangents;
  15247. this.normals = frames.normals;
  15248. this.binormals = frames.binormals;
  15249. // helper variables
  15250. var vertex = new Vector3();
  15251. var normal = new Vector3();
  15252. var uv = new Vector2();
  15253. var i, j;
  15254. // buffer
  15255. var vertices = [];
  15256. var normals = [];
  15257. var uvs = [];
  15258. var indices = [];
  15259. // create buffer data
  15260. generateBufferData();
  15261. // build geometry
  15262. this.setIndex( indices );
  15263. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15264. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15265. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15266. // functions
  15267. function generateBufferData() {
  15268. for ( i = 0; i < tubularSegments; i ++ ) {
  15269. generateSegment( i );
  15270. }
  15271. // if the geometry is not closed, generate the last row of vertices and normals
  15272. // at the regular position on the given path
  15273. //
  15274. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15275. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15276. // uvs are generated in a separate function.
  15277. // this makes it easy compute correct values for closed geometries
  15278. generateUVs();
  15279. // finally create faces
  15280. generateIndices();
  15281. }
  15282. function generateSegment( i ) {
  15283. // we use getPointAt to sample evenly distributed points from the given path
  15284. var P = path.getPointAt( i / tubularSegments );
  15285. // retrieve corresponding normal and binormal
  15286. var N = frames.normals[ i ];
  15287. var B = frames.binormals[ i ];
  15288. // generate normals and vertices for the current segment
  15289. for ( j = 0; j <= radialSegments; j ++ ) {
  15290. var v = j / radialSegments * Math.PI * 2;
  15291. var sin = Math.sin( v );
  15292. var cos = - Math.cos( v );
  15293. // normal
  15294. normal.x = ( cos * N.x + sin * B.x );
  15295. normal.y = ( cos * N.y + sin * B.y );
  15296. normal.z = ( cos * N.z + sin * B.z );
  15297. normal.normalize();
  15298. normals.push( normal.x, normal.y, normal.z );
  15299. // vertex
  15300. vertex.x = P.x + radius * normal.x;
  15301. vertex.y = P.y + radius * normal.y;
  15302. vertex.z = P.z + radius * normal.z;
  15303. vertices.push( vertex.x, vertex.y, vertex.z );
  15304. }
  15305. }
  15306. function generateIndices() {
  15307. for ( j = 1; j <= tubularSegments; j ++ ) {
  15308. for ( i = 1; i <= radialSegments; i ++ ) {
  15309. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15310. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15311. var c = ( radialSegments + 1 ) * j + i;
  15312. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15313. // faces
  15314. indices.push( a, b, d );
  15315. indices.push( b, c, d );
  15316. }
  15317. }
  15318. }
  15319. function generateUVs() {
  15320. for ( i = 0; i <= tubularSegments; i ++ ) {
  15321. for ( j = 0; j <= radialSegments; j ++ ) {
  15322. uv.x = i / tubularSegments;
  15323. uv.y = j / radialSegments;
  15324. uvs.push( uv.x, uv.y );
  15325. }
  15326. }
  15327. }
  15328. }
  15329. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15330. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15331. /**
  15332. * @author oosmoxiecode
  15333. * @author Mugen87 / https://github.com/Mugen87
  15334. *
  15335. * based on http://www.blackpawn.com/texts/pqtorus/
  15336. */
  15337. // TorusKnotGeometry
  15338. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15339. Geometry.call( this );
  15340. this.type = 'TorusKnotGeometry';
  15341. this.parameters = {
  15342. radius: radius,
  15343. tube: tube,
  15344. tubularSegments: tubularSegments,
  15345. radialSegments: radialSegments,
  15346. p: p,
  15347. q: q
  15348. };
  15349. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15350. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15351. this.mergeVertices();
  15352. }
  15353. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15354. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15355. // TorusKnotBufferGeometry
  15356. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15357. BufferGeometry.call( this );
  15358. this.type = 'TorusKnotBufferGeometry';
  15359. this.parameters = {
  15360. radius: radius,
  15361. tube: tube,
  15362. tubularSegments: tubularSegments,
  15363. radialSegments: radialSegments,
  15364. p: p,
  15365. q: q
  15366. };
  15367. radius = radius || 100;
  15368. tube = tube || 40;
  15369. tubularSegments = Math.floor( tubularSegments ) || 64;
  15370. radialSegments = Math.floor( radialSegments ) || 8;
  15371. p = p || 2;
  15372. q = q || 3;
  15373. // buffers
  15374. var indices = [];
  15375. var vertices = [];
  15376. var normals = [];
  15377. var uvs = [];
  15378. // helper variables
  15379. var i, j;
  15380. var vertex = new Vector3();
  15381. var normal = new Vector3();
  15382. var P1 = new Vector3();
  15383. var P2 = new Vector3();
  15384. var B = new Vector3();
  15385. var T = new Vector3();
  15386. var N = new Vector3();
  15387. // generate vertices, normals and uvs
  15388. for ( i = 0; i <= tubularSegments; ++ i ) {
  15389. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15390. var u = i / tubularSegments * p * Math.PI * 2;
  15391. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15392. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15393. calculatePositionOnCurve( u, p, q, radius, P1 );
  15394. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15395. // calculate orthonormal basis
  15396. T.subVectors( P2, P1 );
  15397. N.addVectors( P2, P1 );
  15398. B.crossVectors( T, N );
  15399. N.crossVectors( B, T );
  15400. // normalize B, N. T can be ignored, we don't use it
  15401. B.normalize();
  15402. N.normalize();
  15403. for ( j = 0; j <= radialSegments; ++ j ) {
  15404. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15405. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15406. var v = j / radialSegments * Math.PI * 2;
  15407. var cx = - tube * Math.cos( v );
  15408. var cy = tube * Math.sin( v );
  15409. // now calculate the final vertex position.
  15410. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15411. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15412. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15413. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15414. vertices.push( vertex.x, vertex.y, vertex.z );
  15415. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15416. normal.subVectors( vertex, P1 ).normalize();
  15417. normals.push( normal.x, normal.y, normal.z );
  15418. // uv
  15419. uvs.push( i / tubularSegments );
  15420. uvs.push( j / radialSegments );
  15421. }
  15422. }
  15423. // generate indices
  15424. for ( j = 1; j <= tubularSegments; j ++ ) {
  15425. for ( i = 1; i <= radialSegments; i ++ ) {
  15426. // indices
  15427. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15428. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15429. var c = ( radialSegments + 1 ) * j + i;
  15430. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15431. // faces
  15432. indices.push( a, b, d );
  15433. indices.push( b, c, d );
  15434. }
  15435. }
  15436. // build geometry
  15437. this.setIndex( indices );
  15438. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15439. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15440. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15441. // this function calculates the current position on the torus curve
  15442. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15443. var cu = Math.cos( u );
  15444. var su = Math.sin( u );
  15445. var quOverP = q / p * u;
  15446. var cs = Math.cos( quOverP );
  15447. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15448. position.y = radius * ( 2 + cs ) * su * 0.5;
  15449. position.z = radius * Math.sin( quOverP ) * 0.5;
  15450. }
  15451. }
  15452. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15453. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15454. /**
  15455. * @author oosmoxiecode
  15456. * @author mrdoob / http://mrdoob.com/
  15457. * @author Mugen87 / https://github.com/Mugen87
  15458. */
  15459. // TorusGeometry
  15460. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15461. Geometry.call( this );
  15462. this.type = 'TorusGeometry';
  15463. this.parameters = {
  15464. radius: radius,
  15465. tube: tube,
  15466. radialSegments: radialSegments,
  15467. tubularSegments: tubularSegments,
  15468. arc: arc
  15469. };
  15470. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15471. this.mergeVertices();
  15472. }
  15473. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15474. TorusGeometry.prototype.constructor = TorusGeometry;
  15475. // TorusBufferGeometry
  15476. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15477. BufferGeometry.call( this );
  15478. this.type = 'TorusBufferGeometry';
  15479. this.parameters = {
  15480. radius: radius,
  15481. tube: tube,
  15482. radialSegments: radialSegments,
  15483. tubularSegments: tubularSegments,
  15484. arc: arc
  15485. };
  15486. radius = radius || 100;
  15487. tube = tube || 40;
  15488. radialSegments = Math.floor( radialSegments ) || 8;
  15489. tubularSegments = Math.floor( tubularSegments ) || 6;
  15490. arc = arc || Math.PI * 2;
  15491. // buffers
  15492. var indices = [];
  15493. var vertices = [];
  15494. var normals = [];
  15495. var uvs = [];
  15496. // helper variables
  15497. var center = new Vector3();
  15498. var vertex = new Vector3();
  15499. var normal = new Vector3();
  15500. var j, i;
  15501. // generate vertices, normals and uvs
  15502. for ( j = 0; j <= radialSegments; j ++ ) {
  15503. for ( i = 0; i <= tubularSegments; i ++ ) {
  15504. var u = i / tubularSegments * arc;
  15505. var v = j / radialSegments * Math.PI * 2;
  15506. // vertex
  15507. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15508. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15509. vertex.z = tube * Math.sin( v );
  15510. vertices.push( vertex.x, vertex.y, vertex.z );
  15511. // normal
  15512. center.x = radius * Math.cos( u );
  15513. center.y = radius * Math.sin( u );
  15514. normal.subVectors( vertex, center ).normalize();
  15515. normals.push( normal.x, normal.y, normal.z );
  15516. // uv
  15517. uvs.push( i / tubularSegments );
  15518. uvs.push( j / radialSegments );
  15519. }
  15520. }
  15521. // generate indices
  15522. for ( j = 1; j <= radialSegments; j ++ ) {
  15523. for ( i = 1; i <= tubularSegments; i ++ ) {
  15524. // indices
  15525. var a = ( tubularSegments + 1 ) * j + i - 1;
  15526. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15527. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15528. var d = ( tubularSegments + 1 ) * j + i;
  15529. // faces
  15530. indices.push( a, b, d );
  15531. indices.push( b, c, d );
  15532. }
  15533. }
  15534. // build geometry
  15535. this.setIndex( indices );
  15536. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15537. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15538. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15539. }
  15540. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15541. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15542. /**
  15543. * @author zz85 / http://www.lab4games.net/zz85/blog
  15544. */
  15545. var ShapeUtils = {
  15546. // calculate area of the contour polygon
  15547. area: function ( contour ) {
  15548. var n = contour.length;
  15549. var a = 0.0;
  15550. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15551. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15552. }
  15553. return a * 0.5;
  15554. },
  15555. triangulate: ( function () {
  15556. /**
  15557. * This code is a quick port of code written in C++ which was submitted to
  15558. * flipcode.com by John W. Ratcliff // July 22, 2000
  15559. * See original code and more information here:
  15560. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15561. *
  15562. * ported to actionscript by Zevan Rosser
  15563. * www.actionsnippet.com
  15564. *
  15565. * ported to javascript by Joshua Koo
  15566. * http://www.lab4games.net/zz85/blog
  15567. *
  15568. */
  15569. function snip( contour, u, v, w, n, verts ) {
  15570. var p;
  15571. var ax, ay, bx, by;
  15572. var cx, cy, px, py;
  15573. ax = contour[ verts[ u ] ].x;
  15574. ay = contour[ verts[ u ] ].y;
  15575. bx = contour[ verts[ v ] ].x;
  15576. by = contour[ verts[ v ] ].y;
  15577. cx = contour[ verts[ w ] ].x;
  15578. cy = contour[ verts[ w ] ].y;
  15579. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15580. var aX, aY, bX, bY, cX, cY;
  15581. var apx, apy, bpx, bpy, cpx, cpy;
  15582. var cCROSSap, bCROSScp, aCROSSbp;
  15583. aX = cx - bx; aY = cy - by;
  15584. bX = ax - cx; bY = ay - cy;
  15585. cX = bx - ax; cY = by - ay;
  15586. for ( p = 0; p < n; p ++ ) {
  15587. px = contour[ verts[ p ] ].x;
  15588. py = contour[ verts[ p ] ].y;
  15589. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15590. ( ( px === bx ) && ( py === by ) ) ||
  15591. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15592. apx = px - ax; apy = py - ay;
  15593. bpx = px - bx; bpy = py - by;
  15594. cpx = px - cx; cpy = py - cy;
  15595. // see if p is inside triangle abc
  15596. aCROSSbp = aX * bpy - aY * bpx;
  15597. cCROSSap = cX * apy - cY * apx;
  15598. bCROSScp = bX * cpy - bY * cpx;
  15599. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15600. }
  15601. return true;
  15602. }
  15603. // takes in an contour array and returns
  15604. return function triangulate( contour, indices ) {
  15605. var n = contour.length;
  15606. if ( n < 3 ) return null;
  15607. var result = [],
  15608. verts = [],
  15609. vertIndices = [];
  15610. /* we want a counter-clockwise polygon in verts */
  15611. var u, v, w;
  15612. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15613. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15614. } else {
  15615. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15616. }
  15617. var nv = n;
  15618. /* remove nv - 2 vertices, creating 1 triangle every time */
  15619. var count = 2 * nv; /* error detection */
  15620. for ( v = nv - 1; nv > 2; ) {
  15621. /* if we loop, it is probably a non-simple polygon */
  15622. if ( ( count -- ) <= 0 ) {
  15623. //** Triangulate: ERROR - probable bad polygon!
  15624. //throw ( "Warning, unable to triangulate polygon!" );
  15625. //return null;
  15626. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15627. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15628. if ( indices ) return vertIndices;
  15629. return result;
  15630. }
  15631. /* three consecutive vertices in current polygon, <u,v,w> */
  15632. u = v; if ( nv <= u ) u = 0; /* previous */
  15633. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15634. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15635. if ( snip( contour, u, v, w, nv, verts ) ) {
  15636. var a, b, c, s, t;
  15637. /* true names of the vertices */
  15638. a = verts[ u ];
  15639. b = verts[ v ];
  15640. c = verts[ w ];
  15641. /* output Triangle */
  15642. result.push( [ contour[ a ],
  15643. contour[ b ],
  15644. contour[ c ] ] );
  15645. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15646. /* remove v from the remaining polygon */
  15647. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15648. verts[ s ] = verts[ t ];
  15649. }
  15650. nv --;
  15651. /* reset error detection counter */
  15652. count = 2 * nv;
  15653. }
  15654. }
  15655. if ( indices ) return vertIndices;
  15656. return result;
  15657. };
  15658. } )(),
  15659. triangulateShape: function ( contour, holes ) {
  15660. function removeDupEndPts(points) {
  15661. var l = points.length;
  15662. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15663. points.pop();
  15664. }
  15665. }
  15666. removeDupEndPts( contour );
  15667. holes.forEach( removeDupEndPts );
  15668. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15669. // inOtherPt needs to be collinear to the inSegment
  15670. if ( inSegPt1.x !== inSegPt2.x ) {
  15671. if ( inSegPt1.x < inSegPt2.x ) {
  15672. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15673. } else {
  15674. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15675. }
  15676. } else {
  15677. if ( inSegPt1.y < inSegPt2.y ) {
  15678. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15679. } else {
  15680. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15681. }
  15682. }
  15683. }
  15684. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15685. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15686. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15687. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15688. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15689. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15690. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15691. if ( Math.abs( limit ) > Number.EPSILON ) {
  15692. // not parallel
  15693. var perpSeg2;
  15694. if ( limit > 0 ) {
  15695. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15696. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15697. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15698. } else {
  15699. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15700. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15701. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15702. }
  15703. // i.e. to reduce rounding errors
  15704. // intersection at endpoint of segment#1?
  15705. if ( perpSeg2 === 0 ) {
  15706. if ( ( inExcludeAdjacentSegs ) &&
  15707. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15708. return [ inSeg1Pt1 ];
  15709. }
  15710. if ( perpSeg2 === limit ) {
  15711. if ( ( inExcludeAdjacentSegs ) &&
  15712. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15713. return [ inSeg1Pt2 ];
  15714. }
  15715. // intersection at endpoint of segment#2?
  15716. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15717. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15718. // return real intersection point
  15719. var factorSeg1 = perpSeg2 / limit;
  15720. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15721. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15722. } else {
  15723. // parallel or collinear
  15724. if ( ( perpSeg1 !== 0 ) ||
  15725. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15726. // they are collinear or degenerate
  15727. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15728. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15729. // both segments are points
  15730. if ( seg1Pt && seg2Pt ) {
  15731. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15732. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15733. return [ inSeg1Pt1 ]; // they are the same point
  15734. }
  15735. // segment#1 is a single point
  15736. if ( seg1Pt ) {
  15737. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15738. return [ inSeg1Pt1 ];
  15739. }
  15740. // segment#2 is a single point
  15741. if ( seg2Pt ) {
  15742. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15743. return [ inSeg2Pt1 ];
  15744. }
  15745. // they are collinear segments, which might overlap
  15746. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15747. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15748. if ( seg1dx !== 0 ) {
  15749. // the segments are NOT on a vertical line
  15750. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15751. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15752. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15753. } else {
  15754. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15755. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15756. }
  15757. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15758. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15759. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15760. } else {
  15761. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15762. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15763. }
  15764. } else {
  15765. // the segments are on a vertical line
  15766. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15767. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15768. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15769. } else {
  15770. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15771. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15772. }
  15773. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15774. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15775. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15776. } else {
  15777. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15778. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15779. }
  15780. }
  15781. if ( seg1minVal <= seg2minVal ) {
  15782. if ( seg1maxVal < seg2minVal ) return [];
  15783. if ( seg1maxVal === seg2minVal ) {
  15784. if ( inExcludeAdjacentSegs ) return [];
  15785. return [ seg2min ];
  15786. }
  15787. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15788. return [ seg2min, seg2max ];
  15789. } else {
  15790. if ( seg1minVal > seg2maxVal ) return [];
  15791. if ( seg1minVal === seg2maxVal ) {
  15792. if ( inExcludeAdjacentSegs ) return [];
  15793. return [ seg1min ];
  15794. }
  15795. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15796. return [ seg1min, seg2max ];
  15797. }
  15798. }
  15799. }
  15800. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15801. // The order of legs is important
  15802. // translation of all points, so that Vertex is at (0,0)
  15803. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15804. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15805. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15806. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15807. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15808. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15809. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15810. // angle != 180 deg.
  15811. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15812. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15813. if ( from2toAngle > 0 ) {
  15814. // main angle < 180 deg.
  15815. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15816. } else {
  15817. // main angle > 180 deg.
  15818. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15819. }
  15820. } else {
  15821. // angle == 180 deg.
  15822. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15823. return ( from2otherAngle > 0 );
  15824. }
  15825. }
  15826. function removeHoles( contour, holes ) {
  15827. var shape = contour.concat(); // work on this shape
  15828. var hole;
  15829. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15830. // Check if hole point lies within angle around shape point
  15831. var lastShapeIdx = shape.length - 1;
  15832. var prevShapeIdx = inShapeIdx - 1;
  15833. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15834. var nextShapeIdx = inShapeIdx + 1;
  15835. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15836. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15837. if ( ! insideAngle ) {
  15838. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15839. return false;
  15840. }
  15841. // Check if shape point lies within angle around hole point
  15842. var lastHoleIdx = hole.length - 1;
  15843. var prevHoleIdx = inHoleIdx - 1;
  15844. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15845. var nextHoleIdx = inHoleIdx + 1;
  15846. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15847. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15848. if ( ! insideAngle ) {
  15849. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15850. return false;
  15851. }
  15852. return true;
  15853. }
  15854. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15855. // checks for intersections with shape edges
  15856. var sIdx, nextIdx, intersection;
  15857. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15858. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15859. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15860. if ( intersection.length > 0 ) return true;
  15861. }
  15862. return false;
  15863. }
  15864. var indepHoles = [];
  15865. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15866. // checks for intersections with hole edges
  15867. var ihIdx, chkHole,
  15868. hIdx, nextIdx, intersection;
  15869. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15870. chkHole = holes[ indepHoles[ ihIdx ] ];
  15871. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15872. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15873. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15874. if ( intersection.length > 0 ) return true;
  15875. }
  15876. }
  15877. return false;
  15878. }
  15879. var holeIndex, shapeIndex,
  15880. shapePt, holePt,
  15881. holeIdx, cutKey, failedCuts = [],
  15882. tmpShape1, tmpShape2,
  15883. tmpHole1, tmpHole2;
  15884. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15885. indepHoles.push( h );
  15886. }
  15887. var minShapeIndex = 0;
  15888. var counter = indepHoles.length * 2;
  15889. while ( indepHoles.length > 0 ) {
  15890. counter --;
  15891. if ( counter < 0 ) {
  15892. console.log( 'THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!' );
  15893. break;
  15894. }
  15895. // search for shape-vertex and hole-vertex,
  15896. // which can be connected without intersections
  15897. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15898. shapePt = shape[ shapeIndex ];
  15899. holeIndex = - 1;
  15900. // search for hole which can be reached without intersections
  15901. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15902. holeIdx = indepHoles[ h ];
  15903. // prevent multiple checks
  15904. cutKey = shapePt.x + ':' + shapePt.y + ':' + holeIdx;
  15905. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15906. hole = holes[ holeIdx ];
  15907. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15908. holePt = hole[ h2 ];
  15909. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15910. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15911. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15912. holeIndex = h2;
  15913. indepHoles.splice( h, 1 );
  15914. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15915. tmpShape2 = shape.slice( shapeIndex );
  15916. tmpHole1 = hole.slice( holeIndex );
  15917. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15918. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15919. minShapeIndex = shapeIndex;
  15920. // Debug only, to show the selected cuts
  15921. // glob_CutLines.push( [ shapePt, holePt ] );
  15922. break;
  15923. }
  15924. if ( holeIndex >= 0 ) break; // hole-vertex found
  15925. failedCuts[ cutKey ] = true; // remember failure
  15926. }
  15927. if ( holeIndex >= 0 ) break; // hole-vertex found
  15928. }
  15929. }
  15930. return shape; /* shape with no holes */
  15931. }
  15932. var i, il, f, face,
  15933. key, index,
  15934. allPointsMap = {};
  15935. // 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.
  15936. var allpoints = contour.concat();
  15937. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15938. Array.prototype.push.apply( allpoints, holes[ h ] );
  15939. }
  15940. //console.log( "allpoints",allpoints, allpoints.length );
  15941. // prepare all points map
  15942. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15943. key = allpoints[ i ].x + ':' + allpoints[ i ].y;
  15944. if ( allPointsMap[ key ] !== undefined ) {
  15945. console.warn( 'THREE.ShapeUtils: Duplicate point', key, i );
  15946. }
  15947. allPointsMap[ key ] = i;
  15948. }
  15949. // remove holes by cutting paths to holes and adding them to the shape
  15950. var shapeWithoutHoles = removeHoles( contour, holes );
  15951. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15952. //console.log( "triangles",triangles, triangles.length );
  15953. // check all face vertices against all points map
  15954. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15955. face = triangles[ i ];
  15956. for ( f = 0; f < 3; f ++ ) {
  15957. key = face[ f ].x + ':' + face[ f ].y;
  15958. index = allPointsMap[ key ];
  15959. if ( index !== undefined ) {
  15960. face[ f ] = index;
  15961. }
  15962. }
  15963. }
  15964. return triangles.concat();
  15965. },
  15966. isClockWise: function ( pts ) {
  15967. return ShapeUtils.area( pts ) < 0;
  15968. }
  15969. };
  15970. /**
  15971. * @author zz85 / http://www.lab4games.net/zz85/blog
  15972. *
  15973. * Creates extruded geometry from a path shape.
  15974. *
  15975. * parameters = {
  15976. *
  15977. * curveSegments: <int>, // number of points on the curves
  15978. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15979. * amount: <int>, // Depth to extrude the shape
  15980. *
  15981. * bevelEnabled: <bool>, // turn on bevel
  15982. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15983. * bevelSize: <float>, // how far from shape outline is bevel
  15984. * bevelSegments: <int>, // number of bevel layers
  15985. *
  15986. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15987. * frames: <Object> // containing arrays of tangents, normals, binormals
  15988. *
  15989. * UVGenerator: <Object> // object that provides UV generator functions
  15990. *
  15991. * }
  15992. */
  15993. // ExtrudeGeometry
  15994. function ExtrudeGeometry( shapes, options ) {
  15995. Geometry.call( this );
  15996. this.type = 'ExtrudeGeometry';
  15997. this.parameters = {
  15998. shapes: shapes,
  15999. options: options
  16000. };
  16001. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  16002. this.mergeVertices();
  16003. }
  16004. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  16005. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  16006. // ExtrudeBufferGeometry
  16007. function ExtrudeBufferGeometry( shapes, options ) {
  16008. if ( typeof ( shapes ) === "undefined" ) {
  16009. return;
  16010. }
  16011. BufferGeometry.call( this );
  16012. this.type = 'ExtrudeBufferGeometry';
  16013. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  16014. this.addShapeList( shapes, options );
  16015. this.computeVertexNormals();
  16016. // can't really use automatic vertex normals
  16017. // as then front and back sides get smoothed too
  16018. // should do separate smoothing just for sides
  16019. //this.computeVertexNormals();
  16020. //console.log( "took", ( Date.now() - startTime ) );
  16021. }
  16022. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16023. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  16024. ExtrudeBufferGeometry.prototype.getArrays = function () {
  16025. var positionAttribute = this.getAttribute( "position" );
  16026. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  16027. var uvAttribute = this.getAttribute( "uv" );
  16028. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  16029. var IndexAttribute = this.index;
  16030. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  16031. return {
  16032. position: verticesArray,
  16033. uv: uvArray,
  16034. index: indicesArray
  16035. };
  16036. };
  16037. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  16038. var sl = shapes.length;
  16039. options.arrays = this.getArrays();
  16040. for ( var s = 0; s < sl; s ++ ) {
  16041. var shape = shapes[ s ];
  16042. this.addShape( shape, options );
  16043. }
  16044. this.setIndex( options.arrays.index );
  16045. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  16046. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16047. };
  16048. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  16049. var arrays = options.arrays ? options.arrays : this.getArrays();
  16050. var verticesArray = arrays.position;
  16051. var indicesArray = arrays.index;
  16052. var uvArray = arrays.uv;
  16053. var placeholder = [];
  16054. var amount = options.amount !== undefined ? options.amount : 100;
  16055. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  16056. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  16057. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  16058. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  16059. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  16060. var steps = options.steps !== undefined ? options.steps : 1;
  16061. var extrudePath = options.extrudePath;
  16062. var extrudePts, extrudeByPath = false;
  16063. // Use default WorldUVGenerator if no UV generators are specified.
  16064. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  16065. var splineTube, binormal, normal, position2;
  16066. if ( extrudePath ) {
  16067. extrudePts = extrudePath.getSpacedPoints( steps );
  16068. extrudeByPath = true;
  16069. bevelEnabled = false; // bevels not supported for path extrusion
  16070. // SETUP TNB variables
  16071. // TODO1 - have a .isClosed in spline?
  16072. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  16073. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  16074. binormal = new Vector3();
  16075. normal = new Vector3();
  16076. position2 = new Vector3();
  16077. }
  16078. // Safeguards if bevels are not enabled
  16079. if ( ! bevelEnabled ) {
  16080. bevelSegments = 0;
  16081. bevelThickness = 0;
  16082. bevelSize = 0;
  16083. }
  16084. // Variables initialization
  16085. var ahole, h, hl; // looping of holes
  16086. var scope = this;
  16087. var shapePoints = shape.extractPoints( curveSegments );
  16088. var vertices = shapePoints.shape;
  16089. var holes = shapePoints.holes;
  16090. var reverse = ! ShapeUtils.isClockWise( vertices );
  16091. if ( reverse ) {
  16092. vertices = vertices.reverse();
  16093. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  16094. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16095. ahole = holes[ h ];
  16096. if ( ShapeUtils.isClockWise( ahole ) ) {
  16097. holes[ h ] = ahole.reverse();
  16098. }
  16099. }
  16100. }
  16101. var faces = ShapeUtils.triangulateShape( vertices, holes );
  16102. /* Vertices */
  16103. var contour = vertices; // vertices has all points but contour has only points of circumference
  16104. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16105. ahole = holes[ h ];
  16106. vertices = vertices.concat( ahole );
  16107. }
  16108. function scalePt2( pt, vec, size ) {
  16109. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  16110. return vec.clone().multiplyScalar( size ).add( pt );
  16111. }
  16112. var b, bs, t, z,
  16113. vert, vlen = vertices.length,
  16114. face, flen = faces.length;
  16115. // Find directions for point movement
  16116. function getBevelVec( inPt, inPrev, inNext ) {
  16117. // computes for inPt the corresponding point inPt' on a new contour
  16118. // shifted by 1 unit (length of normalized vector) to the left
  16119. // if we walk along contour clockwise, this new contour is outside the old one
  16120. //
  16121. // inPt' is the intersection of the two lines parallel to the two
  16122. // adjacent edges of inPt at a distance of 1 unit on the left side.
  16123. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  16124. // good reading for geometry algorithms (here: line-line intersection)
  16125. // http://geomalgorithms.com/a05-_intersect-1.html
  16126. var v_prev_x = inPt.x - inPrev.x,
  16127. v_prev_y = inPt.y - inPrev.y;
  16128. var v_next_x = inNext.x - inPt.x,
  16129. v_next_y = inNext.y - inPt.y;
  16130. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  16131. // check for collinear edges
  16132. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16133. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  16134. // not collinear
  16135. // length of vectors for normalizing
  16136. var v_prev_len = Math.sqrt( v_prev_lensq );
  16137. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  16138. // shift adjacent points by unit vectors to the left
  16139. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  16140. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  16141. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  16142. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  16143. // scaling factor for v_prev to intersection point
  16144. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  16145. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  16146. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  16147. // vector from inPt to intersection point
  16148. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  16149. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  16150. // Don't normalize!, otherwise sharp corners become ugly
  16151. // but prevent crazy spikes
  16152. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  16153. if ( v_trans_lensq <= 2 ) {
  16154. return new Vector2( v_trans_x, v_trans_y );
  16155. } else {
  16156. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  16157. }
  16158. } else {
  16159. // handle special case of collinear edges
  16160. var direction_eq = false; // assumes: opposite
  16161. if ( v_prev_x > Number.EPSILON ) {
  16162. if ( v_next_x > Number.EPSILON ) {
  16163. direction_eq = true;
  16164. }
  16165. } else {
  16166. if ( v_prev_x < - Number.EPSILON ) {
  16167. if ( v_next_x < - Number.EPSILON ) {
  16168. direction_eq = true;
  16169. }
  16170. } else {
  16171. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  16172. direction_eq = true;
  16173. }
  16174. }
  16175. }
  16176. if ( direction_eq ) {
  16177. // console.log("Warning: lines are a straight sequence");
  16178. v_trans_x = - v_prev_y;
  16179. v_trans_y = v_prev_x;
  16180. shrink_by = Math.sqrt( v_prev_lensq );
  16181. } else {
  16182. // console.log("Warning: lines are a straight spike");
  16183. v_trans_x = v_prev_x;
  16184. v_trans_y = v_prev_y;
  16185. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  16186. }
  16187. }
  16188. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  16189. }
  16190. var contourMovements = [];
  16191. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16192. if ( j === il ) j = 0;
  16193. if ( k === il ) k = 0;
  16194. // (j)---(i)---(k)
  16195. // console.log('i,j,k', i, j , k)
  16196. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  16197. }
  16198. var holesMovements = [],
  16199. oneHoleMovements, verticesMovements = contourMovements.concat();
  16200. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16201. ahole = holes[ h ];
  16202. oneHoleMovements = [];
  16203. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  16204. if ( j === il ) j = 0;
  16205. if ( k === il ) k = 0;
  16206. // (j)---(i)---(k)
  16207. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  16208. }
  16209. holesMovements.push( oneHoleMovements );
  16210. verticesMovements = verticesMovements.concat( oneHoleMovements );
  16211. }
  16212. // Loop bevelSegments, 1 for the front, 1 for the back
  16213. for ( b = 0; b < bevelSegments; b ++ ) {
  16214. //for ( b = bevelSegments; b > 0; b -- ) {
  16215. t = b / bevelSegments;
  16216. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16217. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16218. // contract shape
  16219. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16220. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16221. v( vert.x, vert.y, - z );
  16222. }
  16223. // expand holes
  16224. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16225. ahole = holes[ h ];
  16226. oneHoleMovements = holesMovements[ h ];
  16227. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16228. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16229. v( vert.x, vert.y, - z );
  16230. }
  16231. }
  16232. }
  16233. bs = bevelSize;
  16234. // Back facing vertices
  16235. for ( i = 0; i < vlen; i ++ ) {
  16236. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16237. if ( ! extrudeByPath ) {
  16238. v( vert.x, vert.y, 0 );
  16239. } else {
  16240. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  16241. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  16242. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  16243. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  16244. v( position2.x, position2.y, position2.z );
  16245. }
  16246. }
  16247. // Add stepped vertices...
  16248. // Including front facing vertices
  16249. var s;
  16250. for ( s = 1; s <= steps; s ++ ) {
  16251. for ( i = 0; i < vlen; i ++ ) {
  16252. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  16253. if ( ! extrudeByPath ) {
  16254. v( vert.x, vert.y, amount / steps * s );
  16255. } else {
  16256. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  16257. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  16258. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  16259. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  16260. v( position2.x, position2.y, position2.z );
  16261. }
  16262. }
  16263. }
  16264. // Add bevel segments planes
  16265. //for ( b = 1; b <= bevelSegments; b ++ ) {
  16266. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  16267. t = b / bevelSegments;
  16268. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  16269. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  16270. // contract shape
  16271. for ( i = 0, il = contour.length; i < il; i ++ ) {
  16272. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  16273. v( vert.x, vert.y, amount + z );
  16274. }
  16275. // expand holes
  16276. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16277. ahole = holes[ h ];
  16278. oneHoleMovements = holesMovements[ h ];
  16279. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  16280. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  16281. if ( ! extrudeByPath ) {
  16282. v( vert.x, vert.y, amount + z );
  16283. } else {
  16284. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  16285. }
  16286. }
  16287. }
  16288. }
  16289. /* Faces */
  16290. // Top and bottom faces
  16291. buildLidFaces();
  16292. // Sides faces
  16293. buildSideFaces();
  16294. ///// Internal functions
  16295. function buildLidFaces() {
  16296. var start = verticesArray.length/3;
  16297. if ( bevelEnabled ) {
  16298. var layer = 0; // steps + 1
  16299. var offset = vlen * layer;
  16300. // Bottom faces
  16301. for ( i = 0; i < flen; i ++ ) {
  16302. face = faces[ i ];
  16303. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16304. }
  16305. layer = steps + bevelSegments * 2;
  16306. offset = vlen * layer;
  16307. // Top faces
  16308. for ( i = 0; i < flen; i ++ ) {
  16309. face = faces[ i ];
  16310. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16311. }
  16312. } else {
  16313. // Bottom faces
  16314. for ( i = 0; i < flen; i ++ ) {
  16315. face = faces[ i ];
  16316. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16317. }
  16318. // Top faces
  16319. for ( i = 0; i < flen; i ++ ) {
  16320. face = faces[ i ];
  16321. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16322. }
  16323. }
  16324. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16325. }
  16326. // Create faces for the z-sides of the shape
  16327. function buildSideFaces() {
  16328. var start = verticesArray.length/3;
  16329. var layeroffset = 0;
  16330. sidewalls( contour, layeroffset );
  16331. layeroffset += contour.length;
  16332. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16333. ahole = holes[ h ];
  16334. sidewalls( ahole, layeroffset );
  16335. //, true
  16336. layeroffset += ahole.length;
  16337. }
  16338. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16339. }
  16340. function sidewalls( contour, layeroffset ) {
  16341. var j, k;
  16342. i = contour.length;
  16343. while ( -- i >= 0 ) {
  16344. j = i;
  16345. k = i - 1;
  16346. if ( k < 0 ) k = contour.length - 1;
  16347. //console.log('b', i,j, i-1, k,vertices.length);
  16348. var s = 0,
  16349. sl = steps + bevelSegments * 2;
  16350. for ( s = 0; s < sl; s ++ ) {
  16351. var slen1 = vlen * s;
  16352. var slen2 = vlen * ( s + 1 );
  16353. var a = layeroffset + j + slen1,
  16354. b = layeroffset + k + slen1,
  16355. c = layeroffset + k + slen2,
  16356. d = layeroffset + j + slen2;
  16357. f4( a, b, c, d, contour, s, sl, j, k );
  16358. }
  16359. }
  16360. }
  16361. function v( x, y, z ) {
  16362. placeholder.push( x );
  16363. placeholder.push( y );
  16364. placeholder.push( z );
  16365. }
  16366. function f3( a, b, c ) {
  16367. addVertex( a );
  16368. addVertex( b );
  16369. addVertex( c );
  16370. var nextIndex = verticesArray.length / 3;
  16371. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16372. addUV( uvs[ 0 ] );
  16373. addUV( uvs[ 1 ] );
  16374. addUV( uvs[ 2 ] );
  16375. }
  16376. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16377. addVertex( a );
  16378. addVertex( b );
  16379. addVertex( d );
  16380. addVertex( b );
  16381. addVertex( c );
  16382. addVertex( d );
  16383. var nextIndex = verticesArray.length / 3;
  16384. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16385. addUV( uvs[ 0 ] );
  16386. addUV( uvs[ 1 ] );
  16387. addUV( uvs[ 3 ] );
  16388. addUV( uvs[ 1 ] );
  16389. addUV( uvs[ 2 ] );
  16390. addUV( uvs[ 3 ] );
  16391. }
  16392. function addVertex( index ) {
  16393. indicesArray.push( verticesArray.length / 3 );
  16394. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16395. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16396. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16397. }
  16398. function addUV( vector2 ) {
  16399. uvArray.push( vector2.x );
  16400. uvArray.push( vector2.y );
  16401. }
  16402. if ( ! options.arrays ) {
  16403. this.setIndex( indicesArray );
  16404. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16405. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16406. }
  16407. };
  16408. ExtrudeGeometry.WorldUVGenerator = {
  16409. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16410. var a_x = vertices[ indexA * 3 ];
  16411. var a_y = vertices[ indexA * 3 + 1 ];
  16412. var b_x = vertices[ indexB * 3 ];
  16413. var b_y = vertices[ indexB * 3 + 1 ];
  16414. var c_x = vertices[ indexC * 3 ];
  16415. var c_y = vertices[ indexC * 3 + 1 ];
  16416. return [
  16417. new Vector2( a_x, a_y ),
  16418. new Vector2( b_x, b_y ),
  16419. new Vector2( c_x, c_y )
  16420. ];
  16421. },
  16422. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16423. var a_x = vertices[ indexA * 3 ];
  16424. var a_y = vertices[ indexA * 3 + 1 ];
  16425. var a_z = vertices[ indexA * 3 + 2 ];
  16426. var b_x = vertices[ indexB * 3 ];
  16427. var b_y = vertices[ indexB * 3 + 1 ];
  16428. var b_z = vertices[ indexB * 3 + 2 ];
  16429. var c_x = vertices[ indexC * 3 ];
  16430. var c_y = vertices[ indexC * 3 + 1 ];
  16431. var c_z = vertices[ indexC * 3 + 2 ];
  16432. var d_x = vertices[ indexD * 3 ];
  16433. var d_y = vertices[ indexD * 3 + 1 ];
  16434. var d_z = vertices[ indexD * 3 + 2 ];
  16435. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16436. return [
  16437. new Vector2( a_x, 1 - a_z ),
  16438. new Vector2( b_x, 1 - b_z ),
  16439. new Vector2( c_x, 1 - c_z ),
  16440. new Vector2( d_x, 1 - d_z )
  16441. ];
  16442. } else {
  16443. return [
  16444. new Vector2( a_y, 1 - a_z ),
  16445. new Vector2( b_y, 1 - b_z ),
  16446. new Vector2( c_y, 1 - c_z ),
  16447. new Vector2( d_y, 1 - d_z )
  16448. ];
  16449. }
  16450. }
  16451. };
  16452. /**
  16453. * @author zz85 / http://www.lab4games.net/zz85/blog
  16454. * @author alteredq / http://alteredqualia.com/
  16455. *
  16456. * Text = 3D Text
  16457. *
  16458. * parameters = {
  16459. * font: <THREE.Font>, // font
  16460. *
  16461. * size: <float>, // size of the text
  16462. * height: <float>, // thickness to extrude text
  16463. * curveSegments: <int>, // number of points on the curves
  16464. *
  16465. * bevelEnabled: <bool>, // turn on bevel
  16466. * bevelThickness: <float>, // how deep into text bevel goes
  16467. * bevelSize: <float> // how far from text outline is bevel
  16468. * }
  16469. */
  16470. // TextGeometry
  16471. function TextGeometry( text, parameters ) {
  16472. Geometry.call( this );
  16473. this.type = 'TextGeometry';
  16474. this.parameters = {
  16475. text: text,
  16476. parameters: parameters
  16477. };
  16478. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16479. this.mergeVertices();
  16480. }
  16481. TextGeometry.prototype = Object.create( Geometry.prototype );
  16482. TextGeometry.prototype.constructor = TextGeometry;
  16483. // TextBufferGeometry
  16484. function TextBufferGeometry( text, parameters ) {
  16485. parameters = parameters || {};
  16486. var font = parameters.font;
  16487. if ( ! ( font && font.isFont ) ) {
  16488. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16489. return new Geometry();
  16490. }
  16491. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16492. // translate parameters to ExtrudeGeometry API
  16493. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16494. // defaults
  16495. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16496. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16497. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16498. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16499. this.type = 'TextBufferGeometry';
  16500. }
  16501. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16502. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16503. /**
  16504. * @author mrdoob / http://mrdoob.com/
  16505. * @author benaadams / https://twitter.com/ben_a_adams
  16506. * @author Mugen87 / https://github.com/Mugen87
  16507. */
  16508. // SphereGeometry
  16509. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16510. Geometry.call( this );
  16511. this.type = 'SphereGeometry';
  16512. this.parameters = {
  16513. radius: radius,
  16514. widthSegments: widthSegments,
  16515. heightSegments: heightSegments,
  16516. phiStart: phiStart,
  16517. phiLength: phiLength,
  16518. thetaStart: thetaStart,
  16519. thetaLength: thetaLength
  16520. };
  16521. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16522. this.mergeVertices();
  16523. }
  16524. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16525. SphereGeometry.prototype.constructor = SphereGeometry;
  16526. // SphereBufferGeometry
  16527. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16528. BufferGeometry.call( this );
  16529. this.type = 'SphereBufferGeometry';
  16530. this.parameters = {
  16531. radius: radius,
  16532. widthSegments: widthSegments,
  16533. heightSegments: heightSegments,
  16534. phiStart: phiStart,
  16535. phiLength: phiLength,
  16536. thetaStart: thetaStart,
  16537. thetaLength: thetaLength
  16538. };
  16539. radius = radius || 50;
  16540. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16541. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16542. phiStart = phiStart !== undefined ? phiStart : 0;
  16543. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16544. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16545. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16546. var thetaEnd = thetaStart + thetaLength;
  16547. var ix, iy;
  16548. var index = 0;
  16549. var grid = [];
  16550. var vertex = new Vector3();
  16551. var normal = new Vector3();
  16552. // buffers
  16553. var indices = [];
  16554. var vertices = [];
  16555. var normals = [];
  16556. var uvs = [];
  16557. // generate vertices, normals and uvs
  16558. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16559. var verticesRow = [];
  16560. var v = iy / heightSegments;
  16561. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16562. var u = ix / widthSegments;
  16563. // vertex
  16564. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16565. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16566. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16567. vertices.push( vertex.x, vertex.y, vertex.z );
  16568. // normal
  16569. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16570. normals.push( normal.x, normal.y, normal.z );
  16571. // uv
  16572. uvs.push( u, 1 - v );
  16573. verticesRow.push( index ++ );
  16574. }
  16575. grid.push( verticesRow );
  16576. }
  16577. // indices
  16578. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16579. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16580. var a = grid[ iy ][ ix + 1 ];
  16581. var b = grid[ iy ][ ix ];
  16582. var c = grid[ iy + 1 ][ ix ];
  16583. var d = grid[ iy + 1 ][ ix + 1 ];
  16584. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16585. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16586. }
  16587. }
  16588. // build geometry
  16589. this.setIndex( indices );
  16590. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16591. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16592. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16593. }
  16594. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16595. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16596. /**
  16597. * @author Kaleb Murphy
  16598. * @author Mugen87 / https://github.com/Mugen87
  16599. */
  16600. // RingGeometry
  16601. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16602. Geometry.call( this );
  16603. this.type = 'RingGeometry';
  16604. this.parameters = {
  16605. innerRadius: innerRadius,
  16606. outerRadius: outerRadius,
  16607. thetaSegments: thetaSegments,
  16608. phiSegments: phiSegments,
  16609. thetaStart: thetaStart,
  16610. thetaLength: thetaLength
  16611. };
  16612. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16613. this.mergeVertices();
  16614. }
  16615. RingGeometry.prototype = Object.create( Geometry.prototype );
  16616. RingGeometry.prototype.constructor = RingGeometry;
  16617. // RingBufferGeometry
  16618. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16619. BufferGeometry.call( this );
  16620. this.type = 'RingBufferGeometry';
  16621. this.parameters = {
  16622. innerRadius: innerRadius,
  16623. outerRadius: outerRadius,
  16624. thetaSegments: thetaSegments,
  16625. phiSegments: phiSegments,
  16626. thetaStart: thetaStart,
  16627. thetaLength: thetaLength
  16628. };
  16629. innerRadius = innerRadius || 20;
  16630. outerRadius = outerRadius || 50;
  16631. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16632. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16633. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16634. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16635. // buffers
  16636. var indices = [];
  16637. var vertices = [];
  16638. var normals = [];
  16639. var uvs = [];
  16640. // some helper variables
  16641. var segment;
  16642. var radius = innerRadius;
  16643. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16644. var vertex = new Vector3();
  16645. var uv = new Vector2();
  16646. var j, i;
  16647. // generate vertices, normals and uvs
  16648. for ( j = 0; j <= phiSegments; j ++ ) {
  16649. for ( i = 0; i <= thetaSegments; i ++ ) {
  16650. // values are generate from the inside of the ring to the outside
  16651. segment = thetaStart + i / thetaSegments * thetaLength;
  16652. // vertex
  16653. vertex.x = radius * Math.cos( segment );
  16654. vertex.y = radius * Math.sin( segment );
  16655. vertices.push( vertex.x, vertex.y, vertex.z );
  16656. // normal
  16657. normals.push( 0, 0, 1 );
  16658. // uv
  16659. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16660. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16661. uvs.push( uv.x, uv.y );
  16662. }
  16663. // increase the radius for next row of vertices
  16664. radius += radiusStep;
  16665. }
  16666. // indices
  16667. for ( j = 0; j < phiSegments; j ++ ) {
  16668. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16669. for ( i = 0; i < thetaSegments; i ++ ) {
  16670. segment = i + thetaSegmentLevel;
  16671. var a = segment;
  16672. var b = segment + thetaSegments + 1;
  16673. var c = segment + thetaSegments + 2;
  16674. var d = segment + 1;
  16675. // faces
  16676. indices.push( a, b, d );
  16677. indices.push( b, c, d );
  16678. }
  16679. }
  16680. // build geometry
  16681. this.setIndex( indices );
  16682. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16683. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16684. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16685. }
  16686. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16687. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16688. /**
  16689. * @author astrodud / http://astrodud.isgreat.org/
  16690. * @author zz85 / https://github.com/zz85
  16691. * @author bhouston / http://clara.io
  16692. * @author Mugen87 / https://github.com/Mugen87
  16693. */
  16694. // LatheGeometry
  16695. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16696. Geometry.call( this );
  16697. this.type = 'LatheGeometry';
  16698. this.parameters = {
  16699. points: points,
  16700. segments: segments,
  16701. phiStart: phiStart,
  16702. phiLength: phiLength
  16703. };
  16704. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16705. this.mergeVertices();
  16706. }
  16707. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16708. LatheGeometry.prototype.constructor = LatheGeometry;
  16709. // LatheBufferGeometry
  16710. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16711. BufferGeometry.call( this );
  16712. this.type = 'LatheBufferGeometry';
  16713. this.parameters = {
  16714. points: points,
  16715. segments: segments,
  16716. phiStart: phiStart,
  16717. phiLength: phiLength
  16718. };
  16719. segments = Math.floor( segments ) || 12;
  16720. phiStart = phiStart || 0;
  16721. phiLength = phiLength || Math.PI * 2;
  16722. // clamp phiLength so it's in range of [ 0, 2PI ]
  16723. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16724. // buffers
  16725. var indices = [];
  16726. var vertices = [];
  16727. var uvs = [];
  16728. // helper variables
  16729. var base;
  16730. var inverseSegments = 1.0 / segments;
  16731. var vertex = new Vector3();
  16732. var uv = new Vector2();
  16733. var i, j;
  16734. // generate vertices and uvs
  16735. for ( i = 0; i <= segments; i ++ ) {
  16736. var phi = phiStart + i * inverseSegments * phiLength;
  16737. var sin = Math.sin( phi );
  16738. var cos = Math.cos( phi );
  16739. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16740. // vertex
  16741. vertex.x = points[ j ].x * sin;
  16742. vertex.y = points[ j ].y;
  16743. vertex.z = points[ j ].x * cos;
  16744. vertices.push( vertex.x, vertex.y, vertex.z );
  16745. // uv
  16746. uv.x = i / segments;
  16747. uv.y = j / ( points.length - 1 );
  16748. uvs.push( uv.x, uv.y );
  16749. }
  16750. }
  16751. // indices
  16752. for ( i = 0; i < segments; i ++ ) {
  16753. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16754. base = j + i * points.length;
  16755. var a = base;
  16756. var b = base + points.length;
  16757. var c = base + points.length + 1;
  16758. var d = base + 1;
  16759. // faces
  16760. indices.push( a, b, d );
  16761. indices.push( b, c, d );
  16762. }
  16763. }
  16764. // build geometry
  16765. this.setIndex( indices );
  16766. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16767. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16768. // generate normals
  16769. this.computeVertexNormals();
  16770. // if the geometry is closed, we need to average the normals along the seam.
  16771. // because the corresponding vertices are identical (but still have different UVs).
  16772. if ( phiLength === Math.PI * 2 ) {
  16773. var normals = this.attributes.normal.array;
  16774. var n1 = new Vector3();
  16775. var n2 = new Vector3();
  16776. var n = new Vector3();
  16777. // this is the buffer offset for the last line of vertices
  16778. base = segments * points.length * 3;
  16779. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16780. // select the normal of the vertex in the first line
  16781. n1.x = normals[ j + 0 ];
  16782. n1.y = normals[ j + 1 ];
  16783. n1.z = normals[ j + 2 ];
  16784. // select the normal of the vertex in the last line
  16785. n2.x = normals[ base + j + 0 ];
  16786. n2.y = normals[ base + j + 1 ];
  16787. n2.z = normals[ base + j + 2 ];
  16788. // average normals
  16789. n.addVectors( n1, n2 ).normalize();
  16790. // assign the new values to both normals
  16791. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16792. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16793. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16794. }
  16795. }
  16796. }
  16797. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16798. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16799. /**
  16800. * @author jonobr1 / http://jonobr1.com
  16801. * @author Mugen87 / https://github.com/Mugen87
  16802. */
  16803. // ShapeGeometry
  16804. function ShapeGeometry( shapes, curveSegments ) {
  16805. Geometry.call( this );
  16806. this.type = 'ShapeGeometry';
  16807. if ( typeof curveSegments === 'object' ) {
  16808. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16809. curveSegments = curveSegments.curveSegments;
  16810. }
  16811. this.parameters = {
  16812. shapes: shapes,
  16813. curveSegments: curveSegments
  16814. };
  16815. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16816. this.mergeVertices();
  16817. }
  16818. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16819. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16820. // ShapeBufferGeometry
  16821. function ShapeBufferGeometry( shapes, curveSegments ) {
  16822. BufferGeometry.call( this );
  16823. this.type = 'ShapeBufferGeometry';
  16824. this.parameters = {
  16825. shapes: shapes,
  16826. curveSegments: curveSegments
  16827. };
  16828. curveSegments = curveSegments || 12;
  16829. // buffers
  16830. var indices = [];
  16831. var vertices = [];
  16832. var normals = [];
  16833. var uvs = [];
  16834. // helper variables
  16835. var groupStart = 0;
  16836. var groupCount = 0;
  16837. // allow single and array values for "shapes" parameter
  16838. if ( Array.isArray( shapes ) === false ) {
  16839. addShape( shapes );
  16840. } else {
  16841. for ( var i = 0; i < shapes.length; i ++ ) {
  16842. addShape( shapes[ i ] );
  16843. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16844. groupStart += groupCount;
  16845. groupCount = 0;
  16846. }
  16847. }
  16848. // build geometry
  16849. this.setIndex( indices );
  16850. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16851. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16852. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16853. // helper functions
  16854. function addShape( shape ) {
  16855. var i, l, shapeHole;
  16856. var indexOffset = vertices.length / 3;
  16857. var points = shape.extractPoints( curveSegments );
  16858. var shapeVertices = points.shape;
  16859. var shapeHoles = points.holes;
  16860. // check direction of vertices
  16861. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16862. shapeVertices = shapeVertices.reverse();
  16863. // also check if holes are in the opposite direction
  16864. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16865. shapeHole = shapeHoles[ i ];
  16866. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16867. shapeHoles[ i ] = shapeHole.reverse();
  16868. }
  16869. }
  16870. }
  16871. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16872. // join vertices of inner and outer paths to a single array
  16873. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16874. shapeHole = shapeHoles[ i ];
  16875. shapeVertices = shapeVertices.concat( shapeHole );
  16876. }
  16877. // vertices, normals, uvs
  16878. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16879. var vertex = shapeVertices[ i ];
  16880. vertices.push( vertex.x, vertex.y, 0 );
  16881. normals.push( 0, 0, 1 );
  16882. uvs.push( vertex.x, vertex.y ); // world uvs
  16883. }
  16884. // incides
  16885. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16886. var face = faces[ i ];
  16887. var a = face[ 0 ] + indexOffset;
  16888. var b = face[ 1 ] + indexOffset;
  16889. var c = face[ 2 ] + indexOffset;
  16890. indices.push( a, b, c );
  16891. groupCount += 3;
  16892. }
  16893. }
  16894. }
  16895. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16896. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16897. /**
  16898. * @author WestLangley / http://github.com/WestLangley
  16899. * @author Mugen87 / https://github.com/Mugen87
  16900. */
  16901. function EdgesGeometry( geometry, thresholdAngle ) {
  16902. BufferGeometry.call( this );
  16903. this.type = 'EdgesGeometry';
  16904. this.parameters = {
  16905. thresholdAngle: thresholdAngle
  16906. };
  16907. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16908. // buffer
  16909. var vertices = [];
  16910. // helper variables
  16911. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16912. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16913. var key, keys = [ 'a', 'b', 'c' ];
  16914. // prepare source geometry
  16915. var geometry2;
  16916. if ( geometry.isBufferGeometry ) {
  16917. geometry2 = new Geometry();
  16918. geometry2.fromBufferGeometry( geometry );
  16919. } else {
  16920. geometry2 = geometry.clone();
  16921. }
  16922. geometry2.mergeVertices();
  16923. geometry2.computeFaceNormals();
  16924. var sourceVertices = geometry2.vertices;
  16925. var faces = geometry2.faces;
  16926. // now create a data structure where each entry represents an edge with its adjoining faces
  16927. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16928. var face = faces[ i ];
  16929. for ( var j = 0; j < 3; j ++ ) {
  16930. edge1 = face[ keys[ j ] ];
  16931. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16932. edge[ 0 ] = Math.min( edge1, edge2 );
  16933. edge[ 1 ] = Math.max( edge1, edge2 );
  16934. key = edge[ 0 ] + ',' + edge[ 1 ];
  16935. if ( edges[ key ] === undefined ) {
  16936. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  16937. } else {
  16938. edges[ key ].face2 = i;
  16939. }
  16940. }
  16941. }
  16942. // generate vertices
  16943. for ( key in edges ) {
  16944. var e = edges[ key ];
  16945. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16946. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  16947. var vertex = sourceVertices[ e.index1 ];
  16948. vertices.push( vertex.x, vertex.y, vertex.z );
  16949. vertex = sourceVertices[ e.index2 ];
  16950. vertices.push( vertex.x, vertex.y, vertex.z );
  16951. }
  16952. }
  16953. // build geometry
  16954. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16955. }
  16956. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16957. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16958. /**
  16959. * @author mrdoob / http://mrdoob.com/
  16960. * @author Mugen87 / https://github.com/Mugen87
  16961. */
  16962. // CylinderGeometry
  16963. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16964. Geometry.call( this );
  16965. this.type = 'CylinderGeometry';
  16966. this.parameters = {
  16967. radiusTop: radiusTop,
  16968. radiusBottom: radiusBottom,
  16969. height: height,
  16970. radialSegments: radialSegments,
  16971. heightSegments: heightSegments,
  16972. openEnded: openEnded,
  16973. thetaStart: thetaStart,
  16974. thetaLength: thetaLength
  16975. };
  16976. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16977. this.mergeVertices();
  16978. }
  16979. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16980. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16981. // CylinderBufferGeometry
  16982. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16983. BufferGeometry.call( this );
  16984. this.type = 'CylinderBufferGeometry';
  16985. this.parameters = {
  16986. radiusTop: radiusTop,
  16987. radiusBottom: radiusBottom,
  16988. height: height,
  16989. radialSegments: radialSegments,
  16990. heightSegments: heightSegments,
  16991. openEnded: openEnded,
  16992. thetaStart: thetaStart,
  16993. thetaLength: thetaLength
  16994. };
  16995. var scope = this;
  16996. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16997. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16998. height = height !== undefined ? height : 100;
  16999. radialSegments = Math.floor( radialSegments ) || 8;
  17000. heightSegments = Math.floor( heightSegments ) || 1;
  17001. openEnded = openEnded !== undefined ? openEnded : false;
  17002. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  17003. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  17004. // buffers
  17005. var indices = [];
  17006. var vertices = [];
  17007. var normals = [];
  17008. var uvs = [];
  17009. // helper variables
  17010. var index = 0;
  17011. var indexArray = [];
  17012. var halfHeight = height / 2;
  17013. var groupStart = 0;
  17014. // generate geometry
  17015. generateTorso();
  17016. if ( openEnded === false ) {
  17017. if ( radiusTop > 0 ) generateCap( true );
  17018. if ( radiusBottom > 0 ) generateCap( false );
  17019. }
  17020. // build geometry
  17021. this.setIndex( indices );
  17022. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17023. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17024. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17025. function generateTorso() {
  17026. var x, y;
  17027. var normal = new Vector3();
  17028. var vertex = new Vector3();
  17029. var groupCount = 0;
  17030. // this will be used to calculate the normal
  17031. var slope = ( radiusBottom - radiusTop ) / height;
  17032. // generate vertices, normals and uvs
  17033. for ( y = 0; y <= heightSegments; y ++ ) {
  17034. var indexRow = [];
  17035. var v = y / heightSegments;
  17036. // calculate the radius of the current row
  17037. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17038. for ( x = 0; x <= radialSegments; x ++ ) {
  17039. var u = x / radialSegments;
  17040. var theta = u * thetaLength + thetaStart;
  17041. var sinTheta = Math.sin( theta );
  17042. var cosTheta = Math.cos( theta );
  17043. // vertex
  17044. vertex.x = radius * sinTheta;
  17045. vertex.y = - v * height + halfHeight;
  17046. vertex.z = radius * cosTheta;
  17047. vertices.push( vertex.x, vertex.y, vertex.z );
  17048. // normal
  17049. normal.set( sinTheta, slope, cosTheta ).normalize();
  17050. normals.push( normal.x, normal.y, normal.z );
  17051. // uv
  17052. uvs.push( u, 1 - v );
  17053. // save index of vertex in respective row
  17054. indexRow.push( index ++ );
  17055. }
  17056. // now save vertices of the row in our index array
  17057. indexArray.push( indexRow );
  17058. }
  17059. // generate indices
  17060. for ( x = 0; x < radialSegments; x ++ ) {
  17061. for ( y = 0; y < heightSegments; y ++ ) {
  17062. // we use the index array to access the correct indices
  17063. var a = indexArray[ y ][ x ];
  17064. var b = indexArray[ y + 1 ][ x ];
  17065. var c = indexArray[ y + 1 ][ x + 1 ];
  17066. var d = indexArray[ y ][ x + 1 ];
  17067. // faces
  17068. indices.push( a, b, d );
  17069. indices.push( b, c, d );
  17070. // update group counter
  17071. groupCount += 6;
  17072. }
  17073. }
  17074. // add a group to the geometry. this will ensure multi material support
  17075. scope.addGroup( groupStart, groupCount, 0 );
  17076. // calculate new start value for groups
  17077. groupStart += groupCount;
  17078. }
  17079. function generateCap( top ) {
  17080. var x, centerIndexStart, centerIndexEnd;
  17081. var uv = new Vector2();
  17082. var vertex = new Vector3();
  17083. var groupCount = 0;
  17084. var radius = ( top === true ) ? radiusTop : radiusBottom;
  17085. var sign = ( top === true ) ? 1 : - 1;
  17086. // save the index of the first center vertex
  17087. centerIndexStart = index;
  17088. // first we generate the center vertex data of the cap.
  17089. // because the geometry needs one set of uvs per face,
  17090. // we must generate a center vertex per face/segment
  17091. for ( x = 1; x <= radialSegments; x ++ ) {
  17092. // vertex
  17093. vertices.push( 0, halfHeight * sign, 0 );
  17094. // normal
  17095. normals.push( 0, sign, 0 );
  17096. // uv
  17097. uvs.push( 0.5, 0.5 );
  17098. // increase index
  17099. index ++;
  17100. }
  17101. // save the index of the last center vertex
  17102. centerIndexEnd = index;
  17103. // now we generate the surrounding vertices, normals and uvs
  17104. for ( x = 0; x <= radialSegments; x ++ ) {
  17105. var u = x / radialSegments;
  17106. var theta = u * thetaLength + thetaStart;
  17107. var cosTheta = Math.cos( theta );
  17108. var sinTheta = Math.sin( theta );
  17109. // vertex
  17110. vertex.x = radius * sinTheta;
  17111. vertex.y = halfHeight * sign;
  17112. vertex.z = radius * cosTheta;
  17113. vertices.push( vertex.x, vertex.y, vertex.z );
  17114. // normal
  17115. normals.push( 0, sign, 0 );
  17116. // uv
  17117. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17118. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17119. uvs.push( uv.x, uv.y );
  17120. // increase index
  17121. index ++;
  17122. }
  17123. // generate indices
  17124. for ( x = 0; x < radialSegments; x ++ ) {
  17125. var c = centerIndexStart + x;
  17126. var i = centerIndexEnd + x;
  17127. if ( top === true ) {
  17128. // face top
  17129. indices.push( i, i + 1, c );
  17130. } else {
  17131. // face bottom
  17132. indices.push( i + 1, i, c );
  17133. }
  17134. groupCount += 3;
  17135. }
  17136. // add a group to the geometry. this will ensure multi material support
  17137. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17138. // calculate new start value for groups
  17139. groupStart += groupCount;
  17140. }
  17141. }
  17142. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17143. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  17144. /**
  17145. * @author abelnation / http://github.com/abelnation
  17146. */
  17147. // ConeGeometry
  17148. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17149. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17150. this.type = 'ConeGeometry';
  17151. this.parameters = {
  17152. radius: radius,
  17153. height: height,
  17154. radialSegments: radialSegments,
  17155. heightSegments: heightSegments,
  17156. openEnded: openEnded,
  17157. thetaStart: thetaStart,
  17158. thetaLength: thetaLength
  17159. };
  17160. }
  17161. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  17162. ConeGeometry.prototype.constructor = ConeGeometry;
  17163. // ConeBufferGeometry
  17164. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17165. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17166. this.type = 'ConeBufferGeometry';
  17167. this.parameters = {
  17168. radius: radius,
  17169. height: height,
  17170. radialSegments: radialSegments,
  17171. heightSegments: heightSegments,
  17172. openEnded: openEnded,
  17173. thetaStart: thetaStart,
  17174. thetaLength: thetaLength
  17175. };
  17176. }
  17177. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  17178. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  17179. /**
  17180. * @author benaadams / https://twitter.com/ben_a_adams
  17181. * @author Mugen87 / https://github.com/Mugen87
  17182. * @author hughes
  17183. */
  17184. // CircleGeometry
  17185. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  17186. Geometry.call( this );
  17187. this.type = 'CircleGeometry';
  17188. this.parameters = {
  17189. radius: radius,
  17190. segments: segments,
  17191. thetaStart: thetaStart,
  17192. thetaLength: thetaLength
  17193. };
  17194. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17195. this.mergeVertices();
  17196. }
  17197. CircleGeometry.prototype = Object.create( Geometry.prototype );
  17198. CircleGeometry.prototype.constructor = CircleGeometry;
  17199. // CircleBufferGeometry
  17200. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  17201. BufferGeometry.call( this );
  17202. this.type = 'CircleBufferGeometry';
  17203. this.parameters = {
  17204. radius: radius,
  17205. segments: segments,
  17206. thetaStart: thetaStart,
  17207. thetaLength: thetaLength
  17208. };
  17209. radius = radius || 50;
  17210. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17211. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17212. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17213. // buffers
  17214. var indices = [];
  17215. var vertices = [];
  17216. var normals = [];
  17217. var uvs = [];
  17218. // helper variables
  17219. var i, s;
  17220. var vertex = new Vector3();
  17221. var uv = new Vector2();
  17222. // center point
  17223. vertices.push( 0, 0, 0 );
  17224. normals.push( 0, 0, 1 );
  17225. uvs.push( 0.5, 0.5 );
  17226. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17227. var segment = thetaStart + s / segments * thetaLength;
  17228. // vertex
  17229. vertex.x = radius * Math.cos( segment );
  17230. vertex.y = radius * Math.sin( segment );
  17231. vertices.push( vertex.x, vertex.y, vertex.z );
  17232. // normal
  17233. normals.push( 0, 0, 1 );
  17234. // uvs
  17235. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17236. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17237. uvs.push( uv.x, uv.y );
  17238. }
  17239. // indices
  17240. for ( i = 1; i <= segments; i ++ ) {
  17241. indices.push( i, i + 1, 0 );
  17242. }
  17243. // build geometry
  17244. this.setIndex( indices );
  17245. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17246. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17247. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17248. }
  17249. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  17250. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  17251. var Geometries = Object.freeze({
  17252. WireframeGeometry: WireframeGeometry,
  17253. ParametricGeometry: ParametricGeometry,
  17254. ParametricBufferGeometry: ParametricBufferGeometry,
  17255. TetrahedronGeometry: TetrahedronGeometry,
  17256. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  17257. OctahedronGeometry: OctahedronGeometry,
  17258. OctahedronBufferGeometry: OctahedronBufferGeometry,
  17259. IcosahedronGeometry: IcosahedronGeometry,
  17260. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  17261. DodecahedronGeometry: DodecahedronGeometry,
  17262. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  17263. PolyhedronGeometry: PolyhedronGeometry,
  17264. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  17265. TubeGeometry: TubeGeometry,
  17266. TubeBufferGeometry: TubeBufferGeometry,
  17267. TorusKnotGeometry: TorusKnotGeometry,
  17268. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  17269. TorusGeometry: TorusGeometry,
  17270. TorusBufferGeometry: TorusBufferGeometry,
  17271. TextGeometry: TextGeometry,
  17272. TextBufferGeometry: TextBufferGeometry,
  17273. SphereGeometry: SphereGeometry,
  17274. SphereBufferGeometry: SphereBufferGeometry,
  17275. RingGeometry: RingGeometry,
  17276. RingBufferGeometry: RingBufferGeometry,
  17277. PlaneGeometry: PlaneGeometry,
  17278. PlaneBufferGeometry: PlaneBufferGeometry,
  17279. LatheGeometry: LatheGeometry,
  17280. LatheBufferGeometry: LatheBufferGeometry,
  17281. ShapeGeometry: ShapeGeometry,
  17282. ShapeBufferGeometry: ShapeBufferGeometry,
  17283. ExtrudeGeometry: ExtrudeGeometry,
  17284. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  17285. EdgesGeometry: EdgesGeometry,
  17286. ConeGeometry: ConeGeometry,
  17287. ConeBufferGeometry: ConeBufferGeometry,
  17288. CylinderGeometry: CylinderGeometry,
  17289. CylinderBufferGeometry: CylinderBufferGeometry,
  17290. CircleGeometry: CircleGeometry,
  17291. CircleBufferGeometry: CircleBufferGeometry,
  17292. BoxGeometry: BoxGeometry,
  17293. BoxBufferGeometry: BoxBufferGeometry
  17294. });
  17295. /**
  17296. * @author mrdoob / http://mrdoob.com/
  17297. *
  17298. * parameters = {
  17299. * opacity: <float>
  17300. * }
  17301. */
  17302. function ShadowMaterial( parameters ) {
  17303. ShaderMaterial.call( this, {
  17304. uniforms: UniformsUtils.merge( [
  17305. UniformsLib.lights,
  17306. {
  17307. opacity: { value: 1.0 }
  17308. }
  17309. ] ),
  17310. vertexShader: ShaderChunk[ 'shadow_vert' ],
  17311. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  17312. } );
  17313. this.lights = true;
  17314. this.transparent = true;
  17315. Object.defineProperties( this, {
  17316. opacity: {
  17317. enumerable: true,
  17318. get: function () {
  17319. return this.uniforms.opacity.value;
  17320. },
  17321. set: function ( value ) {
  17322. this.uniforms.opacity.value = value;
  17323. }
  17324. }
  17325. } );
  17326. this.setValues( parameters );
  17327. }
  17328. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17329. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17330. ShadowMaterial.prototype.isShadowMaterial = true;
  17331. /**
  17332. * @author mrdoob / http://mrdoob.com/
  17333. */
  17334. function RawShaderMaterial( parameters ) {
  17335. ShaderMaterial.call( this, parameters );
  17336. this.type = 'RawShaderMaterial';
  17337. }
  17338. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17339. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17340. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17341. /**
  17342. * @author WestLangley / http://github.com/WestLangley
  17343. *
  17344. * parameters = {
  17345. * color: <hex>,
  17346. * roughness: <float>,
  17347. * metalness: <float>,
  17348. * opacity: <float>,
  17349. *
  17350. * map: new THREE.Texture( <Image> ),
  17351. *
  17352. * lightMap: new THREE.Texture( <Image> ),
  17353. * lightMapIntensity: <float>
  17354. *
  17355. * aoMap: new THREE.Texture( <Image> ),
  17356. * aoMapIntensity: <float>
  17357. *
  17358. * emissive: <hex>,
  17359. * emissiveIntensity: <float>
  17360. * emissiveMap: new THREE.Texture( <Image> ),
  17361. *
  17362. * bumpMap: new THREE.Texture( <Image> ),
  17363. * bumpScale: <float>,
  17364. *
  17365. * normalMap: new THREE.Texture( <Image> ),
  17366. * normalScale: <Vector2>,
  17367. *
  17368. * displacementMap: new THREE.Texture( <Image> ),
  17369. * displacementScale: <float>,
  17370. * displacementBias: <float>,
  17371. *
  17372. * roughnessMap: new THREE.Texture( <Image> ),
  17373. *
  17374. * metalnessMap: new THREE.Texture( <Image> ),
  17375. *
  17376. * alphaMap: new THREE.Texture( <Image> ),
  17377. *
  17378. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17379. * envMapIntensity: <float>
  17380. *
  17381. * refractionRatio: <float>,
  17382. *
  17383. * wireframe: <boolean>,
  17384. * wireframeLinewidth: <float>,
  17385. *
  17386. * skinning: <bool>,
  17387. * morphTargets: <bool>,
  17388. * morphNormals: <bool>
  17389. * }
  17390. */
  17391. function MeshStandardMaterial( parameters ) {
  17392. Material.call( this );
  17393. this.defines = { 'STANDARD': '' };
  17394. this.type = 'MeshStandardMaterial';
  17395. this.color = new Color( 0xffffff ); // diffuse
  17396. this.roughness = 0.5;
  17397. this.metalness = 0.5;
  17398. this.map = null;
  17399. this.lightMap = null;
  17400. this.lightMapIntensity = 1.0;
  17401. this.aoMap = null;
  17402. this.aoMapIntensity = 1.0;
  17403. this.emissive = new Color( 0x000000 );
  17404. this.emissiveIntensity = 1.0;
  17405. this.emissiveMap = null;
  17406. this.bumpMap = null;
  17407. this.bumpScale = 1;
  17408. this.normalMap = null;
  17409. this.normalScale = new Vector2( 1, 1 );
  17410. this.displacementMap = null;
  17411. this.displacementScale = 1;
  17412. this.displacementBias = 0;
  17413. this.roughnessMap = null;
  17414. this.metalnessMap = null;
  17415. this.alphaMap = null;
  17416. this.envMap = null;
  17417. this.envMapIntensity = 1.0;
  17418. this.refractionRatio = 0.98;
  17419. this.wireframe = false;
  17420. this.wireframeLinewidth = 1;
  17421. this.wireframeLinecap = 'round';
  17422. this.wireframeLinejoin = 'round';
  17423. this.skinning = false;
  17424. this.morphTargets = false;
  17425. this.morphNormals = false;
  17426. this.setValues( parameters );
  17427. }
  17428. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17429. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17430. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17431. MeshStandardMaterial.prototype.copy = function ( source ) {
  17432. Material.prototype.copy.call( this, source );
  17433. this.defines = { 'STANDARD': '' };
  17434. this.color.copy( source.color );
  17435. this.roughness = source.roughness;
  17436. this.metalness = source.metalness;
  17437. this.map = source.map;
  17438. this.lightMap = source.lightMap;
  17439. this.lightMapIntensity = source.lightMapIntensity;
  17440. this.aoMap = source.aoMap;
  17441. this.aoMapIntensity = source.aoMapIntensity;
  17442. this.emissive.copy( source.emissive );
  17443. this.emissiveMap = source.emissiveMap;
  17444. this.emissiveIntensity = source.emissiveIntensity;
  17445. this.bumpMap = source.bumpMap;
  17446. this.bumpScale = source.bumpScale;
  17447. this.normalMap = source.normalMap;
  17448. this.normalScale.copy( source.normalScale );
  17449. this.displacementMap = source.displacementMap;
  17450. this.displacementScale = source.displacementScale;
  17451. this.displacementBias = source.displacementBias;
  17452. this.roughnessMap = source.roughnessMap;
  17453. this.metalnessMap = source.metalnessMap;
  17454. this.alphaMap = source.alphaMap;
  17455. this.envMap = source.envMap;
  17456. this.envMapIntensity = source.envMapIntensity;
  17457. this.refractionRatio = source.refractionRatio;
  17458. this.wireframe = source.wireframe;
  17459. this.wireframeLinewidth = source.wireframeLinewidth;
  17460. this.wireframeLinecap = source.wireframeLinecap;
  17461. this.wireframeLinejoin = source.wireframeLinejoin;
  17462. this.skinning = source.skinning;
  17463. this.morphTargets = source.morphTargets;
  17464. this.morphNormals = source.morphNormals;
  17465. return this;
  17466. };
  17467. /**
  17468. * @author WestLangley / http://github.com/WestLangley
  17469. *
  17470. * parameters = {
  17471. * reflectivity: <float>
  17472. * }
  17473. */
  17474. function MeshPhysicalMaterial( parameters ) {
  17475. MeshStandardMaterial.call( this );
  17476. this.defines = { 'PHYSICAL': '' };
  17477. this.type = 'MeshPhysicalMaterial';
  17478. this.reflectivity = 0.5; // maps to F0 = 0.04
  17479. this.clearCoat = 0.0;
  17480. this.clearCoatRoughness = 0.0;
  17481. this.setValues( parameters );
  17482. }
  17483. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17484. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17485. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17486. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17487. MeshStandardMaterial.prototype.copy.call( this, source );
  17488. this.defines = { 'PHYSICAL': '' };
  17489. this.reflectivity = source.reflectivity;
  17490. this.clearCoat = source.clearCoat;
  17491. this.clearCoatRoughness = source.clearCoatRoughness;
  17492. return this;
  17493. };
  17494. /**
  17495. * @author mrdoob / http://mrdoob.com/
  17496. * @author alteredq / http://alteredqualia.com/
  17497. *
  17498. * parameters = {
  17499. * color: <hex>,
  17500. * specular: <hex>,
  17501. * shininess: <float>,
  17502. * opacity: <float>,
  17503. *
  17504. * map: new THREE.Texture( <Image> ),
  17505. *
  17506. * lightMap: new THREE.Texture( <Image> ),
  17507. * lightMapIntensity: <float>
  17508. *
  17509. * aoMap: new THREE.Texture( <Image> ),
  17510. * aoMapIntensity: <float>
  17511. *
  17512. * emissive: <hex>,
  17513. * emissiveIntensity: <float>
  17514. * emissiveMap: new THREE.Texture( <Image> ),
  17515. *
  17516. * bumpMap: new THREE.Texture( <Image> ),
  17517. * bumpScale: <float>,
  17518. *
  17519. * normalMap: new THREE.Texture( <Image> ),
  17520. * normalScale: <Vector2>,
  17521. *
  17522. * displacementMap: new THREE.Texture( <Image> ),
  17523. * displacementScale: <float>,
  17524. * displacementBias: <float>,
  17525. *
  17526. * specularMap: new THREE.Texture( <Image> ),
  17527. *
  17528. * alphaMap: new THREE.Texture( <Image> ),
  17529. *
  17530. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17531. * combine: THREE.Multiply,
  17532. * reflectivity: <float>,
  17533. * refractionRatio: <float>,
  17534. *
  17535. * wireframe: <boolean>,
  17536. * wireframeLinewidth: <float>,
  17537. *
  17538. * skinning: <bool>,
  17539. * morphTargets: <bool>,
  17540. * morphNormals: <bool>
  17541. * }
  17542. */
  17543. function MeshPhongMaterial( parameters ) {
  17544. Material.call( this );
  17545. this.type = 'MeshPhongMaterial';
  17546. this.color = new Color( 0xffffff ); // diffuse
  17547. this.specular = new Color( 0x111111 );
  17548. this.shininess = 30;
  17549. this.map = null;
  17550. this.lightMap = null;
  17551. this.lightMapIntensity = 1.0;
  17552. this.aoMap = null;
  17553. this.aoMapIntensity = 1.0;
  17554. this.emissive = new Color( 0x000000 );
  17555. this.emissiveIntensity = 1.0;
  17556. this.emissiveMap = null;
  17557. this.bumpMap = null;
  17558. this.bumpScale = 1;
  17559. this.normalMap = null;
  17560. this.normalScale = new Vector2( 1, 1 );
  17561. this.displacementMap = null;
  17562. this.displacementScale = 1;
  17563. this.displacementBias = 0;
  17564. this.specularMap = null;
  17565. this.alphaMap = null;
  17566. this.envMap = null;
  17567. this.combine = MultiplyOperation;
  17568. this.reflectivity = 1;
  17569. this.refractionRatio = 0.98;
  17570. this.wireframe = false;
  17571. this.wireframeLinewidth = 1;
  17572. this.wireframeLinecap = 'round';
  17573. this.wireframeLinejoin = 'round';
  17574. this.skinning = false;
  17575. this.morphTargets = false;
  17576. this.morphNormals = false;
  17577. this.setValues( parameters );
  17578. }
  17579. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17580. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17581. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17582. MeshPhongMaterial.prototype.copy = function ( source ) {
  17583. Material.prototype.copy.call( this, source );
  17584. this.color.copy( source.color );
  17585. this.specular.copy( source.specular );
  17586. this.shininess = source.shininess;
  17587. this.map = source.map;
  17588. this.lightMap = source.lightMap;
  17589. this.lightMapIntensity = source.lightMapIntensity;
  17590. this.aoMap = source.aoMap;
  17591. this.aoMapIntensity = source.aoMapIntensity;
  17592. this.emissive.copy( source.emissive );
  17593. this.emissiveMap = source.emissiveMap;
  17594. this.emissiveIntensity = source.emissiveIntensity;
  17595. this.bumpMap = source.bumpMap;
  17596. this.bumpScale = source.bumpScale;
  17597. this.normalMap = source.normalMap;
  17598. this.normalScale.copy( source.normalScale );
  17599. this.displacementMap = source.displacementMap;
  17600. this.displacementScale = source.displacementScale;
  17601. this.displacementBias = source.displacementBias;
  17602. this.specularMap = source.specularMap;
  17603. this.alphaMap = source.alphaMap;
  17604. this.envMap = source.envMap;
  17605. this.combine = source.combine;
  17606. this.reflectivity = source.reflectivity;
  17607. this.refractionRatio = source.refractionRatio;
  17608. this.wireframe = source.wireframe;
  17609. this.wireframeLinewidth = source.wireframeLinewidth;
  17610. this.wireframeLinecap = source.wireframeLinecap;
  17611. this.wireframeLinejoin = source.wireframeLinejoin;
  17612. this.skinning = source.skinning;
  17613. this.morphTargets = source.morphTargets;
  17614. this.morphNormals = source.morphNormals;
  17615. return this;
  17616. };
  17617. /**
  17618. * @author takahirox / http://github.com/takahirox
  17619. *
  17620. * parameters = {
  17621. * gradientMap: new THREE.Texture( <Image> )
  17622. * }
  17623. */
  17624. function MeshToonMaterial( parameters ) {
  17625. MeshPhongMaterial.call( this );
  17626. this.defines = { 'TOON': '' };
  17627. this.type = 'MeshToonMaterial';
  17628. this.gradientMap = null;
  17629. this.setValues( parameters );
  17630. }
  17631. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17632. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17633. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17634. MeshToonMaterial.prototype.copy = function ( source ) {
  17635. MeshPhongMaterial.prototype.copy.call( this, source );
  17636. this.gradientMap = source.gradientMap;
  17637. return this;
  17638. };
  17639. /**
  17640. * @author mrdoob / http://mrdoob.com/
  17641. * @author WestLangley / http://github.com/WestLangley
  17642. *
  17643. * parameters = {
  17644. * opacity: <float>,
  17645. *
  17646. * bumpMap: new THREE.Texture( <Image> ),
  17647. * bumpScale: <float>,
  17648. *
  17649. * normalMap: new THREE.Texture( <Image> ),
  17650. * normalScale: <Vector2>,
  17651. *
  17652. * displacementMap: new THREE.Texture( <Image> ),
  17653. * displacementScale: <float>,
  17654. * displacementBias: <float>,
  17655. *
  17656. * wireframe: <boolean>,
  17657. * wireframeLinewidth: <float>
  17658. *
  17659. * skinning: <bool>,
  17660. * morphTargets: <bool>,
  17661. * morphNormals: <bool>
  17662. * }
  17663. */
  17664. function MeshNormalMaterial( parameters ) {
  17665. Material.call( this );
  17666. this.type = 'MeshNormalMaterial';
  17667. this.bumpMap = null;
  17668. this.bumpScale = 1;
  17669. this.normalMap = null;
  17670. this.normalScale = new Vector2( 1, 1 );
  17671. this.displacementMap = null;
  17672. this.displacementScale = 1;
  17673. this.displacementBias = 0;
  17674. this.wireframe = false;
  17675. this.wireframeLinewidth = 1;
  17676. this.fog = false;
  17677. this.lights = false;
  17678. this.skinning = false;
  17679. this.morphTargets = false;
  17680. this.morphNormals = false;
  17681. this.setValues( parameters );
  17682. }
  17683. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17684. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17685. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17686. MeshNormalMaterial.prototype.copy = function ( source ) {
  17687. Material.prototype.copy.call( this, source );
  17688. this.bumpMap = source.bumpMap;
  17689. this.bumpScale = source.bumpScale;
  17690. this.normalMap = source.normalMap;
  17691. this.normalScale.copy( source.normalScale );
  17692. this.displacementMap = source.displacementMap;
  17693. this.displacementScale = source.displacementScale;
  17694. this.displacementBias = source.displacementBias;
  17695. this.wireframe = source.wireframe;
  17696. this.wireframeLinewidth = source.wireframeLinewidth;
  17697. this.skinning = source.skinning;
  17698. this.morphTargets = source.morphTargets;
  17699. this.morphNormals = source.morphNormals;
  17700. return this;
  17701. };
  17702. /**
  17703. * @author mrdoob / http://mrdoob.com/
  17704. * @author alteredq / http://alteredqualia.com/
  17705. *
  17706. * parameters = {
  17707. * color: <hex>,
  17708. * opacity: <float>,
  17709. *
  17710. * map: new THREE.Texture( <Image> ),
  17711. *
  17712. * lightMap: new THREE.Texture( <Image> ),
  17713. * lightMapIntensity: <float>
  17714. *
  17715. * aoMap: new THREE.Texture( <Image> ),
  17716. * aoMapIntensity: <float>
  17717. *
  17718. * emissive: <hex>,
  17719. * emissiveIntensity: <float>
  17720. * emissiveMap: new THREE.Texture( <Image> ),
  17721. *
  17722. * specularMap: new THREE.Texture( <Image> ),
  17723. *
  17724. * alphaMap: new THREE.Texture( <Image> ),
  17725. *
  17726. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17727. * combine: THREE.Multiply,
  17728. * reflectivity: <float>,
  17729. * refractionRatio: <float>,
  17730. *
  17731. * wireframe: <boolean>,
  17732. * wireframeLinewidth: <float>,
  17733. *
  17734. * skinning: <bool>,
  17735. * morphTargets: <bool>,
  17736. * morphNormals: <bool>
  17737. * }
  17738. */
  17739. function MeshLambertMaterial( parameters ) {
  17740. Material.call( this );
  17741. this.type = 'MeshLambertMaterial';
  17742. this.color = new Color( 0xffffff ); // diffuse
  17743. this.map = null;
  17744. this.lightMap = null;
  17745. this.lightMapIntensity = 1.0;
  17746. this.aoMap = null;
  17747. this.aoMapIntensity = 1.0;
  17748. this.emissive = new Color( 0x000000 );
  17749. this.emissiveIntensity = 1.0;
  17750. this.emissiveMap = null;
  17751. this.specularMap = null;
  17752. this.alphaMap = null;
  17753. this.envMap = null;
  17754. this.combine = MultiplyOperation;
  17755. this.reflectivity = 1;
  17756. this.refractionRatio = 0.98;
  17757. this.wireframe = false;
  17758. this.wireframeLinewidth = 1;
  17759. this.wireframeLinecap = 'round';
  17760. this.wireframeLinejoin = 'round';
  17761. this.skinning = false;
  17762. this.morphTargets = false;
  17763. this.morphNormals = false;
  17764. this.setValues( parameters );
  17765. }
  17766. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17767. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17768. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17769. MeshLambertMaterial.prototype.copy = function ( source ) {
  17770. Material.prototype.copy.call( this, source );
  17771. this.color.copy( source.color );
  17772. this.map = source.map;
  17773. this.lightMap = source.lightMap;
  17774. this.lightMapIntensity = source.lightMapIntensity;
  17775. this.aoMap = source.aoMap;
  17776. this.aoMapIntensity = source.aoMapIntensity;
  17777. this.emissive.copy( source.emissive );
  17778. this.emissiveMap = source.emissiveMap;
  17779. this.emissiveIntensity = source.emissiveIntensity;
  17780. this.specularMap = source.specularMap;
  17781. this.alphaMap = source.alphaMap;
  17782. this.envMap = source.envMap;
  17783. this.combine = source.combine;
  17784. this.reflectivity = source.reflectivity;
  17785. this.refractionRatio = source.refractionRatio;
  17786. this.wireframe = source.wireframe;
  17787. this.wireframeLinewidth = source.wireframeLinewidth;
  17788. this.wireframeLinecap = source.wireframeLinecap;
  17789. this.wireframeLinejoin = source.wireframeLinejoin;
  17790. this.skinning = source.skinning;
  17791. this.morphTargets = source.morphTargets;
  17792. this.morphNormals = source.morphNormals;
  17793. return this;
  17794. };
  17795. /**
  17796. * @author alteredq / http://alteredqualia.com/
  17797. *
  17798. * parameters = {
  17799. * color: <hex>,
  17800. * opacity: <float>,
  17801. *
  17802. * linewidth: <float>,
  17803. *
  17804. * scale: <float>,
  17805. * dashSize: <float>,
  17806. * gapSize: <float>
  17807. * }
  17808. */
  17809. function LineDashedMaterial( parameters ) {
  17810. Material.call( this );
  17811. this.type = 'LineDashedMaterial';
  17812. this.color = new Color( 0xffffff );
  17813. this.linewidth = 1;
  17814. this.scale = 1;
  17815. this.dashSize = 3;
  17816. this.gapSize = 1;
  17817. this.lights = false;
  17818. this.setValues( parameters );
  17819. }
  17820. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17821. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17822. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17823. LineDashedMaterial.prototype.copy = function ( source ) {
  17824. Material.prototype.copy.call( this, source );
  17825. this.color.copy( source.color );
  17826. this.linewidth = source.linewidth;
  17827. this.scale = source.scale;
  17828. this.dashSize = source.dashSize;
  17829. this.gapSize = source.gapSize;
  17830. return this;
  17831. };
  17832. var Materials = Object.freeze({
  17833. ShadowMaterial: ShadowMaterial,
  17834. SpriteMaterial: SpriteMaterial,
  17835. RawShaderMaterial: RawShaderMaterial,
  17836. ShaderMaterial: ShaderMaterial,
  17837. PointsMaterial: PointsMaterial,
  17838. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17839. MeshStandardMaterial: MeshStandardMaterial,
  17840. MeshPhongMaterial: MeshPhongMaterial,
  17841. MeshToonMaterial: MeshToonMaterial,
  17842. MeshNormalMaterial: MeshNormalMaterial,
  17843. MeshLambertMaterial: MeshLambertMaterial,
  17844. MeshDepthMaterial: MeshDepthMaterial,
  17845. MeshDistanceMaterial: MeshDistanceMaterial,
  17846. MeshBasicMaterial: MeshBasicMaterial,
  17847. LineDashedMaterial: LineDashedMaterial,
  17848. LineBasicMaterial: LineBasicMaterial,
  17849. Material: Material
  17850. });
  17851. /**
  17852. * @author mrdoob / http://mrdoob.com/
  17853. */
  17854. var Cache = {
  17855. enabled: false,
  17856. files: {},
  17857. add: function ( key, file ) {
  17858. if ( this.enabled === false ) return;
  17859. // console.log( 'THREE.Cache', 'Adding key:', key );
  17860. this.files[ key ] = file;
  17861. },
  17862. get: function ( key ) {
  17863. if ( this.enabled === false ) return;
  17864. // console.log( 'THREE.Cache', 'Checking key:', key );
  17865. return this.files[ key ];
  17866. },
  17867. remove: function ( key ) {
  17868. delete this.files[ key ];
  17869. },
  17870. clear: function () {
  17871. this.files = {};
  17872. }
  17873. };
  17874. /**
  17875. * @author mrdoob / http://mrdoob.com/
  17876. */
  17877. function LoadingManager( onLoad, onProgress, onError ) {
  17878. var scope = this;
  17879. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17880. this.onStart = undefined;
  17881. this.onLoad = onLoad;
  17882. this.onProgress = onProgress;
  17883. this.onError = onError;
  17884. this.itemStart = function ( url ) {
  17885. itemsTotal ++;
  17886. if ( isLoading === false ) {
  17887. if ( scope.onStart !== undefined ) {
  17888. scope.onStart( url, itemsLoaded, itemsTotal );
  17889. }
  17890. }
  17891. isLoading = true;
  17892. };
  17893. this.itemEnd = function ( url ) {
  17894. itemsLoaded ++;
  17895. if ( scope.onProgress !== undefined ) {
  17896. scope.onProgress( url, itemsLoaded, itemsTotal );
  17897. }
  17898. if ( itemsLoaded === itemsTotal ) {
  17899. isLoading = false;
  17900. if ( scope.onLoad !== undefined ) {
  17901. scope.onLoad();
  17902. }
  17903. }
  17904. };
  17905. this.itemError = function ( url ) {
  17906. if ( scope.onError !== undefined ) {
  17907. scope.onError( url );
  17908. }
  17909. };
  17910. }
  17911. var DefaultLoadingManager = new LoadingManager();
  17912. /**
  17913. * @author mrdoob / http://mrdoob.com/
  17914. */
  17915. function FileLoader( manager ) {
  17916. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17917. }
  17918. Object.assign( FileLoader.prototype, {
  17919. load: function ( url, onLoad, onProgress, onError ) {
  17920. if ( url === undefined ) url = '';
  17921. if ( this.path !== undefined ) url = this.path + url;
  17922. var scope = this;
  17923. var cached = Cache.get( url );
  17924. if ( cached !== undefined ) {
  17925. scope.manager.itemStart( url );
  17926. setTimeout( function () {
  17927. if ( onLoad ) onLoad( cached );
  17928. scope.manager.itemEnd( url );
  17929. }, 0 );
  17930. return cached;
  17931. }
  17932. // Check for data: URI
  17933. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17934. var dataUriRegexResult = url.match( dataUriRegex );
  17935. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17936. if ( dataUriRegexResult ) {
  17937. var mimeType = dataUriRegexResult[ 1 ];
  17938. var isBase64 = !! dataUriRegexResult[ 2 ];
  17939. var data = dataUriRegexResult[ 3 ];
  17940. data = window.decodeURIComponent( data );
  17941. if ( isBase64 ) data = window.atob( data );
  17942. try {
  17943. var response;
  17944. var responseType = ( this.responseType || '' ).toLowerCase();
  17945. switch ( responseType ) {
  17946. case 'arraybuffer':
  17947. case 'blob':
  17948. response = new ArrayBuffer( data.length );
  17949. var view = new Uint8Array( response );
  17950. for ( var i = 0; i < data.length; i ++ ) {
  17951. view[ i ] = data.charCodeAt( i );
  17952. }
  17953. if ( responseType === 'blob' ) {
  17954. response = new Blob( [ response ], { type: mimeType } );
  17955. }
  17956. break;
  17957. case 'document':
  17958. var parser = new DOMParser();
  17959. response = parser.parseFromString( data, mimeType );
  17960. break;
  17961. case 'json':
  17962. response = JSON.parse( data );
  17963. break;
  17964. default: // 'text' or other
  17965. response = data;
  17966. break;
  17967. }
  17968. // Wait for next browser tick
  17969. window.setTimeout( function () {
  17970. if ( onLoad ) onLoad( response );
  17971. scope.manager.itemEnd( url );
  17972. }, 0 );
  17973. } catch ( error ) {
  17974. // Wait for next browser tick
  17975. window.setTimeout( function () {
  17976. if ( onError ) onError( error );
  17977. scope.manager.itemEnd( url );
  17978. scope.manager.itemError( url );
  17979. }, 0 );
  17980. }
  17981. } else {
  17982. var request = new XMLHttpRequest();
  17983. request.open( 'GET', url, true );
  17984. request.addEventListener( 'load', function ( event ) {
  17985. var response = event.target.response;
  17986. Cache.add( url, response );
  17987. if ( this.status === 200 ) {
  17988. if ( onLoad ) onLoad( response );
  17989. scope.manager.itemEnd( url );
  17990. } else if ( this.status === 0 ) {
  17991. // Some browsers return HTTP Status 0 when using non-http protocol
  17992. // e.g. 'file://' or 'data://'. Handle as success.
  17993. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17994. if ( onLoad ) onLoad( response );
  17995. scope.manager.itemEnd( url );
  17996. } else {
  17997. if ( onError ) onError( event );
  17998. scope.manager.itemEnd( url );
  17999. scope.manager.itemError( url );
  18000. }
  18001. }, false );
  18002. if ( onProgress !== undefined ) {
  18003. request.addEventListener( 'progress', function ( event ) {
  18004. onProgress( event );
  18005. }, false );
  18006. }
  18007. request.addEventListener( 'error', function ( event ) {
  18008. if ( onError ) onError( event );
  18009. scope.manager.itemEnd( url );
  18010. scope.manager.itemError( url );
  18011. }, false );
  18012. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  18013. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  18014. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  18015. for ( var header in this.requestHeader ) {
  18016. request.setRequestHeader( header, this.requestHeader[ header ] );
  18017. }
  18018. request.send( null );
  18019. }
  18020. scope.manager.itemStart( url );
  18021. return request;
  18022. },
  18023. setPath: function ( value ) {
  18024. this.path = value;
  18025. return this;
  18026. },
  18027. setResponseType: function ( value ) {
  18028. this.responseType = value;
  18029. return this;
  18030. },
  18031. setWithCredentials: function ( value ) {
  18032. this.withCredentials = value;
  18033. return this;
  18034. },
  18035. setMimeType: function ( value ) {
  18036. this.mimeType = value;
  18037. return this;
  18038. },
  18039. setRequestHeader: function ( value ) {
  18040. this.requestHeader = value;
  18041. return this;
  18042. }
  18043. } );
  18044. /**
  18045. * @author mrdoob / http://mrdoob.com/
  18046. *
  18047. * Abstract Base class to block based textures loader (dds, pvr, ...)
  18048. */
  18049. function CompressedTextureLoader( manager ) {
  18050. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18051. // override in sub classes
  18052. this._parser = null;
  18053. }
  18054. Object.assign( CompressedTextureLoader.prototype, {
  18055. load: function ( url, onLoad, onProgress, onError ) {
  18056. var scope = this;
  18057. var images = [];
  18058. var texture = new CompressedTexture();
  18059. texture.image = images;
  18060. var loader = new FileLoader( this.manager );
  18061. loader.setPath( this.path );
  18062. loader.setResponseType( 'arraybuffer' );
  18063. function loadTexture( i ) {
  18064. loader.load( url[ i ], function ( buffer ) {
  18065. var texDatas = scope._parser( buffer, true );
  18066. images[ i ] = {
  18067. width: texDatas.width,
  18068. height: texDatas.height,
  18069. format: texDatas.format,
  18070. mipmaps: texDatas.mipmaps
  18071. };
  18072. loaded += 1;
  18073. if ( loaded === 6 ) {
  18074. if ( texDatas.mipmapCount === 1 )
  18075. texture.minFilter = LinearFilter;
  18076. texture.format = texDatas.format;
  18077. texture.needsUpdate = true;
  18078. if ( onLoad ) onLoad( texture );
  18079. }
  18080. }, onProgress, onError );
  18081. }
  18082. if ( Array.isArray( url ) ) {
  18083. var loaded = 0;
  18084. for ( var i = 0, il = url.length; i < il; ++ i ) {
  18085. loadTexture( i );
  18086. }
  18087. } else {
  18088. // compressed cubemap texture stored in a single DDS file
  18089. loader.load( url, function ( buffer ) {
  18090. var texDatas = scope._parser( buffer, true );
  18091. if ( texDatas.isCubemap ) {
  18092. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  18093. for ( var f = 0; f < faces; f ++ ) {
  18094. images[ f ] = { mipmaps : [] };
  18095. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  18096. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  18097. images[ f ].format = texDatas.format;
  18098. images[ f ].width = texDatas.width;
  18099. images[ f ].height = texDatas.height;
  18100. }
  18101. }
  18102. } else {
  18103. texture.image.width = texDatas.width;
  18104. texture.image.height = texDatas.height;
  18105. texture.mipmaps = texDatas.mipmaps;
  18106. }
  18107. if ( texDatas.mipmapCount === 1 ) {
  18108. texture.minFilter = LinearFilter;
  18109. }
  18110. texture.format = texDatas.format;
  18111. texture.needsUpdate = true;
  18112. if ( onLoad ) onLoad( texture );
  18113. }, onProgress, onError );
  18114. }
  18115. return texture;
  18116. },
  18117. setPath: function ( value ) {
  18118. this.path = value;
  18119. return this;
  18120. }
  18121. } );
  18122. /**
  18123. * @author Nikos M. / https://github.com/foo123/
  18124. *
  18125. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18126. */
  18127. function DataTextureLoader( manager ) {
  18128. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18129. // override in sub classes
  18130. this._parser = null;
  18131. }
  18132. Object.assign( DataTextureLoader.prototype, {
  18133. load: function ( url, onLoad, onProgress, onError ) {
  18134. var scope = this;
  18135. var texture = new DataTexture();
  18136. var loader = new FileLoader( this.manager );
  18137. loader.setResponseType( 'arraybuffer' );
  18138. loader.load( url, function ( buffer ) {
  18139. var texData = scope._parser( buffer );
  18140. if ( ! texData ) return;
  18141. if ( undefined !== texData.image ) {
  18142. texture.image = texData.image;
  18143. } else if ( undefined !== texData.data ) {
  18144. texture.image.width = texData.width;
  18145. texture.image.height = texData.height;
  18146. texture.image.data = texData.data;
  18147. }
  18148. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  18149. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  18150. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  18151. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  18152. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  18153. if ( undefined !== texData.format ) {
  18154. texture.format = texData.format;
  18155. }
  18156. if ( undefined !== texData.type ) {
  18157. texture.type = texData.type;
  18158. }
  18159. if ( undefined !== texData.mipmaps ) {
  18160. texture.mipmaps = texData.mipmaps;
  18161. }
  18162. if ( 1 === texData.mipmapCount ) {
  18163. texture.minFilter = LinearFilter;
  18164. }
  18165. texture.needsUpdate = true;
  18166. if ( onLoad ) onLoad( texture, texData );
  18167. }, onProgress, onError );
  18168. return texture;
  18169. }
  18170. } );
  18171. /**
  18172. * @author mrdoob / http://mrdoob.com/
  18173. */
  18174. function ImageLoader( manager ) {
  18175. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18176. }
  18177. Object.assign( ImageLoader.prototype, {
  18178. load: function ( url, onLoad, onProgress, onError ) {
  18179. if ( url === undefined ) url = '';
  18180. if ( this.path !== undefined ) url = this.path + url;
  18181. var scope = this;
  18182. var cached = Cache.get( url );
  18183. if ( cached !== undefined ) {
  18184. scope.manager.itemStart( url );
  18185. setTimeout( function () {
  18186. if ( onLoad ) onLoad( cached );
  18187. scope.manager.itemEnd( url );
  18188. }, 0 );
  18189. return cached;
  18190. }
  18191. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  18192. image.addEventListener( 'load', function () {
  18193. Cache.add( url, this );
  18194. if ( onLoad ) onLoad( this );
  18195. scope.manager.itemEnd( url );
  18196. }, false );
  18197. /*
  18198. image.addEventListener( 'progress', function ( event ) {
  18199. if ( onProgress ) onProgress( event );
  18200. }, false );
  18201. */
  18202. image.addEventListener( 'error', function ( event ) {
  18203. if ( onError ) onError( event );
  18204. scope.manager.itemEnd( url );
  18205. scope.manager.itemError( url );
  18206. }, false );
  18207. if ( url.substr( 0, 5 ) !== 'data:' ) {
  18208. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18209. }
  18210. scope.manager.itemStart( url );
  18211. image.src = url;
  18212. return image;
  18213. },
  18214. setCrossOrigin: function ( value ) {
  18215. this.crossOrigin = value;
  18216. return this;
  18217. },
  18218. setPath: function ( value ) {
  18219. this.path = value;
  18220. return this;
  18221. }
  18222. } );
  18223. /**
  18224. * @author mrdoob / http://mrdoob.com/
  18225. */
  18226. function CubeTextureLoader( manager ) {
  18227. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18228. }
  18229. Object.assign( CubeTextureLoader.prototype, {
  18230. load: function ( urls, onLoad, onProgress, onError ) {
  18231. var texture = new CubeTexture();
  18232. var loader = new ImageLoader( this.manager );
  18233. loader.setCrossOrigin( this.crossOrigin );
  18234. loader.setPath( this.path );
  18235. var loaded = 0;
  18236. function loadTexture( i ) {
  18237. loader.load( urls[ i ], function ( image ) {
  18238. texture.images[ i ] = image;
  18239. loaded ++;
  18240. if ( loaded === 6 ) {
  18241. texture.needsUpdate = true;
  18242. if ( onLoad ) onLoad( texture );
  18243. }
  18244. }, undefined, onError );
  18245. }
  18246. for ( var i = 0; i < urls.length; ++ i ) {
  18247. loadTexture( i );
  18248. }
  18249. return texture;
  18250. },
  18251. setCrossOrigin: function ( value ) {
  18252. this.crossOrigin = value;
  18253. return this;
  18254. },
  18255. setPath: function ( value ) {
  18256. this.path = value;
  18257. return this;
  18258. }
  18259. } );
  18260. /**
  18261. * @author mrdoob / http://mrdoob.com/
  18262. */
  18263. function TextureLoader( manager ) {
  18264. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  18265. }
  18266. Object.assign( TextureLoader.prototype, {
  18267. load: function ( url, onLoad, onProgress, onError ) {
  18268. var loader = new ImageLoader( this.manager );
  18269. loader.setCrossOrigin( this.crossOrigin );
  18270. loader.setPath( this.path );
  18271. var texture = new Texture();
  18272. texture.image = loader.load( url, function () {
  18273. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  18274. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  18275. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  18276. texture.needsUpdate = true;
  18277. if ( onLoad !== undefined ) {
  18278. onLoad( texture );
  18279. }
  18280. }, onProgress, onError );
  18281. return texture;
  18282. },
  18283. setCrossOrigin: function ( value ) {
  18284. this.crossOrigin = value;
  18285. return this;
  18286. },
  18287. setPath: function ( value ) {
  18288. this.path = value;
  18289. return this;
  18290. }
  18291. } );
  18292. /**
  18293. * @author mrdoob / http://mrdoob.com/
  18294. * @author alteredq / http://alteredqualia.com/
  18295. */
  18296. function Light( color, intensity ) {
  18297. Object3D.call( this );
  18298. this.type = 'Light';
  18299. this.color = new Color( color );
  18300. this.intensity = intensity !== undefined ? intensity : 1;
  18301. this.receiveShadow = undefined;
  18302. }
  18303. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18304. constructor: Light,
  18305. isLight: true,
  18306. copy: function ( source ) {
  18307. Object3D.prototype.copy.call( this, source );
  18308. this.color.copy( source.color );
  18309. this.intensity = source.intensity;
  18310. return this;
  18311. },
  18312. toJSON: function ( meta ) {
  18313. var data = Object3D.prototype.toJSON.call( this, meta );
  18314. data.object.color = this.color.getHex();
  18315. data.object.intensity = this.intensity;
  18316. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18317. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18318. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18319. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18320. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18321. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18322. return data;
  18323. }
  18324. } );
  18325. /**
  18326. * @author alteredq / http://alteredqualia.com/
  18327. */
  18328. function HemisphereLight( skyColor, groundColor, intensity ) {
  18329. Light.call( this, skyColor, intensity );
  18330. this.type = 'HemisphereLight';
  18331. this.castShadow = undefined;
  18332. this.position.copy( Object3D.DefaultUp );
  18333. this.updateMatrix();
  18334. this.groundColor = new Color( groundColor );
  18335. }
  18336. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18337. constructor: HemisphereLight,
  18338. isHemisphereLight: true,
  18339. copy: function ( source ) {
  18340. Light.prototype.copy.call( this, source );
  18341. this.groundColor.copy( source.groundColor );
  18342. return this;
  18343. }
  18344. } );
  18345. /**
  18346. * @author mrdoob / http://mrdoob.com/
  18347. */
  18348. function LightShadow( camera ) {
  18349. this.camera = camera;
  18350. this.bias = 0;
  18351. this.radius = 1;
  18352. this.mapSize = new Vector2( 512, 512 );
  18353. this.map = null;
  18354. this.matrix = new Matrix4();
  18355. }
  18356. Object.assign( LightShadow.prototype, {
  18357. copy: function ( source ) {
  18358. this.camera = source.camera.clone();
  18359. this.bias = source.bias;
  18360. this.radius = source.radius;
  18361. this.mapSize.copy( source.mapSize );
  18362. return this;
  18363. },
  18364. clone: function () {
  18365. return new this.constructor().copy( this );
  18366. },
  18367. toJSON: function () {
  18368. var object = {};
  18369. if ( this.bias !== 0 ) object.bias = this.bias;
  18370. if ( this.radius !== 1 ) object.radius = this.radius;
  18371. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18372. object.camera = this.camera.toJSON( false ).object;
  18373. delete object.camera.matrix;
  18374. return object;
  18375. }
  18376. } );
  18377. /**
  18378. * @author mrdoob / http://mrdoob.com/
  18379. */
  18380. function SpotLightShadow() {
  18381. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18382. }
  18383. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18384. constructor: SpotLightShadow,
  18385. isSpotLightShadow: true,
  18386. update: function ( light ) {
  18387. var camera = this.camera;
  18388. var fov = _Math.RAD2DEG * 2 * light.angle;
  18389. var aspect = this.mapSize.width / this.mapSize.height;
  18390. var far = light.distance || camera.far;
  18391. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18392. camera.fov = fov;
  18393. camera.aspect = aspect;
  18394. camera.far = far;
  18395. camera.updateProjectionMatrix();
  18396. }
  18397. }
  18398. } );
  18399. /**
  18400. * @author alteredq / http://alteredqualia.com/
  18401. */
  18402. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18403. Light.call( this, color, intensity );
  18404. this.type = 'SpotLight';
  18405. this.position.copy( Object3D.DefaultUp );
  18406. this.updateMatrix();
  18407. this.target = new Object3D();
  18408. Object.defineProperty( this, 'power', {
  18409. get: function () {
  18410. // intensity = power per solid angle.
  18411. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18412. return this.intensity * Math.PI;
  18413. },
  18414. set: function ( power ) {
  18415. // intensity = power per solid angle.
  18416. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18417. this.intensity = power / Math.PI;
  18418. }
  18419. } );
  18420. this.distance = ( distance !== undefined ) ? distance : 0;
  18421. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18422. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18423. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18424. this.shadow = new SpotLightShadow();
  18425. }
  18426. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18427. constructor: SpotLight,
  18428. isSpotLight: true,
  18429. copy: function ( source ) {
  18430. Light.prototype.copy.call( this, source );
  18431. this.distance = source.distance;
  18432. this.angle = source.angle;
  18433. this.penumbra = source.penumbra;
  18434. this.decay = source.decay;
  18435. this.target = source.target.clone();
  18436. this.shadow = source.shadow.clone();
  18437. return this;
  18438. }
  18439. } );
  18440. /**
  18441. * @author mrdoob / http://mrdoob.com/
  18442. */
  18443. function PointLight( color, intensity, distance, decay ) {
  18444. Light.call( this, color, intensity );
  18445. this.type = 'PointLight';
  18446. Object.defineProperty( this, 'power', {
  18447. get: function () {
  18448. // intensity = power per solid angle.
  18449. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18450. return this.intensity * 4 * Math.PI;
  18451. },
  18452. set: function ( power ) {
  18453. // intensity = power per solid angle.
  18454. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18455. this.intensity = power / ( 4 * Math.PI );
  18456. }
  18457. } );
  18458. this.distance = ( distance !== undefined ) ? distance : 0;
  18459. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18460. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18461. }
  18462. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18463. constructor: PointLight,
  18464. isPointLight: true,
  18465. copy: function ( source ) {
  18466. Light.prototype.copy.call( this, source );
  18467. this.distance = source.distance;
  18468. this.decay = source.decay;
  18469. this.shadow = source.shadow.clone();
  18470. return this;
  18471. }
  18472. } );
  18473. /**
  18474. * @author mrdoob / http://mrdoob.com/
  18475. */
  18476. function DirectionalLightShadow( ) {
  18477. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18478. }
  18479. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18480. constructor: DirectionalLightShadow
  18481. } );
  18482. /**
  18483. * @author mrdoob / http://mrdoob.com/
  18484. * @author alteredq / http://alteredqualia.com/
  18485. */
  18486. function DirectionalLight( color, intensity ) {
  18487. Light.call( this, color, intensity );
  18488. this.type = 'DirectionalLight';
  18489. this.position.copy( Object3D.DefaultUp );
  18490. this.updateMatrix();
  18491. this.target = new Object3D();
  18492. this.shadow = new DirectionalLightShadow();
  18493. }
  18494. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18495. constructor: DirectionalLight,
  18496. isDirectionalLight: true,
  18497. copy: function ( source ) {
  18498. Light.prototype.copy.call( this, source );
  18499. this.target = source.target.clone();
  18500. this.shadow = source.shadow.clone();
  18501. return this;
  18502. }
  18503. } );
  18504. /**
  18505. * @author mrdoob / http://mrdoob.com/
  18506. */
  18507. function AmbientLight( color, intensity ) {
  18508. Light.call( this, color, intensity );
  18509. this.type = 'AmbientLight';
  18510. this.castShadow = undefined;
  18511. }
  18512. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18513. constructor: AmbientLight,
  18514. isAmbientLight: true
  18515. } );
  18516. /**
  18517. * @author abelnation / http://github.com/abelnation
  18518. */
  18519. function RectAreaLight( color, intensity, width, height ) {
  18520. Light.call( this, color, intensity );
  18521. this.type = 'RectAreaLight';
  18522. this.position.set( 0, 1, 0 );
  18523. this.updateMatrix();
  18524. this.width = ( width !== undefined ) ? width : 10;
  18525. this.height = ( height !== undefined ) ? height : 10;
  18526. // TODO (abelnation): distance/decay
  18527. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18528. // TODO (abelnation): shadows
  18529. }
  18530. // TODO (abelnation): RectAreaLight update when light shape is changed
  18531. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18532. constructor: RectAreaLight,
  18533. isRectAreaLight: true,
  18534. copy: function ( source ) {
  18535. Light.prototype.copy.call( this, source );
  18536. this.width = source.width;
  18537. this.height = source.height;
  18538. return this;
  18539. },
  18540. toJSON: function ( meta ) {
  18541. var data = Light.prototype.toJSON.call( this, meta );
  18542. data.object.width = this.width;
  18543. data.object.height = this.height;
  18544. return data;
  18545. }
  18546. } );
  18547. /**
  18548. * @author tschw
  18549. * @author Ben Houston / http://clara.io/
  18550. * @author David Sarno / http://lighthaus.us/
  18551. */
  18552. var AnimationUtils = {
  18553. // same as Array.prototype.slice, but also works on typed arrays
  18554. arraySlice: function ( array, from, to ) {
  18555. if ( AnimationUtils.isTypedArray( array ) ) {
  18556. // in ios9 array.subarray(from, undefined) will return empty array
  18557. // but array.subarray(from) or array.subarray(from, len) is correct
  18558. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18559. }
  18560. return array.slice( from, to );
  18561. },
  18562. // converts an array to a specific type
  18563. convertArray: function ( array, type, forceClone ) {
  18564. if ( ! array || // let 'undefined' and 'null' pass
  18565. ! forceClone && array.constructor === type ) return array;
  18566. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18567. return new type( array ); // create typed array
  18568. }
  18569. return Array.prototype.slice.call( array ); // create Array
  18570. },
  18571. isTypedArray: function ( object ) {
  18572. return ArrayBuffer.isView( object ) &&
  18573. ! ( object instanceof DataView );
  18574. },
  18575. // returns an array by which times and values can be sorted
  18576. getKeyframeOrder: function ( times ) {
  18577. function compareTime( i, j ) {
  18578. return times[ i ] - times[ j ];
  18579. }
  18580. var n = times.length;
  18581. var result = new Array( n );
  18582. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18583. result.sort( compareTime );
  18584. return result;
  18585. },
  18586. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18587. sortedArray: function ( values, stride, order ) {
  18588. var nValues = values.length;
  18589. var result = new values.constructor( nValues );
  18590. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18591. var srcOffset = order[ i ] * stride;
  18592. for ( var j = 0; j !== stride; ++ j ) {
  18593. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18594. }
  18595. }
  18596. return result;
  18597. },
  18598. // function for parsing AOS keyframe formats
  18599. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18600. var i = 1, key = jsonKeys[ 0 ];
  18601. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18602. key = jsonKeys[ i ++ ];
  18603. }
  18604. if ( key === undefined ) return; // no data
  18605. var value = key[ valuePropertyName ];
  18606. if ( value === undefined ) return; // no data
  18607. if ( Array.isArray( value ) ) {
  18608. do {
  18609. value = key[ valuePropertyName ];
  18610. if ( value !== undefined ) {
  18611. times.push( key.time );
  18612. values.push.apply( values, value ); // push all elements
  18613. }
  18614. key = jsonKeys[ i ++ ];
  18615. } while ( key !== undefined );
  18616. } else if ( value.toArray !== undefined ) {
  18617. // ...assume THREE.Math-ish
  18618. do {
  18619. value = key[ valuePropertyName ];
  18620. if ( value !== undefined ) {
  18621. times.push( key.time );
  18622. value.toArray( values, values.length );
  18623. }
  18624. key = jsonKeys[ i ++ ];
  18625. } while ( key !== undefined );
  18626. } else {
  18627. // otherwise push as-is
  18628. do {
  18629. value = key[ valuePropertyName ];
  18630. if ( value !== undefined ) {
  18631. times.push( key.time );
  18632. values.push( value );
  18633. }
  18634. key = jsonKeys[ i ++ ];
  18635. } while ( key !== undefined );
  18636. }
  18637. }
  18638. };
  18639. /**
  18640. * Abstract base class of interpolants over parametric samples.
  18641. *
  18642. * The parameter domain is one dimensional, typically the time or a path
  18643. * along a curve defined by the data.
  18644. *
  18645. * The sample values can have any dimensionality and derived classes may
  18646. * apply special interpretations to the data.
  18647. *
  18648. * This class provides the interval seek in a Template Method, deferring
  18649. * the actual interpolation to derived classes.
  18650. *
  18651. * Time complexity is O(1) for linear access crossing at most two points
  18652. * and O(log N) for random access, where N is the number of positions.
  18653. *
  18654. * References:
  18655. *
  18656. * http://www.oodesign.com/template-method-pattern.html
  18657. *
  18658. * @author tschw
  18659. */
  18660. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18661. this.parameterPositions = parameterPositions;
  18662. this._cachedIndex = 0;
  18663. this.resultBuffer = resultBuffer !== undefined ?
  18664. resultBuffer : new sampleValues.constructor( sampleSize );
  18665. this.sampleValues = sampleValues;
  18666. this.valueSize = sampleSize;
  18667. }
  18668. Object.assign( Interpolant.prototype, {
  18669. evaluate: function( t ) {
  18670. var pp = this.parameterPositions,
  18671. i1 = this._cachedIndex,
  18672. t1 = pp[ i1 ],
  18673. t0 = pp[ i1 - 1 ];
  18674. validate_interval: {
  18675. seek: {
  18676. var right;
  18677. linear_scan: {
  18678. //- See http://jsperf.com/comparison-to-undefined/3
  18679. //- slower code:
  18680. //-
  18681. //- if ( t >= t1 || t1 === undefined ) {
  18682. forward_scan: if ( ! ( t < t1 ) ) {
  18683. for ( var giveUpAt = i1 + 2; ;) {
  18684. if ( t1 === undefined ) {
  18685. if ( t < t0 ) break forward_scan;
  18686. // after end
  18687. i1 = pp.length;
  18688. this._cachedIndex = i1;
  18689. return this.afterEnd_( i1 - 1, t, t0 );
  18690. }
  18691. if ( i1 === giveUpAt ) break; // this loop
  18692. t0 = t1;
  18693. t1 = pp[ ++ i1 ];
  18694. if ( t < t1 ) {
  18695. // we have arrived at the sought interval
  18696. break seek;
  18697. }
  18698. }
  18699. // prepare binary search on the right side of the index
  18700. right = pp.length;
  18701. break linear_scan;
  18702. }
  18703. //- slower code:
  18704. //- if ( t < t0 || t0 === undefined ) {
  18705. if ( ! ( t >= t0 ) ) {
  18706. // looping?
  18707. var t1global = pp[ 1 ];
  18708. if ( t < t1global ) {
  18709. i1 = 2; // + 1, using the scan for the details
  18710. t0 = t1global;
  18711. }
  18712. // linear reverse scan
  18713. for ( var giveUpAt = i1 - 2; ;) {
  18714. if ( t0 === undefined ) {
  18715. // before start
  18716. this._cachedIndex = 0;
  18717. return this.beforeStart_( 0, t, t1 );
  18718. }
  18719. if ( i1 === giveUpAt ) break; // this loop
  18720. t1 = t0;
  18721. t0 = pp[ -- i1 - 1 ];
  18722. if ( t >= t0 ) {
  18723. // we have arrived at the sought interval
  18724. break seek;
  18725. }
  18726. }
  18727. // prepare binary search on the left side of the index
  18728. right = i1;
  18729. i1 = 0;
  18730. break linear_scan;
  18731. }
  18732. // the interval is valid
  18733. break validate_interval;
  18734. } // linear scan
  18735. // binary search
  18736. while ( i1 < right ) {
  18737. var mid = ( i1 + right ) >>> 1;
  18738. if ( t < pp[ mid ] ) {
  18739. right = mid;
  18740. } else {
  18741. i1 = mid + 1;
  18742. }
  18743. }
  18744. t1 = pp[ i1 ];
  18745. t0 = pp[ i1 - 1 ];
  18746. // check boundary cases, again
  18747. if ( t0 === undefined ) {
  18748. this._cachedIndex = 0;
  18749. return this.beforeStart_( 0, t, t1 );
  18750. }
  18751. if ( t1 === undefined ) {
  18752. i1 = pp.length;
  18753. this._cachedIndex = i1;
  18754. return this.afterEnd_( i1 - 1, t0, t );
  18755. }
  18756. } // seek
  18757. this._cachedIndex = i1;
  18758. this.intervalChanged_( i1, t0, t1 );
  18759. } // validate_interval
  18760. return this.interpolate_( i1, t0, t, t1 );
  18761. },
  18762. settings: null, // optional, subclass-specific settings structure
  18763. // Note: The indirection allows central control of many interpolants.
  18764. // --- Protected interface
  18765. DefaultSettings_: {},
  18766. getSettings_: function() {
  18767. return this.settings || this.DefaultSettings_;
  18768. },
  18769. copySampleValue_: function( index ) {
  18770. // copies a sample value to the result buffer
  18771. var result = this.resultBuffer,
  18772. values = this.sampleValues,
  18773. stride = this.valueSize,
  18774. offset = index * stride;
  18775. for ( var i = 0; i !== stride; ++ i ) {
  18776. result[ i ] = values[ offset + i ];
  18777. }
  18778. return result;
  18779. },
  18780. // Template methods for derived classes:
  18781. interpolate_: function( i1, t0, t, t1 ) {
  18782. throw new Error( "call to abstract method" );
  18783. // implementations shall return this.resultBuffer
  18784. },
  18785. intervalChanged_: function( i1, t0, t1 ) {
  18786. // empty
  18787. }
  18788. } );
  18789. //!\ DECLARE ALIAS AFTER assign prototype !
  18790. Object.assign( Interpolant.prototype, {
  18791. //( 0, t, t0 ), returns this.resultBuffer
  18792. beforeStart_: Interpolant.prototype.copySampleValue_,
  18793. //( N-1, tN-1, t ), returns this.resultBuffer
  18794. afterEnd_: Interpolant.prototype.copySampleValue_,
  18795. } );
  18796. /**
  18797. * Fast and simple cubic spline interpolant.
  18798. *
  18799. * It was derived from a Hermitian construction setting the first derivative
  18800. * at each sample position to the linear slope between neighboring positions
  18801. * over their parameter interval.
  18802. *
  18803. * @author tschw
  18804. */
  18805. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18806. Interpolant.call(
  18807. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18808. this._weightPrev = -0;
  18809. this._offsetPrev = -0;
  18810. this._weightNext = -0;
  18811. this._offsetNext = -0;
  18812. }
  18813. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18814. constructor: CubicInterpolant,
  18815. DefaultSettings_: {
  18816. endingStart: ZeroCurvatureEnding,
  18817. endingEnd: ZeroCurvatureEnding
  18818. },
  18819. intervalChanged_: function( i1, t0, t1 ) {
  18820. var pp = this.parameterPositions,
  18821. iPrev = i1 - 2,
  18822. iNext = i1 + 1,
  18823. tPrev = pp[ iPrev ],
  18824. tNext = pp[ iNext ];
  18825. if ( tPrev === undefined ) {
  18826. switch ( this.getSettings_().endingStart ) {
  18827. case ZeroSlopeEnding:
  18828. // f'(t0) = 0
  18829. iPrev = i1;
  18830. tPrev = 2 * t0 - t1;
  18831. break;
  18832. case WrapAroundEnding:
  18833. // use the other end of the curve
  18834. iPrev = pp.length - 2;
  18835. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18836. break;
  18837. default: // ZeroCurvatureEnding
  18838. // f''(t0) = 0 a.k.a. Natural Spline
  18839. iPrev = i1;
  18840. tPrev = t1;
  18841. }
  18842. }
  18843. if ( tNext === undefined ) {
  18844. switch ( this.getSettings_().endingEnd ) {
  18845. case ZeroSlopeEnding:
  18846. // f'(tN) = 0
  18847. iNext = i1;
  18848. tNext = 2 * t1 - t0;
  18849. break;
  18850. case WrapAroundEnding:
  18851. // use the other end of the curve
  18852. iNext = 1;
  18853. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18854. break;
  18855. default: // ZeroCurvatureEnding
  18856. // f''(tN) = 0, a.k.a. Natural Spline
  18857. iNext = i1 - 1;
  18858. tNext = t0;
  18859. }
  18860. }
  18861. var halfDt = ( t1 - t0 ) * 0.5,
  18862. stride = this.valueSize;
  18863. this._weightPrev = halfDt / ( t0 - tPrev );
  18864. this._weightNext = halfDt / ( tNext - t1 );
  18865. this._offsetPrev = iPrev * stride;
  18866. this._offsetNext = iNext * stride;
  18867. },
  18868. interpolate_: function( i1, t0, t, t1 ) {
  18869. var result = this.resultBuffer,
  18870. values = this.sampleValues,
  18871. stride = this.valueSize,
  18872. o1 = i1 * stride, o0 = o1 - stride,
  18873. oP = this._offsetPrev, oN = this._offsetNext,
  18874. wP = this._weightPrev, wN = this._weightNext,
  18875. p = ( t - t0 ) / ( t1 - t0 ),
  18876. pp = p * p,
  18877. ppp = pp * p;
  18878. // evaluate polynomials
  18879. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18880. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18881. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18882. var sN = wN * ppp - wN * pp;
  18883. // combine data linearly
  18884. for ( var i = 0; i !== stride; ++ i ) {
  18885. result[ i ] =
  18886. sP * values[ oP + i ] +
  18887. s0 * values[ o0 + i ] +
  18888. s1 * values[ o1 + i ] +
  18889. sN * values[ oN + i ];
  18890. }
  18891. return result;
  18892. }
  18893. } );
  18894. /**
  18895. * @author tschw
  18896. */
  18897. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18898. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18899. }
  18900. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18901. constructor: LinearInterpolant,
  18902. interpolate_: function( i1, t0, t, t1 ) {
  18903. var result = this.resultBuffer,
  18904. values = this.sampleValues,
  18905. stride = this.valueSize,
  18906. offset1 = i1 * stride,
  18907. offset0 = offset1 - stride,
  18908. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18909. weight0 = 1 - weight1;
  18910. for ( var i = 0; i !== stride; ++ i ) {
  18911. result[ i ] =
  18912. values[ offset0 + i ] * weight0 +
  18913. values[ offset1 + i ] * weight1;
  18914. }
  18915. return result;
  18916. }
  18917. } );
  18918. /**
  18919. *
  18920. * Interpolant that evaluates to the sample value at the position preceeding
  18921. * the parameter.
  18922. *
  18923. * @author tschw
  18924. */
  18925. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18926. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18927. }
  18928. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18929. constructor: DiscreteInterpolant,
  18930. interpolate_: function( i1, t0, t, t1 ) {
  18931. return this.copySampleValue_( i1 - 1 );
  18932. }
  18933. } );
  18934. var KeyframeTrackPrototype;
  18935. KeyframeTrackPrototype = {
  18936. TimeBufferType: Float32Array,
  18937. ValueBufferType: Float32Array,
  18938. DefaultInterpolation: InterpolateLinear,
  18939. InterpolantFactoryMethodDiscrete: function ( result ) {
  18940. return new DiscreteInterpolant(
  18941. this.times, this.values, this.getValueSize(), result );
  18942. },
  18943. InterpolantFactoryMethodLinear: function ( result ) {
  18944. return new LinearInterpolant(
  18945. this.times, this.values, this.getValueSize(), result );
  18946. },
  18947. InterpolantFactoryMethodSmooth: function ( result ) {
  18948. return new CubicInterpolant(
  18949. this.times, this.values, this.getValueSize(), result );
  18950. },
  18951. setInterpolation: function ( interpolation ) {
  18952. var factoryMethod;
  18953. switch ( interpolation ) {
  18954. case InterpolateDiscrete:
  18955. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18956. break;
  18957. case InterpolateLinear:
  18958. factoryMethod = this.InterpolantFactoryMethodLinear;
  18959. break;
  18960. case InterpolateSmooth:
  18961. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18962. break;
  18963. }
  18964. if ( factoryMethod === undefined ) {
  18965. var message = "unsupported interpolation for " +
  18966. this.ValueTypeName + " keyframe track named " + this.name;
  18967. if ( this.createInterpolant === undefined ) {
  18968. // fall back to default, unless the default itself is messed up
  18969. if ( interpolation !== this.DefaultInterpolation ) {
  18970. this.setInterpolation( this.DefaultInterpolation );
  18971. } else {
  18972. throw new Error( message ); // fatal, in this case
  18973. }
  18974. }
  18975. console.warn( 'THREE.KeyframeTrackPrototype:', message );
  18976. return;
  18977. }
  18978. this.createInterpolant = factoryMethod;
  18979. },
  18980. getInterpolation: function () {
  18981. switch ( this.createInterpolant ) {
  18982. case this.InterpolantFactoryMethodDiscrete:
  18983. return InterpolateDiscrete;
  18984. case this.InterpolantFactoryMethodLinear:
  18985. return InterpolateLinear;
  18986. case this.InterpolantFactoryMethodSmooth:
  18987. return InterpolateSmooth;
  18988. }
  18989. },
  18990. getValueSize: function () {
  18991. return this.values.length / this.times.length;
  18992. },
  18993. // move all keyframes either forwards or backwards in time
  18994. shift: function ( timeOffset ) {
  18995. if ( timeOffset !== 0.0 ) {
  18996. var times = this.times;
  18997. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18998. times[ i ] += timeOffset;
  18999. }
  19000. }
  19001. return this;
  19002. },
  19003. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19004. scale: function ( timeScale ) {
  19005. if ( timeScale !== 1.0 ) {
  19006. var times = this.times;
  19007. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  19008. times[ i ] *= timeScale;
  19009. }
  19010. }
  19011. return this;
  19012. },
  19013. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19014. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19015. trim: function ( startTime, endTime ) {
  19016. var times = this.times,
  19017. nKeys = times.length,
  19018. from = 0,
  19019. to = nKeys - 1;
  19020. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  19021. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  19022. ++ to; // inclusive -> exclusive bound
  19023. if ( from !== 0 || to !== nKeys ) {
  19024. // empty tracks are forbidden, so keep at least one keyframe
  19025. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  19026. var stride = this.getValueSize();
  19027. this.times = AnimationUtils.arraySlice( times, from, to );
  19028. this.values = AnimationUtils.
  19029. arraySlice( this.values, from * stride, to * stride );
  19030. }
  19031. return this;
  19032. },
  19033. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19034. validate: function () {
  19035. var valid = true;
  19036. var valueSize = this.getValueSize();
  19037. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  19038. console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this );
  19039. valid = false;
  19040. }
  19041. var times = this.times,
  19042. values = this.values,
  19043. nKeys = times.length;
  19044. if ( nKeys === 0 ) {
  19045. console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this );
  19046. valid = false;
  19047. }
  19048. var prevTime = null;
  19049. for ( var i = 0; i !== nKeys; i ++ ) {
  19050. var currTime = times[ i ];
  19051. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  19052. console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime );
  19053. valid = false;
  19054. break;
  19055. }
  19056. if ( prevTime !== null && prevTime > currTime ) {
  19057. console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime );
  19058. valid = false;
  19059. break;
  19060. }
  19061. prevTime = currTime;
  19062. }
  19063. if ( values !== undefined ) {
  19064. if ( AnimationUtils.isTypedArray( values ) ) {
  19065. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  19066. var value = values[ i ];
  19067. if ( isNaN( value ) ) {
  19068. console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value );
  19069. valid = false;
  19070. break;
  19071. }
  19072. }
  19073. }
  19074. }
  19075. return valid;
  19076. },
  19077. // removes equivalent sequential keys as common in morph target sequences
  19078. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19079. optimize: function () {
  19080. var times = this.times,
  19081. values = this.values,
  19082. stride = this.getValueSize(),
  19083. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19084. writeIndex = 1,
  19085. lastIndex = times.length - 1;
  19086. for ( var i = 1; i < lastIndex; ++ i ) {
  19087. var keep = false;
  19088. var time = times[ i ];
  19089. var timeNext = times[ i + 1 ];
  19090. // remove adjacent keyframes scheduled at the same time
  19091. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  19092. if ( ! smoothInterpolation ) {
  19093. // remove unnecessary keyframes same as their neighbors
  19094. var offset = i * stride,
  19095. offsetP = offset - stride,
  19096. offsetN = offset + stride;
  19097. for ( var j = 0; j !== stride; ++ j ) {
  19098. var value = values[ offset + j ];
  19099. if ( value !== values[ offsetP + j ] ||
  19100. value !== values[ offsetN + j ] ) {
  19101. keep = true;
  19102. break;
  19103. }
  19104. }
  19105. } else keep = true;
  19106. }
  19107. // in-place compaction
  19108. if ( keep ) {
  19109. if ( i !== writeIndex ) {
  19110. times[ writeIndex ] = times[ i ];
  19111. var readOffset = i * stride,
  19112. writeOffset = writeIndex * stride;
  19113. for ( var j = 0; j !== stride; ++ j )
  19114. values[ writeOffset + j ] = values[ readOffset + j ];
  19115. }
  19116. ++ writeIndex;
  19117. }
  19118. }
  19119. // flush last keyframe (compaction looks ahead)
  19120. if ( lastIndex > 0 ) {
  19121. times[ writeIndex ] = times[ lastIndex ];
  19122. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  19123. values[ writeOffset + j ] = values[ readOffset + j ];
  19124. ++ writeIndex;
  19125. }
  19126. if ( writeIndex !== times.length ) {
  19127. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  19128. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  19129. }
  19130. return this;
  19131. }
  19132. };
  19133. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  19134. if ( name === undefined ) throw new Error( "track name is undefined" );
  19135. if ( times === undefined || times.length === 0 ) {
  19136. throw new Error( "no keyframes in track named " + name );
  19137. }
  19138. this.name = name;
  19139. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19140. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19141. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19142. this.validate();
  19143. this.optimize();
  19144. }
  19145. /**
  19146. *
  19147. * A Track of vectored keyframe values.
  19148. *
  19149. *
  19150. * @author Ben Houston / http://clara.io/
  19151. * @author David Sarno / http://lighthaus.us/
  19152. * @author tschw
  19153. */
  19154. function VectorKeyframeTrack( name, times, values, interpolation ) {
  19155. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19156. }
  19157. VectorKeyframeTrack.prototype =
  19158. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19159. constructor: VectorKeyframeTrack,
  19160. ValueTypeName: 'vector'
  19161. // ValueBufferType is inherited
  19162. // DefaultInterpolation is inherited
  19163. } );
  19164. /**
  19165. * Spherical linear unit quaternion interpolant.
  19166. *
  19167. * @author tschw
  19168. */
  19169. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19170. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19171. }
  19172. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19173. constructor: QuaternionLinearInterpolant,
  19174. interpolate_: function( i1, t0, t, t1 ) {
  19175. var result = this.resultBuffer,
  19176. values = this.sampleValues,
  19177. stride = this.valueSize,
  19178. offset = i1 * stride,
  19179. alpha = ( t - t0 ) / ( t1 - t0 );
  19180. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  19181. Quaternion.slerpFlat( result, 0,
  19182. values, offset - stride, values, offset, alpha );
  19183. }
  19184. return result;
  19185. }
  19186. } );
  19187. /**
  19188. *
  19189. * A Track of quaternion keyframe values.
  19190. *
  19191. * @author Ben Houston / http://clara.io/
  19192. * @author David Sarno / http://lighthaus.us/
  19193. * @author tschw
  19194. */
  19195. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  19196. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19197. }
  19198. QuaternionKeyframeTrack.prototype =
  19199. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19200. constructor: QuaternionKeyframeTrack,
  19201. ValueTypeName: 'quaternion',
  19202. // ValueBufferType is inherited
  19203. DefaultInterpolation: InterpolateLinear,
  19204. InterpolantFactoryMethodLinear: function( result ) {
  19205. return new QuaternionLinearInterpolant(
  19206. this.times, this.values, this.getValueSize(), result );
  19207. },
  19208. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  19209. } );
  19210. /**
  19211. *
  19212. * A Track of numeric keyframe values.
  19213. *
  19214. * @author Ben Houston / http://clara.io/
  19215. * @author David Sarno / http://lighthaus.us/
  19216. * @author tschw
  19217. */
  19218. function NumberKeyframeTrack( name, times, values, interpolation ) {
  19219. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19220. }
  19221. NumberKeyframeTrack.prototype =
  19222. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19223. constructor: NumberKeyframeTrack,
  19224. ValueTypeName: 'number'
  19225. // ValueBufferType is inherited
  19226. // DefaultInterpolation is inherited
  19227. } );
  19228. /**
  19229. *
  19230. * A Track that interpolates Strings
  19231. *
  19232. *
  19233. * @author Ben Houston / http://clara.io/
  19234. * @author David Sarno / http://lighthaus.us/
  19235. * @author tschw
  19236. */
  19237. function StringKeyframeTrack( name, times, values, interpolation ) {
  19238. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19239. }
  19240. StringKeyframeTrack.prototype =
  19241. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19242. constructor: StringKeyframeTrack,
  19243. ValueTypeName: 'string',
  19244. ValueBufferType: Array,
  19245. DefaultInterpolation: InterpolateDiscrete,
  19246. InterpolantFactoryMethodLinear: undefined,
  19247. InterpolantFactoryMethodSmooth: undefined
  19248. } );
  19249. /**
  19250. *
  19251. * A Track of Boolean keyframe values.
  19252. *
  19253. *
  19254. * @author Ben Houston / http://clara.io/
  19255. * @author David Sarno / http://lighthaus.us/
  19256. * @author tschw
  19257. */
  19258. function BooleanKeyframeTrack( name, times, values ) {
  19259. KeyframeTrackConstructor.call( this, name, times, values );
  19260. }
  19261. BooleanKeyframeTrack.prototype =
  19262. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19263. constructor: BooleanKeyframeTrack,
  19264. ValueTypeName: 'bool',
  19265. ValueBufferType: Array,
  19266. DefaultInterpolation: InterpolateDiscrete,
  19267. InterpolantFactoryMethodLinear: undefined,
  19268. InterpolantFactoryMethodSmooth: undefined
  19269. // Note: Actually this track could have a optimized / compressed
  19270. // representation of a single value and a custom interpolant that
  19271. // computes "firstValue ^ isOdd( index )".
  19272. } );
  19273. /**
  19274. *
  19275. * A Track of keyframe values that represent color.
  19276. *
  19277. *
  19278. * @author Ben Houston / http://clara.io/
  19279. * @author David Sarno / http://lighthaus.us/
  19280. * @author tschw
  19281. */
  19282. function ColorKeyframeTrack( name, times, values, interpolation ) {
  19283. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  19284. }
  19285. ColorKeyframeTrack.prototype =
  19286. Object.assign( Object.create( KeyframeTrackPrototype ), {
  19287. constructor: ColorKeyframeTrack,
  19288. ValueTypeName: 'color'
  19289. // ValueBufferType is inherited
  19290. // DefaultInterpolation is inherited
  19291. // Note: Very basic implementation and nothing special yet.
  19292. // However, this is the place for color space parameterization.
  19293. } );
  19294. /**
  19295. *
  19296. * A timed sequence of keyframes for a specific property.
  19297. *
  19298. *
  19299. * @author Ben Houston / http://clara.io/
  19300. * @author David Sarno / http://lighthaus.us/
  19301. * @author tschw
  19302. */
  19303. function KeyframeTrack( name, times, values, interpolation ) {
  19304. KeyframeTrackConstructor.apply( this, arguments );
  19305. }
  19306. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19307. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19308. // Static methods:
  19309. Object.assign( KeyframeTrack, {
  19310. // Serialization (in static context, because of constructor invocation
  19311. // and automatic invocation of .toJSON):
  19312. parse: function( json ) {
  19313. if( json.type === undefined ) {
  19314. throw new Error( "track type undefined, can not parse" );
  19315. }
  19316. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19317. if ( json.times === undefined ) {
  19318. var times = [], values = [];
  19319. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19320. json.times = times;
  19321. json.values = values;
  19322. }
  19323. // derived classes can define a static parse method
  19324. if ( trackType.parse !== undefined ) {
  19325. return trackType.parse( json );
  19326. } else {
  19327. // by default, we asssume a constructor compatible with the base
  19328. return new trackType(
  19329. json.name, json.times, json.values, json.interpolation );
  19330. }
  19331. },
  19332. toJSON: function( track ) {
  19333. var trackType = track.constructor;
  19334. var json;
  19335. // derived classes can define a static toJSON method
  19336. if ( trackType.toJSON !== undefined ) {
  19337. json = trackType.toJSON( track );
  19338. } else {
  19339. // by default, we assume the data can be serialized as-is
  19340. json = {
  19341. 'name': track.name,
  19342. 'times': AnimationUtils.convertArray( track.times, Array ),
  19343. 'values': AnimationUtils.convertArray( track.values, Array )
  19344. };
  19345. var interpolation = track.getInterpolation();
  19346. if ( interpolation !== track.DefaultInterpolation ) {
  19347. json.interpolation = interpolation;
  19348. }
  19349. }
  19350. json.type = track.ValueTypeName; // mandatory
  19351. return json;
  19352. },
  19353. _getTrackTypeForValueTypeName: function( typeName ) {
  19354. switch( typeName.toLowerCase() ) {
  19355. case "scalar":
  19356. case "double":
  19357. case "float":
  19358. case "number":
  19359. case "integer":
  19360. return NumberKeyframeTrack;
  19361. case "vector":
  19362. case "vector2":
  19363. case "vector3":
  19364. case "vector4":
  19365. return VectorKeyframeTrack;
  19366. case "color":
  19367. return ColorKeyframeTrack;
  19368. case "quaternion":
  19369. return QuaternionKeyframeTrack;
  19370. case "bool":
  19371. case "boolean":
  19372. return BooleanKeyframeTrack;
  19373. case "string":
  19374. return StringKeyframeTrack;
  19375. }
  19376. throw new Error( "Unsupported typeName: " + typeName );
  19377. }
  19378. } );
  19379. /**
  19380. *
  19381. * Reusable set of Tracks that represent an animation.
  19382. *
  19383. * @author Ben Houston / http://clara.io/
  19384. * @author David Sarno / http://lighthaus.us/
  19385. */
  19386. function AnimationClip( name, duration, tracks ) {
  19387. this.name = name;
  19388. this.tracks = tracks;
  19389. this.duration = ( duration !== undefined ) ? duration : - 1;
  19390. this.uuid = _Math.generateUUID();
  19391. // this means it should figure out its duration by scanning the tracks
  19392. if ( this.duration < 0 ) {
  19393. this.resetDuration();
  19394. }
  19395. this.optimize();
  19396. }
  19397. Object.assign( AnimationClip, {
  19398. parse: function ( json ) {
  19399. var tracks = [],
  19400. jsonTracks = json.tracks,
  19401. frameTime = 1.0 / ( json.fps || 1.0 );
  19402. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19403. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19404. }
  19405. return new AnimationClip( json.name, json.duration, tracks );
  19406. },
  19407. toJSON: function ( clip ) {
  19408. var tracks = [],
  19409. clipTracks = clip.tracks;
  19410. var json = {
  19411. 'name': clip.name,
  19412. 'duration': clip.duration,
  19413. 'tracks': tracks
  19414. };
  19415. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19416. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19417. }
  19418. return json;
  19419. },
  19420. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19421. var numMorphTargets = morphTargetSequence.length;
  19422. var tracks = [];
  19423. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19424. var times = [];
  19425. var values = [];
  19426. times.push(
  19427. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19428. i,
  19429. ( i + 1 ) % numMorphTargets );
  19430. values.push( 0, 1, 0 );
  19431. var order = AnimationUtils.getKeyframeOrder( times );
  19432. times = AnimationUtils.sortedArray( times, 1, order );
  19433. values = AnimationUtils.sortedArray( values, 1, order );
  19434. // if there is a key at the first frame, duplicate it as the
  19435. // last frame as well for perfect loop.
  19436. if ( ! noLoop && times[ 0 ] === 0 ) {
  19437. times.push( numMorphTargets );
  19438. values.push( values[ 0 ] );
  19439. }
  19440. tracks.push(
  19441. new NumberKeyframeTrack(
  19442. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19443. times, values
  19444. ).scale( 1.0 / fps ) );
  19445. }
  19446. return new AnimationClip( name, - 1, tracks );
  19447. },
  19448. findByName: function ( objectOrClipArray, name ) {
  19449. var clipArray = objectOrClipArray;
  19450. if ( ! Array.isArray( objectOrClipArray ) ) {
  19451. var o = objectOrClipArray;
  19452. clipArray = o.geometry && o.geometry.animations || o.animations;
  19453. }
  19454. for ( var i = 0; i < clipArray.length; i ++ ) {
  19455. if ( clipArray[ i ].name === name ) {
  19456. return clipArray[ i ];
  19457. }
  19458. }
  19459. return null;
  19460. },
  19461. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19462. var animationToMorphTargets = {};
  19463. // tested with https://regex101.com/ on trick sequences
  19464. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19465. var pattern = /^([\w-]*?)([\d]+)$/;
  19466. // sort morph target names into animation groups based
  19467. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19468. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19469. var morphTarget = morphTargets[ i ];
  19470. var parts = morphTarget.name.match( pattern );
  19471. if ( parts && parts.length > 1 ) {
  19472. var name = parts[ 1 ];
  19473. var animationMorphTargets = animationToMorphTargets[ name ];
  19474. if ( ! animationMorphTargets ) {
  19475. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19476. }
  19477. animationMorphTargets.push( morphTarget );
  19478. }
  19479. }
  19480. var clips = [];
  19481. for ( var name in animationToMorphTargets ) {
  19482. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19483. }
  19484. return clips;
  19485. },
  19486. // parse the animation.hierarchy format
  19487. parseAnimation: function ( animation, bones ) {
  19488. if ( ! animation ) {
  19489. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  19490. return null;
  19491. }
  19492. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19493. // only return track if there are actually keys.
  19494. if ( animationKeys.length !== 0 ) {
  19495. var times = [];
  19496. var values = [];
  19497. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19498. // empty keys are filtered out, so check again
  19499. if ( times.length !== 0 ) {
  19500. destTracks.push( new trackType( trackName, times, values ) );
  19501. }
  19502. }
  19503. };
  19504. var tracks = [];
  19505. var clipName = animation.name || 'default';
  19506. // automatic length determination in AnimationClip.
  19507. var duration = animation.length || - 1;
  19508. var fps = animation.fps || 30;
  19509. var hierarchyTracks = animation.hierarchy || [];
  19510. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19511. var animationKeys = hierarchyTracks[ h ].keys;
  19512. // skip empty tracks
  19513. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19514. // process morph targets
  19515. if ( animationKeys[ 0 ].morphTargets ) {
  19516. // figure out all morph targets used in this track
  19517. var morphTargetNames = {};
  19518. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19519. if ( animationKeys[ k ].morphTargets ) {
  19520. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19521. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19522. }
  19523. }
  19524. }
  19525. // create a track for each morph target with all zero
  19526. // morphTargetInfluences except for the keys in which
  19527. // the morphTarget is named.
  19528. for ( var morphTargetName in morphTargetNames ) {
  19529. var times = [];
  19530. var values = [];
  19531. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19532. var animationKey = animationKeys[ k ];
  19533. times.push( animationKey.time );
  19534. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19535. }
  19536. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19537. }
  19538. duration = morphTargetNames.length * ( fps || 1.0 );
  19539. } else {
  19540. // ...assume skeletal animation
  19541. var boneName = '.bones[' + bones[ h ].name + ']';
  19542. addNonemptyTrack(
  19543. VectorKeyframeTrack, boneName + '.position',
  19544. animationKeys, 'pos', tracks );
  19545. addNonemptyTrack(
  19546. QuaternionKeyframeTrack, boneName + '.quaternion',
  19547. animationKeys, 'rot', tracks );
  19548. addNonemptyTrack(
  19549. VectorKeyframeTrack, boneName + '.scale',
  19550. animationKeys, 'scl', tracks );
  19551. }
  19552. }
  19553. if ( tracks.length === 0 ) {
  19554. return null;
  19555. }
  19556. var clip = new AnimationClip( clipName, duration, tracks );
  19557. return clip;
  19558. }
  19559. } );
  19560. Object.assign( AnimationClip.prototype, {
  19561. resetDuration: function () {
  19562. var tracks = this.tracks, duration = 0;
  19563. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19564. var track = this.tracks[ i ];
  19565. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19566. }
  19567. this.duration = duration;
  19568. },
  19569. trim: function () {
  19570. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19571. this.tracks[ i ].trim( 0, this.duration );
  19572. }
  19573. return this;
  19574. },
  19575. optimize: function () {
  19576. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19577. this.tracks[ i ].optimize();
  19578. }
  19579. return this;
  19580. }
  19581. } );
  19582. /**
  19583. * @author mrdoob / http://mrdoob.com/
  19584. */
  19585. function MaterialLoader( manager ) {
  19586. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19587. this.textures = {};
  19588. }
  19589. Object.assign( MaterialLoader.prototype, {
  19590. load: function ( url, onLoad, onProgress, onError ) {
  19591. var scope = this;
  19592. var loader = new FileLoader( scope.manager );
  19593. loader.load( url, function ( text ) {
  19594. onLoad( scope.parse( JSON.parse( text ) ) );
  19595. }, onProgress, onError );
  19596. },
  19597. setTextures: function ( value ) {
  19598. this.textures = value;
  19599. },
  19600. parse: function ( json ) {
  19601. var textures = this.textures;
  19602. function getTexture( name ) {
  19603. if ( textures[ name ] === undefined ) {
  19604. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19605. }
  19606. return textures[ name ];
  19607. }
  19608. var material = new Materials[ json.type ]();
  19609. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19610. if ( json.name !== undefined ) material.name = json.name;
  19611. if ( json.color !== undefined ) material.color.setHex( json.color );
  19612. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19613. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19614. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19615. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19616. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19617. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19618. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19619. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19620. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19621. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19622. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19623. if ( json.fog !== undefined ) material.fog = json.fog;
  19624. if ( json.shading !== undefined ) material.shading = json.shading;
  19625. if ( json.blending !== undefined ) material.blending = json.blending;
  19626. if ( json.side !== undefined ) material.side = json.side;
  19627. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19628. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19629. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19630. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19631. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19632. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19633. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19634. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19635. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19636. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19637. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19638. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19639. // for PointsMaterial
  19640. if ( json.size !== undefined ) material.size = json.size;
  19641. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19642. // maps
  19643. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19644. if ( json.alphaMap !== undefined ) {
  19645. material.alphaMap = getTexture( json.alphaMap );
  19646. material.transparent = true;
  19647. }
  19648. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19649. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19650. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19651. if ( json.normalScale !== undefined ) {
  19652. var normalScale = json.normalScale;
  19653. if ( Array.isArray( normalScale ) === false ) {
  19654. // Blender exporter used to export a scalar. See #7459
  19655. normalScale = [ normalScale, normalScale ];
  19656. }
  19657. material.normalScale = new Vector2().fromArray( normalScale );
  19658. }
  19659. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19660. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19661. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19662. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19663. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19664. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19665. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19666. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19667. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19668. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19669. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19670. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19671. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19672. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19673. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19674. return material;
  19675. }
  19676. } );
  19677. /**
  19678. * @author mrdoob / http://mrdoob.com/
  19679. */
  19680. function BufferGeometryLoader( manager ) {
  19681. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19682. }
  19683. Object.assign( BufferGeometryLoader.prototype, {
  19684. load: function ( url, onLoad, onProgress, onError ) {
  19685. var scope = this;
  19686. var loader = new FileLoader( scope.manager );
  19687. loader.load( url, function ( text ) {
  19688. onLoad( scope.parse( JSON.parse( text ) ) );
  19689. }, onProgress, onError );
  19690. },
  19691. parse: function ( json ) {
  19692. var geometry = new BufferGeometry();
  19693. var index = json.data.index;
  19694. if ( index !== undefined ) {
  19695. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19696. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19697. }
  19698. var attributes = json.data.attributes;
  19699. for ( var key in attributes ) {
  19700. var attribute = attributes[ key ];
  19701. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19702. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19703. }
  19704. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19705. if ( groups !== undefined ) {
  19706. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19707. var group = groups[ i ];
  19708. geometry.addGroup( group.start, group.count, group.materialIndex );
  19709. }
  19710. }
  19711. var boundingSphere = json.data.boundingSphere;
  19712. if ( boundingSphere !== undefined ) {
  19713. var center = new Vector3();
  19714. if ( boundingSphere.center !== undefined ) {
  19715. center.fromArray( boundingSphere.center );
  19716. }
  19717. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19718. }
  19719. return geometry;
  19720. }
  19721. } );
  19722. var TYPED_ARRAYS = {
  19723. Int8Array: Int8Array,
  19724. Uint8Array: Uint8Array,
  19725. // Workaround for IE11 pre KB2929437. See #11440
  19726. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  19727. Int16Array: Int16Array,
  19728. Uint16Array: Uint16Array,
  19729. Int32Array: Int32Array,
  19730. Uint32Array: Uint32Array,
  19731. Float32Array: Float32Array,
  19732. Float64Array: Float64Array
  19733. };
  19734. /**
  19735. * @author alteredq / http://alteredqualia.com/
  19736. */
  19737. function Loader() {
  19738. this.onLoadStart = function () {};
  19739. this.onLoadProgress = function () {};
  19740. this.onLoadComplete = function () {};
  19741. }
  19742. Loader.Handlers = {
  19743. handlers: [],
  19744. add: function ( regex, loader ) {
  19745. this.handlers.push( regex, loader );
  19746. },
  19747. get: function ( file ) {
  19748. var handlers = this.handlers;
  19749. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19750. var regex = handlers[ i ];
  19751. var loader = handlers[ i + 1 ];
  19752. if ( regex.test( file ) ) {
  19753. return loader;
  19754. }
  19755. }
  19756. return null;
  19757. }
  19758. };
  19759. Object.assign( Loader.prototype, {
  19760. crossOrigin: undefined,
  19761. extractUrlBase: function ( url ) {
  19762. var parts = url.split( '/' );
  19763. if ( parts.length === 1 ) return './';
  19764. parts.pop();
  19765. return parts.join( '/' ) + '/';
  19766. },
  19767. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19768. var array = [];
  19769. for ( var i = 0; i < materials.length; ++ i ) {
  19770. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19771. }
  19772. return array;
  19773. },
  19774. createMaterial: ( function () {
  19775. var BlendingMode = {
  19776. NoBlending: NoBlending,
  19777. NormalBlending: NormalBlending,
  19778. AdditiveBlending: AdditiveBlending,
  19779. SubtractiveBlending: SubtractiveBlending,
  19780. MultiplyBlending: MultiplyBlending,
  19781. CustomBlending: CustomBlending
  19782. };
  19783. var color = new Color();
  19784. var textureLoader = new TextureLoader();
  19785. var materialLoader = new MaterialLoader();
  19786. return function createMaterial( m, texturePath, crossOrigin ) {
  19787. // convert from old material format
  19788. var textures = {};
  19789. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19790. var fullPath = texturePath + path;
  19791. var loader = Loader.Handlers.get( fullPath );
  19792. var texture;
  19793. if ( loader !== null ) {
  19794. texture = loader.load( fullPath );
  19795. } else {
  19796. textureLoader.setCrossOrigin( crossOrigin );
  19797. texture = textureLoader.load( fullPath );
  19798. }
  19799. if ( repeat !== undefined ) {
  19800. texture.repeat.fromArray( repeat );
  19801. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19802. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19803. }
  19804. if ( offset !== undefined ) {
  19805. texture.offset.fromArray( offset );
  19806. }
  19807. if ( wrap !== undefined ) {
  19808. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19809. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19810. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19811. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19812. }
  19813. if ( anisotropy !== undefined ) {
  19814. texture.anisotropy = anisotropy;
  19815. }
  19816. var uuid = _Math.generateUUID();
  19817. textures[ uuid ] = texture;
  19818. return uuid;
  19819. }
  19820. //
  19821. var json = {
  19822. uuid: _Math.generateUUID(),
  19823. type: 'MeshLambertMaterial'
  19824. };
  19825. for ( var name in m ) {
  19826. var value = m[ name ];
  19827. switch ( name ) {
  19828. case 'DbgColor':
  19829. case 'DbgIndex':
  19830. case 'opticalDensity':
  19831. case 'illumination':
  19832. break;
  19833. case 'DbgName':
  19834. json.name = value;
  19835. break;
  19836. case 'blending':
  19837. json.blending = BlendingMode[ value ];
  19838. break;
  19839. case 'colorAmbient':
  19840. case 'mapAmbient':
  19841. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19842. break;
  19843. case 'colorDiffuse':
  19844. json.color = color.fromArray( value ).getHex();
  19845. break;
  19846. case 'colorSpecular':
  19847. json.specular = color.fromArray( value ).getHex();
  19848. break;
  19849. case 'colorEmissive':
  19850. json.emissive = color.fromArray( value ).getHex();
  19851. break;
  19852. case 'specularCoef':
  19853. json.shininess = value;
  19854. break;
  19855. case 'shading':
  19856. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19857. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19858. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19859. break;
  19860. case 'mapDiffuse':
  19861. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19862. break;
  19863. case 'mapDiffuseRepeat':
  19864. case 'mapDiffuseOffset':
  19865. case 'mapDiffuseWrap':
  19866. case 'mapDiffuseAnisotropy':
  19867. break;
  19868. case 'mapEmissive':
  19869. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19870. break;
  19871. case 'mapEmissiveRepeat':
  19872. case 'mapEmissiveOffset':
  19873. case 'mapEmissiveWrap':
  19874. case 'mapEmissiveAnisotropy':
  19875. break;
  19876. case 'mapLight':
  19877. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19878. break;
  19879. case 'mapLightRepeat':
  19880. case 'mapLightOffset':
  19881. case 'mapLightWrap':
  19882. case 'mapLightAnisotropy':
  19883. break;
  19884. case 'mapAO':
  19885. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19886. break;
  19887. case 'mapAORepeat':
  19888. case 'mapAOOffset':
  19889. case 'mapAOWrap':
  19890. case 'mapAOAnisotropy':
  19891. break;
  19892. case 'mapBump':
  19893. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19894. break;
  19895. case 'mapBumpScale':
  19896. json.bumpScale = value;
  19897. break;
  19898. case 'mapBumpRepeat':
  19899. case 'mapBumpOffset':
  19900. case 'mapBumpWrap':
  19901. case 'mapBumpAnisotropy':
  19902. break;
  19903. case 'mapNormal':
  19904. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19905. break;
  19906. case 'mapNormalFactor':
  19907. json.normalScale = [ value, value ];
  19908. break;
  19909. case 'mapNormalRepeat':
  19910. case 'mapNormalOffset':
  19911. case 'mapNormalWrap':
  19912. case 'mapNormalAnisotropy':
  19913. break;
  19914. case 'mapSpecular':
  19915. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19916. break;
  19917. case 'mapSpecularRepeat':
  19918. case 'mapSpecularOffset':
  19919. case 'mapSpecularWrap':
  19920. case 'mapSpecularAnisotropy':
  19921. break;
  19922. case 'mapMetalness':
  19923. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19924. break;
  19925. case 'mapMetalnessRepeat':
  19926. case 'mapMetalnessOffset':
  19927. case 'mapMetalnessWrap':
  19928. case 'mapMetalnessAnisotropy':
  19929. break;
  19930. case 'mapRoughness':
  19931. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19932. break;
  19933. case 'mapRoughnessRepeat':
  19934. case 'mapRoughnessOffset':
  19935. case 'mapRoughnessWrap':
  19936. case 'mapRoughnessAnisotropy':
  19937. break;
  19938. case 'mapAlpha':
  19939. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19940. break;
  19941. case 'mapAlphaRepeat':
  19942. case 'mapAlphaOffset':
  19943. case 'mapAlphaWrap':
  19944. case 'mapAlphaAnisotropy':
  19945. break;
  19946. case 'flipSided':
  19947. json.side = BackSide;
  19948. break;
  19949. case 'doubleSided':
  19950. json.side = DoubleSide;
  19951. break;
  19952. case 'transparency':
  19953. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19954. json.opacity = value;
  19955. break;
  19956. case 'depthTest':
  19957. case 'depthWrite':
  19958. case 'colorWrite':
  19959. case 'opacity':
  19960. case 'reflectivity':
  19961. case 'transparent':
  19962. case 'visible':
  19963. case 'wireframe':
  19964. json[ name ] = value;
  19965. break;
  19966. case 'vertexColors':
  19967. if ( value === true ) json.vertexColors = VertexColors;
  19968. if ( value === 'face' ) json.vertexColors = FaceColors;
  19969. break;
  19970. default:
  19971. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19972. break;
  19973. }
  19974. }
  19975. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19976. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19977. if ( json.opacity < 1 ) json.transparent = true;
  19978. materialLoader.setTextures( textures );
  19979. return materialLoader.parse( json );
  19980. };
  19981. } )()
  19982. } );
  19983. /**
  19984. * @author mrdoob / http://mrdoob.com/
  19985. * @author alteredq / http://alteredqualia.com/
  19986. */
  19987. function JSONLoader( manager ) {
  19988. if ( typeof manager === 'boolean' ) {
  19989. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19990. manager = undefined;
  19991. }
  19992. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19993. this.withCredentials = false;
  19994. }
  19995. Object.assign( JSONLoader.prototype, {
  19996. load: function ( url, onLoad, onProgress, onError ) {
  19997. var scope = this;
  19998. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19999. var loader = new FileLoader( this.manager );
  20000. loader.setWithCredentials( this.withCredentials );
  20001. loader.load( url, function ( text ) {
  20002. var json = JSON.parse( text );
  20003. var metadata = json.metadata;
  20004. if ( metadata !== undefined ) {
  20005. var type = metadata.type;
  20006. if ( type !== undefined ) {
  20007. if ( type.toLowerCase() === 'object' ) {
  20008. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  20009. return;
  20010. }
  20011. if ( type.toLowerCase() === 'scene' ) {
  20012. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  20013. return;
  20014. }
  20015. }
  20016. }
  20017. var object = scope.parse( json, texturePath );
  20018. onLoad( object.geometry, object.materials );
  20019. }, onProgress, onError );
  20020. },
  20021. setTexturePath: function ( value ) {
  20022. this.texturePath = value;
  20023. },
  20024. parse: ( function () {
  20025. function parseModel( json, geometry ) {
  20026. function isBitSet( value, position ) {
  20027. return value & ( 1 << position );
  20028. }
  20029. var i, j, fi,
  20030. offset, zLength,
  20031. colorIndex, normalIndex, uvIndex, materialIndex,
  20032. type,
  20033. isQuad,
  20034. hasMaterial,
  20035. hasFaceVertexUv,
  20036. hasFaceNormal, hasFaceVertexNormal,
  20037. hasFaceColor, hasFaceVertexColor,
  20038. vertex, face, faceA, faceB, hex, normal,
  20039. uvLayer, uv, u, v,
  20040. faces = json.faces,
  20041. vertices = json.vertices,
  20042. normals = json.normals,
  20043. colors = json.colors,
  20044. scale = json.scale,
  20045. nUvLayers = 0;
  20046. if ( json.uvs !== undefined ) {
  20047. // disregard empty arrays
  20048. for ( i = 0; i < json.uvs.length; i ++ ) {
  20049. if ( json.uvs[ i ].length ) nUvLayers ++;
  20050. }
  20051. for ( i = 0; i < nUvLayers; i ++ ) {
  20052. geometry.faceVertexUvs[ i ] = [];
  20053. }
  20054. }
  20055. offset = 0;
  20056. zLength = vertices.length;
  20057. while ( offset < zLength ) {
  20058. vertex = new Vector3();
  20059. vertex.x = vertices[ offset ++ ] * scale;
  20060. vertex.y = vertices[ offset ++ ] * scale;
  20061. vertex.z = vertices[ offset ++ ] * scale;
  20062. geometry.vertices.push( vertex );
  20063. }
  20064. offset = 0;
  20065. zLength = faces.length;
  20066. while ( offset < zLength ) {
  20067. type = faces[ offset ++ ];
  20068. isQuad = isBitSet( type, 0 );
  20069. hasMaterial = isBitSet( type, 1 );
  20070. hasFaceVertexUv = isBitSet( type, 3 );
  20071. hasFaceNormal = isBitSet( type, 4 );
  20072. hasFaceVertexNormal = isBitSet( type, 5 );
  20073. hasFaceColor = isBitSet( type, 6 );
  20074. hasFaceVertexColor = isBitSet( type, 7 );
  20075. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  20076. if ( isQuad ) {
  20077. faceA = new Face3();
  20078. faceA.a = faces[ offset ];
  20079. faceA.b = faces[ offset + 1 ];
  20080. faceA.c = faces[ offset + 3 ];
  20081. faceB = new Face3();
  20082. faceB.a = faces[ offset + 1 ];
  20083. faceB.b = faces[ offset + 2 ];
  20084. faceB.c = faces[ offset + 3 ];
  20085. offset += 4;
  20086. if ( hasMaterial ) {
  20087. materialIndex = faces[ offset ++ ];
  20088. faceA.materialIndex = materialIndex;
  20089. faceB.materialIndex = materialIndex;
  20090. }
  20091. // to get face <=> uv index correspondence
  20092. fi = geometry.faces.length;
  20093. if ( hasFaceVertexUv ) {
  20094. for ( i = 0; i < nUvLayers; i ++ ) {
  20095. uvLayer = json.uvs[ i ];
  20096. geometry.faceVertexUvs[ i ][ fi ] = [];
  20097. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  20098. for ( j = 0; j < 4; j ++ ) {
  20099. uvIndex = faces[ offset ++ ];
  20100. u = uvLayer[ uvIndex * 2 ];
  20101. v = uvLayer[ uvIndex * 2 + 1 ];
  20102. uv = new Vector2( u, v );
  20103. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20104. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  20105. }
  20106. }
  20107. }
  20108. if ( hasFaceNormal ) {
  20109. normalIndex = faces[ offset ++ ] * 3;
  20110. faceA.normal.set(
  20111. normals[ normalIndex ++ ],
  20112. normals[ normalIndex ++ ],
  20113. normals[ normalIndex ]
  20114. );
  20115. faceB.normal.copy( faceA.normal );
  20116. }
  20117. if ( hasFaceVertexNormal ) {
  20118. for ( i = 0; i < 4; i ++ ) {
  20119. normalIndex = faces[ offset ++ ] * 3;
  20120. normal = new Vector3(
  20121. normals[ normalIndex ++ ],
  20122. normals[ normalIndex ++ ],
  20123. normals[ normalIndex ]
  20124. );
  20125. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  20126. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  20127. }
  20128. }
  20129. if ( hasFaceColor ) {
  20130. colorIndex = faces[ offset ++ ];
  20131. hex = colors[ colorIndex ];
  20132. faceA.color.setHex( hex );
  20133. faceB.color.setHex( hex );
  20134. }
  20135. if ( hasFaceVertexColor ) {
  20136. for ( i = 0; i < 4; i ++ ) {
  20137. colorIndex = faces[ offset ++ ];
  20138. hex = colors[ colorIndex ];
  20139. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  20140. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  20141. }
  20142. }
  20143. geometry.faces.push( faceA );
  20144. geometry.faces.push( faceB );
  20145. } else {
  20146. face = new Face3();
  20147. face.a = faces[ offset ++ ];
  20148. face.b = faces[ offset ++ ];
  20149. face.c = faces[ offset ++ ];
  20150. if ( hasMaterial ) {
  20151. materialIndex = faces[ offset ++ ];
  20152. face.materialIndex = materialIndex;
  20153. }
  20154. // to get face <=> uv index correspondence
  20155. fi = geometry.faces.length;
  20156. if ( hasFaceVertexUv ) {
  20157. for ( i = 0; i < nUvLayers; i ++ ) {
  20158. uvLayer = json.uvs[ i ];
  20159. geometry.faceVertexUvs[ i ][ fi ] = [];
  20160. for ( j = 0; j < 3; j ++ ) {
  20161. uvIndex = faces[ offset ++ ];
  20162. u = uvLayer[ uvIndex * 2 ];
  20163. v = uvLayer[ uvIndex * 2 + 1 ];
  20164. uv = new Vector2( u, v );
  20165. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  20166. }
  20167. }
  20168. }
  20169. if ( hasFaceNormal ) {
  20170. normalIndex = faces[ offset ++ ] * 3;
  20171. face.normal.set(
  20172. normals[ normalIndex ++ ],
  20173. normals[ normalIndex ++ ],
  20174. normals[ normalIndex ]
  20175. );
  20176. }
  20177. if ( hasFaceVertexNormal ) {
  20178. for ( i = 0; i < 3; i ++ ) {
  20179. normalIndex = faces[ offset ++ ] * 3;
  20180. normal = new Vector3(
  20181. normals[ normalIndex ++ ],
  20182. normals[ normalIndex ++ ],
  20183. normals[ normalIndex ]
  20184. );
  20185. face.vertexNormals.push( normal );
  20186. }
  20187. }
  20188. if ( hasFaceColor ) {
  20189. colorIndex = faces[ offset ++ ];
  20190. face.color.setHex( colors[ colorIndex ] );
  20191. }
  20192. if ( hasFaceVertexColor ) {
  20193. for ( i = 0; i < 3; i ++ ) {
  20194. colorIndex = faces[ offset ++ ];
  20195. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  20196. }
  20197. }
  20198. geometry.faces.push( face );
  20199. }
  20200. }
  20201. }
  20202. function parseSkin( json, geometry ) {
  20203. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  20204. if ( json.skinWeights ) {
  20205. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  20206. var x = json.skinWeights[ i ];
  20207. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  20208. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  20209. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  20210. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  20211. }
  20212. }
  20213. if ( json.skinIndices ) {
  20214. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  20215. var a = json.skinIndices[ i ];
  20216. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  20217. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  20218. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  20219. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  20220. }
  20221. }
  20222. geometry.bones = json.bones;
  20223. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  20224. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  20225. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  20226. }
  20227. }
  20228. function parseMorphing( json, geometry ) {
  20229. var scale = json.scale;
  20230. if ( json.morphTargets !== undefined ) {
  20231. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20232. geometry.morphTargets[ i ] = {};
  20233. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20234. geometry.morphTargets[ i ].vertices = [];
  20235. var dstVertices = geometry.morphTargets[ i ].vertices;
  20236. var srcVertices = json.morphTargets[ i ].vertices;
  20237. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20238. var vertex = new Vector3();
  20239. vertex.x = srcVertices[ v ] * scale;
  20240. vertex.y = srcVertices[ v + 1 ] * scale;
  20241. vertex.z = srcVertices[ v + 2 ] * scale;
  20242. dstVertices.push( vertex );
  20243. }
  20244. }
  20245. }
  20246. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  20247. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  20248. var faces = geometry.faces;
  20249. var morphColors = json.morphColors[ 0 ].colors;
  20250. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20251. faces[ i ].color.fromArray( morphColors, i * 3 );
  20252. }
  20253. }
  20254. }
  20255. function parseAnimations( json, geometry ) {
  20256. var outputAnimations = [];
  20257. // parse old style Bone/Hierarchy animations
  20258. var animations = [];
  20259. if ( json.animation !== undefined ) {
  20260. animations.push( json.animation );
  20261. }
  20262. if ( json.animations !== undefined ) {
  20263. if ( json.animations.length ) {
  20264. animations = animations.concat( json.animations );
  20265. } else {
  20266. animations.push( json.animations );
  20267. }
  20268. }
  20269. for ( var i = 0; i < animations.length; i ++ ) {
  20270. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  20271. if ( clip ) outputAnimations.push( clip );
  20272. }
  20273. // parse implicit morph animations
  20274. if ( geometry.morphTargets ) {
  20275. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  20276. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  20277. outputAnimations = outputAnimations.concat( morphAnimationClips );
  20278. }
  20279. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  20280. }
  20281. return function ( json, texturePath ) {
  20282. if ( json.data !== undefined ) {
  20283. // Geometry 4.0 spec
  20284. json = json.data;
  20285. }
  20286. if ( json.scale !== undefined ) {
  20287. json.scale = 1.0 / json.scale;
  20288. } else {
  20289. json.scale = 1.0;
  20290. }
  20291. var geometry = new Geometry();
  20292. parseModel( json, geometry );
  20293. parseSkin( json, geometry );
  20294. parseMorphing( json, geometry );
  20295. parseAnimations( json, geometry );
  20296. geometry.computeFaceNormals();
  20297. geometry.computeBoundingSphere();
  20298. if ( json.materials === undefined || json.materials.length === 0 ) {
  20299. return { geometry: geometry };
  20300. } else {
  20301. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20302. return { geometry: geometry, materials: materials };
  20303. }
  20304. };
  20305. } )()
  20306. } );
  20307. /**
  20308. * @author mrdoob / http://mrdoob.com/
  20309. */
  20310. function ObjectLoader( manager ) {
  20311. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20312. this.texturePath = '';
  20313. }
  20314. Object.assign( ObjectLoader.prototype, {
  20315. load: function ( url, onLoad, onProgress, onError ) {
  20316. if ( this.texturePath === '' ) {
  20317. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20318. }
  20319. var scope = this;
  20320. var loader = new FileLoader( scope.manager );
  20321. loader.load( url, function ( text ) {
  20322. var json = null;
  20323. try {
  20324. json = JSON.parse( text );
  20325. } catch ( error ) {
  20326. if ( onError !== undefined ) onError( error );
  20327. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20328. return;
  20329. }
  20330. var metadata = json.metadata;
  20331. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20332. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20333. return;
  20334. }
  20335. scope.parse( json, onLoad );
  20336. }, onProgress, onError );
  20337. },
  20338. setTexturePath: function ( value ) {
  20339. this.texturePath = value;
  20340. },
  20341. setCrossOrigin: function ( value ) {
  20342. this.crossOrigin = value;
  20343. },
  20344. parse: function ( json, onLoad ) {
  20345. var geometries = this.parseGeometries( json.geometries );
  20346. var images = this.parseImages( json.images, function () {
  20347. if ( onLoad !== undefined ) onLoad( object );
  20348. } );
  20349. var textures = this.parseTextures( json.textures, images );
  20350. var materials = this.parseMaterials( json.materials, textures );
  20351. var object = this.parseObject( json.object, geometries, materials );
  20352. if ( json.animations ) {
  20353. object.animations = this.parseAnimations( json.animations );
  20354. }
  20355. if ( json.images === undefined || json.images.length === 0 ) {
  20356. if ( onLoad !== undefined ) onLoad( object );
  20357. }
  20358. return object;
  20359. },
  20360. parseGeometries: function ( json ) {
  20361. var geometries = {};
  20362. if ( json !== undefined ) {
  20363. var geometryLoader = new JSONLoader();
  20364. var bufferGeometryLoader = new BufferGeometryLoader();
  20365. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20366. var geometry;
  20367. var data = json[ i ];
  20368. switch ( data.type ) {
  20369. case 'PlaneGeometry':
  20370. case 'PlaneBufferGeometry':
  20371. geometry = new Geometries[ data.type ](
  20372. data.width,
  20373. data.height,
  20374. data.widthSegments,
  20375. data.heightSegments
  20376. );
  20377. break;
  20378. case 'BoxGeometry':
  20379. case 'BoxBufferGeometry':
  20380. case 'CubeGeometry': // backwards compatible
  20381. geometry = new Geometries[ data.type ](
  20382. data.width,
  20383. data.height,
  20384. data.depth,
  20385. data.widthSegments,
  20386. data.heightSegments,
  20387. data.depthSegments
  20388. );
  20389. break;
  20390. case 'CircleGeometry':
  20391. case 'CircleBufferGeometry':
  20392. geometry = new Geometries[ data.type ](
  20393. data.radius,
  20394. data.segments,
  20395. data.thetaStart,
  20396. data.thetaLength
  20397. );
  20398. break;
  20399. case 'CylinderGeometry':
  20400. case 'CylinderBufferGeometry':
  20401. geometry = new Geometries[ data.type ](
  20402. data.radiusTop,
  20403. data.radiusBottom,
  20404. data.height,
  20405. data.radialSegments,
  20406. data.heightSegments,
  20407. data.openEnded,
  20408. data.thetaStart,
  20409. data.thetaLength
  20410. );
  20411. break;
  20412. case 'ConeGeometry':
  20413. case 'ConeBufferGeometry':
  20414. geometry = new Geometries[ data.type ](
  20415. data.radius,
  20416. data.height,
  20417. data.radialSegments,
  20418. data.heightSegments,
  20419. data.openEnded,
  20420. data.thetaStart,
  20421. data.thetaLength
  20422. );
  20423. break;
  20424. case 'SphereGeometry':
  20425. case 'SphereBufferGeometry':
  20426. geometry = new Geometries[ data.type ](
  20427. data.radius,
  20428. data.widthSegments,
  20429. data.heightSegments,
  20430. data.phiStart,
  20431. data.phiLength,
  20432. data.thetaStart,
  20433. data.thetaLength
  20434. );
  20435. break;
  20436. case 'DodecahedronGeometry':
  20437. case 'IcosahedronGeometry':
  20438. case 'OctahedronGeometry':
  20439. case 'TetrahedronGeometry':
  20440. geometry = new Geometries[ data.type ](
  20441. data.radius,
  20442. data.detail
  20443. );
  20444. break;
  20445. case 'RingGeometry':
  20446. case 'RingBufferGeometry':
  20447. geometry = new Geometries[ data.type ](
  20448. data.innerRadius,
  20449. data.outerRadius,
  20450. data.thetaSegments,
  20451. data.phiSegments,
  20452. data.thetaStart,
  20453. data.thetaLength
  20454. );
  20455. break;
  20456. case 'TorusGeometry':
  20457. case 'TorusBufferGeometry':
  20458. geometry = new Geometries[ data.type ](
  20459. data.radius,
  20460. data.tube,
  20461. data.radialSegments,
  20462. data.tubularSegments,
  20463. data.arc
  20464. );
  20465. break;
  20466. case 'TorusKnotGeometry':
  20467. case 'TorusKnotBufferGeometry':
  20468. geometry = new Geometries[ data.type ](
  20469. data.radius,
  20470. data.tube,
  20471. data.tubularSegments,
  20472. data.radialSegments,
  20473. data.p,
  20474. data.q
  20475. );
  20476. break;
  20477. case 'LatheGeometry':
  20478. case 'LatheBufferGeometry':
  20479. geometry = new Geometries[ data.type ](
  20480. data.points,
  20481. data.segments,
  20482. data.phiStart,
  20483. data.phiLength
  20484. );
  20485. break;
  20486. case 'BufferGeometry':
  20487. geometry = bufferGeometryLoader.parse( data );
  20488. break;
  20489. case 'Geometry':
  20490. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20491. break;
  20492. default:
  20493. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20494. continue;
  20495. }
  20496. geometry.uuid = data.uuid;
  20497. if ( data.name !== undefined ) geometry.name = data.name;
  20498. geometries[ data.uuid ] = geometry;
  20499. }
  20500. }
  20501. return geometries;
  20502. },
  20503. parseMaterials: function ( json, textures ) {
  20504. var materials = {};
  20505. if ( json !== undefined ) {
  20506. var loader = new MaterialLoader();
  20507. loader.setTextures( textures );
  20508. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20509. var data = json[ i ];
  20510. if ( data.type === 'MultiMaterial' ) {
  20511. // Deprecated
  20512. var array = [];
  20513. for ( var j = 0; j < data.materials.length; j ++ ) {
  20514. array.push( loader.parse( data.materials[ j ] ) );
  20515. }
  20516. materials[ data.uuid ] = array;
  20517. } else {
  20518. materials[ data.uuid ] = loader.parse( data );
  20519. }
  20520. }
  20521. }
  20522. return materials;
  20523. },
  20524. parseAnimations: function ( json ) {
  20525. var animations = [];
  20526. for ( var i = 0; i < json.length; i ++ ) {
  20527. var clip = AnimationClip.parse( json[ i ] );
  20528. animations.push( clip );
  20529. }
  20530. return animations;
  20531. },
  20532. parseImages: function ( json, onLoad ) {
  20533. var scope = this;
  20534. var images = {};
  20535. function loadImage( url ) {
  20536. scope.manager.itemStart( url );
  20537. return loader.load( url, function () {
  20538. scope.manager.itemEnd( url );
  20539. }, undefined, function () {
  20540. scope.manager.itemEnd( url );
  20541. scope.manager.itemError( url );
  20542. } );
  20543. }
  20544. if ( json !== undefined && json.length > 0 ) {
  20545. var manager = new LoadingManager( onLoad );
  20546. var loader = new ImageLoader( manager );
  20547. loader.setCrossOrigin( this.crossOrigin );
  20548. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20549. var image = json[ i ];
  20550. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20551. images[ image.uuid ] = loadImage( path );
  20552. }
  20553. }
  20554. return images;
  20555. },
  20556. parseTextures: function ( json, images ) {
  20557. function parseConstant( value, type ) {
  20558. if ( typeof( value ) === 'number' ) return value;
  20559. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20560. return type[ value ];
  20561. }
  20562. var textures = {};
  20563. if ( json !== undefined ) {
  20564. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20565. var data = json[ i ];
  20566. if ( data.image === undefined ) {
  20567. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20568. }
  20569. if ( images[ data.image ] === undefined ) {
  20570. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20571. }
  20572. var texture = new Texture( images[ data.image ] );
  20573. texture.needsUpdate = true;
  20574. texture.uuid = data.uuid;
  20575. if ( data.name !== undefined ) texture.name = data.name;
  20576. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20577. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20578. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20579. if ( data.wrap !== undefined ) {
  20580. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20581. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20582. }
  20583. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20584. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20585. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20586. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20587. textures[ data.uuid ] = texture;
  20588. }
  20589. }
  20590. return textures;
  20591. },
  20592. parseObject: function () {
  20593. var matrix = new Matrix4();
  20594. return function parseObject( data, geometries, materials ) {
  20595. var object;
  20596. function getGeometry( name ) {
  20597. if ( geometries[ name ] === undefined ) {
  20598. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20599. }
  20600. return geometries[ name ];
  20601. }
  20602. function getMaterial( name ) {
  20603. if ( name === undefined ) return undefined;
  20604. if ( Array.isArray( name ) ) {
  20605. var array = [];
  20606. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20607. var uuid = name[ i ];
  20608. if ( materials[ uuid ] === undefined ) {
  20609. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20610. }
  20611. array.push( materials[ uuid ] );
  20612. }
  20613. return array;
  20614. }
  20615. if ( materials[ name ] === undefined ) {
  20616. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20617. }
  20618. return materials[ name ];
  20619. }
  20620. switch ( data.type ) {
  20621. case 'Scene':
  20622. object = new Scene();
  20623. if ( data.background !== undefined ) {
  20624. if ( Number.isInteger( data.background ) ) {
  20625. object.background = new Color( data.background );
  20626. }
  20627. }
  20628. if ( data.fog !== undefined ) {
  20629. if ( data.fog.type === 'Fog' ) {
  20630. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20631. } else if ( data.fog.type === 'FogExp2' ) {
  20632. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20633. }
  20634. }
  20635. break;
  20636. case 'PerspectiveCamera':
  20637. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20638. if ( data.focus !== undefined ) object.focus = data.focus;
  20639. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20640. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20641. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20642. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20643. break;
  20644. case 'OrthographicCamera':
  20645. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20646. break;
  20647. case 'AmbientLight':
  20648. object = new AmbientLight( data.color, data.intensity );
  20649. break;
  20650. case 'DirectionalLight':
  20651. object = new DirectionalLight( data.color, data.intensity );
  20652. break;
  20653. case 'PointLight':
  20654. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20655. break;
  20656. case 'RectAreaLight':
  20657. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20658. break;
  20659. case 'SpotLight':
  20660. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20661. break;
  20662. case 'HemisphereLight':
  20663. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20664. break;
  20665. case 'SkinnedMesh':
  20666. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20667. case 'Mesh':
  20668. var geometry = getGeometry( data.geometry );
  20669. var material = getMaterial( data.material );
  20670. if ( geometry.bones && geometry.bones.length > 0 ) {
  20671. object = new SkinnedMesh( geometry, material );
  20672. } else {
  20673. object = new Mesh( geometry, material );
  20674. }
  20675. break;
  20676. case 'LOD':
  20677. object = new LOD();
  20678. break;
  20679. case 'Line':
  20680. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20681. break;
  20682. case 'LineLoop':
  20683. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20684. break;
  20685. case 'LineSegments':
  20686. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20687. break;
  20688. case 'PointCloud':
  20689. case 'Points':
  20690. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20691. break;
  20692. case 'Sprite':
  20693. object = new Sprite( getMaterial( data.material ) );
  20694. break;
  20695. case 'Group':
  20696. object = new Group();
  20697. break;
  20698. default:
  20699. object = new Object3D();
  20700. }
  20701. object.uuid = data.uuid;
  20702. if ( data.name !== undefined ) object.name = data.name;
  20703. if ( data.matrix !== undefined ) {
  20704. matrix.fromArray( data.matrix );
  20705. matrix.decompose( object.position, object.quaternion, object.scale );
  20706. } else {
  20707. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20708. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20709. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20710. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20711. }
  20712. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20713. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20714. if ( data.shadow ) {
  20715. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20716. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20717. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20718. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20719. }
  20720. if ( data.visible !== undefined ) object.visible = data.visible;
  20721. if ( data.userData !== undefined ) object.userData = data.userData;
  20722. if ( data.children !== undefined ) {
  20723. var children = data.children;
  20724. for ( var i = 0; i < children.length; i ++ ) {
  20725. object.add( this.parseObject( children[ i ], geometries, materials ) );
  20726. }
  20727. }
  20728. if ( data.type === 'LOD' ) {
  20729. var levels = data.levels;
  20730. for ( var l = 0; l < levels.length; l ++ ) {
  20731. var level = levels[ l ];
  20732. var child = object.getObjectByProperty( 'uuid', level.object );
  20733. if ( child !== undefined ) {
  20734. object.addLevel( child, level.distance );
  20735. }
  20736. }
  20737. }
  20738. return object;
  20739. };
  20740. }()
  20741. } );
  20742. var TEXTURE_MAPPING = {
  20743. UVMapping: UVMapping,
  20744. CubeReflectionMapping: CubeReflectionMapping,
  20745. CubeRefractionMapping: CubeRefractionMapping,
  20746. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20747. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20748. SphericalReflectionMapping: SphericalReflectionMapping,
  20749. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20750. CubeUVRefractionMapping: CubeUVRefractionMapping
  20751. };
  20752. var TEXTURE_WRAPPING = {
  20753. RepeatWrapping: RepeatWrapping,
  20754. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20755. MirroredRepeatWrapping: MirroredRepeatWrapping
  20756. };
  20757. var TEXTURE_FILTER = {
  20758. NearestFilter: NearestFilter,
  20759. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20760. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20761. LinearFilter: LinearFilter,
  20762. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20763. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20764. };
  20765. /**
  20766. * @author zz85 / http://www.lab4games.net/zz85/blog
  20767. *
  20768. * Bezier Curves formulas obtained from
  20769. * http://en.wikipedia.org/wiki/Bézier_curve
  20770. */
  20771. function CatmullRom( t, p0, p1, p2, p3 ) {
  20772. var v0 = ( p2 - p0 ) * 0.5;
  20773. var v1 = ( p3 - p1 ) * 0.5;
  20774. var t2 = t * t;
  20775. var t3 = t * t2;
  20776. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20777. }
  20778. //
  20779. function QuadraticBezierP0( t, p ) {
  20780. var k = 1 - t;
  20781. return k * k * p;
  20782. }
  20783. function QuadraticBezierP1( t, p ) {
  20784. return 2 * ( 1 - t ) * t * p;
  20785. }
  20786. function QuadraticBezierP2( t, p ) {
  20787. return t * t * p;
  20788. }
  20789. function QuadraticBezier( t, p0, p1, p2 ) {
  20790. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20791. QuadraticBezierP2( t, p2 );
  20792. }
  20793. //
  20794. function CubicBezierP0( t, p ) {
  20795. var k = 1 - t;
  20796. return k * k * k * p;
  20797. }
  20798. function CubicBezierP1( t, p ) {
  20799. var k = 1 - t;
  20800. return 3 * k * k * t * p;
  20801. }
  20802. function CubicBezierP2( t, p ) {
  20803. return 3 * ( 1 - t ) * t * t * p;
  20804. }
  20805. function CubicBezierP3( t, p ) {
  20806. return t * t * t * p;
  20807. }
  20808. function CubicBezier( t, p0, p1, p2, p3 ) {
  20809. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20810. CubicBezierP3( t, p3 );
  20811. }
  20812. /**
  20813. * @author zz85 / http://www.lab4games.net/zz85/blog
  20814. * Extensible curve object
  20815. *
  20816. * Some common of curve methods:
  20817. * .getPoint(t), getTangent(t)
  20818. * .getPointAt(u), getTangentAt(u)
  20819. * .getPoints(), .getSpacedPoints()
  20820. * .getLength()
  20821. * .updateArcLengths()
  20822. *
  20823. * This following curves inherit from THREE.Curve:
  20824. *
  20825. * -- 2D curves --
  20826. * THREE.ArcCurve
  20827. * THREE.CubicBezierCurve
  20828. * THREE.EllipseCurve
  20829. * THREE.LineCurve
  20830. * THREE.QuadraticBezierCurve
  20831. * THREE.SplineCurve
  20832. *
  20833. * -- 3D curves --
  20834. * THREE.CatmullRomCurve3
  20835. * THREE.CubicBezierCurve3
  20836. * THREE.LineCurve3
  20837. * THREE.QuadraticBezierCurve3
  20838. *
  20839. * A series of curves can be represented as a THREE.CurvePath.
  20840. *
  20841. **/
  20842. /**************************************************************
  20843. * Abstract Curve base class
  20844. **************************************************************/
  20845. function Curve() {
  20846. this.arcLengthDivisions = 200;
  20847. }
  20848. Object.assign( Curve.prototype, {
  20849. // Virtual base class method to overwrite and implement in subclasses
  20850. // - t [0 .. 1]
  20851. getPoint: function () {
  20852. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20853. return null;
  20854. },
  20855. // Get point at relative position in curve according to arc length
  20856. // - u [0 .. 1]
  20857. getPointAt: function ( u ) {
  20858. var t = this.getUtoTmapping( u );
  20859. return this.getPoint( t );
  20860. },
  20861. // Get sequence of points using getPoint( t )
  20862. getPoints: function ( divisions ) {
  20863. if ( divisions === undefined ) divisions = 5;
  20864. var points = [];
  20865. for ( var d = 0; d <= divisions; d ++ ) {
  20866. points.push( this.getPoint( d / divisions ) );
  20867. }
  20868. return points;
  20869. },
  20870. // Get sequence of points using getPointAt( u )
  20871. getSpacedPoints: function ( divisions ) {
  20872. if ( divisions === undefined ) divisions = 5;
  20873. var points = [];
  20874. for ( var d = 0; d <= divisions; d ++ ) {
  20875. points.push( this.getPointAt( d / divisions ) );
  20876. }
  20877. return points;
  20878. },
  20879. // Get total curve arc length
  20880. getLength: function () {
  20881. var lengths = this.getLengths();
  20882. return lengths[ lengths.length - 1 ];
  20883. },
  20884. // Get list of cumulative segment lengths
  20885. getLengths: function ( divisions ) {
  20886. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20887. if ( this.cacheArcLengths &&
  20888. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20889. ! this.needsUpdate ) {
  20890. return this.cacheArcLengths;
  20891. }
  20892. this.needsUpdate = false;
  20893. var cache = [];
  20894. var current, last = this.getPoint( 0 );
  20895. var p, sum = 0;
  20896. cache.push( 0 );
  20897. for ( p = 1; p <= divisions; p ++ ) {
  20898. current = this.getPoint( p / divisions );
  20899. sum += current.distanceTo( last );
  20900. cache.push( sum );
  20901. last = current;
  20902. }
  20903. this.cacheArcLengths = cache;
  20904. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20905. },
  20906. updateArcLengths: function () {
  20907. this.needsUpdate = true;
  20908. this.getLengths();
  20909. },
  20910. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20911. getUtoTmapping: function ( u, distance ) {
  20912. var arcLengths = this.getLengths();
  20913. var i = 0, il = arcLengths.length;
  20914. var targetArcLength; // The targeted u distance value to get
  20915. if ( distance ) {
  20916. targetArcLength = distance;
  20917. } else {
  20918. targetArcLength = u * arcLengths[ il - 1 ];
  20919. }
  20920. // binary search for the index with largest value smaller than target u distance
  20921. var low = 0, high = il - 1, comparison;
  20922. while ( low <= high ) {
  20923. 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
  20924. comparison = arcLengths[ i ] - targetArcLength;
  20925. if ( comparison < 0 ) {
  20926. low = i + 1;
  20927. } else if ( comparison > 0 ) {
  20928. high = i - 1;
  20929. } else {
  20930. high = i;
  20931. break;
  20932. // DONE
  20933. }
  20934. }
  20935. i = high;
  20936. if ( arcLengths[ i ] === targetArcLength ) {
  20937. return i / ( il - 1 );
  20938. }
  20939. // we could get finer grain at lengths, or use simple interpolation between two points
  20940. var lengthBefore = arcLengths[ i ];
  20941. var lengthAfter = arcLengths[ i + 1 ];
  20942. var segmentLength = lengthAfter - lengthBefore;
  20943. // determine where we are between the 'before' and 'after' points
  20944. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20945. // add that fractional amount to t
  20946. var t = ( i + segmentFraction ) / ( il - 1 );
  20947. return t;
  20948. },
  20949. // Returns a unit vector tangent at t
  20950. // In case any sub curve does not implement its tangent derivation,
  20951. // 2 points a small delta apart will be used to find its gradient
  20952. // which seems to give a reasonable approximation
  20953. getTangent: function ( t ) {
  20954. var delta = 0.0001;
  20955. var t1 = t - delta;
  20956. var t2 = t + delta;
  20957. // Capping in case of danger
  20958. if ( t1 < 0 ) t1 = 0;
  20959. if ( t2 > 1 ) t2 = 1;
  20960. var pt1 = this.getPoint( t1 );
  20961. var pt2 = this.getPoint( t2 );
  20962. var vec = pt2.clone().sub( pt1 );
  20963. return vec.normalize();
  20964. },
  20965. getTangentAt: function ( u ) {
  20966. var t = this.getUtoTmapping( u );
  20967. return this.getTangent( t );
  20968. },
  20969. computeFrenetFrames: function ( segments, closed ) {
  20970. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20971. var normal = new Vector3();
  20972. var tangents = [];
  20973. var normals = [];
  20974. var binormals = [];
  20975. var vec = new Vector3();
  20976. var mat = new Matrix4();
  20977. var i, u, theta;
  20978. // compute the tangent vectors for each segment on the curve
  20979. for ( i = 0; i <= segments; i ++ ) {
  20980. u = i / segments;
  20981. tangents[ i ] = this.getTangentAt( u );
  20982. tangents[ i ].normalize();
  20983. }
  20984. // select an initial normal vector perpendicular to the first tangent vector,
  20985. // and in the direction of the minimum tangent xyz component
  20986. normals[ 0 ] = new Vector3();
  20987. binormals[ 0 ] = new Vector3();
  20988. var min = Number.MAX_VALUE;
  20989. var tx = Math.abs( tangents[ 0 ].x );
  20990. var ty = Math.abs( tangents[ 0 ].y );
  20991. var tz = Math.abs( tangents[ 0 ].z );
  20992. if ( tx <= min ) {
  20993. min = tx;
  20994. normal.set( 1, 0, 0 );
  20995. }
  20996. if ( ty <= min ) {
  20997. min = ty;
  20998. normal.set( 0, 1, 0 );
  20999. }
  21000. if ( tz <= min ) {
  21001. normal.set( 0, 0, 1 );
  21002. }
  21003. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21004. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21005. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21006. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21007. for ( i = 1; i <= segments; i ++ ) {
  21008. normals[ i ] = normals[ i - 1 ].clone();
  21009. binormals[ i ] = binormals[ i - 1 ].clone();
  21010. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21011. if ( vec.length() > Number.EPSILON ) {
  21012. vec.normalize();
  21013. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21014. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21015. }
  21016. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21017. }
  21018. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21019. if ( closed === true ) {
  21020. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21021. theta /= segments;
  21022. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21023. theta = - theta;
  21024. }
  21025. for ( i = 1; i <= segments; i ++ ) {
  21026. // twist a little...
  21027. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21028. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21029. }
  21030. }
  21031. return {
  21032. tangents: tangents,
  21033. normals: normals,
  21034. binormals: binormals
  21035. };
  21036. }
  21037. } );
  21038. function LineCurve( v1, v2 ) {
  21039. Curve.call( this );
  21040. this.v1 = v1;
  21041. this.v2 = v2;
  21042. }
  21043. LineCurve.prototype = Object.create( Curve.prototype );
  21044. LineCurve.prototype.constructor = LineCurve;
  21045. LineCurve.prototype.isLineCurve = true;
  21046. LineCurve.prototype.getPoint = function ( t ) {
  21047. if ( t === 1 ) {
  21048. return this.v2.clone();
  21049. }
  21050. var point = this.v2.clone().sub( this.v1 );
  21051. point.multiplyScalar( t ).add( this.v1 );
  21052. return point;
  21053. };
  21054. // Line curve is linear, so we can overwrite default getPointAt
  21055. LineCurve.prototype.getPointAt = function ( u ) {
  21056. return this.getPoint( u );
  21057. };
  21058. LineCurve.prototype.getTangent = function ( t ) {
  21059. var tangent = this.v2.clone().sub( this.v1 );
  21060. return tangent.normalize();
  21061. };
  21062. /**
  21063. * @author zz85 / http://www.lab4games.net/zz85/blog
  21064. *
  21065. **/
  21066. /**************************************************************
  21067. * Curved Path - a curve path is simply a array of connected
  21068. * curves, but retains the api of a curve
  21069. **************************************************************/
  21070. function CurvePath() {
  21071. Curve.call( this );
  21072. this.curves = [];
  21073. this.autoClose = false; // Automatically closes the path
  21074. }
  21075. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  21076. constructor: CurvePath,
  21077. add: function ( curve ) {
  21078. this.curves.push( curve );
  21079. },
  21080. closePath: function () {
  21081. // Add a line curve if start and end of lines are not connected
  21082. var startPoint = this.curves[ 0 ].getPoint( 0 );
  21083. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21084. if ( ! startPoint.equals( endPoint ) ) {
  21085. this.curves.push( new LineCurve( endPoint, startPoint ) );
  21086. }
  21087. },
  21088. // To get accurate point with reference to
  21089. // entire path distance at time t,
  21090. // following has to be done:
  21091. // 1. Length of each sub path have to be known
  21092. // 2. Locate and identify type of curve
  21093. // 3. Get t for the curve
  21094. // 4. Return curve.getPointAt(t')
  21095. getPoint: function ( t ) {
  21096. var d = t * this.getLength();
  21097. var curveLengths = this.getCurveLengths();
  21098. var i = 0;
  21099. // To think about boundaries points.
  21100. while ( i < curveLengths.length ) {
  21101. if ( curveLengths[ i ] >= d ) {
  21102. var diff = curveLengths[ i ] - d;
  21103. var curve = this.curves[ i ];
  21104. var segmentLength = curve.getLength();
  21105. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21106. return curve.getPointAt( u );
  21107. }
  21108. i ++;
  21109. }
  21110. return null;
  21111. // loop where sum != 0, sum > d , sum+1 <d
  21112. },
  21113. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21114. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21115. // getPoint() depends on getLength
  21116. getLength: function () {
  21117. var lens = this.getCurveLengths();
  21118. return lens[ lens.length - 1 ];
  21119. },
  21120. // cacheLengths must be recalculated.
  21121. updateArcLengths: function () {
  21122. this.needsUpdate = true;
  21123. this.cacheLengths = null;
  21124. this.getCurveLengths();
  21125. },
  21126. // Compute lengths and cache them
  21127. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21128. getCurveLengths: function () {
  21129. // We use cache values if curves and cache array are same length
  21130. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21131. return this.cacheLengths;
  21132. }
  21133. // Get length of sub-curve
  21134. // Push sums into cached array
  21135. var lengths = [], sums = 0;
  21136. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  21137. sums += this.curves[ i ].getLength();
  21138. lengths.push( sums );
  21139. }
  21140. this.cacheLengths = lengths;
  21141. return lengths;
  21142. },
  21143. getSpacedPoints: function ( divisions ) {
  21144. if ( divisions === undefined ) divisions = 40;
  21145. var points = [];
  21146. for ( var i = 0; i <= divisions; i ++ ) {
  21147. points.push( this.getPoint( i / divisions ) );
  21148. }
  21149. if ( this.autoClose ) {
  21150. points.push( points[ 0 ] );
  21151. }
  21152. return points;
  21153. },
  21154. getPoints: function ( divisions ) {
  21155. divisions = divisions || 12;
  21156. var points = [], last;
  21157. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21158. var curve = curves[ i ];
  21159. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  21160. : (curve && curve.isLineCurve) ? 1
  21161. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  21162. : divisions;
  21163. var pts = curve.getPoints( resolution );
  21164. for ( var j = 0; j < pts.length; j++ ) {
  21165. var point = pts[ j ];
  21166. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21167. points.push( point );
  21168. last = point;
  21169. }
  21170. }
  21171. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21172. points.push( points[ 0 ] );
  21173. }
  21174. return points;
  21175. },
  21176. /**************************************************************
  21177. * Create Geometries Helpers
  21178. **************************************************************/
  21179. /// Generate geometry from path points (for Line or Points objects)
  21180. createPointsGeometry: function ( divisions ) {
  21181. var pts = this.getPoints( divisions );
  21182. return this.createGeometry( pts );
  21183. },
  21184. // Generate geometry from equidistant sampling along the path
  21185. createSpacedPointsGeometry: function ( divisions ) {
  21186. var pts = this.getSpacedPoints( divisions );
  21187. return this.createGeometry( pts );
  21188. },
  21189. createGeometry: function ( points ) {
  21190. var geometry = new Geometry();
  21191. for ( var i = 0, l = points.length; i < l; i ++ ) {
  21192. var point = points[ i ];
  21193. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  21194. }
  21195. return geometry;
  21196. }
  21197. } );
  21198. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21199. Curve.call( this );
  21200. this.aX = aX;
  21201. this.aY = aY;
  21202. this.xRadius = xRadius;
  21203. this.yRadius = yRadius;
  21204. this.aStartAngle = aStartAngle;
  21205. this.aEndAngle = aEndAngle;
  21206. this.aClockwise = aClockwise;
  21207. this.aRotation = aRotation || 0;
  21208. }
  21209. EllipseCurve.prototype = Object.create( Curve.prototype );
  21210. EllipseCurve.prototype.constructor = EllipseCurve;
  21211. EllipseCurve.prototype.isEllipseCurve = true;
  21212. EllipseCurve.prototype.getPoint = function ( t ) {
  21213. var twoPi = Math.PI * 2;
  21214. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21215. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21216. // ensures that deltaAngle is 0 .. 2 PI
  21217. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21218. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21219. if ( deltaAngle < Number.EPSILON ) {
  21220. if ( samePoints ) {
  21221. deltaAngle = 0;
  21222. } else {
  21223. deltaAngle = twoPi;
  21224. }
  21225. }
  21226. if ( this.aClockwise === true && ! samePoints ) {
  21227. if ( deltaAngle === twoPi ) {
  21228. deltaAngle = - twoPi;
  21229. } else {
  21230. deltaAngle = deltaAngle - twoPi;
  21231. }
  21232. }
  21233. var angle = this.aStartAngle + t * deltaAngle;
  21234. var x = this.aX + this.xRadius * Math.cos( angle );
  21235. var y = this.aY + this.yRadius * Math.sin( angle );
  21236. if ( this.aRotation !== 0 ) {
  21237. var cos = Math.cos( this.aRotation );
  21238. var sin = Math.sin( this.aRotation );
  21239. var tx = x - this.aX;
  21240. var ty = y - this.aY;
  21241. // Rotate the point about the center of the ellipse.
  21242. x = tx * cos - ty * sin + this.aX;
  21243. y = tx * sin + ty * cos + this.aY;
  21244. }
  21245. return new Vector2( x, y );
  21246. };
  21247. function SplineCurve( points /* array of Vector2 */ ) {
  21248. Curve.call( this );
  21249. this.points = ( points === undefined ) ? [] : points;
  21250. }
  21251. SplineCurve.prototype = Object.create( Curve.prototype );
  21252. SplineCurve.prototype.constructor = SplineCurve;
  21253. SplineCurve.prototype.isSplineCurve = true;
  21254. SplineCurve.prototype.getPoint = function ( t ) {
  21255. var points = this.points;
  21256. var point = ( points.length - 1 ) * t;
  21257. var intPoint = Math.floor( point );
  21258. var weight = point - intPoint;
  21259. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21260. var point1 = points[ intPoint ];
  21261. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21262. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21263. return new Vector2(
  21264. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  21265. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  21266. );
  21267. };
  21268. function CubicBezierCurve( v0, v1, v2, v3 ) {
  21269. Curve.call( this );
  21270. this.v0 = v0;
  21271. this.v1 = v1;
  21272. this.v2 = v2;
  21273. this.v3 = v3;
  21274. }
  21275. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  21276. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  21277. CubicBezierCurve.prototype.getPoint = function ( t ) {
  21278. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21279. return new Vector2(
  21280. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21281. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21282. );
  21283. };
  21284. function QuadraticBezierCurve( v0, v1, v2 ) {
  21285. Curve.call( this );
  21286. this.v0 = v0;
  21287. this.v1 = v1;
  21288. this.v2 = v2;
  21289. }
  21290. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  21291. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  21292. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21293. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21294. return new Vector2(
  21295. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21296. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21297. );
  21298. };
  21299. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21300. fromPoints: function ( vectors ) {
  21301. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21302. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21303. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21304. }
  21305. },
  21306. moveTo: function ( x, y ) {
  21307. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21308. },
  21309. lineTo: function ( x, y ) {
  21310. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21311. this.curves.push( curve );
  21312. this.currentPoint.set( x, y );
  21313. },
  21314. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21315. var curve = new QuadraticBezierCurve(
  21316. this.currentPoint.clone(),
  21317. new Vector2( aCPx, aCPy ),
  21318. new Vector2( aX, aY )
  21319. );
  21320. this.curves.push( curve );
  21321. this.currentPoint.set( aX, aY );
  21322. },
  21323. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21324. var curve = new CubicBezierCurve(
  21325. this.currentPoint.clone(),
  21326. new Vector2( aCP1x, aCP1y ),
  21327. new Vector2( aCP2x, aCP2y ),
  21328. new Vector2( aX, aY )
  21329. );
  21330. this.curves.push( curve );
  21331. this.currentPoint.set( aX, aY );
  21332. },
  21333. splineThru: function ( pts /*Array of Vector*/ ) {
  21334. var npts = [ this.currentPoint.clone() ].concat( pts );
  21335. var curve = new SplineCurve( npts );
  21336. this.curves.push( curve );
  21337. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21338. },
  21339. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21340. var x0 = this.currentPoint.x;
  21341. var y0 = this.currentPoint.y;
  21342. this.absarc( aX + x0, aY + y0, aRadius,
  21343. aStartAngle, aEndAngle, aClockwise );
  21344. },
  21345. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21346. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21347. },
  21348. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21349. var x0 = this.currentPoint.x;
  21350. var y0 = this.currentPoint.y;
  21351. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21352. },
  21353. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21354. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21355. if ( this.curves.length > 0 ) {
  21356. // if a previous curve is present, attempt to join
  21357. var firstPoint = curve.getPoint( 0 );
  21358. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21359. this.lineTo( firstPoint.x, firstPoint.y );
  21360. }
  21361. }
  21362. this.curves.push( curve );
  21363. var lastPoint = curve.getPoint( 1 );
  21364. this.currentPoint.copy( lastPoint );
  21365. }
  21366. } );
  21367. /**
  21368. * @author zz85 / http://www.lab4games.net/zz85/blog
  21369. * Creates free form 2d path using series of points, lines or curves.
  21370. **/
  21371. function Path( points ) {
  21372. CurvePath.call( this );
  21373. this.currentPoint = new Vector2();
  21374. if ( points ) {
  21375. this.fromPoints( points );
  21376. }
  21377. }
  21378. Path.prototype = PathPrototype;
  21379. PathPrototype.constructor = Path;
  21380. /**
  21381. * @author zz85 / http://www.lab4games.net/zz85/blog
  21382. * Defines a 2d shape plane using paths.
  21383. **/
  21384. // STEP 1 Create a path.
  21385. // STEP 2 Turn path into shape.
  21386. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21387. // STEP 3a - Extract points from each shape, turn to vertices
  21388. // STEP 3b - Triangulate each shape, add faces.
  21389. function Shape() {
  21390. Path.apply( this, arguments );
  21391. this.holes = [];
  21392. }
  21393. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21394. constructor: Shape,
  21395. getPointsHoles: function ( divisions ) {
  21396. var holesPts = [];
  21397. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21398. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21399. }
  21400. return holesPts;
  21401. },
  21402. // Get points of shape and holes (keypoints based on segments parameter)
  21403. extractAllPoints: function ( divisions ) {
  21404. return {
  21405. shape: this.getPoints( divisions ),
  21406. holes: this.getPointsHoles( divisions )
  21407. };
  21408. },
  21409. extractPoints: function ( divisions ) {
  21410. return this.extractAllPoints( divisions );
  21411. }
  21412. } );
  21413. /**
  21414. * @author zz85 / http://www.lab4games.net/zz85/blog
  21415. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21416. **/
  21417. function ShapePath() {
  21418. this.subPaths = [];
  21419. this.currentPath = null;
  21420. }
  21421. Object.assign( ShapePath.prototype, {
  21422. moveTo: function ( x, y ) {
  21423. this.currentPath = new Path();
  21424. this.subPaths.push( this.currentPath );
  21425. this.currentPath.moveTo( x, y );
  21426. },
  21427. lineTo: function ( x, y ) {
  21428. this.currentPath.lineTo( x, y );
  21429. },
  21430. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21431. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21432. },
  21433. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21434. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21435. },
  21436. splineThru: function ( pts ) {
  21437. this.currentPath.splineThru( pts );
  21438. },
  21439. toShapes: function ( isCCW, noHoles ) {
  21440. function toShapesNoHoles( inSubpaths ) {
  21441. var shapes = [];
  21442. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21443. var tmpPath = inSubpaths[ i ];
  21444. var tmpShape = new Shape();
  21445. tmpShape.curves = tmpPath.curves;
  21446. shapes.push( tmpShape );
  21447. }
  21448. return shapes;
  21449. }
  21450. function isPointInsidePolygon( inPt, inPolygon ) {
  21451. var polyLen = inPolygon.length;
  21452. // inPt on polygon contour => immediate success or
  21453. // toggling of inside/outside at every single! intersection point of an edge
  21454. // with the horizontal line through inPt, left of inPt
  21455. // not counting lowerY endpoints of edges and whole edges on that line
  21456. var inside = false;
  21457. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21458. var edgeLowPt = inPolygon[ p ];
  21459. var edgeHighPt = inPolygon[ q ];
  21460. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21461. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21462. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21463. // not parallel
  21464. if ( edgeDy < 0 ) {
  21465. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21466. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21467. }
  21468. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21469. if ( inPt.y === edgeLowPt.y ) {
  21470. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21471. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21472. } else {
  21473. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21474. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21475. if ( perpEdge < 0 ) continue;
  21476. inside = ! inside; // true intersection left of inPt
  21477. }
  21478. } else {
  21479. // parallel or collinear
  21480. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21481. // edge lies on the same horizontal line as inPt
  21482. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21483. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21484. // continue;
  21485. }
  21486. }
  21487. return inside;
  21488. }
  21489. var isClockWise = ShapeUtils.isClockWise;
  21490. var subPaths = this.subPaths;
  21491. if ( subPaths.length === 0 ) return [];
  21492. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21493. var solid, tmpPath, tmpShape, shapes = [];
  21494. if ( subPaths.length === 1 ) {
  21495. tmpPath = subPaths[ 0 ];
  21496. tmpShape = new Shape();
  21497. tmpShape.curves = tmpPath.curves;
  21498. shapes.push( tmpShape );
  21499. return shapes;
  21500. }
  21501. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21502. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21503. // console.log("Holes first", holesFirst);
  21504. var betterShapeHoles = [];
  21505. var newShapes = [];
  21506. var newShapeHoles = [];
  21507. var mainIdx = 0;
  21508. var tmpPoints;
  21509. newShapes[ mainIdx ] = undefined;
  21510. newShapeHoles[ mainIdx ] = [];
  21511. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21512. tmpPath = subPaths[ i ];
  21513. tmpPoints = tmpPath.getPoints();
  21514. solid = isClockWise( tmpPoints );
  21515. solid = isCCW ? ! solid : solid;
  21516. if ( solid ) {
  21517. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21518. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21519. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21520. if ( holesFirst ) mainIdx ++;
  21521. newShapeHoles[ mainIdx ] = [];
  21522. //console.log('cw', i);
  21523. } else {
  21524. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21525. //console.log('ccw', i);
  21526. }
  21527. }
  21528. // only Holes? -> probably all Shapes with wrong orientation
  21529. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21530. if ( newShapes.length > 1 ) {
  21531. var ambiguous = false;
  21532. var toChange = [];
  21533. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21534. betterShapeHoles[ sIdx ] = [];
  21535. }
  21536. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21537. var sho = newShapeHoles[ sIdx ];
  21538. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21539. var ho = sho[ hIdx ];
  21540. var hole_unassigned = true;
  21541. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21542. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21543. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21544. if ( hole_unassigned ) {
  21545. hole_unassigned = false;
  21546. betterShapeHoles[ s2Idx ].push( ho );
  21547. } else {
  21548. ambiguous = true;
  21549. }
  21550. }
  21551. }
  21552. if ( hole_unassigned ) {
  21553. betterShapeHoles[ sIdx ].push( ho );
  21554. }
  21555. }
  21556. }
  21557. // console.log("ambiguous: ", ambiguous);
  21558. if ( toChange.length > 0 ) {
  21559. // console.log("to change: ", toChange);
  21560. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21561. }
  21562. }
  21563. var tmpHoles;
  21564. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21565. tmpShape = newShapes[ i ].s;
  21566. shapes.push( tmpShape );
  21567. tmpHoles = newShapeHoles[ i ];
  21568. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21569. tmpShape.holes.push( tmpHoles[ j ].h );
  21570. }
  21571. }
  21572. //console.log("shape", shapes);
  21573. return shapes;
  21574. }
  21575. } );
  21576. /**
  21577. * @author zz85 / http://www.lab4games.net/zz85/blog
  21578. * @author mrdoob / http://mrdoob.com/
  21579. */
  21580. function Font( data ) {
  21581. this.data = data;
  21582. }
  21583. Object.assign( Font.prototype, {
  21584. isFont: true,
  21585. generateShapes: function ( text, size, divisions ) {
  21586. function createPaths( text ) {
  21587. var chars = String( text ).split( '' );
  21588. var scale = size / data.resolution;
  21589. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21590. var offsetX = 0, offsetY = 0;
  21591. var paths = [];
  21592. for ( var i = 0; i < chars.length; i ++ ) {
  21593. var char = chars[ i ];
  21594. if ( char === '\n' ) {
  21595. offsetX = 0;
  21596. offsetY -= line_height;
  21597. } else {
  21598. var ret = createPath( char, scale, offsetX, offsetY );
  21599. offsetX += ret.offsetX;
  21600. paths.push( ret.path );
  21601. }
  21602. }
  21603. return paths;
  21604. }
  21605. function createPath( c, scale, offsetX, offsetY ) {
  21606. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21607. if ( ! glyph ) return;
  21608. var path = new ShapePath();
  21609. var pts = [];
  21610. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21611. if ( glyph.o ) {
  21612. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21613. for ( var i = 0, l = outline.length; i < l; ) {
  21614. var action = outline[ i ++ ];
  21615. switch ( action ) {
  21616. case 'm': // moveTo
  21617. x = outline[ i ++ ] * scale + offsetX;
  21618. y = outline[ i ++ ] * scale + offsetY;
  21619. path.moveTo( x, y );
  21620. break;
  21621. case 'l': // lineTo
  21622. x = outline[ i ++ ] * scale + offsetX;
  21623. y = outline[ i ++ ] * scale + offsetY;
  21624. path.lineTo( x, y );
  21625. break;
  21626. case 'q': // quadraticCurveTo
  21627. cpx = outline[ i ++ ] * scale + offsetX;
  21628. cpy = outline[ i ++ ] * scale + offsetY;
  21629. cpx1 = outline[ i ++ ] * scale + offsetX;
  21630. cpy1 = outline[ i ++ ] * scale + offsetY;
  21631. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21632. laste = pts[ pts.length - 1 ];
  21633. if ( laste ) {
  21634. cpx0 = laste.x;
  21635. cpy0 = laste.y;
  21636. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21637. var t = i2 / divisions;
  21638. QuadraticBezier( t, cpx0, cpx1, cpx );
  21639. QuadraticBezier( t, cpy0, cpy1, cpy );
  21640. }
  21641. }
  21642. break;
  21643. case 'b': // bezierCurveTo
  21644. cpx = outline[ i ++ ] * scale + offsetX;
  21645. cpy = outline[ i ++ ] * scale + offsetY;
  21646. cpx1 = outline[ i ++ ] * scale + offsetX;
  21647. cpy1 = outline[ i ++ ] * scale + offsetY;
  21648. cpx2 = outline[ i ++ ] * scale + offsetX;
  21649. cpy2 = outline[ i ++ ] * scale + offsetY;
  21650. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21651. laste = pts[ pts.length - 1 ];
  21652. if ( laste ) {
  21653. cpx0 = laste.x;
  21654. cpy0 = laste.y;
  21655. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21656. var t = i2 / divisions;
  21657. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21658. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21659. }
  21660. }
  21661. break;
  21662. }
  21663. }
  21664. }
  21665. return { offsetX: glyph.ha * scale, path: path };
  21666. }
  21667. //
  21668. if ( size === undefined ) size = 100;
  21669. if ( divisions === undefined ) divisions = 4;
  21670. var data = this.data;
  21671. var paths = createPaths( text );
  21672. var shapes = [];
  21673. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21674. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21675. }
  21676. return shapes;
  21677. }
  21678. } );
  21679. /**
  21680. * @author mrdoob / http://mrdoob.com/
  21681. */
  21682. function FontLoader( manager ) {
  21683. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21684. }
  21685. Object.assign( FontLoader.prototype, {
  21686. load: function ( url, onLoad, onProgress, onError ) {
  21687. var scope = this;
  21688. var loader = new FileLoader( this.manager );
  21689. loader.load( url, function ( text ) {
  21690. var json;
  21691. try {
  21692. json = JSON.parse( text );
  21693. } catch ( e ) {
  21694. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21695. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21696. }
  21697. var font = scope.parse( json );
  21698. if ( onLoad ) onLoad( font );
  21699. }, onProgress, onError );
  21700. },
  21701. parse: function ( json ) {
  21702. return new Font( json );
  21703. }
  21704. } );
  21705. var context;
  21706. var AudioContext = {
  21707. getContext: function () {
  21708. if ( context === undefined ) {
  21709. context = new ( window.AudioContext || window.webkitAudioContext )();
  21710. }
  21711. return context;
  21712. },
  21713. setContext: function ( value ) {
  21714. context = value;
  21715. }
  21716. };
  21717. /**
  21718. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21719. */
  21720. function AudioLoader( manager ) {
  21721. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21722. }
  21723. Object.assign( AudioLoader.prototype, {
  21724. load: function ( url, onLoad, onProgress, onError ) {
  21725. var loader = new FileLoader( this.manager );
  21726. loader.setResponseType( 'arraybuffer' );
  21727. loader.load( url, function ( buffer ) {
  21728. var context = AudioContext.getContext();
  21729. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21730. onLoad( audioBuffer );
  21731. } );
  21732. }, onProgress, onError );
  21733. }
  21734. } );
  21735. /**
  21736. * @author mrdoob / http://mrdoob.com/
  21737. */
  21738. function StereoCamera() {
  21739. this.type = 'StereoCamera';
  21740. this.aspect = 1;
  21741. this.eyeSep = 0.064;
  21742. this.cameraL = new PerspectiveCamera();
  21743. this.cameraL.layers.enable( 1 );
  21744. this.cameraL.matrixAutoUpdate = false;
  21745. this.cameraR = new PerspectiveCamera();
  21746. this.cameraR.layers.enable( 2 );
  21747. this.cameraR.matrixAutoUpdate = false;
  21748. }
  21749. Object.assign( StereoCamera.prototype, {
  21750. update: ( function () {
  21751. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21752. var eyeRight = new Matrix4();
  21753. var eyeLeft = new Matrix4();
  21754. return function update( camera ) {
  21755. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21756. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21757. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21758. if ( needsUpdate ) {
  21759. instance = this;
  21760. focus = camera.focus;
  21761. fov = camera.fov;
  21762. aspect = camera.aspect * this.aspect;
  21763. near = camera.near;
  21764. far = camera.far;
  21765. zoom = camera.zoom;
  21766. // Off-axis stereoscopic effect based on
  21767. // http://paulbourke.net/stereographics/stereorender/
  21768. var projectionMatrix = camera.projectionMatrix.clone();
  21769. eyeSep = this.eyeSep / 2;
  21770. var eyeSepOnProjection = eyeSep * near / focus;
  21771. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21772. var xmin, xmax;
  21773. // translate xOffset
  21774. eyeLeft.elements[ 12 ] = - eyeSep;
  21775. eyeRight.elements[ 12 ] = eyeSep;
  21776. // for left eye
  21777. xmin = - ymax * aspect + eyeSepOnProjection;
  21778. xmax = ymax * aspect + eyeSepOnProjection;
  21779. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21780. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21781. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21782. // for right eye
  21783. xmin = - ymax * aspect - eyeSepOnProjection;
  21784. xmax = ymax * aspect - eyeSepOnProjection;
  21785. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21786. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21787. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21788. }
  21789. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21790. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21791. };
  21792. } )()
  21793. } );
  21794. /**
  21795. * Camera for rendering cube maps
  21796. * - renders scene into axis-aligned cube
  21797. *
  21798. * @author alteredq / http://alteredqualia.com/
  21799. */
  21800. function CubeCamera( near, far, cubeResolution ) {
  21801. Object3D.call( this );
  21802. this.type = 'CubeCamera';
  21803. var fov = 90, aspect = 1;
  21804. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21805. cameraPX.up.set( 0, - 1, 0 );
  21806. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21807. this.add( cameraPX );
  21808. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21809. cameraNX.up.set( 0, - 1, 0 );
  21810. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21811. this.add( cameraNX );
  21812. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21813. cameraPY.up.set( 0, 0, 1 );
  21814. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21815. this.add( cameraPY );
  21816. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21817. cameraNY.up.set( 0, 0, - 1 );
  21818. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21819. this.add( cameraNY );
  21820. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21821. cameraPZ.up.set( 0, - 1, 0 );
  21822. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21823. this.add( cameraPZ );
  21824. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21825. cameraNZ.up.set( 0, - 1, 0 );
  21826. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21827. this.add( cameraNZ );
  21828. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21829. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21830. this.renderTarget.texture.name = "CubeCamera";
  21831. this.updateCubeMap = function ( renderer, scene ) {
  21832. if ( this.parent === null ) this.updateMatrixWorld();
  21833. var renderTarget = this.renderTarget;
  21834. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21835. renderTarget.texture.generateMipmaps = false;
  21836. renderTarget.activeCubeFace = 0;
  21837. renderer.render( scene, cameraPX, renderTarget );
  21838. renderTarget.activeCubeFace = 1;
  21839. renderer.render( scene, cameraNX, renderTarget );
  21840. renderTarget.activeCubeFace = 2;
  21841. renderer.render( scene, cameraPY, renderTarget );
  21842. renderTarget.activeCubeFace = 3;
  21843. renderer.render( scene, cameraNY, renderTarget );
  21844. renderTarget.activeCubeFace = 4;
  21845. renderer.render( scene, cameraPZ, renderTarget );
  21846. renderTarget.texture.generateMipmaps = generateMipmaps;
  21847. renderTarget.activeCubeFace = 5;
  21848. renderer.render( scene, cameraNZ, renderTarget );
  21849. renderer.setRenderTarget( null );
  21850. };
  21851. }
  21852. CubeCamera.prototype = Object.create( Object3D.prototype );
  21853. CubeCamera.prototype.constructor = CubeCamera;
  21854. /**
  21855. * @author mrdoob / http://mrdoob.com/
  21856. */
  21857. function AudioListener() {
  21858. Object3D.call( this );
  21859. this.type = 'AudioListener';
  21860. this.context = AudioContext.getContext();
  21861. this.gain = this.context.createGain();
  21862. this.gain.connect( this.context.destination );
  21863. this.filter = null;
  21864. }
  21865. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21866. constructor: AudioListener,
  21867. getInput: function () {
  21868. return this.gain;
  21869. },
  21870. removeFilter: function ( ) {
  21871. if ( this.filter !== null ) {
  21872. this.gain.disconnect( this.filter );
  21873. this.filter.disconnect( this.context.destination );
  21874. this.gain.connect( this.context.destination );
  21875. this.filter = null;
  21876. }
  21877. },
  21878. getFilter: function () {
  21879. return this.filter;
  21880. },
  21881. setFilter: function ( value ) {
  21882. if ( this.filter !== null ) {
  21883. this.gain.disconnect( this.filter );
  21884. this.filter.disconnect( this.context.destination );
  21885. } else {
  21886. this.gain.disconnect( this.context.destination );
  21887. }
  21888. this.filter = value;
  21889. this.gain.connect( this.filter );
  21890. this.filter.connect( this.context.destination );
  21891. },
  21892. getMasterVolume: function () {
  21893. return this.gain.gain.value;
  21894. },
  21895. setMasterVolume: function ( value ) {
  21896. this.gain.gain.value = value;
  21897. },
  21898. updateMatrixWorld: ( function () {
  21899. var position = new Vector3();
  21900. var quaternion = new Quaternion();
  21901. var scale = new Vector3();
  21902. var orientation = new Vector3();
  21903. return function updateMatrixWorld( force ) {
  21904. Object3D.prototype.updateMatrixWorld.call( this, force );
  21905. var listener = this.context.listener;
  21906. var up = this.up;
  21907. this.matrixWorld.decompose( position, quaternion, scale );
  21908. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21909. if ( listener.positionX ) {
  21910. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21911. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21912. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21913. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21914. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21915. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21916. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21917. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21918. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21919. } else {
  21920. listener.setPosition( position.x, position.y, position.z );
  21921. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21922. }
  21923. };
  21924. } )()
  21925. } );
  21926. /**
  21927. * @author mrdoob / http://mrdoob.com/
  21928. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21929. */
  21930. function Audio( listener ) {
  21931. Object3D.call( this );
  21932. this.type = 'Audio';
  21933. this.context = listener.context;
  21934. this.gain = this.context.createGain();
  21935. this.gain.connect( listener.getInput() );
  21936. this.autoplay = false;
  21937. this.buffer = null;
  21938. this.loop = false;
  21939. this.startTime = 0;
  21940. this.playbackRate = 1;
  21941. this.isPlaying = false;
  21942. this.hasPlaybackControl = true;
  21943. this.sourceType = 'empty';
  21944. this.filters = [];
  21945. }
  21946. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21947. constructor: Audio,
  21948. getOutput: function () {
  21949. return this.gain;
  21950. },
  21951. setNodeSource: function ( audioNode ) {
  21952. this.hasPlaybackControl = false;
  21953. this.sourceType = 'audioNode';
  21954. this.source = audioNode;
  21955. this.connect();
  21956. return this;
  21957. },
  21958. setBuffer: function ( audioBuffer ) {
  21959. this.buffer = audioBuffer;
  21960. this.sourceType = 'buffer';
  21961. if ( this.autoplay ) this.play();
  21962. return this;
  21963. },
  21964. play: function () {
  21965. if ( this.isPlaying === true ) {
  21966. console.warn( 'THREE.Audio: Audio is already playing.' );
  21967. return;
  21968. }
  21969. if ( this.hasPlaybackControl === false ) {
  21970. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21971. return;
  21972. }
  21973. var source = this.context.createBufferSource();
  21974. source.buffer = this.buffer;
  21975. source.loop = this.loop;
  21976. source.onended = this.onEnded.bind( this );
  21977. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21978. source.start( 0, this.startTime );
  21979. this.isPlaying = true;
  21980. this.source = source;
  21981. return this.connect();
  21982. },
  21983. pause: function () {
  21984. if ( this.hasPlaybackControl === false ) {
  21985. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21986. return;
  21987. }
  21988. this.source.stop();
  21989. this.startTime = this.context.currentTime;
  21990. this.isPlaying = false;
  21991. return this;
  21992. },
  21993. stop: function () {
  21994. if ( this.hasPlaybackControl === false ) {
  21995. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21996. return;
  21997. }
  21998. this.source.stop();
  21999. this.startTime = 0;
  22000. this.isPlaying = false;
  22001. return this;
  22002. },
  22003. connect: function () {
  22004. if ( this.filters.length > 0 ) {
  22005. this.source.connect( this.filters[ 0 ] );
  22006. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22007. this.filters[ i - 1 ].connect( this.filters[ i ] );
  22008. }
  22009. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  22010. } else {
  22011. this.source.connect( this.getOutput() );
  22012. }
  22013. return this;
  22014. },
  22015. disconnect: function () {
  22016. if ( this.filters.length > 0 ) {
  22017. this.source.disconnect( this.filters[ 0 ] );
  22018. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  22019. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  22020. }
  22021. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  22022. } else {
  22023. this.source.disconnect( this.getOutput() );
  22024. }
  22025. return this;
  22026. },
  22027. getFilters: function () {
  22028. return this.filters;
  22029. },
  22030. setFilters: function ( value ) {
  22031. if ( ! value ) value = [];
  22032. if ( this.isPlaying === true ) {
  22033. this.disconnect();
  22034. this.filters = value;
  22035. this.connect();
  22036. } else {
  22037. this.filters = value;
  22038. }
  22039. return this;
  22040. },
  22041. getFilter: function () {
  22042. return this.getFilters()[ 0 ];
  22043. },
  22044. setFilter: function ( filter ) {
  22045. return this.setFilters( filter ? [ filter ] : [] );
  22046. },
  22047. setPlaybackRate: function ( value ) {
  22048. if ( this.hasPlaybackControl === false ) {
  22049. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22050. return;
  22051. }
  22052. this.playbackRate = value;
  22053. if ( this.isPlaying === true ) {
  22054. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  22055. }
  22056. return this;
  22057. },
  22058. getPlaybackRate: function () {
  22059. return this.playbackRate;
  22060. },
  22061. onEnded: function () {
  22062. this.isPlaying = false;
  22063. },
  22064. getLoop: function () {
  22065. if ( this.hasPlaybackControl === false ) {
  22066. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22067. return false;
  22068. }
  22069. return this.loop;
  22070. },
  22071. setLoop: function ( value ) {
  22072. if ( this.hasPlaybackControl === false ) {
  22073. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  22074. return;
  22075. }
  22076. this.loop = value;
  22077. if ( this.isPlaying === true ) {
  22078. this.source.loop = this.loop;
  22079. }
  22080. return this;
  22081. },
  22082. getVolume: function () {
  22083. return this.gain.gain.value;
  22084. },
  22085. setVolume: function ( value ) {
  22086. this.gain.gain.value = value;
  22087. return this;
  22088. }
  22089. } );
  22090. /**
  22091. * @author mrdoob / http://mrdoob.com/
  22092. */
  22093. function PositionalAudio( listener ) {
  22094. Audio.call( this, listener );
  22095. this.panner = this.context.createPanner();
  22096. this.panner.connect( this.gain );
  22097. }
  22098. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  22099. constructor: PositionalAudio,
  22100. getOutput: function () {
  22101. return this.panner;
  22102. },
  22103. getRefDistance: function () {
  22104. return this.panner.refDistance;
  22105. },
  22106. setRefDistance: function ( value ) {
  22107. this.panner.refDistance = value;
  22108. },
  22109. getRolloffFactor: function () {
  22110. return this.panner.rolloffFactor;
  22111. },
  22112. setRolloffFactor: function ( value ) {
  22113. this.panner.rolloffFactor = value;
  22114. },
  22115. getDistanceModel: function () {
  22116. return this.panner.distanceModel;
  22117. },
  22118. setDistanceModel: function ( value ) {
  22119. this.panner.distanceModel = value;
  22120. },
  22121. getMaxDistance: function () {
  22122. return this.panner.maxDistance;
  22123. },
  22124. setMaxDistance: function ( value ) {
  22125. this.panner.maxDistance = value;
  22126. },
  22127. updateMatrixWorld: ( function () {
  22128. var position = new Vector3();
  22129. return function updateMatrixWorld( force ) {
  22130. Object3D.prototype.updateMatrixWorld.call( this, force );
  22131. position.setFromMatrixPosition( this.matrixWorld );
  22132. this.panner.setPosition( position.x, position.y, position.z );
  22133. };
  22134. } )()
  22135. } );
  22136. /**
  22137. * @author mrdoob / http://mrdoob.com/
  22138. */
  22139. function AudioAnalyser( audio, fftSize ) {
  22140. this.analyser = audio.context.createAnalyser();
  22141. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  22142. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  22143. audio.getOutput().connect( this.analyser );
  22144. }
  22145. Object.assign( AudioAnalyser.prototype, {
  22146. getFrequencyData: function () {
  22147. this.analyser.getByteFrequencyData( this.data );
  22148. return this.data;
  22149. },
  22150. getAverageFrequency: function () {
  22151. var value = 0, data = this.getFrequencyData();
  22152. for ( var i = 0; i < data.length; i ++ ) {
  22153. value += data[ i ];
  22154. }
  22155. return value / data.length;
  22156. }
  22157. } );
  22158. /**
  22159. *
  22160. * Buffered scene graph property that allows weighted accumulation.
  22161. *
  22162. *
  22163. * @author Ben Houston / http://clara.io/
  22164. * @author David Sarno / http://lighthaus.us/
  22165. * @author tschw
  22166. */
  22167. function PropertyMixer( binding, typeName, valueSize ) {
  22168. this.binding = binding;
  22169. this.valueSize = valueSize;
  22170. var bufferType = Float64Array,
  22171. mixFunction;
  22172. switch ( typeName ) {
  22173. case 'quaternion':
  22174. mixFunction = this._slerp;
  22175. break;
  22176. case 'string':
  22177. case 'bool':
  22178. bufferType = Array;
  22179. mixFunction = this._select;
  22180. break;
  22181. default:
  22182. mixFunction = this._lerp;
  22183. }
  22184. this.buffer = new bufferType( valueSize * 4 );
  22185. // layout: [ incoming | accu0 | accu1 | orig ]
  22186. //
  22187. // interpolators can use .buffer as their .result
  22188. // the data then goes to 'incoming'
  22189. //
  22190. // 'accu0' and 'accu1' are used frame-interleaved for
  22191. // the cumulative result and are compared to detect
  22192. // changes
  22193. //
  22194. // 'orig' stores the original state of the property
  22195. this._mixBufferRegion = mixFunction;
  22196. this.cumulativeWeight = 0;
  22197. this.useCount = 0;
  22198. this.referenceCount = 0;
  22199. }
  22200. Object.assign( PropertyMixer.prototype, {
  22201. // accumulate data in the 'incoming' region into 'accu<i>'
  22202. accumulate: function ( accuIndex, weight ) {
  22203. // note: happily accumulating nothing when weight = 0, the caller knows
  22204. // the weight and shouldn't have made the call in the first place
  22205. var buffer = this.buffer,
  22206. stride = this.valueSize,
  22207. offset = accuIndex * stride + stride,
  22208. currentWeight = this.cumulativeWeight;
  22209. if ( currentWeight === 0 ) {
  22210. // accuN := incoming * weight
  22211. for ( var i = 0; i !== stride; ++ i ) {
  22212. buffer[ offset + i ] = buffer[ i ];
  22213. }
  22214. currentWeight = weight;
  22215. } else {
  22216. // accuN := accuN + incoming * weight
  22217. currentWeight += weight;
  22218. var mix = weight / currentWeight;
  22219. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  22220. }
  22221. this.cumulativeWeight = currentWeight;
  22222. },
  22223. // apply the state of 'accu<i>' to the binding when accus differ
  22224. apply: function ( accuIndex ) {
  22225. var stride = this.valueSize,
  22226. buffer = this.buffer,
  22227. offset = accuIndex * stride + stride,
  22228. weight = this.cumulativeWeight,
  22229. binding = this.binding;
  22230. this.cumulativeWeight = 0;
  22231. if ( weight < 1 ) {
  22232. // accuN := accuN + original * ( 1 - cumulativeWeight )
  22233. var originalValueOffset = stride * 3;
  22234. this._mixBufferRegion(
  22235. buffer, offset, originalValueOffset, 1 - weight, stride );
  22236. }
  22237. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  22238. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  22239. // value has changed -> update scene graph
  22240. binding.setValue( buffer, offset );
  22241. break;
  22242. }
  22243. }
  22244. },
  22245. // remember the state of the bound property and copy it to both accus
  22246. saveOriginalState: function () {
  22247. var binding = this.binding;
  22248. var buffer = this.buffer,
  22249. stride = this.valueSize,
  22250. originalValueOffset = stride * 3;
  22251. binding.getValue( buffer, originalValueOffset );
  22252. // accu[0..1] := orig -- initially detect changes against the original
  22253. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22254. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22255. }
  22256. this.cumulativeWeight = 0;
  22257. },
  22258. // apply the state previously taken via 'saveOriginalState' to the binding
  22259. restoreOriginalState: function () {
  22260. var originalValueOffset = this.valueSize * 3;
  22261. this.binding.setValue( this.buffer, originalValueOffset );
  22262. },
  22263. // mix functions
  22264. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22265. if ( t >= 0.5 ) {
  22266. for ( var i = 0; i !== stride; ++ i ) {
  22267. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22268. }
  22269. }
  22270. },
  22271. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  22272. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22273. },
  22274. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  22275. var s = 1 - t;
  22276. for ( var i = 0; i !== stride; ++ i ) {
  22277. var j = dstOffset + i;
  22278. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22279. }
  22280. }
  22281. } );
  22282. /**
  22283. *
  22284. * A reference to a real property in the scene graph.
  22285. *
  22286. *
  22287. * @author Ben Houston / http://clara.io/
  22288. * @author David Sarno / http://lighthaus.us/
  22289. * @author tschw
  22290. */
  22291. function Composite( targetGroup, path, optionalParsedPath ) {
  22292. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22293. this._targetGroup = targetGroup;
  22294. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22295. }
  22296. Object.assign( Composite.prototype, {
  22297. getValue: function ( array, offset ) {
  22298. this.bind(); // bind all binding
  22299. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22300. binding = this._bindings[ firstValidIndex ];
  22301. // and only call .getValue on the first
  22302. if ( binding !== undefined ) binding.getValue( array, offset );
  22303. },
  22304. setValue: function ( array, offset ) {
  22305. var bindings = this._bindings;
  22306. for ( var i = this._targetGroup.nCachedObjects_,
  22307. n = bindings.length; i !== n; ++ i ) {
  22308. bindings[ i ].setValue( array, offset );
  22309. }
  22310. },
  22311. bind: function () {
  22312. var bindings = this._bindings;
  22313. for ( var i = this._targetGroup.nCachedObjects_,
  22314. n = bindings.length; i !== n; ++ i ) {
  22315. bindings[ i ].bind();
  22316. }
  22317. },
  22318. unbind: function () {
  22319. var bindings = this._bindings;
  22320. for ( var i = this._targetGroup.nCachedObjects_,
  22321. n = bindings.length; i !== n; ++ i ) {
  22322. bindings[ i ].unbind();
  22323. }
  22324. }
  22325. } );
  22326. function PropertyBinding( rootNode, path, parsedPath ) {
  22327. this.path = path;
  22328. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22329. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22330. this.rootNode = rootNode;
  22331. }
  22332. Object.assign( PropertyBinding, {
  22333. Composite: Composite,
  22334. create: function ( root, path, parsedPath ) {
  22335. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22336. return new PropertyBinding( root, path, parsedPath );
  22337. } else {
  22338. return new PropertyBinding.Composite( root, path, parsedPath );
  22339. }
  22340. },
  22341. /**
  22342. * Replaces spaces with underscores and removes unsupported characters from
  22343. * node names, to ensure compatibility with parseTrackName().
  22344. *
  22345. * @param {string} name Node name to be sanitized.
  22346. * @return {string}
  22347. */
  22348. sanitizeNodeName: function ( name ) {
  22349. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  22350. },
  22351. parseTrackName: function () {
  22352. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22353. // be matched to parse the rest of the track name.
  22354. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22355. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22356. var nodeRe = /([\w-\.]+)?/;
  22357. // Object on target node, and accessor. Name may contain only word
  22358. // characters. Accessor may contain any character except closing bracket.
  22359. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22360. // Property and accessor. May contain only word characters. Accessor may
  22361. // contain any non-bracket characters.
  22362. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22363. var trackRe = new RegExp(''
  22364. + '^'
  22365. + directoryRe.source
  22366. + nodeRe.source
  22367. + objectRe.source
  22368. + propertyRe.source
  22369. + '$'
  22370. );
  22371. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22372. return function ( trackName ) {
  22373. var matches = trackRe.exec( trackName );
  22374. if ( ! matches ) {
  22375. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22376. }
  22377. var results = {
  22378. // directoryName: matches[ 1 ], // (tschw) currently unused
  22379. nodeName: matches[ 2 ],
  22380. objectName: matches[ 3 ],
  22381. objectIndex: matches[ 4 ],
  22382. propertyName: matches[ 5 ], // required
  22383. propertyIndex: matches[ 6 ]
  22384. };
  22385. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22386. if ( lastDot !== undefined && lastDot !== -1 ) {
  22387. var objectName = results.nodeName.substring( lastDot + 1 );
  22388. // Object names must be checked against a whitelist. Otherwise, there
  22389. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22390. // 'bar' could be the objectName, or part of a nodeName (which can
  22391. // include '.' characters).
  22392. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22393. results.nodeName = results.nodeName.substring( 0, lastDot );
  22394. results.objectName = objectName;
  22395. }
  22396. }
  22397. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22398. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22399. }
  22400. return results;
  22401. };
  22402. }(),
  22403. findNode: function ( root, nodeName ) {
  22404. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22405. return root;
  22406. }
  22407. // search into skeleton bones.
  22408. if ( root.skeleton ) {
  22409. var searchSkeleton = function ( skeleton ) {
  22410. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22411. var bone = skeleton.bones[ i ];
  22412. if ( bone.name === nodeName ) {
  22413. return bone;
  22414. }
  22415. }
  22416. return null;
  22417. };
  22418. var bone = searchSkeleton( root.skeleton );
  22419. if ( bone ) {
  22420. return bone;
  22421. }
  22422. }
  22423. // search into node subtree.
  22424. if ( root.children ) {
  22425. var searchNodeSubtree = function ( children ) {
  22426. for ( var i = 0; i < children.length; i ++ ) {
  22427. var childNode = children[ i ];
  22428. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22429. return childNode;
  22430. }
  22431. var result = searchNodeSubtree( childNode.children );
  22432. if ( result ) return result;
  22433. }
  22434. return null;
  22435. };
  22436. var subTreeNode = searchNodeSubtree( root.children );
  22437. if ( subTreeNode ) {
  22438. return subTreeNode;
  22439. }
  22440. }
  22441. return null;
  22442. }
  22443. } );
  22444. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22445. // these are used to "bind" a nonexistent property
  22446. _getValue_unavailable: function () {},
  22447. _setValue_unavailable: function () {},
  22448. BindingType: {
  22449. Direct: 0,
  22450. EntireArray: 1,
  22451. ArrayElement: 2,
  22452. HasFromToArray: 3
  22453. },
  22454. Versioning: {
  22455. None: 0,
  22456. NeedsUpdate: 1,
  22457. MatrixWorldNeedsUpdate: 2
  22458. },
  22459. GetterByBindingType: [
  22460. function getValue_direct( buffer, offset ) {
  22461. buffer[ offset ] = this.node[ this.propertyName ];
  22462. },
  22463. function getValue_array( buffer, offset ) {
  22464. var source = this.resolvedProperty;
  22465. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22466. buffer[ offset ++ ] = source[ i ];
  22467. }
  22468. },
  22469. function getValue_arrayElement( buffer, offset ) {
  22470. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22471. },
  22472. function getValue_toArray( buffer, offset ) {
  22473. this.resolvedProperty.toArray( buffer, offset );
  22474. }
  22475. ],
  22476. SetterByBindingTypeAndVersioning: [
  22477. [
  22478. // Direct
  22479. function setValue_direct( buffer, offset ) {
  22480. this.node[ this.propertyName ] = buffer[ offset ];
  22481. },
  22482. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22483. this.node[ this.propertyName ] = buffer[ offset ];
  22484. this.targetObject.needsUpdate = true;
  22485. },
  22486. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22487. this.node[ this.propertyName ] = buffer[ offset ];
  22488. this.targetObject.matrixWorldNeedsUpdate = true;
  22489. }
  22490. ], [
  22491. // EntireArray
  22492. function setValue_array( buffer, offset ) {
  22493. var dest = this.resolvedProperty;
  22494. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22495. dest[ i ] = buffer[ offset ++ ];
  22496. }
  22497. },
  22498. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22499. var dest = this.resolvedProperty;
  22500. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22501. dest[ i ] = buffer[ offset ++ ];
  22502. }
  22503. this.targetObject.needsUpdate = true;
  22504. },
  22505. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22506. var dest = this.resolvedProperty;
  22507. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22508. dest[ i ] = buffer[ offset ++ ];
  22509. }
  22510. this.targetObject.matrixWorldNeedsUpdate = true;
  22511. }
  22512. ], [
  22513. // ArrayElement
  22514. function setValue_arrayElement( buffer, offset ) {
  22515. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22516. },
  22517. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22518. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22519. this.targetObject.needsUpdate = true;
  22520. },
  22521. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22522. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22523. this.targetObject.matrixWorldNeedsUpdate = true;
  22524. }
  22525. ], [
  22526. // HasToFromArray
  22527. function setValue_fromArray( buffer, offset ) {
  22528. this.resolvedProperty.fromArray( buffer, offset );
  22529. },
  22530. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22531. this.resolvedProperty.fromArray( buffer, offset );
  22532. this.targetObject.needsUpdate = true;
  22533. },
  22534. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22535. this.resolvedProperty.fromArray( buffer, offset );
  22536. this.targetObject.matrixWorldNeedsUpdate = true;
  22537. }
  22538. ]
  22539. ],
  22540. getValue: function getValue_unbound( targetArray, offset ) {
  22541. this.bind();
  22542. this.getValue( targetArray, offset );
  22543. // Note: This class uses a State pattern on a per-method basis:
  22544. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22545. // prototype version of these methods with one that represents
  22546. // the bound state. When the property is not found, the methods
  22547. // become no-ops.
  22548. },
  22549. setValue: function getValue_unbound( sourceArray, offset ) {
  22550. this.bind();
  22551. this.setValue( sourceArray, offset );
  22552. },
  22553. // create getter / setter pair for a property in the scene graph
  22554. bind: function () {
  22555. var targetObject = this.node,
  22556. parsedPath = this.parsedPath,
  22557. objectName = parsedPath.objectName,
  22558. propertyName = parsedPath.propertyName,
  22559. propertyIndex = parsedPath.propertyIndex;
  22560. if ( ! targetObject ) {
  22561. targetObject = PropertyBinding.findNode(
  22562. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22563. this.node = targetObject;
  22564. }
  22565. // set fail state so we can just 'return' on error
  22566. this.getValue = this._getValue_unavailable;
  22567. this.setValue = this._setValue_unavailable;
  22568. // ensure there is a value node
  22569. if ( ! targetObject ) {
  22570. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  22571. return;
  22572. }
  22573. if ( objectName ) {
  22574. var objectIndex = parsedPath.objectIndex;
  22575. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22576. switch ( objectName ) {
  22577. case 'materials':
  22578. if ( ! targetObject.material ) {
  22579. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  22580. return;
  22581. }
  22582. if ( ! targetObject.material.materials ) {
  22583. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  22584. return;
  22585. }
  22586. targetObject = targetObject.material.materials;
  22587. break;
  22588. case 'bones':
  22589. if ( ! targetObject.skeleton ) {
  22590. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  22591. return;
  22592. }
  22593. // potential future optimization: skip this if propertyIndex is already an integer
  22594. // and convert the integer string to a true integer.
  22595. targetObject = targetObject.skeleton.bones;
  22596. // support resolving morphTarget names into indices.
  22597. for ( var i = 0; i < targetObject.length; i ++ ) {
  22598. if ( targetObject[ i ].name === objectIndex ) {
  22599. objectIndex = i;
  22600. break;
  22601. }
  22602. }
  22603. break;
  22604. default:
  22605. if ( targetObject[ objectName ] === undefined ) {
  22606. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  22607. return;
  22608. }
  22609. targetObject = targetObject[ objectName ];
  22610. }
  22611. if ( objectIndex !== undefined ) {
  22612. if ( targetObject[ objectIndex ] === undefined ) {
  22613. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  22614. return;
  22615. }
  22616. targetObject = targetObject[ objectIndex ];
  22617. }
  22618. }
  22619. // resolve property
  22620. var nodeProperty = targetObject[ propertyName ];
  22621. if ( nodeProperty === undefined ) {
  22622. var nodeName = parsedPath.nodeName;
  22623. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  22624. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  22625. return;
  22626. }
  22627. // determine versioning scheme
  22628. var versioning = this.Versioning.None;
  22629. if ( targetObject.needsUpdate !== undefined ) { // material
  22630. versioning = this.Versioning.NeedsUpdate;
  22631. this.targetObject = targetObject;
  22632. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22633. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22634. this.targetObject = targetObject;
  22635. }
  22636. // determine how the property gets bound
  22637. var bindingType = this.BindingType.Direct;
  22638. if ( propertyIndex !== undefined ) {
  22639. // access a sub element of the property array (only primitives are supported right now)
  22640. if ( propertyName === "morphTargetInfluences" ) {
  22641. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22642. // support resolving morphTarget names into indices.
  22643. if ( ! targetObject.geometry ) {
  22644. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  22645. return;
  22646. }
  22647. if ( targetObject.geometry.isBufferGeometry ) {
  22648. if ( ! targetObject.geometry.morphAttributes ) {
  22649. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  22650. return;
  22651. }
  22652. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  22653. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  22654. propertyIndex = i;
  22655. break;
  22656. }
  22657. }
  22658. } else {
  22659. if ( ! targetObject.geometry.morphTargets ) {
  22660. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  22661. return;
  22662. }
  22663. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22664. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22665. propertyIndex = i;
  22666. break;
  22667. }
  22668. }
  22669. }
  22670. }
  22671. bindingType = this.BindingType.ArrayElement;
  22672. this.resolvedProperty = nodeProperty;
  22673. this.propertyIndex = propertyIndex;
  22674. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22675. // must use copy for Object3D.Euler/Quaternion
  22676. bindingType = this.BindingType.HasFromToArray;
  22677. this.resolvedProperty = nodeProperty;
  22678. } else if ( Array.isArray( nodeProperty ) ) {
  22679. bindingType = this.BindingType.EntireArray;
  22680. this.resolvedProperty = nodeProperty;
  22681. } else {
  22682. this.propertyName = propertyName;
  22683. }
  22684. // select getter / setter
  22685. this.getValue = this.GetterByBindingType[ bindingType ];
  22686. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22687. },
  22688. unbind: function () {
  22689. this.node = null;
  22690. // back to the prototype version of getValue / setValue
  22691. // note: avoiding to mutate the shape of 'this' via 'delete'
  22692. this.getValue = this._getValue_unbound;
  22693. this.setValue = this._setValue_unbound;
  22694. }
  22695. } );
  22696. //!\ DECLARE ALIAS AFTER assign prototype !
  22697. Object.assign( PropertyBinding.prototype, {
  22698. // initial state of these methods that calls 'bind'
  22699. _getValue_unbound: PropertyBinding.prototype.getValue,
  22700. _setValue_unbound: PropertyBinding.prototype.setValue,
  22701. } );
  22702. /**
  22703. *
  22704. * A group of objects that receives a shared animation state.
  22705. *
  22706. * Usage:
  22707. *
  22708. * - Add objects you would otherwise pass as 'root' to the
  22709. * constructor or the .clipAction method of AnimationMixer.
  22710. *
  22711. * - Instead pass this object as 'root'.
  22712. *
  22713. * - You can also add and remove objects later when the mixer
  22714. * is running.
  22715. *
  22716. * Note:
  22717. *
  22718. * Objects of this class appear as one object to the mixer,
  22719. * so cache control of the individual objects must be done
  22720. * on the group.
  22721. *
  22722. * Limitation:
  22723. *
  22724. * - The animated properties must be compatible among the
  22725. * all objects in the group.
  22726. *
  22727. * - A single property can either be controlled through a
  22728. * target group or directly, but not both.
  22729. *
  22730. * @author tschw
  22731. */
  22732. function AnimationObjectGroup( var_args ) {
  22733. this.uuid = _Math.generateUUID();
  22734. // cached objects followed by the active ones
  22735. this._objects = Array.prototype.slice.call( arguments );
  22736. this.nCachedObjects_ = 0; // threshold
  22737. // note: read by PropertyBinding.Composite
  22738. var indices = {};
  22739. this._indicesByUUID = indices; // for bookkeeping
  22740. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22741. indices[ arguments[ i ].uuid ] = i;
  22742. }
  22743. this._paths = []; // inside: string
  22744. this._parsedPaths = []; // inside: { we don't care, here }
  22745. this._bindings = []; // inside: Array< PropertyBinding >
  22746. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22747. var scope = this;
  22748. this.stats = {
  22749. objects: {
  22750. get total() { return scope._objects.length; },
  22751. get inUse() { return this.total - scope.nCachedObjects_; }
  22752. },
  22753. get bindingsPerObject() { return scope._bindings.length; }
  22754. };
  22755. }
  22756. Object.assign( AnimationObjectGroup.prototype, {
  22757. isAnimationObjectGroup: true,
  22758. add: function( var_args ) {
  22759. var objects = this._objects,
  22760. nObjects = objects.length,
  22761. nCachedObjects = this.nCachedObjects_,
  22762. indicesByUUID = this._indicesByUUID,
  22763. paths = this._paths,
  22764. parsedPaths = this._parsedPaths,
  22765. bindings = this._bindings,
  22766. nBindings = bindings.length;
  22767. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22768. var object = arguments[ i ],
  22769. uuid = object.uuid,
  22770. index = indicesByUUID[ uuid ],
  22771. knownObject = undefined;
  22772. if ( index === undefined ) {
  22773. // unknown object -> add it to the ACTIVE region
  22774. index = nObjects ++;
  22775. indicesByUUID[ uuid ] = index;
  22776. objects.push( object );
  22777. // accounting is done, now do the same for all bindings
  22778. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22779. bindings[ j ].push(
  22780. new PropertyBinding(
  22781. object, paths[ j ], parsedPaths[ j ] ) );
  22782. }
  22783. } else if ( index < nCachedObjects ) {
  22784. knownObject = objects[ index ];
  22785. // move existing object to the ACTIVE region
  22786. var firstActiveIndex = -- nCachedObjects,
  22787. lastCachedObject = objects[ firstActiveIndex ];
  22788. indicesByUUID[ lastCachedObject.uuid ] = index;
  22789. objects[ index ] = lastCachedObject;
  22790. indicesByUUID[ uuid ] = firstActiveIndex;
  22791. objects[ firstActiveIndex ] = object;
  22792. // accounting is done, now do the same for all bindings
  22793. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22794. var bindingsForPath = bindings[ j ],
  22795. lastCached = bindingsForPath[ firstActiveIndex ],
  22796. binding = bindingsForPath[ index ];
  22797. bindingsForPath[ index ] = lastCached;
  22798. if ( binding === undefined ) {
  22799. // since we do not bother to create new bindings
  22800. // for objects that are cached, the binding may
  22801. // or may not exist
  22802. binding = new PropertyBinding(
  22803. object, paths[ j ], parsedPaths[ j ] );
  22804. }
  22805. bindingsForPath[ firstActiveIndex ] = binding;
  22806. }
  22807. } else if ( objects[ index ] !== knownObject ) {
  22808. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  22809. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  22810. } // else the object is already where we want it to be
  22811. } // for arguments
  22812. this.nCachedObjects_ = nCachedObjects;
  22813. },
  22814. remove: function( var_args ) {
  22815. var objects = this._objects,
  22816. nCachedObjects = this.nCachedObjects_,
  22817. indicesByUUID = this._indicesByUUID,
  22818. bindings = this._bindings,
  22819. nBindings = bindings.length;
  22820. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22821. var object = arguments[ i ],
  22822. uuid = object.uuid,
  22823. index = indicesByUUID[ uuid ];
  22824. if ( index !== undefined && index >= nCachedObjects ) {
  22825. // move existing object into the CACHED region
  22826. var lastCachedIndex = nCachedObjects ++,
  22827. firstActiveObject = objects[ lastCachedIndex ];
  22828. indicesByUUID[ firstActiveObject.uuid ] = index;
  22829. objects[ index ] = firstActiveObject;
  22830. indicesByUUID[ uuid ] = lastCachedIndex;
  22831. objects[ lastCachedIndex ] = object;
  22832. // accounting is done, now do the same for all bindings
  22833. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22834. var bindingsForPath = bindings[ j ],
  22835. firstActive = bindingsForPath[ lastCachedIndex ],
  22836. binding = bindingsForPath[ index ];
  22837. bindingsForPath[ index ] = firstActive;
  22838. bindingsForPath[ lastCachedIndex ] = binding;
  22839. }
  22840. }
  22841. } // for arguments
  22842. this.nCachedObjects_ = nCachedObjects;
  22843. },
  22844. // remove & forget
  22845. uncache: function( var_args ) {
  22846. var objects = this._objects,
  22847. nObjects = objects.length,
  22848. nCachedObjects = this.nCachedObjects_,
  22849. indicesByUUID = this._indicesByUUID,
  22850. bindings = this._bindings,
  22851. nBindings = bindings.length;
  22852. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22853. var object = arguments[ i ],
  22854. uuid = object.uuid,
  22855. index = indicesByUUID[ uuid ];
  22856. if ( index !== undefined ) {
  22857. delete indicesByUUID[ uuid ];
  22858. if ( index < nCachedObjects ) {
  22859. // object is cached, shrink the CACHED region
  22860. var firstActiveIndex = -- nCachedObjects,
  22861. lastCachedObject = objects[ firstActiveIndex ],
  22862. lastIndex = -- nObjects,
  22863. lastObject = objects[ lastIndex ];
  22864. // last cached object takes this object's place
  22865. indicesByUUID[ lastCachedObject.uuid ] = index;
  22866. objects[ index ] = lastCachedObject;
  22867. // last object goes to the activated slot and pop
  22868. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22869. objects[ firstActiveIndex ] = lastObject;
  22870. objects.pop();
  22871. // accounting is done, now do the same for all bindings
  22872. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22873. var bindingsForPath = bindings[ j ],
  22874. lastCached = bindingsForPath[ firstActiveIndex ],
  22875. last = bindingsForPath[ lastIndex ];
  22876. bindingsForPath[ index ] = lastCached;
  22877. bindingsForPath[ firstActiveIndex ] = last;
  22878. bindingsForPath.pop();
  22879. }
  22880. } else {
  22881. // object is active, just swap with the last and pop
  22882. var lastIndex = -- nObjects,
  22883. lastObject = objects[ lastIndex ];
  22884. indicesByUUID[ lastObject.uuid ] = index;
  22885. objects[ index ] = lastObject;
  22886. objects.pop();
  22887. // accounting is done, now do the same for all bindings
  22888. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22889. var bindingsForPath = bindings[ j ];
  22890. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22891. bindingsForPath.pop();
  22892. }
  22893. } // cached or active
  22894. } // if object is known
  22895. } // for arguments
  22896. this.nCachedObjects_ = nCachedObjects;
  22897. },
  22898. // Internal interface used by befriended PropertyBinding.Composite:
  22899. subscribe_: function ( path, parsedPath ) {
  22900. // returns an array of bindings for the given path that is changed
  22901. // according to the contained objects in the group
  22902. var indicesByPath = this._bindingsIndicesByPath,
  22903. index = indicesByPath[ path ],
  22904. bindings = this._bindings;
  22905. if ( index !== undefined ) return bindings[ index ];
  22906. var paths = this._paths,
  22907. parsedPaths = this._parsedPaths,
  22908. objects = this._objects,
  22909. nObjects = objects.length,
  22910. nCachedObjects = this.nCachedObjects_,
  22911. bindingsForPath = new Array( nObjects );
  22912. index = bindings.length;
  22913. indicesByPath[ path ] = index;
  22914. paths.push( path );
  22915. parsedPaths.push( parsedPath );
  22916. bindings.push( bindingsForPath );
  22917. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22918. var object = objects[ i ];
  22919. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22920. }
  22921. return bindingsForPath;
  22922. },
  22923. unsubscribe_: function ( path ) {
  22924. // tells the group to forget about a property path and no longer
  22925. // update the array previously obtained with 'subscribe_'
  22926. var indicesByPath = this._bindingsIndicesByPath,
  22927. index = indicesByPath[ path ];
  22928. if ( index !== undefined ) {
  22929. var paths = this._paths,
  22930. parsedPaths = this._parsedPaths,
  22931. bindings = this._bindings,
  22932. lastBindingsIndex = bindings.length - 1,
  22933. lastBindings = bindings[ lastBindingsIndex ],
  22934. lastBindingsPath = path[ lastBindingsIndex ];
  22935. indicesByPath[ lastBindingsPath ] = index;
  22936. bindings[ index ] = lastBindings;
  22937. bindings.pop();
  22938. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22939. parsedPaths.pop();
  22940. paths[ index ] = paths[ lastBindingsIndex ];
  22941. paths.pop();
  22942. }
  22943. }
  22944. } );
  22945. /**
  22946. *
  22947. * Action provided by AnimationMixer for scheduling clip playback on specific
  22948. * objects.
  22949. *
  22950. * @author Ben Houston / http://clara.io/
  22951. * @author David Sarno / http://lighthaus.us/
  22952. * @author tschw
  22953. *
  22954. */
  22955. function AnimationAction( mixer, clip, localRoot ) {
  22956. this._mixer = mixer;
  22957. this._clip = clip;
  22958. this._localRoot = localRoot || null;
  22959. var tracks = clip.tracks,
  22960. nTracks = tracks.length,
  22961. interpolants = new Array( nTracks );
  22962. var interpolantSettings = {
  22963. endingStart: ZeroCurvatureEnding,
  22964. endingEnd: ZeroCurvatureEnding
  22965. };
  22966. for ( var i = 0; i !== nTracks; ++ i ) {
  22967. var interpolant = tracks[ i ].createInterpolant( null );
  22968. interpolants[ i ] = interpolant;
  22969. interpolant.settings = interpolantSettings;
  22970. }
  22971. this._interpolantSettings = interpolantSettings;
  22972. this._interpolants = interpolants; // bound by the mixer
  22973. // inside: PropertyMixer (managed by the mixer)
  22974. this._propertyBindings = new Array( nTracks );
  22975. this._cacheIndex = null; // for the memory manager
  22976. this._byClipCacheIndex = null; // for the memory manager
  22977. this._timeScaleInterpolant = null;
  22978. this._weightInterpolant = null;
  22979. this.loop = LoopRepeat;
  22980. this._loopCount = -1;
  22981. // global mixer time when the action is to be started
  22982. // it's set back to 'null' upon start of the action
  22983. this._startTime = null;
  22984. // scaled local time of the action
  22985. // gets clamped or wrapped to 0..clip.duration according to loop
  22986. this.time = 0;
  22987. this.timeScale = 1;
  22988. this._effectiveTimeScale = 1;
  22989. this.weight = 1;
  22990. this._effectiveWeight = 1;
  22991. this.repetitions = Infinity; // no. of repetitions when looping
  22992. this.paused = false; // true -> zero effective time scale
  22993. this.enabled = true; // false -> zero effective weight
  22994. this.clampWhenFinished = false; // keep feeding the last frame?
  22995. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22996. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22997. }
  22998. Object.assign( AnimationAction.prototype, {
  22999. // State & Scheduling
  23000. play: function() {
  23001. this._mixer._activateAction( this );
  23002. return this;
  23003. },
  23004. stop: function() {
  23005. this._mixer._deactivateAction( this );
  23006. return this.reset();
  23007. },
  23008. reset: function() {
  23009. this.paused = false;
  23010. this.enabled = true;
  23011. this.time = 0; // restart clip
  23012. this._loopCount = -1; // forget previous loops
  23013. this._startTime = null; // forget scheduling
  23014. return this.stopFading().stopWarping();
  23015. },
  23016. isRunning: function() {
  23017. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  23018. this._startTime === null && this._mixer._isActiveAction( this );
  23019. },
  23020. // return true when play has been called
  23021. isScheduled: function() {
  23022. return this._mixer._isActiveAction( this );
  23023. },
  23024. startAt: function( time ) {
  23025. this._startTime = time;
  23026. return this;
  23027. },
  23028. setLoop: function( mode, repetitions ) {
  23029. this.loop = mode;
  23030. this.repetitions = repetitions;
  23031. return this;
  23032. },
  23033. // Weight
  23034. // set the weight stopping any scheduled fading
  23035. // although .enabled = false yields an effective weight of zero, this
  23036. // method does *not* change .enabled, because it would be confusing
  23037. setEffectiveWeight: function( weight ) {
  23038. this.weight = weight;
  23039. // note: same logic as when updated at runtime
  23040. this._effectiveWeight = this.enabled ? weight : 0;
  23041. return this.stopFading();
  23042. },
  23043. // return the weight considering fading and .enabled
  23044. getEffectiveWeight: function() {
  23045. return this._effectiveWeight;
  23046. },
  23047. fadeIn: function( duration ) {
  23048. return this._scheduleFading( duration, 0, 1 );
  23049. },
  23050. fadeOut: function( duration ) {
  23051. return this._scheduleFading( duration, 1, 0 );
  23052. },
  23053. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  23054. fadeOutAction.fadeOut( duration );
  23055. this.fadeIn( duration );
  23056. if( warp ) {
  23057. var fadeInDuration = this._clip.duration,
  23058. fadeOutDuration = fadeOutAction._clip.duration,
  23059. startEndRatio = fadeOutDuration / fadeInDuration,
  23060. endStartRatio = fadeInDuration / fadeOutDuration;
  23061. fadeOutAction.warp( 1.0, startEndRatio, duration );
  23062. this.warp( endStartRatio, 1.0, duration );
  23063. }
  23064. return this;
  23065. },
  23066. crossFadeTo: function( fadeInAction, duration, warp ) {
  23067. return fadeInAction.crossFadeFrom( this, duration, warp );
  23068. },
  23069. stopFading: function() {
  23070. var weightInterpolant = this._weightInterpolant;
  23071. if ( weightInterpolant !== null ) {
  23072. this._weightInterpolant = null;
  23073. this._mixer._takeBackControlInterpolant( weightInterpolant );
  23074. }
  23075. return this;
  23076. },
  23077. // Time Scale Control
  23078. // set the time scale stopping any scheduled warping
  23079. // although .paused = true yields an effective time scale of zero, this
  23080. // method does *not* change .paused, because it would be confusing
  23081. setEffectiveTimeScale: function( timeScale ) {
  23082. this.timeScale = timeScale;
  23083. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  23084. return this.stopWarping();
  23085. },
  23086. // return the time scale considering warping and .paused
  23087. getEffectiveTimeScale: function() {
  23088. return this._effectiveTimeScale;
  23089. },
  23090. setDuration: function( duration ) {
  23091. this.timeScale = this._clip.duration / duration;
  23092. return this.stopWarping();
  23093. },
  23094. syncWith: function( action ) {
  23095. this.time = action.time;
  23096. this.timeScale = action.timeScale;
  23097. return this.stopWarping();
  23098. },
  23099. halt: function( duration ) {
  23100. return this.warp( this._effectiveTimeScale, 0, duration );
  23101. },
  23102. warp: function( startTimeScale, endTimeScale, duration ) {
  23103. var mixer = this._mixer, now = mixer.time,
  23104. interpolant = this._timeScaleInterpolant,
  23105. timeScale = this.timeScale;
  23106. if ( interpolant === null ) {
  23107. interpolant = mixer._lendControlInterpolant();
  23108. this._timeScaleInterpolant = interpolant;
  23109. }
  23110. var times = interpolant.parameterPositions,
  23111. values = interpolant.sampleValues;
  23112. times[ 0 ] = now;
  23113. times[ 1 ] = now + duration;
  23114. values[ 0 ] = startTimeScale / timeScale;
  23115. values[ 1 ] = endTimeScale / timeScale;
  23116. return this;
  23117. },
  23118. stopWarping: function() {
  23119. var timeScaleInterpolant = this._timeScaleInterpolant;
  23120. if ( timeScaleInterpolant !== null ) {
  23121. this._timeScaleInterpolant = null;
  23122. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  23123. }
  23124. return this;
  23125. },
  23126. // Object Accessors
  23127. getMixer: function() {
  23128. return this._mixer;
  23129. },
  23130. getClip: function() {
  23131. return this._clip;
  23132. },
  23133. getRoot: function() {
  23134. return this._localRoot || this._mixer._root;
  23135. },
  23136. // Interna
  23137. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  23138. // called by the mixer
  23139. if ( ! this.enabled ) {
  23140. // call ._updateWeight() to update ._effectiveWeight
  23141. this._updateWeight( time );
  23142. return;
  23143. }
  23144. var startTime = this._startTime;
  23145. if ( startTime !== null ) {
  23146. // check for scheduled start of action
  23147. var timeRunning = ( time - startTime ) * timeDirection;
  23148. if ( timeRunning < 0 || timeDirection === 0 ) {
  23149. return; // yet to come / don't decide when delta = 0
  23150. }
  23151. // start
  23152. this._startTime = null; // unschedule
  23153. deltaTime = timeDirection * timeRunning;
  23154. }
  23155. // apply time scale and advance time
  23156. deltaTime *= this._updateTimeScale( time );
  23157. var clipTime = this._updateTime( deltaTime );
  23158. // note: _updateTime may disable the action resulting in
  23159. // an effective weight of 0
  23160. var weight = this._updateWeight( time );
  23161. if ( weight > 0 ) {
  23162. var interpolants = this._interpolants;
  23163. var propertyMixers = this._propertyBindings;
  23164. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  23165. interpolants[ j ].evaluate( clipTime );
  23166. propertyMixers[ j ].accumulate( accuIndex, weight );
  23167. }
  23168. }
  23169. },
  23170. _updateWeight: function( time ) {
  23171. var weight = 0;
  23172. if ( this.enabled ) {
  23173. weight = this.weight;
  23174. var interpolant = this._weightInterpolant;
  23175. if ( interpolant !== null ) {
  23176. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23177. weight *= interpolantValue;
  23178. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23179. this.stopFading();
  23180. if ( interpolantValue === 0 ) {
  23181. // faded out, disable
  23182. this.enabled = false;
  23183. }
  23184. }
  23185. }
  23186. }
  23187. this._effectiveWeight = weight;
  23188. return weight;
  23189. },
  23190. _updateTimeScale: function( time ) {
  23191. var timeScale = 0;
  23192. if ( ! this.paused ) {
  23193. timeScale = this.timeScale;
  23194. var interpolant = this._timeScaleInterpolant;
  23195. if ( interpolant !== null ) {
  23196. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  23197. timeScale *= interpolantValue;
  23198. if ( time > interpolant.parameterPositions[ 1 ] ) {
  23199. this.stopWarping();
  23200. if ( timeScale === 0 ) {
  23201. // motion has halted, pause
  23202. this.paused = true;
  23203. } else {
  23204. // warp done - apply final time scale
  23205. this.timeScale = timeScale;
  23206. }
  23207. }
  23208. }
  23209. }
  23210. this._effectiveTimeScale = timeScale;
  23211. return timeScale;
  23212. },
  23213. _updateTime: function( deltaTime ) {
  23214. var time = this.time + deltaTime;
  23215. if ( deltaTime === 0 ) return time;
  23216. var duration = this._clip.duration,
  23217. loop = this.loop,
  23218. loopCount = this._loopCount;
  23219. if ( loop === LoopOnce ) {
  23220. if ( loopCount === -1 ) {
  23221. // just started
  23222. this._loopCount = 0;
  23223. this._setEndings( true, true, false );
  23224. }
  23225. handle_stop: {
  23226. if ( time >= duration ) {
  23227. time = duration;
  23228. } else if ( time < 0 ) {
  23229. time = 0;
  23230. } else break handle_stop;
  23231. if ( this.clampWhenFinished ) this.paused = true;
  23232. else this.enabled = false;
  23233. this._mixer.dispatchEvent( {
  23234. type: 'finished', action: this,
  23235. direction: deltaTime < 0 ? -1 : 1
  23236. } );
  23237. }
  23238. } else { // repetitive Repeat or PingPong
  23239. var pingPong = ( loop === LoopPingPong );
  23240. if ( loopCount === -1 ) {
  23241. // just started
  23242. if ( deltaTime >= 0 ) {
  23243. loopCount = 0;
  23244. this._setEndings(
  23245. true, this.repetitions === 0, pingPong );
  23246. } else {
  23247. // when looping in reverse direction, the initial
  23248. // transition through zero counts as a repetition,
  23249. // so leave loopCount at -1
  23250. this._setEndings(
  23251. this.repetitions === 0, true, pingPong );
  23252. }
  23253. }
  23254. if ( time >= duration || time < 0 ) {
  23255. // wrap around
  23256. var loopDelta = Math.floor( time / duration ); // signed
  23257. time -= duration * loopDelta;
  23258. loopCount += Math.abs( loopDelta );
  23259. var pending = this.repetitions - loopCount;
  23260. if ( pending < 0 ) {
  23261. // have to stop (switch state, clamp time, fire event)
  23262. if ( this.clampWhenFinished ) this.paused = true;
  23263. else this.enabled = false;
  23264. time = deltaTime > 0 ? duration : 0;
  23265. this._mixer.dispatchEvent( {
  23266. type: 'finished', action: this,
  23267. direction: deltaTime > 0 ? 1 : -1
  23268. } );
  23269. } else {
  23270. // keep running
  23271. if ( pending === 0 ) {
  23272. // entering the last round
  23273. var atStart = deltaTime < 0;
  23274. this._setEndings( atStart, ! atStart, pingPong );
  23275. } else {
  23276. this._setEndings( false, false, pingPong );
  23277. }
  23278. this._loopCount = loopCount;
  23279. this._mixer.dispatchEvent( {
  23280. type: 'loop', action: this, loopDelta: loopDelta
  23281. } );
  23282. }
  23283. }
  23284. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  23285. // invert time for the "pong round"
  23286. this.time = time;
  23287. return duration - time;
  23288. }
  23289. }
  23290. this.time = time;
  23291. return time;
  23292. },
  23293. _setEndings: function( atStart, atEnd, pingPong ) {
  23294. var settings = this._interpolantSettings;
  23295. if ( pingPong ) {
  23296. settings.endingStart = ZeroSlopeEnding;
  23297. settings.endingEnd = ZeroSlopeEnding;
  23298. } else {
  23299. // assuming for LoopOnce atStart == atEnd == true
  23300. if ( atStart ) {
  23301. settings.endingStart = this.zeroSlopeAtStart ?
  23302. ZeroSlopeEnding : ZeroCurvatureEnding;
  23303. } else {
  23304. settings.endingStart = WrapAroundEnding;
  23305. }
  23306. if ( atEnd ) {
  23307. settings.endingEnd = this.zeroSlopeAtEnd ?
  23308. ZeroSlopeEnding : ZeroCurvatureEnding;
  23309. } else {
  23310. settings.endingEnd = WrapAroundEnding;
  23311. }
  23312. }
  23313. },
  23314. _scheduleFading: function( duration, weightNow, weightThen ) {
  23315. var mixer = this._mixer, now = mixer.time,
  23316. interpolant = this._weightInterpolant;
  23317. if ( interpolant === null ) {
  23318. interpolant = mixer._lendControlInterpolant();
  23319. this._weightInterpolant = interpolant;
  23320. }
  23321. var times = interpolant.parameterPositions,
  23322. values = interpolant.sampleValues;
  23323. times[ 0 ] = now; values[ 0 ] = weightNow;
  23324. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23325. return this;
  23326. }
  23327. } );
  23328. /**
  23329. *
  23330. * Player for AnimationClips.
  23331. *
  23332. *
  23333. * @author Ben Houston / http://clara.io/
  23334. * @author David Sarno / http://lighthaus.us/
  23335. * @author tschw
  23336. */
  23337. function AnimationMixer( root ) {
  23338. this._root = root;
  23339. this._initMemoryManager();
  23340. this._accuIndex = 0;
  23341. this.time = 0;
  23342. this.timeScale = 1.0;
  23343. }
  23344. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23345. _bindAction: function ( action, prototypeAction ) {
  23346. var root = action._localRoot || this._root,
  23347. tracks = action._clip.tracks,
  23348. nTracks = tracks.length,
  23349. bindings = action._propertyBindings,
  23350. interpolants = action._interpolants,
  23351. rootUuid = root.uuid,
  23352. bindingsByRoot = this._bindingsByRootAndName,
  23353. bindingsByName = bindingsByRoot[ rootUuid ];
  23354. if ( bindingsByName === undefined ) {
  23355. bindingsByName = {};
  23356. bindingsByRoot[ rootUuid ] = bindingsByName;
  23357. }
  23358. for ( var i = 0; i !== nTracks; ++ i ) {
  23359. var track = tracks[ i ],
  23360. trackName = track.name,
  23361. binding = bindingsByName[ trackName ];
  23362. if ( binding !== undefined ) {
  23363. bindings[ i ] = binding;
  23364. } else {
  23365. binding = bindings[ i ];
  23366. if ( binding !== undefined ) {
  23367. // existing binding, make sure the cache knows
  23368. if ( binding._cacheIndex === null ) {
  23369. ++ binding.referenceCount;
  23370. this._addInactiveBinding( binding, rootUuid, trackName );
  23371. }
  23372. continue;
  23373. }
  23374. var path = prototypeAction && prototypeAction.
  23375. _propertyBindings[ i ].binding.parsedPath;
  23376. binding = new PropertyMixer(
  23377. PropertyBinding.create( root, trackName, path ),
  23378. track.ValueTypeName, track.getValueSize() );
  23379. ++ binding.referenceCount;
  23380. this._addInactiveBinding( binding, rootUuid, trackName );
  23381. bindings[ i ] = binding;
  23382. }
  23383. interpolants[ i ].resultBuffer = binding.buffer;
  23384. }
  23385. },
  23386. _activateAction: function ( action ) {
  23387. if ( ! this._isActiveAction( action ) ) {
  23388. if ( action._cacheIndex === null ) {
  23389. // this action has been forgotten by the cache, but the user
  23390. // appears to be still using it -> rebind
  23391. var rootUuid = ( action._localRoot || this._root ).uuid,
  23392. clipUuid = action._clip.uuid,
  23393. actionsForClip = this._actionsByClip[ clipUuid ];
  23394. this._bindAction( action,
  23395. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23396. this._addInactiveAction( action, clipUuid, rootUuid );
  23397. }
  23398. var bindings = action._propertyBindings;
  23399. // increment reference counts / sort out state
  23400. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23401. var binding = bindings[ i ];
  23402. if ( binding.useCount ++ === 0 ) {
  23403. this._lendBinding( binding );
  23404. binding.saveOriginalState();
  23405. }
  23406. }
  23407. this._lendAction( action );
  23408. }
  23409. },
  23410. _deactivateAction: function ( action ) {
  23411. if ( this._isActiveAction( action ) ) {
  23412. var bindings = action._propertyBindings;
  23413. // decrement reference counts / sort out state
  23414. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23415. var binding = bindings[ i ];
  23416. if ( -- binding.useCount === 0 ) {
  23417. binding.restoreOriginalState();
  23418. this._takeBackBinding( binding );
  23419. }
  23420. }
  23421. this._takeBackAction( action );
  23422. }
  23423. },
  23424. // Memory manager
  23425. _initMemoryManager: function () {
  23426. this._actions = []; // 'nActiveActions' followed by inactive ones
  23427. this._nActiveActions = 0;
  23428. this._actionsByClip = {};
  23429. // inside:
  23430. // {
  23431. // knownActions: Array< AnimationAction > - used as prototypes
  23432. // actionByRoot: AnimationAction - lookup
  23433. // }
  23434. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23435. this._nActiveBindings = 0;
  23436. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23437. this._controlInterpolants = []; // same game as above
  23438. this._nActiveControlInterpolants = 0;
  23439. var scope = this;
  23440. this.stats = {
  23441. actions: {
  23442. get total() { return scope._actions.length; },
  23443. get inUse() { return scope._nActiveActions; }
  23444. },
  23445. bindings: {
  23446. get total() { return scope._bindings.length; },
  23447. get inUse() { return scope._nActiveBindings; }
  23448. },
  23449. controlInterpolants: {
  23450. get total() { return scope._controlInterpolants.length; },
  23451. get inUse() { return scope._nActiveControlInterpolants; }
  23452. }
  23453. };
  23454. },
  23455. // Memory management for AnimationAction objects
  23456. _isActiveAction: function ( action ) {
  23457. var index = action._cacheIndex;
  23458. return index !== null && index < this._nActiveActions;
  23459. },
  23460. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23461. var actions = this._actions,
  23462. actionsByClip = this._actionsByClip,
  23463. actionsForClip = actionsByClip[ clipUuid ];
  23464. if ( actionsForClip === undefined ) {
  23465. actionsForClip = {
  23466. knownActions: [ action ],
  23467. actionByRoot: {}
  23468. };
  23469. action._byClipCacheIndex = 0;
  23470. actionsByClip[ clipUuid ] = actionsForClip;
  23471. } else {
  23472. var knownActions = actionsForClip.knownActions;
  23473. action._byClipCacheIndex = knownActions.length;
  23474. knownActions.push( action );
  23475. }
  23476. action._cacheIndex = actions.length;
  23477. actions.push( action );
  23478. actionsForClip.actionByRoot[ rootUuid ] = action;
  23479. },
  23480. _removeInactiveAction: function ( action ) {
  23481. var actions = this._actions,
  23482. lastInactiveAction = actions[ actions.length - 1 ],
  23483. cacheIndex = action._cacheIndex;
  23484. lastInactiveAction._cacheIndex = cacheIndex;
  23485. actions[ cacheIndex ] = lastInactiveAction;
  23486. actions.pop();
  23487. action._cacheIndex = null;
  23488. var clipUuid = action._clip.uuid,
  23489. actionsByClip = this._actionsByClip,
  23490. actionsForClip = actionsByClip[ clipUuid ],
  23491. knownActionsForClip = actionsForClip.knownActions,
  23492. lastKnownAction =
  23493. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23494. byClipCacheIndex = action._byClipCacheIndex;
  23495. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23496. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23497. knownActionsForClip.pop();
  23498. action._byClipCacheIndex = null;
  23499. var actionByRoot = actionsForClip.actionByRoot,
  23500. rootUuid = ( action._localRoot || this._root ).uuid;
  23501. delete actionByRoot[ rootUuid ];
  23502. if ( knownActionsForClip.length === 0 ) {
  23503. delete actionsByClip[ clipUuid ];
  23504. }
  23505. this._removeInactiveBindingsForAction( action );
  23506. },
  23507. _removeInactiveBindingsForAction: function ( action ) {
  23508. var bindings = action._propertyBindings;
  23509. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23510. var binding = bindings[ i ];
  23511. if ( -- binding.referenceCount === 0 ) {
  23512. this._removeInactiveBinding( binding );
  23513. }
  23514. }
  23515. },
  23516. _lendAction: function ( action ) {
  23517. // [ active actions | inactive actions ]
  23518. // [ active actions >| inactive actions ]
  23519. // s a
  23520. // <-swap->
  23521. // a s
  23522. var actions = this._actions,
  23523. prevIndex = action._cacheIndex,
  23524. lastActiveIndex = this._nActiveActions ++,
  23525. firstInactiveAction = actions[ lastActiveIndex ];
  23526. action._cacheIndex = lastActiveIndex;
  23527. actions[ lastActiveIndex ] = action;
  23528. firstInactiveAction._cacheIndex = prevIndex;
  23529. actions[ prevIndex ] = firstInactiveAction;
  23530. },
  23531. _takeBackAction: function ( action ) {
  23532. // [ active actions | inactive actions ]
  23533. // [ active actions |< inactive actions ]
  23534. // a s
  23535. // <-swap->
  23536. // s a
  23537. var actions = this._actions,
  23538. prevIndex = action._cacheIndex,
  23539. firstInactiveIndex = -- this._nActiveActions,
  23540. lastActiveAction = actions[ firstInactiveIndex ];
  23541. action._cacheIndex = firstInactiveIndex;
  23542. actions[ firstInactiveIndex ] = action;
  23543. lastActiveAction._cacheIndex = prevIndex;
  23544. actions[ prevIndex ] = lastActiveAction;
  23545. },
  23546. // Memory management for PropertyMixer objects
  23547. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23548. var bindingsByRoot = this._bindingsByRootAndName,
  23549. bindingByName = bindingsByRoot[ rootUuid ],
  23550. bindings = this._bindings;
  23551. if ( bindingByName === undefined ) {
  23552. bindingByName = {};
  23553. bindingsByRoot[ rootUuid ] = bindingByName;
  23554. }
  23555. bindingByName[ trackName ] = binding;
  23556. binding._cacheIndex = bindings.length;
  23557. bindings.push( binding );
  23558. },
  23559. _removeInactiveBinding: function ( binding ) {
  23560. var bindings = this._bindings,
  23561. propBinding = binding.binding,
  23562. rootUuid = propBinding.rootNode.uuid,
  23563. trackName = propBinding.path,
  23564. bindingsByRoot = this._bindingsByRootAndName,
  23565. bindingByName = bindingsByRoot[ rootUuid ],
  23566. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23567. cacheIndex = binding._cacheIndex;
  23568. lastInactiveBinding._cacheIndex = cacheIndex;
  23569. bindings[ cacheIndex ] = lastInactiveBinding;
  23570. bindings.pop();
  23571. delete bindingByName[ trackName ];
  23572. remove_empty_map: {
  23573. for ( var _ in bindingByName ) break remove_empty_map;
  23574. delete bindingsByRoot[ rootUuid ];
  23575. }
  23576. },
  23577. _lendBinding: function ( binding ) {
  23578. var bindings = this._bindings,
  23579. prevIndex = binding._cacheIndex,
  23580. lastActiveIndex = this._nActiveBindings ++,
  23581. firstInactiveBinding = bindings[ lastActiveIndex ];
  23582. binding._cacheIndex = lastActiveIndex;
  23583. bindings[ lastActiveIndex ] = binding;
  23584. firstInactiveBinding._cacheIndex = prevIndex;
  23585. bindings[ prevIndex ] = firstInactiveBinding;
  23586. },
  23587. _takeBackBinding: function ( binding ) {
  23588. var bindings = this._bindings,
  23589. prevIndex = binding._cacheIndex,
  23590. firstInactiveIndex = -- this._nActiveBindings,
  23591. lastActiveBinding = bindings[ firstInactiveIndex ];
  23592. binding._cacheIndex = firstInactiveIndex;
  23593. bindings[ firstInactiveIndex ] = binding;
  23594. lastActiveBinding._cacheIndex = prevIndex;
  23595. bindings[ prevIndex ] = lastActiveBinding;
  23596. },
  23597. // Memory management of Interpolants for weight and time scale
  23598. _lendControlInterpolant: function () {
  23599. var interpolants = this._controlInterpolants,
  23600. lastActiveIndex = this._nActiveControlInterpolants ++,
  23601. interpolant = interpolants[ lastActiveIndex ];
  23602. if ( interpolant === undefined ) {
  23603. interpolant = new LinearInterpolant(
  23604. new Float32Array( 2 ), new Float32Array( 2 ),
  23605. 1, this._controlInterpolantsResultBuffer );
  23606. interpolant.__cacheIndex = lastActiveIndex;
  23607. interpolants[ lastActiveIndex ] = interpolant;
  23608. }
  23609. return interpolant;
  23610. },
  23611. _takeBackControlInterpolant: function ( interpolant ) {
  23612. var interpolants = this._controlInterpolants,
  23613. prevIndex = interpolant.__cacheIndex,
  23614. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23615. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23616. interpolant.__cacheIndex = firstInactiveIndex;
  23617. interpolants[ firstInactiveIndex ] = interpolant;
  23618. lastActiveInterpolant.__cacheIndex = prevIndex;
  23619. interpolants[ prevIndex ] = lastActiveInterpolant;
  23620. },
  23621. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23622. // return an action for a clip optionally using a custom root target
  23623. // object (this method allocates a lot of dynamic memory in case a
  23624. // previously unknown clip/root combination is specified)
  23625. clipAction: function ( clip, optionalRoot ) {
  23626. var root = optionalRoot || this._root,
  23627. rootUuid = root.uuid,
  23628. clipObject = typeof clip === 'string' ?
  23629. AnimationClip.findByName( root, clip ) : clip,
  23630. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23631. actionsForClip = this._actionsByClip[ clipUuid ],
  23632. prototypeAction = null;
  23633. if ( actionsForClip !== undefined ) {
  23634. var existingAction =
  23635. actionsForClip.actionByRoot[ rootUuid ];
  23636. if ( existingAction !== undefined ) {
  23637. return existingAction;
  23638. }
  23639. // we know the clip, so we don't have to parse all
  23640. // the bindings again but can just copy
  23641. prototypeAction = actionsForClip.knownActions[ 0 ];
  23642. // also, take the clip from the prototype action
  23643. if ( clipObject === null )
  23644. clipObject = prototypeAction._clip;
  23645. }
  23646. // clip must be known when specified via string
  23647. if ( clipObject === null ) return null;
  23648. // allocate all resources required to run it
  23649. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23650. this._bindAction( newAction, prototypeAction );
  23651. // and make the action known to the memory manager
  23652. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23653. return newAction;
  23654. },
  23655. // get an existing action
  23656. existingAction: function ( clip, optionalRoot ) {
  23657. var root = optionalRoot || this._root,
  23658. rootUuid = root.uuid,
  23659. clipObject = typeof clip === 'string' ?
  23660. AnimationClip.findByName( root, clip ) : clip,
  23661. clipUuid = clipObject ? clipObject.uuid : clip,
  23662. actionsForClip = this._actionsByClip[ clipUuid ];
  23663. if ( actionsForClip !== undefined ) {
  23664. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23665. }
  23666. return null;
  23667. },
  23668. // deactivates all previously scheduled actions
  23669. stopAllAction: function () {
  23670. var actions = this._actions,
  23671. nActions = this._nActiveActions,
  23672. bindings = this._bindings,
  23673. nBindings = this._nActiveBindings;
  23674. this._nActiveActions = 0;
  23675. this._nActiveBindings = 0;
  23676. for ( var i = 0; i !== nActions; ++ i ) {
  23677. actions[ i ].reset();
  23678. }
  23679. for ( var i = 0; i !== nBindings; ++ i ) {
  23680. bindings[ i ].useCount = 0;
  23681. }
  23682. return this;
  23683. },
  23684. // advance the time and update apply the animation
  23685. update: function ( deltaTime ) {
  23686. deltaTime *= this.timeScale;
  23687. var actions = this._actions,
  23688. nActions = this._nActiveActions,
  23689. time = this.time += deltaTime,
  23690. timeDirection = Math.sign( deltaTime ),
  23691. accuIndex = this._accuIndex ^= 1;
  23692. // run active actions
  23693. for ( var i = 0; i !== nActions; ++ i ) {
  23694. var action = actions[ i ];
  23695. action._update( time, deltaTime, timeDirection, accuIndex );
  23696. }
  23697. // update scene graph
  23698. var bindings = this._bindings,
  23699. nBindings = this._nActiveBindings;
  23700. for ( var i = 0; i !== nBindings; ++ i ) {
  23701. bindings[ i ].apply( accuIndex );
  23702. }
  23703. return this;
  23704. },
  23705. // return this mixer's root target object
  23706. getRoot: function () {
  23707. return this._root;
  23708. },
  23709. // free all resources specific to a particular clip
  23710. uncacheClip: function ( clip ) {
  23711. var actions = this._actions,
  23712. clipUuid = clip.uuid,
  23713. actionsByClip = this._actionsByClip,
  23714. actionsForClip = actionsByClip[ clipUuid ];
  23715. if ( actionsForClip !== undefined ) {
  23716. // note: just calling _removeInactiveAction would mess up the
  23717. // iteration state and also require updating the state we can
  23718. // just throw away
  23719. var actionsToRemove = actionsForClip.knownActions;
  23720. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23721. var action = actionsToRemove[ i ];
  23722. this._deactivateAction( action );
  23723. var cacheIndex = action._cacheIndex,
  23724. lastInactiveAction = actions[ actions.length - 1 ];
  23725. action._cacheIndex = null;
  23726. action._byClipCacheIndex = null;
  23727. lastInactiveAction._cacheIndex = cacheIndex;
  23728. actions[ cacheIndex ] = lastInactiveAction;
  23729. actions.pop();
  23730. this._removeInactiveBindingsForAction( action );
  23731. }
  23732. delete actionsByClip[ clipUuid ];
  23733. }
  23734. },
  23735. // free all resources specific to a particular root target object
  23736. uncacheRoot: function ( root ) {
  23737. var rootUuid = root.uuid,
  23738. actionsByClip = this._actionsByClip;
  23739. for ( var clipUuid in actionsByClip ) {
  23740. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23741. action = actionByRoot[ rootUuid ];
  23742. if ( action !== undefined ) {
  23743. this._deactivateAction( action );
  23744. this._removeInactiveAction( action );
  23745. }
  23746. }
  23747. var bindingsByRoot = this._bindingsByRootAndName,
  23748. bindingByName = bindingsByRoot[ rootUuid ];
  23749. if ( bindingByName !== undefined ) {
  23750. for ( var trackName in bindingByName ) {
  23751. var binding = bindingByName[ trackName ];
  23752. binding.restoreOriginalState();
  23753. this._removeInactiveBinding( binding );
  23754. }
  23755. }
  23756. },
  23757. // remove a targeted clip from the cache
  23758. uncacheAction: function ( clip, optionalRoot ) {
  23759. var action = this.existingAction( clip, optionalRoot );
  23760. if ( action !== null ) {
  23761. this._deactivateAction( action );
  23762. this._removeInactiveAction( action );
  23763. }
  23764. }
  23765. } );
  23766. /**
  23767. * @author mrdoob / http://mrdoob.com/
  23768. */
  23769. function Uniform( value ) {
  23770. if ( typeof value === 'string' ) {
  23771. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23772. value = arguments[ 1 ];
  23773. }
  23774. this.value = value;
  23775. }
  23776. Uniform.prototype.clone = function () {
  23777. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23778. };
  23779. /**
  23780. * @author benaadams / https://twitter.com/ben_a_adams
  23781. */
  23782. function InstancedBufferGeometry() {
  23783. BufferGeometry.call( this );
  23784. this.type = 'InstancedBufferGeometry';
  23785. this.maxInstancedCount = undefined;
  23786. }
  23787. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23788. constructor: InstancedBufferGeometry,
  23789. isInstancedBufferGeometry: true,
  23790. addGroup: function ( start, count, materialIndex ) {
  23791. this.groups.push( {
  23792. start: start,
  23793. count: count,
  23794. materialIndex: materialIndex
  23795. } );
  23796. },
  23797. copy: function ( source ) {
  23798. var index = source.index;
  23799. if ( index !== null ) {
  23800. this.setIndex( index.clone() );
  23801. }
  23802. var attributes = source.attributes;
  23803. for ( var name in attributes ) {
  23804. var attribute = attributes[ name ];
  23805. this.addAttribute( name, attribute.clone() );
  23806. }
  23807. var groups = source.groups;
  23808. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23809. var group = groups[ i ];
  23810. this.addGroup( group.start, group.count, group.materialIndex );
  23811. }
  23812. return this;
  23813. }
  23814. } );
  23815. /**
  23816. * @author benaadams / https://twitter.com/ben_a_adams
  23817. */
  23818. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23819. this.uuid = _Math.generateUUID();
  23820. this.data = interleavedBuffer;
  23821. this.itemSize = itemSize;
  23822. this.offset = offset;
  23823. this.normalized = normalized === true;
  23824. }
  23825. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23826. count: {
  23827. get: function () {
  23828. return this.data.count;
  23829. }
  23830. },
  23831. array: {
  23832. get: function () {
  23833. return this.data.array;
  23834. }
  23835. }
  23836. } );
  23837. Object.assign( InterleavedBufferAttribute.prototype, {
  23838. isInterleavedBufferAttribute: true,
  23839. setX: function ( index, x ) {
  23840. this.data.array[ index * this.data.stride + this.offset ] = x;
  23841. return this;
  23842. },
  23843. setY: function ( index, y ) {
  23844. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23845. return this;
  23846. },
  23847. setZ: function ( index, z ) {
  23848. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23849. return this;
  23850. },
  23851. setW: function ( index, w ) {
  23852. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23853. return this;
  23854. },
  23855. getX: function ( index ) {
  23856. return this.data.array[ index * this.data.stride + this.offset ];
  23857. },
  23858. getY: function ( index ) {
  23859. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23860. },
  23861. getZ: function ( index ) {
  23862. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23863. },
  23864. getW: function ( index ) {
  23865. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23866. },
  23867. setXY: function ( index, x, y ) {
  23868. index = index * this.data.stride + this.offset;
  23869. this.data.array[ index + 0 ] = x;
  23870. this.data.array[ index + 1 ] = y;
  23871. return this;
  23872. },
  23873. setXYZ: function ( index, x, y, z ) {
  23874. index = index * this.data.stride + this.offset;
  23875. this.data.array[ index + 0 ] = x;
  23876. this.data.array[ index + 1 ] = y;
  23877. this.data.array[ index + 2 ] = z;
  23878. return this;
  23879. },
  23880. setXYZW: function ( index, x, y, z, w ) {
  23881. index = index * this.data.stride + this.offset;
  23882. this.data.array[ index + 0 ] = x;
  23883. this.data.array[ index + 1 ] = y;
  23884. this.data.array[ index + 2 ] = z;
  23885. this.data.array[ index + 3 ] = w;
  23886. return this;
  23887. }
  23888. } );
  23889. /**
  23890. * @author benaadams / https://twitter.com/ben_a_adams
  23891. */
  23892. function InterleavedBuffer( array, stride ) {
  23893. this.uuid = _Math.generateUUID();
  23894. this.array = array;
  23895. this.stride = stride;
  23896. this.count = array !== undefined ? array.length / stride : 0;
  23897. this.dynamic = false;
  23898. this.updateRange = { offset: 0, count: - 1 };
  23899. this.onUploadCallback = function () {};
  23900. this.version = 0;
  23901. }
  23902. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23903. set: function ( value ) {
  23904. if ( value === true ) this.version ++;
  23905. }
  23906. } );
  23907. Object.assign( InterleavedBuffer.prototype, {
  23908. isInterleavedBuffer: true,
  23909. setArray: function ( array ) {
  23910. if ( Array.isArray( array ) ) {
  23911. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23912. }
  23913. this.count = array !== undefined ? array.length / this.stride : 0;
  23914. this.array = array;
  23915. },
  23916. setDynamic: function ( value ) {
  23917. this.dynamic = value;
  23918. return this;
  23919. },
  23920. copy: function ( source ) {
  23921. this.array = new source.array.constructor( source.array );
  23922. this.count = source.count;
  23923. this.stride = source.stride;
  23924. this.dynamic = source.dynamic;
  23925. return this;
  23926. },
  23927. copyAt: function ( index1, attribute, index2 ) {
  23928. index1 *= this.stride;
  23929. index2 *= attribute.stride;
  23930. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23931. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23932. }
  23933. return this;
  23934. },
  23935. set: function ( value, offset ) {
  23936. if ( offset === undefined ) offset = 0;
  23937. this.array.set( value, offset );
  23938. return this;
  23939. },
  23940. clone: function () {
  23941. return new this.constructor().copy( this );
  23942. },
  23943. onUpload: function ( callback ) {
  23944. this.onUploadCallback = callback;
  23945. return this;
  23946. }
  23947. } );
  23948. /**
  23949. * @author benaadams / https://twitter.com/ben_a_adams
  23950. */
  23951. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23952. InterleavedBuffer.call( this, array, stride );
  23953. this.meshPerAttribute = meshPerAttribute || 1;
  23954. }
  23955. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  23956. constructor: InstancedInterleavedBuffer,
  23957. isInstancedInterleavedBuffer: true,
  23958. copy: function ( source ) {
  23959. InterleavedBuffer.prototype.copy.call( this, source );
  23960. this.meshPerAttribute = source.meshPerAttribute;
  23961. return this;
  23962. }
  23963. } );
  23964. /**
  23965. * @author benaadams / https://twitter.com/ben_a_adams
  23966. */
  23967. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23968. BufferAttribute.call( this, array, itemSize );
  23969. this.meshPerAttribute = meshPerAttribute || 1;
  23970. }
  23971. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  23972. constructor: InstancedBufferAttribute,
  23973. isInstancedBufferAttribute: true,
  23974. copy: function ( source ) {
  23975. BufferAttribute.prototype.copy.call( this, source );
  23976. this.meshPerAttribute = source.meshPerAttribute;
  23977. return this;
  23978. }
  23979. } );
  23980. /**
  23981. * @author mrdoob / http://mrdoob.com/
  23982. * @author bhouston / http://clara.io/
  23983. * @author stephomi / http://stephaneginier.com/
  23984. */
  23985. function Raycaster( origin, direction, near, far ) {
  23986. this.ray = new Ray( origin, direction );
  23987. // direction is assumed to be normalized (for accurate distance calculations)
  23988. this.near = near || 0;
  23989. this.far = far || Infinity;
  23990. this.params = {
  23991. Mesh: {},
  23992. Line: {},
  23993. LOD: {},
  23994. Points: { threshold: 1 },
  23995. Sprite: {}
  23996. };
  23997. Object.defineProperties( this.params, {
  23998. PointCloud: {
  23999. get: function () {
  24000. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  24001. return this.Points;
  24002. }
  24003. }
  24004. } );
  24005. }
  24006. function ascSort( a, b ) {
  24007. return a.distance - b.distance;
  24008. }
  24009. function intersectObject( object, raycaster, intersects, recursive ) {
  24010. if ( object.visible === false ) return;
  24011. object.raycast( raycaster, intersects );
  24012. if ( recursive === true ) {
  24013. var children = object.children;
  24014. for ( var i = 0, l = children.length; i < l; i ++ ) {
  24015. intersectObject( children[ i ], raycaster, intersects, true );
  24016. }
  24017. }
  24018. }
  24019. Object.assign( Raycaster.prototype, {
  24020. linePrecision: 1,
  24021. set: function ( origin, direction ) {
  24022. // direction is assumed to be normalized (for accurate distance calculations)
  24023. this.ray.set( origin, direction );
  24024. },
  24025. setFromCamera: function ( coords, camera ) {
  24026. if ( ( camera && camera.isPerspectiveCamera ) ) {
  24027. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  24028. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  24029. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  24030. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  24031. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  24032. } else {
  24033. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  24034. }
  24035. },
  24036. intersectObject: function ( object, recursive ) {
  24037. var intersects = [];
  24038. intersectObject( object, this, intersects, recursive );
  24039. intersects.sort( ascSort );
  24040. return intersects;
  24041. },
  24042. intersectObjects: function ( objects, recursive ) {
  24043. var intersects = [];
  24044. if ( Array.isArray( objects ) === false ) {
  24045. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  24046. return intersects;
  24047. }
  24048. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  24049. intersectObject( objects[ i ], this, intersects, recursive );
  24050. }
  24051. intersects.sort( ascSort );
  24052. return intersects;
  24053. }
  24054. } );
  24055. /**
  24056. * @author alteredq / http://alteredqualia.com/
  24057. */
  24058. function Clock( autoStart ) {
  24059. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  24060. this.startTime = 0;
  24061. this.oldTime = 0;
  24062. this.elapsedTime = 0;
  24063. this.running = false;
  24064. }
  24065. Object.assign( Clock.prototype, {
  24066. start: function () {
  24067. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  24068. this.oldTime = this.startTime;
  24069. this.elapsedTime = 0;
  24070. this.running = true;
  24071. },
  24072. stop: function () {
  24073. this.getElapsedTime();
  24074. this.running = false;
  24075. this.autoStart = false;
  24076. },
  24077. getElapsedTime: function () {
  24078. this.getDelta();
  24079. return this.elapsedTime;
  24080. },
  24081. getDelta: function () {
  24082. var diff = 0;
  24083. if ( this.autoStart && ! this.running ) {
  24084. this.start();
  24085. return 0;
  24086. }
  24087. if ( this.running ) {
  24088. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  24089. diff = ( newTime - this.oldTime ) / 1000;
  24090. this.oldTime = newTime;
  24091. this.elapsedTime += diff;
  24092. }
  24093. return diff;
  24094. }
  24095. } );
  24096. /**
  24097. * @author bhouston / http://clara.io
  24098. * @author WestLangley / http://github.com/WestLangley
  24099. *
  24100. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  24101. *
  24102. * The poles (phi) are at the positive and negative y axis.
  24103. * The equator starts at positive z.
  24104. */
  24105. function Spherical( radius, phi, theta ) {
  24106. this.radius = ( radius !== undefined ) ? radius : 1.0;
  24107. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  24108. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  24109. return this;
  24110. }
  24111. Object.assign( Spherical.prototype, {
  24112. set: function ( radius, phi, theta ) {
  24113. this.radius = radius;
  24114. this.phi = phi;
  24115. this.theta = theta;
  24116. return this;
  24117. },
  24118. clone: function () {
  24119. return new this.constructor().copy( this );
  24120. },
  24121. copy: function ( other ) {
  24122. this.radius = other.radius;
  24123. this.phi = other.phi;
  24124. this.theta = other.theta;
  24125. return this;
  24126. },
  24127. // restrict phi to be betwee EPS and PI-EPS
  24128. makeSafe: function() {
  24129. var EPS = 0.000001;
  24130. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  24131. return this;
  24132. },
  24133. setFromVector3: function( vec3 ) {
  24134. this.radius = vec3.length();
  24135. if ( this.radius === 0 ) {
  24136. this.theta = 0;
  24137. this.phi = 0;
  24138. } else {
  24139. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  24140. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  24141. }
  24142. return this;
  24143. }
  24144. } );
  24145. /**
  24146. * @author Mugen87 / https://github.com/Mugen87
  24147. *
  24148. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  24149. *
  24150. */
  24151. function Cylindrical( radius, theta, y ) {
  24152. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  24153. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  24154. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  24155. return this;
  24156. }
  24157. Object.assign( Cylindrical.prototype, {
  24158. set: function ( radius, theta, y ) {
  24159. this.radius = radius;
  24160. this.theta = theta;
  24161. this.y = y;
  24162. return this;
  24163. },
  24164. clone: function () {
  24165. return new this.constructor().copy( this );
  24166. },
  24167. copy: function ( other ) {
  24168. this.radius = other.radius;
  24169. this.theta = other.theta;
  24170. this.y = other.y;
  24171. return this;
  24172. },
  24173. setFromVector3: function( vec3 ) {
  24174. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  24175. this.theta = Math.atan2( vec3.x, vec3.z );
  24176. this.y = vec3.y;
  24177. return this;
  24178. }
  24179. } );
  24180. /**
  24181. * @author alteredq / http://alteredqualia.com/
  24182. */
  24183. function MorphBlendMesh( geometry, material ) {
  24184. Mesh.call( this, geometry, material );
  24185. this.animationsMap = {};
  24186. this.animationsList = [];
  24187. // prepare default animation
  24188. // (all frames played together in 1 second)
  24189. var numFrames = this.geometry.morphTargets.length;
  24190. var name = "__default";
  24191. var startFrame = 0;
  24192. var endFrame = numFrames - 1;
  24193. var fps = numFrames / 1;
  24194. this.createAnimation( name, startFrame, endFrame, fps );
  24195. this.setAnimationWeight( name, 1 );
  24196. }
  24197. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  24198. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  24199. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  24200. var animation = {
  24201. start: start,
  24202. end: end,
  24203. length: end - start + 1,
  24204. fps: fps,
  24205. duration: ( end - start ) / fps,
  24206. lastFrame: 0,
  24207. currentFrame: 0,
  24208. active: false,
  24209. time: 0,
  24210. direction: 1,
  24211. weight: 1,
  24212. directionBackwards: false,
  24213. mirroredLoop: false
  24214. };
  24215. this.animationsMap[ name ] = animation;
  24216. this.animationsList.push( animation );
  24217. };
  24218. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  24219. var pattern = /([a-z]+)_?(\d+)/i;
  24220. var firstAnimation, frameRanges = {};
  24221. var geometry = this.geometry;
  24222. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  24223. var morph = geometry.morphTargets[ i ];
  24224. var chunks = morph.name.match( pattern );
  24225. if ( chunks && chunks.length > 1 ) {
  24226. var name = chunks[ 1 ];
  24227. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  24228. var range = frameRanges[ name ];
  24229. if ( i < range.start ) range.start = i;
  24230. if ( i > range.end ) range.end = i;
  24231. if ( ! firstAnimation ) firstAnimation = name;
  24232. }
  24233. }
  24234. for ( var name in frameRanges ) {
  24235. var range = frameRanges[ name ];
  24236. this.createAnimation( name, range.start, range.end, fps );
  24237. }
  24238. this.firstAnimation = firstAnimation;
  24239. };
  24240. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  24241. var animation = this.animationsMap[ name ];
  24242. if ( animation ) {
  24243. animation.direction = 1;
  24244. animation.directionBackwards = false;
  24245. }
  24246. };
  24247. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  24248. var animation = this.animationsMap[ name ];
  24249. if ( animation ) {
  24250. animation.direction = - 1;
  24251. animation.directionBackwards = true;
  24252. }
  24253. };
  24254. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  24255. var animation = this.animationsMap[ name ];
  24256. if ( animation ) {
  24257. animation.fps = fps;
  24258. animation.duration = ( animation.end - animation.start ) / animation.fps;
  24259. }
  24260. };
  24261. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  24262. var animation = this.animationsMap[ name ];
  24263. if ( animation ) {
  24264. animation.duration = duration;
  24265. animation.fps = ( animation.end - animation.start ) / animation.duration;
  24266. }
  24267. };
  24268. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  24269. var animation = this.animationsMap[ name ];
  24270. if ( animation ) {
  24271. animation.weight = weight;
  24272. }
  24273. };
  24274. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  24275. var animation = this.animationsMap[ name ];
  24276. if ( animation ) {
  24277. animation.time = time;
  24278. }
  24279. };
  24280. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  24281. var time = 0;
  24282. var animation = this.animationsMap[ name ];
  24283. if ( animation ) {
  24284. time = animation.time;
  24285. }
  24286. return time;
  24287. };
  24288. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24289. var duration = - 1;
  24290. var animation = this.animationsMap[ name ];
  24291. if ( animation ) {
  24292. duration = animation.duration;
  24293. }
  24294. return duration;
  24295. };
  24296. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24297. var animation = this.animationsMap[ name ];
  24298. if ( animation ) {
  24299. animation.time = 0;
  24300. animation.active = true;
  24301. } else {
  24302. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24303. }
  24304. };
  24305. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24306. var animation = this.animationsMap[ name ];
  24307. if ( animation ) {
  24308. animation.active = false;
  24309. }
  24310. };
  24311. MorphBlendMesh.prototype.update = function ( delta ) {
  24312. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24313. var animation = this.animationsList[ i ];
  24314. if ( ! animation.active ) continue;
  24315. var frameTime = animation.duration / animation.length;
  24316. animation.time += animation.direction * delta;
  24317. if ( animation.mirroredLoop ) {
  24318. if ( animation.time > animation.duration || animation.time < 0 ) {
  24319. animation.direction *= - 1;
  24320. if ( animation.time > animation.duration ) {
  24321. animation.time = animation.duration;
  24322. animation.directionBackwards = true;
  24323. }
  24324. if ( animation.time < 0 ) {
  24325. animation.time = 0;
  24326. animation.directionBackwards = false;
  24327. }
  24328. }
  24329. } else {
  24330. animation.time = animation.time % animation.duration;
  24331. if ( animation.time < 0 ) animation.time += animation.duration;
  24332. }
  24333. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24334. var weight = animation.weight;
  24335. if ( keyframe !== animation.currentFrame ) {
  24336. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24337. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24338. this.morphTargetInfluences[ keyframe ] = 0;
  24339. animation.lastFrame = animation.currentFrame;
  24340. animation.currentFrame = keyframe;
  24341. }
  24342. var mix = ( animation.time % frameTime ) / frameTime;
  24343. if ( animation.directionBackwards ) mix = 1 - mix;
  24344. if ( animation.currentFrame !== animation.lastFrame ) {
  24345. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24346. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24347. } else {
  24348. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24349. }
  24350. }
  24351. };
  24352. /**
  24353. * @author alteredq / http://alteredqualia.com/
  24354. */
  24355. function ImmediateRenderObject( material ) {
  24356. Object3D.call( this );
  24357. this.material = material;
  24358. this.render = function ( renderCallback ) {};
  24359. }
  24360. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24361. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24362. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24363. /**
  24364. * @author mrdoob / http://mrdoob.com/
  24365. * @author WestLangley / http://github.com/WestLangley
  24366. */
  24367. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24368. this.object = object;
  24369. this.size = ( size !== undefined ) ? size : 1;
  24370. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24371. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24372. //
  24373. var nNormals = 0;
  24374. var objGeometry = this.object.geometry;
  24375. if ( objGeometry && objGeometry.isGeometry ) {
  24376. nNormals = objGeometry.faces.length * 3;
  24377. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24378. nNormals = objGeometry.attributes.normal.count;
  24379. }
  24380. //
  24381. var geometry = new BufferGeometry();
  24382. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24383. geometry.addAttribute( 'position', positions );
  24384. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24385. //
  24386. this.matrixAutoUpdate = false;
  24387. this.update();
  24388. }
  24389. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24390. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24391. VertexNormalsHelper.prototype.update = ( function () {
  24392. var v1 = new Vector3();
  24393. var v2 = new Vector3();
  24394. var normalMatrix = new Matrix3();
  24395. return function update() {
  24396. var keys = [ 'a', 'b', 'c' ];
  24397. this.object.updateMatrixWorld( true );
  24398. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24399. var matrixWorld = this.object.matrixWorld;
  24400. var position = this.geometry.attributes.position;
  24401. //
  24402. var objGeometry = this.object.geometry;
  24403. if ( objGeometry && objGeometry.isGeometry ) {
  24404. var vertices = objGeometry.vertices;
  24405. var faces = objGeometry.faces;
  24406. var idx = 0;
  24407. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24408. var face = faces[ i ];
  24409. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24410. var vertex = vertices[ face[ keys[ j ] ] ];
  24411. var normal = face.vertexNormals[ j ];
  24412. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24413. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24414. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24415. idx = idx + 1;
  24416. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24417. idx = idx + 1;
  24418. }
  24419. }
  24420. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24421. var objPos = objGeometry.attributes.position;
  24422. var objNorm = objGeometry.attributes.normal;
  24423. var idx = 0;
  24424. // for simplicity, ignore index and drawcalls, and render every normal
  24425. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24426. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24427. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24428. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24429. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24430. idx = idx + 1;
  24431. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24432. idx = idx + 1;
  24433. }
  24434. }
  24435. position.needsUpdate = true;
  24436. };
  24437. }() );
  24438. /**
  24439. * @author alteredq / http://alteredqualia.com/
  24440. * @author mrdoob / http://mrdoob.com/
  24441. * @author WestLangley / http://github.com/WestLangley
  24442. */
  24443. function SpotLightHelper( light, color ) {
  24444. Object3D.call( this );
  24445. this.light = light;
  24446. this.light.updateMatrixWorld();
  24447. this.matrix = light.matrixWorld;
  24448. this.matrixAutoUpdate = false;
  24449. this.color = color;
  24450. var geometry = new BufferGeometry();
  24451. var positions = [
  24452. 0, 0, 0, 0, 0, 1,
  24453. 0, 0, 0, 1, 0, 1,
  24454. 0, 0, 0, - 1, 0, 1,
  24455. 0, 0, 0, 0, 1, 1,
  24456. 0, 0, 0, 0, - 1, 1
  24457. ];
  24458. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24459. var p1 = ( i / l ) * Math.PI * 2;
  24460. var p2 = ( j / l ) * Math.PI * 2;
  24461. positions.push(
  24462. Math.cos( p1 ), Math.sin( p1 ), 1,
  24463. Math.cos( p2 ), Math.sin( p2 ), 1
  24464. );
  24465. }
  24466. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24467. var material = new LineBasicMaterial( { fog: false } );
  24468. this.cone = new LineSegments( geometry, material );
  24469. this.add( this.cone );
  24470. this.update();
  24471. }
  24472. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24473. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24474. SpotLightHelper.prototype.dispose = function () {
  24475. this.cone.geometry.dispose();
  24476. this.cone.material.dispose();
  24477. };
  24478. SpotLightHelper.prototype.update = function () {
  24479. var vector = new Vector3();
  24480. var vector2 = new Vector3();
  24481. return function update() {
  24482. this.light.updateMatrixWorld();
  24483. var coneLength = this.light.distance ? this.light.distance : 1000;
  24484. var coneWidth = coneLength * Math.tan( this.light.angle );
  24485. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24486. vector.setFromMatrixPosition( this.light.matrixWorld );
  24487. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24488. this.cone.lookAt( vector2.sub( vector ) );
  24489. if ( this.color !== undefined ) {
  24490. this.cone.material.color.set( this.color );
  24491. } else {
  24492. this.cone.material.color.copy( this.light.color );
  24493. }
  24494. };
  24495. }();
  24496. /**
  24497. * @author Sean Griffin / http://twitter.com/sgrif
  24498. * @author Michael Guerrero / http://realitymeltdown.com
  24499. * @author mrdoob / http://mrdoob.com/
  24500. * @author ikerr / http://verold.com
  24501. * @author Mugen87 / https://github.com/Mugen87
  24502. */
  24503. function getBoneList( object ) {
  24504. var boneList = [];
  24505. if ( object && object.isBone ) {
  24506. boneList.push( object );
  24507. }
  24508. for ( var i = 0; i < object.children.length; i ++ ) {
  24509. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  24510. }
  24511. return boneList;
  24512. }
  24513. function SkeletonHelper( object ) {
  24514. var bones = getBoneList( object );
  24515. var geometry = new BufferGeometry();
  24516. var vertices = [];
  24517. var colors = [];
  24518. var color1 = new Color( 0, 0, 1 );
  24519. var color2 = new Color( 0, 1, 0 );
  24520. for ( var i = 0; i < bones.length; i ++ ) {
  24521. var bone = bones[ i ];
  24522. if ( bone.parent && bone.parent.isBone ) {
  24523. vertices.push( 0, 0, 0 );
  24524. vertices.push( 0, 0, 0 );
  24525. colors.push( color1.r, color1.g, color1.b );
  24526. colors.push( color2.r, color2.g, color2.b );
  24527. }
  24528. }
  24529. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24530. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24531. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24532. LineSegments.call( this, geometry, material );
  24533. this.root = object;
  24534. this.bones = bones;
  24535. this.matrix = object.matrixWorld;
  24536. this.matrixAutoUpdate = false;
  24537. this.onBeforeRender();
  24538. }
  24539. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24540. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24541. SkeletonHelper.prototype.onBeforeRender = function () {
  24542. var vector = new Vector3();
  24543. var boneMatrix = new Matrix4();
  24544. var matrixWorldInv = new Matrix4();
  24545. return function onBeforeRender() {
  24546. var bones = this.bones;
  24547. var geometry = this.geometry;
  24548. var position = geometry.getAttribute( 'position' );
  24549. matrixWorldInv.getInverse( this.root.matrixWorld );
  24550. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  24551. var bone = bones[ i ];
  24552. if ( bone.parent && bone.parent.isBone ) {
  24553. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24554. vector.setFromMatrixPosition( boneMatrix );
  24555. position.setXYZ( j, vector.x, vector.y, vector.z );
  24556. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24557. vector.setFromMatrixPosition( boneMatrix );
  24558. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24559. j += 2;
  24560. }
  24561. }
  24562. geometry.getAttribute( 'position' ).needsUpdate = true;
  24563. };
  24564. }();
  24565. /**
  24566. * @author alteredq / http://alteredqualia.com/
  24567. * @author mrdoob / http://mrdoob.com/
  24568. */
  24569. function PointLightHelper( light, sphereSize, color ) {
  24570. this.light = light;
  24571. this.light.updateMatrixWorld();
  24572. this.color = color;
  24573. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24574. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24575. Mesh.call( this, geometry, material );
  24576. this.matrix = this.light.matrixWorld;
  24577. this.matrixAutoUpdate = false;
  24578. this.update();
  24579. /*
  24580. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24581. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24582. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24583. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24584. var d = light.distance;
  24585. if ( d === 0.0 ) {
  24586. this.lightDistance.visible = false;
  24587. } else {
  24588. this.lightDistance.scale.set( d, d, d );
  24589. }
  24590. this.add( this.lightDistance );
  24591. */
  24592. }
  24593. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24594. PointLightHelper.prototype.constructor = PointLightHelper;
  24595. PointLightHelper.prototype.dispose = function () {
  24596. this.geometry.dispose();
  24597. this.material.dispose();
  24598. };
  24599. PointLightHelper.prototype.update = function () {
  24600. if ( this.color !== undefined ) {
  24601. this.material.color.set( this.color );
  24602. } else {
  24603. this.material.color.copy( this.light.color );
  24604. }
  24605. /*
  24606. var d = this.light.distance;
  24607. if ( d === 0.0 ) {
  24608. this.lightDistance.visible = false;
  24609. } else {
  24610. this.lightDistance.visible = true;
  24611. this.lightDistance.scale.set( d, d, d );
  24612. }
  24613. */
  24614. };
  24615. /**
  24616. * @author abelnation / http://github.com/abelnation
  24617. * @author Mugen87 / http://github.com/Mugen87
  24618. * @author WestLangley / http://github.com/WestLangley
  24619. */
  24620. function RectAreaLightHelper( light, color ) {
  24621. Object3D.call( this );
  24622. this.light = light;
  24623. this.light.updateMatrixWorld();
  24624. this.matrix = light.matrixWorld;
  24625. this.matrixAutoUpdate = false;
  24626. this.color = color;
  24627. var material = new LineBasicMaterial( { fog: false } );
  24628. var geometry = new BufferGeometry();
  24629. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  24630. this.line = new Line( geometry, material );
  24631. this.add( this.line );
  24632. this.update();
  24633. }
  24634. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24635. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24636. RectAreaLightHelper.prototype.dispose = function () {
  24637. this.children[ 0 ].geometry.dispose();
  24638. this.children[ 0 ].material.dispose();
  24639. };
  24640. RectAreaLightHelper.prototype.update = function () {
  24641. // calculate new dimensions of the helper
  24642. var hx = this.light.width * 0.5;
  24643. var hy = this.light.height * 0.5;
  24644. var position = this.line.geometry.attributes.position;
  24645. var array = position.array;
  24646. // update vertices
  24647. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24648. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24649. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24650. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  24651. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24652. position.needsUpdate = true;
  24653. if ( this.color !== undefined ) {
  24654. this.line.material.color.set( this.color );
  24655. } else {
  24656. this.line.material.color.copy( this.light.color );
  24657. }
  24658. };
  24659. /**
  24660. * @author alteredq / http://alteredqualia.com/
  24661. * @author mrdoob / http://mrdoob.com/
  24662. * @author Mugen87 / https://github.com/Mugen87
  24663. */
  24664. function HemisphereLightHelper( light, size, color ) {
  24665. Object3D.call( this );
  24666. this.light = light;
  24667. this.light.updateMatrixWorld();
  24668. this.matrix = light.matrixWorld;
  24669. this.matrixAutoUpdate = false;
  24670. this.color = color;
  24671. var geometry = new OctahedronBufferGeometry( size );
  24672. geometry.rotateY( Math.PI * 0.5 );
  24673. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24674. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  24675. var position = geometry.getAttribute( 'position' );
  24676. var colors = new Float32Array( position.count * 3 );
  24677. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24678. this.add( new Mesh( geometry, this.material ) );
  24679. this.update();
  24680. }
  24681. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24682. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24683. HemisphereLightHelper.prototype.dispose = function () {
  24684. this.children[ 0 ].geometry.dispose();
  24685. this.children[ 0 ].material.dispose();
  24686. };
  24687. HemisphereLightHelper.prototype.update = function () {
  24688. var vector = new Vector3();
  24689. var color1 = new Color();
  24690. var color2 = new Color();
  24691. return function update() {
  24692. var mesh = this.children[ 0 ];
  24693. if ( this.color !== undefined ) {
  24694. this.material.color.set( this.color );
  24695. } else {
  24696. var colors = mesh.geometry.getAttribute( 'color' );
  24697. color1.copy( this.light.color );
  24698. color2.copy( this.light.groundColor );
  24699. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24700. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24701. colors.setXYZ( i, color.r, color.g, color.b );
  24702. }
  24703. colors.needsUpdate = true;
  24704. }
  24705. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24706. };
  24707. }();
  24708. /**
  24709. * @author mrdoob / http://mrdoob.com/
  24710. */
  24711. function GridHelper( size, divisions, color1, color2 ) {
  24712. size = size || 10;
  24713. divisions = divisions || 10;
  24714. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24715. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24716. var center = divisions / 2;
  24717. var step = size / divisions;
  24718. var halfSize = size / 2;
  24719. var vertices = [], colors = [];
  24720. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24721. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24722. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24723. var color = i === center ? color1 : color2;
  24724. color.toArray( colors, j ); j += 3;
  24725. color.toArray( colors, j ); j += 3;
  24726. color.toArray( colors, j ); j += 3;
  24727. color.toArray( colors, j ); j += 3;
  24728. }
  24729. var geometry = new BufferGeometry();
  24730. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24731. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24732. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24733. LineSegments.call( this, geometry, material );
  24734. }
  24735. GridHelper.prototype = Object.create( LineSegments.prototype );
  24736. GridHelper.prototype.constructor = GridHelper;
  24737. /**
  24738. * @author mrdoob / http://mrdoob.com/
  24739. * @author Mugen87 / http://github.com/Mugen87
  24740. * @author Hectate / http://www.github.com/Hectate
  24741. */
  24742. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24743. radius = radius || 10;
  24744. radials = radials || 16;
  24745. circles = circles || 8;
  24746. divisions = divisions || 64;
  24747. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24748. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24749. var vertices = [];
  24750. var colors = [];
  24751. var x, z;
  24752. var v, i, j, r, color;
  24753. // create the radials
  24754. for ( i = 0; i <= radials; i ++ ) {
  24755. v = ( i / radials ) * ( Math.PI * 2 );
  24756. x = Math.sin( v ) * radius;
  24757. z = Math.cos( v ) * radius;
  24758. vertices.push( 0, 0, 0 );
  24759. vertices.push( x, 0, z );
  24760. color = ( i & 1 ) ? color1 : color2;
  24761. colors.push( color.r, color.g, color.b );
  24762. colors.push( color.r, color.g, color.b );
  24763. }
  24764. // create the circles
  24765. for ( i = 0; i <= circles; i ++ ) {
  24766. color = ( i & 1 ) ? color1 : color2;
  24767. r = radius - ( radius / circles * i );
  24768. for ( j = 0; j < divisions; j ++ ) {
  24769. // first vertex
  24770. v = ( j / divisions ) * ( Math.PI * 2 );
  24771. x = Math.sin( v ) * r;
  24772. z = Math.cos( v ) * r;
  24773. vertices.push( x, 0, z );
  24774. colors.push( color.r, color.g, color.b );
  24775. // second vertex
  24776. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24777. x = Math.sin( v ) * r;
  24778. z = Math.cos( v ) * r;
  24779. vertices.push( x, 0, z );
  24780. colors.push( color.r, color.g, color.b );
  24781. }
  24782. }
  24783. var geometry = new BufferGeometry();
  24784. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24785. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24786. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24787. LineSegments.call( this, geometry, material );
  24788. }
  24789. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24790. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24791. /**
  24792. * @author mrdoob / http://mrdoob.com/
  24793. * @author WestLangley / http://github.com/WestLangley
  24794. */
  24795. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24796. // FaceNormalsHelper only supports THREE.Geometry
  24797. this.object = object;
  24798. this.size = ( size !== undefined ) ? size : 1;
  24799. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24800. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24801. //
  24802. var nNormals = 0;
  24803. var objGeometry = this.object.geometry;
  24804. if ( objGeometry && objGeometry.isGeometry ) {
  24805. nNormals = objGeometry.faces.length;
  24806. } else {
  24807. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24808. }
  24809. //
  24810. var geometry = new BufferGeometry();
  24811. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24812. geometry.addAttribute( 'position', positions );
  24813. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24814. //
  24815. this.matrixAutoUpdate = false;
  24816. this.update();
  24817. }
  24818. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24819. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24820. FaceNormalsHelper.prototype.update = ( function () {
  24821. var v1 = new Vector3();
  24822. var v2 = new Vector3();
  24823. var normalMatrix = new Matrix3();
  24824. return function update() {
  24825. this.object.updateMatrixWorld( true );
  24826. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24827. var matrixWorld = this.object.matrixWorld;
  24828. var position = this.geometry.attributes.position;
  24829. //
  24830. var objGeometry = this.object.geometry;
  24831. var vertices = objGeometry.vertices;
  24832. var faces = objGeometry.faces;
  24833. var idx = 0;
  24834. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24835. var face = faces[ i ];
  24836. var normal = face.normal;
  24837. v1.copy( vertices[ face.a ] )
  24838. .add( vertices[ face.b ] )
  24839. .add( vertices[ face.c ] )
  24840. .divideScalar( 3 )
  24841. .applyMatrix4( matrixWorld );
  24842. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24843. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24844. idx = idx + 1;
  24845. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24846. idx = idx + 1;
  24847. }
  24848. position.needsUpdate = true;
  24849. };
  24850. }() );
  24851. /**
  24852. * @author alteredq / http://alteredqualia.com/
  24853. * @author mrdoob / http://mrdoob.com/
  24854. * @author WestLangley / http://github.com/WestLangley
  24855. */
  24856. function DirectionalLightHelper( light, size, color ) {
  24857. Object3D.call( this );
  24858. this.light = light;
  24859. this.light.updateMatrixWorld();
  24860. this.matrix = light.matrixWorld;
  24861. this.matrixAutoUpdate = false;
  24862. this.color = color;
  24863. if ( size === undefined ) size = 1;
  24864. var geometry = new BufferGeometry();
  24865. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24866. - size, size, 0,
  24867. size, size, 0,
  24868. size, - size, 0,
  24869. - size, - size, 0,
  24870. - size, size, 0
  24871. ], 3 ) );
  24872. var material = new LineBasicMaterial( { fog: false } );
  24873. this.lightPlane = new Line( geometry, material );
  24874. this.add( this.lightPlane );
  24875. geometry = new BufferGeometry();
  24876. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24877. this.targetLine = new Line( geometry, material );
  24878. this.add( this.targetLine );
  24879. this.update();
  24880. }
  24881. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24882. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24883. DirectionalLightHelper.prototype.dispose = function () {
  24884. this.lightPlane.geometry.dispose();
  24885. this.lightPlane.material.dispose();
  24886. this.targetLine.geometry.dispose();
  24887. this.targetLine.material.dispose();
  24888. };
  24889. DirectionalLightHelper.prototype.update = function () {
  24890. var v1 = new Vector3();
  24891. var v2 = new Vector3();
  24892. var v3 = new Vector3();
  24893. return function update() {
  24894. v1.setFromMatrixPosition( this.light.matrixWorld );
  24895. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24896. v3.subVectors( v2, v1 );
  24897. this.lightPlane.lookAt( v3 );
  24898. if ( this.color !== undefined ) {
  24899. this.lightPlane.material.color.set( this.color );
  24900. this.targetLine.material.color.set( this.color );
  24901. } else {
  24902. this.lightPlane.material.color.copy( this.light.color );
  24903. this.targetLine.material.color.copy( this.light.color );
  24904. }
  24905. this.targetLine.lookAt( v3 );
  24906. this.targetLine.scale.z = v3.length();
  24907. };
  24908. }();
  24909. /**
  24910. * @author alteredq / http://alteredqualia.com/
  24911. * @author Mugen87 / https://github.com/Mugen87
  24912. *
  24913. * - shows frustum, line of sight and up of the camera
  24914. * - suitable for fast updates
  24915. * - based on frustum visualization in lightgl.js shadowmap example
  24916. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24917. */
  24918. function CameraHelper( camera ) {
  24919. var geometry = new BufferGeometry();
  24920. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24921. var vertices = [];
  24922. var colors = [];
  24923. var pointMap = {};
  24924. // colors
  24925. var colorFrustum = new Color( 0xffaa00 );
  24926. var colorCone = new Color( 0xff0000 );
  24927. var colorUp = new Color( 0x00aaff );
  24928. var colorTarget = new Color( 0xffffff );
  24929. var colorCross = new Color( 0x333333 );
  24930. // near
  24931. addLine( "n1", "n2", colorFrustum );
  24932. addLine( "n2", "n4", colorFrustum );
  24933. addLine( "n4", "n3", colorFrustum );
  24934. addLine( "n3", "n1", colorFrustum );
  24935. // far
  24936. addLine( "f1", "f2", colorFrustum );
  24937. addLine( "f2", "f4", colorFrustum );
  24938. addLine( "f4", "f3", colorFrustum );
  24939. addLine( "f3", "f1", colorFrustum );
  24940. // sides
  24941. addLine( "n1", "f1", colorFrustum );
  24942. addLine( "n2", "f2", colorFrustum );
  24943. addLine( "n3", "f3", colorFrustum );
  24944. addLine( "n4", "f4", colorFrustum );
  24945. // cone
  24946. addLine( "p", "n1", colorCone );
  24947. addLine( "p", "n2", colorCone );
  24948. addLine( "p", "n3", colorCone );
  24949. addLine( "p", "n4", colorCone );
  24950. // up
  24951. addLine( "u1", "u2", colorUp );
  24952. addLine( "u2", "u3", colorUp );
  24953. addLine( "u3", "u1", colorUp );
  24954. // target
  24955. addLine( "c", "t", colorTarget );
  24956. addLine( "p", "c", colorCross );
  24957. // cross
  24958. addLine( "cn1", "cn2", colorCross );
  24959. addLine( "cn3", "cn4", colorCross );
  24960. addLine( "cf1", "cf2", colorCross );
  24961. addLine( "cf3", "cf4", colorCross );
  24962. function addLine( a, b, color ) {
  24963. addPoint( a, color );
  24964. addPoint( b, color );
  24965. }
  24966. function addPoint( id, color ) {
  24967. vertices.push( 0, 0, 0 );
  24968. colors.push( color.r, color.g, color.b );
  24969. if ( pointMap[ id ] === undefined ) {
  24970. pointMap[ id ] = [];
  24971. }
  24972. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24973. }
  24974. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24975. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24976. LineSegments.call( this, geometry, material );
  24977. this.camera = camera;
  24978. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24979. this.matrix = camera.matrixWorld;
  24980. this.matrixAutoUpdate = false;
  24981. this.pointMap = pointMap;
  24982. this.update();
  24983. }
  24984. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24985. CameraHelper.prototype.constructor = CameraHelper;
  24986. CameraHelper.prototype.update = function () {
  24987. var geometry, pointMap;
  24988. var vector = new Vector3();
  24989. var camera = new Camera();
  24990. function setPoint( point, x, y, z ) {
  24991. vector.set( x, y, z ).unproject( camera );
  24992. var points = pointMap[ point ];
  24993. if ( points !== undefined ) {
  24994. var position = geometry.getAttribute( 'position' );
  24995. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24996. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24997. }
  24998. }
  24999. }
  25000. return function update() {
  25001. geometry = this.geometry;
  25002. pointMap = this.pointMap;
  25003. var w = 1, h = 1;
  25004. // we need just camera projection matrix
  25005. // world matrix must be identity
  25006. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  25007. // center / target
  25008. setPoint( "c", 0, 0, - 1 );
  25009. setPoint( "t", 0, 0, 1 );
  25010. // near
  25011. setPoint( "n1", - w, - h, - 1 );
  25012. setPoint( "n2", w, - h, - 1 );
  25013. setPoint( "n3", - w, h, - 1 );
  25014. setPoint( "n4", w, h, - 1 );
  25015. // far
  25016. setPoint( "f1", - w, - h, 1 );
  25017. setPoint( "f2", w, - h, 1 );
  25018. setPoint( "f3", - w, h, 1 );
  25019. setPoint( "f4", w, h, 1 );
  25020. // up
  25021. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  25022. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  25023. setPoint( "u3", 0, h * 2, - 1 );
  25024. // cross
  25025. setPoint( "cf1", - w, 0, 1 );
  25026. setPoint( "cf2", w, 0, 1 );
  25027. setPoint( "cf3", 0, - h, 1 );
  25028. setPoint( "cf4", 0, h, 1 );
  25029. setPoint( "cn1", - w, 0, - 1 );
  25030. setPoint( "cn2", w, 0, - 1 );
  25031. setPoint( "cn3", 0, - h, - 1 );
  25032. setPoint( "cn4", 0, h, - 1 );
  25033. geometry.getAttribute( 'position' ).needsUpdate = true;
  25034. };
  25035. }();
  25036. /**
  25037. * @author mrdoob / http://mrdoob.com/
  25038. * @author Mugen87 / http://github.com/Mugen87
  25039. */
  25040. function BoxHelper( object, color ) {
  25041. this.object = object;
  25042. if ( color === undefined ) color = 0xffff00;
  25043. 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 ] );
  25044. var positions = new Float32Array( 8 * 3 );
  25045. var geometry = new BufferGeometry();
  25046. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25047. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  25048. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25049. this.matrixAutoUpdate = false;
  25050. this.update();
  25051. }
  25052. BoxHelper.prototype = Object.create( LineSegments.prototype );
  25053. BoxHelper.prototype.constructor = BoxHelper;
  25054. BoxHelper.prototype.update = ( function () {
  25055. var box = new Box3();
  25056. return function update( object ) {
  25057. if ( object !== undefined ) {
  25058. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  25059. }
  25060. if ( this.object !== undefined ) {
  25061. box.setFromObject( this.object );
  25062. }
  25063. if ( box.isEmpty() ) return;
  25064. var min = box.min;
  25065. var max = box.max;
  25066. /*
  25067. 5____4
  25068. 1/___0/|
  25069. | 6__|_7
  25070. 2/___3/
  25071. 0: max.x, max.y, max.z
  25072. 1: min.x, max.y, max.z
  25073. 2: min.x, min.y, max.z
  25074. 3: max.x, min.y, max.z
  25075. 4: max.x, max.y, min.z
  25076. 5: min.x, max.y, min.z
  25077. 6: min.x, min.y, min.z
  25078. 7: max.x, min.y, min.z
  25079. */
  25080. var position = this.geometry.attributes.position;
  25081. var array = position.array;
  25082. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  25083. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  25084. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  25085. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  25086. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  25087. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  25088. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  25089. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  25090. position.needsUpdate = true;
  25091. this.geometry.computeBoundingSphere();
  25092. };
  25093. } )();
  25094. BoxHelper.prototype.setFromObject = function ( object ) {
  25095. this.object = object;
  25096. this.update();
  25097. return this;
  25098. };
  25099. /**
  25100. * @author WestLangley / http://github.com/WestLangley
  25101. */
  25102. function Box3Helper( box, hex ) {
  25103. this.type = 'Box3Helper';
  25104. this.box = box;
  25105. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25106. 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 ] );
  25107. var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  25108. var geometry = new BufferGeometry();
  25109. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  25110. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25111. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25112. this.geometry.computeBoundingSphere();
  25113. this.onBeforeRender();
  25114. }
  25115. Box3Helper.prototype = Object.create( LineSegments.prototype );
  25116. Box3Helper.prototype.constructor = Box3Helper;
  25117. Box3Helper.prototype.onBeforeRender = function () {
  25118. var box = this.box;
  25119. if ( box.isEmpty() ) return;
  25120. box.getCenter( this.position );
  25121. box.getSize( this.scale );
  25122. this.scale.multiplyScalar( 0.5 );
  25123. };
  25124. /**
  25125. * @author WestLangley / http://github.com/WestLangley
  25126. */
  25127. function PlaneHelper( plane, size, hex ) {
  25128. this.type = 'PlaneHelper';
  25129. this.plane = plane;
  25130. this.size = ( size === undefined ) ? 1 : size;
  25131. var color = ( hex !== undefined ) ? hex : 0xffff00;
  25132. var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  25133. var geometry = new BufferGeometry();
  25134. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  25135. geometry.computeBoundingSphere();
  25136. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  25137. //
  25138. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  25139. var geometry2 = new BufferGeometry();
  25140. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  25141. geometry2.computeBoundingSphere();
  25142. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  25143. //
  25144. this.onBeforeRender();
  25145. }
  25146. PlaneHelper.prototype = Object.create( Line.prototype );
  25147. PlaneHelper.prototype.constructor = PlaneHelper;
  25148. PlaneHelper.prototype.onBeforeRender = function () {
  25149. var scale = - this.plane.constant;
  25150. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  25151. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  25152. this.lookAt( this.plane.normal );
  25153. this.updateMatrixWorld();
  25154. };
  25155. /**
  25156. * @author WestLangley / http://github.com/WestLangley
  25157. * @author zz85 / http://github.com/zz85
  25158. * @author bhouston / http://clara.io
  25159. *
  25160. * Creates an arrow for visualizing directions
  25161. *
  25162. * Parameters:
  25163. * dir - Vector3
  25164. * origin - Vector3
  25165. * length - Number
  25166. * color - color in hex value
  25167. * headLength - Number
  25168. * headWidth - Number
  25169. */
  25170. var lineGeometry;
  25171. var coneGeometry;
  25172. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  25173. // dir is assumed to be normalized
  25174. Object3D.call( this );
  25175. if ( color === undefined ) color = 0xffff00;
  25176. if ( length === undefined ) length = 1;
  25177. if ( headLength === undefined ) headLength = 0.2 * length;
  25178. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25179. if ( lineGeometry === undefined ) {
  25180. lineGeometry = new BufferGeometry();
  25181. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  25182. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  25183. coneGeometry.translate( 0, - 0.5, 0 );
  25184. }
  25185. this.position.copy( origin );
  25186. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  25187. this.line.matrixAutoUpdate = false;
  25188. this.add( this.line );
  25189. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  25190. this.cone.matrixAutoUpdate = false;
  25191. this.add( this.cone );
  25192. this.setDirection( dir );
  25193. this.setLength( length, headLength, headWidth );
  25194. }
  25195. ArrowHelper.prototype = Object.create( Object3D.prototype );
  25196. ArrowHelper.prototype.constructor = ArrowHelper;
  25197. ArrowHelper.prototype.setDirection = ( function () {
  25198. var axis = new Vector3();
  25199. var radians;
  25200. return function setDirection( dir ) {
  25201. // dir is assumed to be normalized
  25202. if ( dir.y > 0.99999 ) {
  25203. this.quaternion.set( 0, 0, 0, 1 );
  25204. } else if ( dir.y < - 0.99999 ) {
  25205. this.quaternion.set( 1, 0, 0, 0 );
  25206. } else {
  25207. axis.set( dir.z, 0, - dir.x ).normalize();
  25208. radians = Math.acos( dir.y );
  25209. this.quaternion.setFromAxisAngle( axis, radians );
  25210. }
  25211. };
  25212. }() );
  25213. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  25214. if ( headLength === undefined ) headLength = 0.2 * length;
  25215. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  25216. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  25217. this.line.updateMatrix();
  25218. this.cone.scale.set( headWidth, headLength, headWidth );
  25219. this.cone.position.y = length;
  25220. this.cone.updateMatrix();
  25221. };
  25222. ArrowHelper.prototype.setColor = function ( color ) {
  25223. this.line.material.color.copy( color );
  25224. this.cone.material.color.copy( color );
  25225. };
  25226. /**
  25227. * @author sroucheray / http://sroucheray.org/
  25228. * @author mrdoob / http://mrdoob.com/
  25229. */
  25230. function AxisHelper( size ) {
  25231. size = size || 1;
  25232. var vertices = [
  25233. 0, 0, 0, size, 0, 0,
  25234. 0, 0, 0, 0, size, 0,
  25235. 0, 0, 0, 0, 0, size
  25236. ];
  25237. var colors = [
  25238. 1, 0, 0, 1, 0.6, 0,
  25239. 0, 1, 0, 0.6, 1, 0,
  25240. 0, 0, 1, 0, 0.6, 1
  25241. ];
  25242. var geometry = new BufferGeometry();
  25243. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25244. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  25245. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  25246. LineSegments.call( this, geometry, material );
  25247. }
  25248. AxisHelper.prototype = Object.create( LineSegments.prototype );
  25249. AxisHelper.prototype.constructor = AxisHelper;
  25250. /**
  25251. * @author zz85 https://github.com/zz85
  25252. *
  25253. * Centripetal CatmullRom Curve - which is useful for avoiding
  25254. * cusps and self-intersections in non-uniform catmull rom curves.
  25255. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  25256. *
  25257. * curve.type accepts centripetal(default), chordal and catmullrom
  25258. * curve.tension is used for catmullrom which defaults to 0.5
  25259. */
  25260. /*
  25261. Based on an optimized c++ solution in
  25262. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  25263. - http://ideone.com/NoEbVM
  25264. This CubicPoly class could be used for reusing some variables and calculations,
  25265. but for three.js curve use, it could be possible inlined and flatten into a single function call
  25266. which can be placed in CurveUtils.
  25267. */
  25268. function CubicPoly() {
  25269. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  25270. /*
  25271. * Compute coefficients for a cubic polynomial
  25272. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  25273. * such that
  25274. * p(0) = x0, p(1) = x1
  25275. * and
  25276. * p'(0) = t0, p'(1) = t1.
  25277. */
  25278. function init( x0, x1, t0, t1 ) {
  25279. c0 = x0;
  25280. c1 = t0;
  25281. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  25282. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  25283. }
  25284. return {
  25285. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  25286. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  25287. },
  25288. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  25289. // compute tangents when parameterized in [t1,t2]
  25290. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  25291. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  25292. // rescale tangents for parametrization in [0,1]
  25293. t1 *= dt1;
  25294. t2 *= dt1;
  25295. init( x1, x2, t1, t2 );
  25296. },
  25297. calc: function ( t ) {
  25298. var t2 = t * t;
  25299. var t3 = t2 * t;
  25300. return c0 + c1 * t + c2 * t2 + c3 * t3;
  25301. }
  25302. };
  25303. }
  25304. //
  25305. var tmp = new Vector3();
  25306. var px = new CubicPoly();
  25307. var py = new CubicPoly();
  25308. var pz = new CubicPoly();
  25309. function CatmullRomCurve3( points ) {
  25310. Curve.call( this );
  25311. if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' );
  25312. this.points = points || [];
  25313. this.closed = false;
  25314. }
  25315. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  25316. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  25317. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  25318. var points = this.points;
  25319. var l = points.length;
  25320. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  25321. var intPoint = Math.floor( point );
  25322. var weight = point - intPoint;
  25323. if ( this.closed ) {
  25324. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  25325. } else if ( weight === 0 && intPoint === l - 1 ) {
  25326. intPoint = l - 2;
  25327. weight = 1;
  25328. }
  25329. var p0, p1, p2, p3; // 4 points
  25330. if ( this.closed || intPoint > 0 ) {
  25331. p0 = points[ ( intPoint - 1 ) % l ];
  25332. } else {
  25333. // extrapolate first point
  25334. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  25335. p0 = tmp;
  25336. }
  25337. p1 = points[ intPoint % l ];
  25338. p2 = points[ ( intPoint + 1 ) % l ];
  25339. if ( this.closed || intPoint + 2 < l ) {
  25340. p3 = points[ ( intPoint + 2 ) % l ];
  25341. } else {
  25342. // extrapolate last point
  25343. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  25344. p3 = tmp;
  25345. }
  25346. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  25347. // init Centripetal / Chordal Catmull-Rom
  25348. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  25349. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  25350. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  25351. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  25352. // safety check for repeated points
  25353. if ( dt1 < 1e-4 ) dt1 = 1.0;
  25354. if ( dt0 < 1e-4 ) dt0 = dt1;
  25355. if ( dt2 < 1e-4 ) dt2 = dt1;
  25356. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  25357. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  25358. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  25359. } else if ( this.type === 'catmullrom' ) {
  25360. var tension = this.tension !== undefined ? this.tension : 0.5;
  25361. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  25362. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  25363. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25364. }
  25365. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25366. };
  25367. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25368. Curve.call( this );
  25369. this.v0 = v0;
  25370. this.v1 = v1;
  25371. this.v2 = v2;
  25372. this.v3 = v3;
  25373. }
  25374. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25375. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25376. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25377. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25378. return new Vector3(
  25379. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25380. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25381. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25382. );
  25383. };
  25384. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25385. Curve.call( this );
  25386. this.v0 = v0;
  25387. this.v1 = v1;
  25388. this.v2 = v2;
  25389. }
  25390. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25391. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25392. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25393. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25394. return new Vector3(
  25395. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25396. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25397. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25398. );
  25399. };
  25400. function LineCurve3( v1, v2 ) {
  25401. Curve.call( this );
  25402. this.v1 = v1;
  25403. this.v2 = v2;
  25404. }
  25405. LineCurve3.prototype = Object.create( Curve.prototype );
  25406. LineCurve3.prototype.constructor = LineCurve3;
  25407. LineCurve3.prototype.getPoint = function ( t ) {
  25408. if ( t === 1 ) {
  25409. return this.v2.clone();
  25410. }
  25411. var vector = new Vector3();
  25412. vector.subVectors( this.v2, this.v1 ); // diff
  25413. vector.multiplyScalar( t );
  25414. vector.add( this.v1 );
  25415. return vector;
  25416. };
  25417. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25418. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25419. }
  25420. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25421. ArcCurve.prototype.constructor = ArcCurve;
  25422. /**
  25423. * @author alteredq / http://alteredqualia.com/
  25424. */
  25425. var SceneUtils = {
  25426. createMultiMaterialObject: function ( geometry, materials ) {
  25427. var group = new Group();
  25428. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25429. group.add( new Mesh( geometry, materials[ i ] ) );
  25430. }
  25431. return group;
  25432. },
  25433. detach: function ( child, parent, scene ) {
  25434. child.applyMatrix( parent.matrixWorld );
  25435. parent.remove( child );
  25436. scene.add( child );
  25437. },
  25438. attach: function ( child, scene, parent ) {
  25439. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  25440. scene.remove( child );
  25441. parent.add( child );
  25442. }
  25443. };
  25444. /**
  25445. * @author mrdoob / http://mrdoob.com/
  25446. */
  25447. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25448. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25449. return new Face3( a, b, c, normal, color, materialIndex );
  25450. }
  25451. var LineStrip = 0;
  25452. var LinePieces = 1;
  25453. function MeshFaceMaterial( materials ) {
  25454. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25455. return materials;
  25456. }
  25457. function MultiMaterial( materials ) {
  25458. if ( materials === undefined ) materials = [];
  25459. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25460. materials.isMultiMaterial = true;
  25461. materials.materials = materials;
  25462. materials.clone = function () {
  25463. return materials.slice();
  25464. };
  25465. return materials;
  25466. }
  25467. function PointCloud( geometry, material ) {
  25468. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25469. return new Points( geometry, material );
  25470. }
  25471. function Particle( material ) {
  25472. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25473. return new Sprite( material );
  25474. }
  25475. function ParticleSystem( geometry, material ) {
  25476. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25477. return new Points( geometry, material );
  25478. }
  25479. function PointCloudMaterial( parameters ) {
  25480. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25481. return new PointsMaterial( parameters );
  25482. }
  25483. function ParticleBasicMaterial( parameters ) {
  25484. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25485. return new PointsMaterial( parameters );
  25486. }
  25487. function ParticleSystemMaterial( parameters ) {
  25488. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25489. return new PointsMaterial( parameters );
  25490. }
  25491. function Vertex( x, y, z ) {
  25492. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25493. return new Vector3( x, y, z );
  25494. }
  25495. //
  25496. function DynamicBufferAttribute( array, itemSize ) {
  25497. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25498. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25499. }
  25500. function Int8Attribute( array, itemSize ) {
  25501. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25502. return new Int8BufferAttribute( array, itemSize );
  25503. }
  25504. function Uint8Attribute( array, itemSize ) {
  25505. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25506. return new Uint8BufferAttribute( array, itemSize );
  25507. }
  25508. function Uint8ClampedAttribute( array, itemSize ) {
  25509. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25510. return new Uint8ClampedBufferAttribute( array, itemSize );
  25511. }
  25512. function Int16Attribute( array, itemSize ) {
  25513. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25514. return new Int16BufferAttribute( array, itemSize );
  25515. }
  25516. function Uint16Attribute( array, itemSize ) {
  25517. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25518. return new Uint16BufferAttribute( array, itemSize );
  25519. }
  25520. function Int32Attribute( array, itemSize ) {
  25521. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25522. return new Int32BufferAttribute( array, itemSize );
  25523. }
  25524. function Uint32Attribute( array, itemSize ) {
  25525. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25526. return new Uint32BufferAttribute( array, itemSize );
  25527. }
  25528. function Float32Attribute( array, itemSize ) {
  25529. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25530. return new Float32BufferAttribute( array, itemSize );
  25531. }
  25532. function Float64Attribute( array, itemSize ) {
  25533. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25534. return new Float64BufferAttribute( array, itemSize );
  25535. }
  25536. //
  25537. Curve.create = function ( construct, getPoint ) {
  25538. console.log( 'THREE.Curve.create() has been deprecated' );
  25539. construct.prototype = Object.create( Curve.prototype );
  25540. construct.prototype.constructor = construct;
  25541. construct.prototype.getPoint = getPoint;
  25542. return construct;
  25543. };
  25544. //
  25545. function ClosedSplineCurve3( points ) {
  25546. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25547. CatmullRomCurve3.call( this, points );
  25548. this.type = 'catmullrom';
  25549. this.closed = true;
  25550. }
  25551. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25552. //
  25553. function SplineCurve3( points ) {
  25554. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25555. CatmullRomCurve3.call( this, points );
  25556. this.type = 'catmullrom';
  25557. }
  25558. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25559. //
  25560. function Spline( points ) {
  25561. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25562. CatmullRomCurve3.call( this, points );
  25563. this.type = 'catmullrom';
  25564. }
  25565. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25566. Object.assign( Spline.prototype, {
  25567. initFromArray: function ( a ) {
  25568. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25569. },
  25570. getControlPointsArray: function ( optionalTarget ) {
  25571. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25572. },
  25573. reparametrizeByArcLength: function ( samplingCoef ) {
  25574. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25575. }
  25576. } );
  25577. //
  25578. function BoundingBoxHelper( object, color ) {
  25579. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25580. return new BoxHelper( object, color );
  25581. }
  25582. function EdgesHelper( object, hex ) {
  25583. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25584. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25585. }
  25586. GridHelper.prototype.setColors = function () {
  25587. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25588. };
  25589. SkeletonHelper.prototype.update = function () {
  25590. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  25591. };
  25592. function WireframeHelper( object, hex ) {
  25593. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25594. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25595. }
  25596. //
  25597. function XHRLoader( manager ) {
  25598. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25599. return new FileLoader( manager );
  25600. }
  25601. function BinaryTextureLoader( manager ) {
  25602. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25603. return new DataTextureLoader( manager );
  25604. }
  25605. //
  25606. Object.assign( Box2.prototype, {
  25607. center: function ( optionalTarget ) {
  25608. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25609. return this.getCenter( optionalTarget );
  25610. },
  25611. empty: function () {
  25612. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25613. return this.isEmpty();
  25614. },
  25615. isIntersectionBox: function ( box ) {
  25616. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25617. return this.intersectsBox( box );
  25618. },
  25619. size: function ( optionalTarget ) {
  25620. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25621. return this.getSize( optionalTarget );
  25622. }
  25623. } );
  25624. Object.assign( Box3.prototype, {
  25625. center: function ( optionalTarget ) {
  25626. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25627. return this.getCenter( optionalTarget );
  25628. },
  25629. empty: function () {
  25630. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25631. return this.isEmpty();
  25632. },
  25633. isIntersectionBox: function ( box ) {
  25634. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25635. return this.intersectsBox( box );
  25636. },
  25637. isIntersectionSphere: function ( sphere ) {
  25638. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25639. return this.intersectsSphere( sphere );
  25640. },
  25641. size: function ( optionalTarget ) {
  25642. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25643. return this.getSize( optionalTarget );
  25644. }
  25645. } );
  25646. Line3.prototype.center = function ( optionalTarget ) {
  25647. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25648. return this.getCenter( optionalTarget );
  25649. };
  25650. _Math.random16 = function () {
  25651. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25652. return Math.random();
  25653. };
  25654. Object.assign( Matrix3.prototype, {
  25655. flattenToArrayOffset: function ( array, offset ) {
  25656. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25657. return this.toArray( array, offset );
  25658. },
  25659. multiplyVector3: function ( vector ) {
  25660. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25661. return vector.applyMatrix3( this );
  25662. },
  25663. multiplyVector3Array: function ( a ) {
  25664. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  25665. },
  25666. applyToBuffer: function( buffer, offset, length ) {
  25667. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25668. return this.applyToBufferAttribute( buffer );
  25669. },
  25670. applyToVector3Array: function( array, offset, length ) {
  25671. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25672. }
  25673. } );
  25674. Object.assign( Matrix4.prototype, {
  25675. extractPosition: function ( m ) {
  25676. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25677. return this.copyPosition( m );
  25678. },
  25679. flattenToArrayOffset: function ( array, offset ) {
  25680. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25681. return this.toArray( array, offset );
  25682. },
  25683. getPosition: function () {
  25684. var v1;
  25685. return function getPosition() {
  25686. if ( v1 === undefined ) v1 = new Vector3();
  25687. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25688. return v1.setFromMatrixColumn( this, 3 );
  25689. };
  25690. }(),
  25691. setRotationFromQuaternion: function ( q ) {
  25692. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25693. return this.makeRotationFromQuaternion( q );
  25694. },
  25695. multiplyToArray: function () {
  25696. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25697. },
  25698. multiplyVector3: function ( vector ) {
  25699. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25700. return vector.applyMatrix4( this );
  25701. },
  25702. multiplyVector4: function ( vector ) {
  25703. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25704. return vector.applyMatrix4( this );
  25705. },
  25706. multiplyVector3Array: function ( a ) {
  25707. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  25708. },
  25709. rotateAxis: function ( v ) {
  25710. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25711. v.transformDirection( this );
  25712. },
  25713. crossVector: function ( vector ) {
  25714. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25715. return vector.applyMatrix4( this );
  25716. },
  25717. translate: function () {
  25718. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25719. },
  25720. rotateX: function () {
  25721. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25722. },
  25723. rotateY: function () {
  25724. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25725. },
  25726. rotateZ: function () {
  25727. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25728. },
  25729. rotateByAxis: function () {
  25730. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25731. },
  25732. applyToBuffer: function( buffer, offset, length ) {
  25733. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25734. return this.applyToBufferAttribute( buffer );
  25735. },
  25736. applyToVector3Array: function( array, offset, length ) {
  25737. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25738. },
  25739. makeFrustum: function( left, right, bottom, top, near, far ) {
  25740. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25741. return this.makePerspective( left, right, top, bottom, near, far );
  25742. }
  25743. } );
  25744. Plane.prototype.isIntersectionLine = function ( line ) {
  25745. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25746. return this.intersectsLine( line );
  25747. };
  25748. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25749. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25750. return vector.applyQuaternion( this );
  25751. };
  25752. Object.assign( Ray.prototype, {
  25753. isIntersectionBox: function ( box ) {
  25754. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25755. return this.intersectsBox( box );
  25756. },
  25757. isIntersectionPlane: function ( plane ) {
  25758. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25759. return this.intersectsPlane( plane );
  25760. },
  25761. isIntersectionSphere: function ( sphere ) {
  25762. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25763. return this.intersectsSphere( sphere );
  25764. }
  25765. } );
  25766. Object.assign( Shape.prototype, {
  25767. extrude: function ( options ) {
  25768. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25769. return new ExtrudeGeometry( this, options );
  25770. },
  25771. makeGeometry: function ( options ) {
  25772. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25773. return new ShapeGeometry( this, options );
  25774. }
  25775. } );
  25776. Object.assign( Vector2.prototype, {
  25777. fromAttribute: function ( attribute, index, offset ) {
  25778. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25779. return this.fromBufferAttribute( attribute, index, offset );
  25780. }
  25781. } );
  25782. Object.assign( Vector3.prototype, {
  25783. setEulerFromRotationMatrix: function () {
  25784. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25785. },
  25786. setEulerFromQuaternion: function () {
  25787. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25788. },
  25789. getPositionFromMatrix: function ( m ) {
  25790. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25791. return this.setFromMatrixPosition( m );
  25792. },
  25793. getScaleFromMatrix: function ( m ) {
  25794. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25795. return this.setFromMatrixScale( m );
  25796. },
  25797. getColumnFromMatrix: function ( index, matrix ) {
  25798. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25799. return this.setFromMatrixColumn( matrix, index );
  25800. },
  25801. applyProjection: function ( m ) {
  25802. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25803. return this.applyMatrix4( m );
  25804. },
  25805. fromAttribute: function ( attribute, index, offset ) {
  25806. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25807. return this.fromBufferAttribute( attribute, index, offset );
  25808. }
  25809. } );
  25810. Object.assign( Vector4.prototype, {
  25811. fromAttribute: function ( attribute, index, offset ) {
  25812. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25813. return this.fromBufferAttribute( attribute, index, offset );
  25814. }
  25815. } );
  25816. //
  25817. Geometry.prototype.computeTangents = function () {
  25818. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25819. };
  25820. Object.assign( Object3D.prototype, {
  25821. getChildByName: function ( name ) {
  25822. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25823. return this.getObjectByName( name );
  25824. },
  25825. renderDepth: function () {
  25826. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25827. },
  25828. translate: function ( distance, axis ) {
  25829. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25830. return this.translateOnAxis( axis, distance );
  25831. }
  25832. } );
  25833. Object.defineProperties( Object3D.prototype, {
  25834. eulerOrder: {
  25835. get: function () {
  25836. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25837. return this.rotation.order;
  25838. },
  25839. set: function ( value ) {
  25840. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25841. this.rotation.order = value;
  25842. }
  25843. },
  25844. useQuaternion: {
  25845. get: function () {
  25846. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25847. },
  25848. set: function () {
  25849. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25850. }
  25851. }
  25852. } );
  25853. Object.defineProperties( LOD.prototype, {
  25854. objects: {
  25855. get: function () {
  25856. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25857. return this.levels;
  25858. }
  25859. }
  25860. } );
  25861. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25862. get: function () {
  25863. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25864. },
  25865. set: function () {
  25866. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25867. }
  25868. } );
  25869. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25870. get: function () {
  25871. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25872. return this.arcLengthDivisions;
  25873. },
  25874. set: function ( value ) {
  25875. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25876. this.arcLengthDivisions = value;
  25877. }
  25878. } );
  25879. //
  25880. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25881. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25882. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25883. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25884. this.setFocalLength( focalLength );
  25885. };
  25886. //
  25887. Object.defineProperties( Light.prototype, {
  25888. onlyShadow: {
  25889. set: function () {
  25890. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25891. }
  25892. },
  25893. shadowCameraFov: {
  25894. set: function ( value ) {
  25895. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25896. this.shadow.camera.fov = value;
  25897. }
  25898. },
  25899. shadowCameraLeft: {
  25900. set: function ( value ) {
  25901. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25902. this.shadow.camera.left = value;
  25903. }
  25904. },
  25905. shadowCameraRight: {
  25906. set: function ( value ) {
  25907. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25908. this.shadow.camera.right = value;
  25909. }
  25910. },
  25911. shadowCameraTop: {
  25912. set: function ( value ) {
  25913. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25914. this.shadow.camera.top = value;
  25915. }
  25916. },
  25917. shadowCameraBottom: {
  25918. set: function ( value ) {
  25919. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25920. this.shadow.camera.bottom = value;
  25921. }
  25922. },
  25923. shadowCameraNear: {
  25924. set: function ( value ) {
  25925. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25926. this.shadow.camera.near = value;
  25927. }
  25928. },
  25929. shadowCameraFar: {
  25930. set: function ( value ) {
  25931. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25932. this.shadow.camera.far = value;
  25933. }
  25934. },
  25935. shadowCameraVisible: {
  25936. set: function () {
  25937. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25938. }
  25939. },
  25940. shadowBias: {
  25941. set: function ( value ) {
  25942. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25943. this.shadow.bias = value;
  25944. }
  25945. },
  25946. shadowDarkness: {
  25947. set: function () {
  25948. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25949. }
  25950. },
  25951. shadowMapWidth: {
  25952. set: function ( value ) {
  25953. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25954. this.shadow.mapSize.width = value;
  25955. }
  25956. },
  25957. shadowMapHeight: {
  25958. set: function ( value ) {
  25959. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25960. this.shadow.mapSize.height = value;
  25961. }
  25962. }
  25963. } );
  25964. //
  25965. Object.defineProperties( BufferAttribute.prototype, {
  25966. length: {
  25967. get: function () {
  25968. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25969. return this.array.length;
  25970. }
  25971. }
  25972. } );
  25973. Object.assign( BufferGeometry.prototype, {
  25974. addIndex: function ( index ) {
  25975. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25976. this.setIndex( index );
  25977. },
  25978. addDrawCall: function ( start, count, indexOffset ) {
  25979. if ( indexOffset !== undefined ) {
  25980. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25981. }
  25982. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25983. this.addGroup( start, count );
  25984. },
  25985. clearDrawCalls: function () {
  25986. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25987. this.clearGroups();
  25988. },
  25989. computeTangents: function () {
  25990. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25991. },
  25992. computeOffsets: function () {
  25993. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25994. }
  25995. } );
  25996. Object.defineProperties( BufferGeometry.prototype, {
  25997. drawcalls: {
  25998. get: function () {
  25999. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  26000. return this.groups;
  26001. }
  26002. },
  26003. offsets: {
  26004. get: function () {
  26005. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  26006. return this.groups;
  26007. }
  26008. }
  26009. } );
  26010. //
  26011. Object.defineProperties( Uniform.prototype, {
  26012. dynamic: {
  26013. set: function () {
  26014. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  26015. }
  26016. },
  26017. onUpdate: {
  26018. value: function () {
  26019. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  26020. return this;
  26021. }
  26022. }
  26023. } );
  26024. //
  26025. Object.defineProperties( Material.prototype, {
  26026. wrapAround: {
  26027. get: function () {
  26028. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  26029. },
  26030. set: function () {
  26031. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  26032. }
  26033. },
  26034. wrapRGB: {
  26035. get: function () {
  26036. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  26037. return new Color();
  26038. }
  26039. },
  26040. shading: {
  26041. get: function () {
  26042. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  26043. },
  26044. set: function ( value ) {
  26045. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  26046. this.flatShading = ( value === THREE.FlatShading ) ? true : false;
  26047. }
  26048. }
  26049. } );
  26050. Object.defineProperties( MeshPhongMaterial.prototype, {
  26051. metal: {
  26052. get: function () {
  26053. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  26054. return false;
  26055. },
  26056. set: function () {
  26057. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  26058. }
  26059. }
  26060. } );
  26061. Object.defineProperties( ShaderMaterial.prototype, {
  26062. derivatives: {
  26063. get: function () {
  26064. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  26065. return this.extensions.derivatives;
  26066. },
  26067. set: function ( value ) {
  26068. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  26069. this.extensions.derivatives = value;
  26070. }
  26071. }
  26072. } );
  26073. //
  26074. Object.assign( WebGLRenderer.prototype, {
  26075. getCurrentRenderTarget: function () {
  26076. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  26077. return this.getRenderTarget();
  26078. },
  26079. getMaxAnisotropy: function () {
  26080. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  26081. return this.capabilities.getMaxAnisotropy();
  26082. },
  26083. getPrecision: function () {
  26084. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  26085. return this.capabilities.precision;
  26086. },
  26087. supportsFloatTextures: function () {
  26088. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  26089. return this.extensions.get( 'OES_texture_float' );
  26090. },
  26091. supportsHalfFloatTextures: function () {
  26092. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  26093. return this.extensions.get( 'OES_texture_half_float' );
  26094. },
  26095. supportsStandardDerivatives: function () {
  26096. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  26097. return this.extensions.get( 'OES_standard_derivatives' );
  26098. },
  26099. supportsCompressedTextureS3TC: function () {
  26100. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  26101. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  26102. },
  26103. supportsCompressedTexturePVRTC: function () {
  26104. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  26105. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  26106. },
  26107. supportsBlendMinMax: function () {
  26108. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  26109. return this.extensions.get( 'EXT_blend_minmax' );
  26110. },
  26111. supportsVertexTextures: function () {
  26112. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  26113. return this.capabilities.vertexTextures;
  26114. },
  26115. supportsInstancedArrays: function () {
  26116. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  26117. return this.extensions.get( 'ANGLE_instanced_arrays' );
  26118. },
  26119. enableScissorTest: function ( boolean ) {
  26120. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  26121. this.setScissorTest( boolean );
  26122. },
  26123. initMaterial: function () {
  26124. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  26125. },
  26126. addPrePlugin: function () {
  26127. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  26128. },
  26129. addPostPlugin: function () {
  26130. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  26131. },
  26132. updateShadowMap: function () {
  26133. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  26134. }
  26135. } );
  26136. Object.defineProperties( WebGLRenderer.prototype, {
  26137. shadowMapEnabled: {
  26138. get: function () {
  26139. return this.shadowMap.enabled;
  26140. },
  26141. set: function ( value ) {
  26142. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  26143. this.shadowMap.enabled = value;
  26144. }
  26145. },
  26146. shadowMapType: {
  26147. get: function () {
  26148. return this.shadowMap.type;
  26149. },
  26150. set: function ( value ) {
  26151. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  26152. this.shadowMap.type = value;
  26153. }
  26154. },
  26155. shadowMapCullFace: {
  26156. get: function () {
  26157. return this.shadowMap.cullFace;
  26158. },
  26159. set: function ( value ) {
  26160. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  26161. this.shadowMap.cullFace = value;
  26162. }
  26163. }
  26164. } );
  26165. Object.defineProperties( WebGLShadowMap.prototype, {
  26166. cullFace: {
  26167. get: function () {
  26168. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  26169. },
  26170. set: function ( cullFace ) {
  26171. var value = ( cullFace !== CullFaceBack );
  26172. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  26173. this.renderReverseSided = value;
  26174. }
  26175. }
  26176. } );
  26177. //
  26178. Object.defineProperties( WebGLRenderTarget.prototype, {
  26179. wrapS: {
  26180. get: function () {
  26181. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26182. return this.texture.wrapS;
  26183. },
  26184. set: function ( value ) {
  26185. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  26186. this.texture.wrapS = value;
  26187. }
  26188. },
  26189. wrapT: {
  26190. get: function () {
  26191. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26192. return this.texture.wrapT;
  26193. },
  26194. set: function ( value ) {
  26195. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  26196. this.texture.wrapT = value;
  26197. }
  26198. },
  26199. magFilter: {
  26200. get: function () {
  26201. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26202. return this.texture.magFilter;
  26203. },
  26204. set: function ( value ) {
  26205. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  26206. this.texture.magFilter = value;
  26207. }
  26208. },
  26209. minFilter: {
  26210. get: function () {
  26211. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26212. return this.texture.minFilter;
  26213. },
  26214. set: function ( value ) {
  26215. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  26216. this.texture.minFilter = value;
  26217. }
  26218. },
  26219. anisotropy: {
  26220. get: function () {
  26221. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26222. return this.texture.anisotropy;
  26223. },
  26224. set: function ( value ) {
  26225. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  26226. this.texture.anisotropy = value;
  26227. }
  26228. },
  26229. offset: {
  26230. get: function () {
  26231. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26232. return this.texture.offset;
  26233. },
  26234. set: function ( value ) {
  26235. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  26236. this.texture.offset = value;
  26237. }
  26238. },
  26239. repeat: {
  26240. get: function () {
  26241. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26242. return this.texture.repeat;
  26243. },
  26244. set: function ( value ) {
  26245. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  26246. this.texture.repeat = value;
  26247. }
  26248. },
  26249. format: {
  26250. get: function () {
  26251. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26252. return this.texture.format;
  26253. },
  26254. set: function ( value ) {
  26255. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  26256. this.texture.format = value;
  26257. }
  26258. },
  26259. type: {
  26260. get: function () {
  26261. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26262. return this.texture.type;
  26263. },
  26264. set: function ( value ) {
  26265. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  26266. this.texture.type = value;
  26267. }
  26268. },
  26269. generateMipmaps: {
  26270. get: function () {
  26271. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26272. return this.texture.generateMipmaps;
  26273. },
  26274. set: function ( value ) {
  26275. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  26276. this.texture.generateMipmaps = value;
  26277. }
  26278. }
  26279. } );
  26280. //
  26281. Audio.prototype.load = function ( file ) {
  26282. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  26283. var scope = this;
  26284. var audioLoader = new AudioLoader();
  26285. audioLoader.load( file, function ( buffer ) {
  26286. scope.setBuffer( buffer );
  26287. } );
  26288. return this;
  26289. };
  26290. AudioAnalyser.prototype.getData = function () {
  26291. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  26292. return this.getFrequencyData();
  26293. };
  26294. //
  26295. var GeometryUtils = {
  26296. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  26297. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  26298. var matrix;
  26299. if ( geometry2.isMesh ) {
  26300. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  26301. matrix = geometry2.matrix;
  26302. geometry2 = geometry2.geometry;
  26303. }
  26304. geometry1.merge( geometry2, matrix, materialIndexOffset );
  26305. },
  26306. center: function ( geometry ) {
  26307. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  26308. return geometry.center();
  26309. }
  26310. };
  26311. var ImageUtils = {
  26312. crossOrigin: undefined,
  26313. loadTexture: function ( url, mapping, onLoad, onError ) {
  26314. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  26315. var loader = new TextureLoader();
  26316. loader.setCrossOrigin( this.crossOrigin );
  26317. var texture = loader.load( url, onLoad, undefined, onError );
  26318. if ( mapping ) texture.mapping = mapping;
  26319. return texture;
  26320. },
  26321. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  26322. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  26323. var loader = new CubeTextureLoader();
  26324. loader.setCrossOrigin( this.crossOrigin );
  26325. var texture = loader.load( urls, onLoad, undefined, onError );
  26326. if ( mapping ) texture.mapping = mapping;
  26327. return texture;
  26328. },
  26329. loadCompressedTexture: function () {
  26330. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  26331. },
  26332. loadCompressedTextureCube: function () {
  26333. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  26334. }
  26335. };
  26336. //
  26337. function Projector() {
  26338. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  26339. this.projectVector = function ( vector, camera ) {
  26340. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  26341. vector.project( camera );
  26342. };
  26343. this.unprojectVector = function ( vector, camera ) {
  26344. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  26345. vector.unproject( camera );
  26346. };
  26347. this.pickingRay = function () {
  26348. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  26349. };
  26350. }
  26351. //
  26352. function CanvasRenderer() {
  26353. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  26354. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  26355. this.clear = function () {};
  26356. this.render = function () {};
  26357. this.setClearColor = function () {};
  26358. this.setSize = function () {};
  26359. }
  26360. 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, Box3Helper, PlaneHelper, 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, MeshDistanceMaterial, 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 };