three.js 1015 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.THREE = global.THREE || {})));
  5. }(this, (function (exports) { 'use strict';
  6. // Polyfills
  7. if ( Number.EPSILON === undefined ) {
  8. Number.EPSILON = Math.pow( 2, - 52 );
  9. }
  10. if ( Number.isInteger === undefined ) {
  11. // Missing in IE
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  13. Number.isInteger = function ( value ) {
  14. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  15. };
  16. }
  17. //
  18. if ( Math.sign === undefined ) {
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  20. Math.sign = function ( x ) {
  21. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  22. };
  23. }
  24. if ( Function.prototype.name === undefined ) {
  25. // Missing in IE
  26. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  27. Object.defineProperty( Function.prototype, 'name', {
  28. get: function () {
  29. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  30. }
  31. } );
  32. }
  33. if ( Object.assign === undefined ) {
  34. // Missing in IE
  35. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  36. ( function () {
  37. Object.assign = function ( target ) {
  38. 'use strict';
  39. if ( target === undefined || target === null ) {
  40. throw new TypeError( 'Cannot convert undefined or null to object' );
  41. }
  42. var output = Object( target );
  43. for ( var index = 1; index < arguments.length; index ++ ) {
  44. var source = arguments[ index ];
  45. if ( source !== undefined && source !== null ) {
  46. for ( var nextKey in source ) {
  47. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  48. output[ nextKey ] = source[ nextKey ];
  49. }
  50. }
  51. }
  52. }
  53. return output;
  54. };
  55. } )();
  56. }
  57. /**
  58. * https://github.com/mrdoob/eventdispatcher.js/
  59. */
  60. function EventDispatcher() {}
  61. Object.assign( EventDispatcher.prototype, {
  62. addEventListener: function ( type, listener ) {
  63. if ( this._listeners === undefined ) this._listeners = {};
  64. var listeners = this._listeners;
  65. if ( listeners[ type ] === undefined ) {
  66. listeners[ type ] = [];
  67. }
  68. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  69. listeners[ type ].push( listener );
  70. }
  71. },
  72. hasEventListener: function ( type, listener ) {
  73. if ( this._listeners === undefined ) return false;
  74. var listeners = this._listeners;
  75. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  76. },
  77. removeEventListener: function ( type, listener ) {
  78. if ( this._listeners === undefined ) return;
  79. var listeners = this._listeners;
  80. var listenerArray = listeners[ type ];
  81. if ( listenerArray !== undefined ) {
  82. var index = listenerArray.indexOf( listener );
  83. if ( index !== - 1 ) {
  84. listenerArray.splice( index, 1 );
  85. }
  86. }
  87. },
  88. dispatchEvent: function ( event ) {
  89. if ( this._listeners === undefined ) return;
  90. var listeners = this._listeners;
  91. var listenerArray = listeners[ event.type ];
  92. if ( listenerArray !== undefined ) {
  93. event.target = this;
  94. var array = [], i = 0;
  95. var length = listenerArray.length;
  96. for ( i = 0; i < length; i ++ ) {
  97. array[ i ] = listenerArray[ i ];
  98. }
  99. for ( i = 0; i < length; i ++ ) {
  100. array[ i ].call( this, event );
  101. }
  102. }
  103. }
  104. } );
  105. var REVISION = '85';
  106. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  107. var CullFaceNone = 0;
  108. var CullFaceBack = 1;
  109. var CullFaceFront = 2;
  110. var CullFaceFrontBack = 3;
  111. var FrontFaceDirectionCW = 0;
  112. var FrontFaceDirectionCCW = 1;
  113. var BasicShadowMap = 0;
  114. var PCFShadowMap = 1;
  115. var PCFSoftShadowMap = 2;
  116. var FrontSide = 0;
  117. var BackSide = 1;
  118. var DoubleSide = 2;
  119. var FlatShading = 1;
  120. var SmoothShading = 2;
  121. var NoColors = 0;
  122. var FaceColors = 1;
  123. var VertexColors = 2;
  124. var NoBlending = 0;
  125. var NormalBlending = 1;
  126. var AdditiveBlending = 2;
  127. var SubtractiveBlending = 3;
  128. var MultiplyBlending = 4;
  129. var CustomBlending = 5;
  130. var AddEquation = 100;
  131. var SubtractEquation = 101;
  132. var ReverseSubtractEquation = 102;
  133. var MinEquation = 103;
  134. var MaxEquation = 104;
  135. var ZeroFactor = 200;
  136. var OneFactor = 201;
  137. var SrcColorFactor = 202;
  138. var OneMinusSrcColorFactor = 203;
  139. var SrcAlphaFactor = 204;
  140. var OneMinusSrcAlphaFactor = 205;
  141. var DstAlphaFactor = 206;
  142. var OneMinusDstAlphaFactor = 207;
  143. var DstColorFactor = 208;
  144. var OneMinusDstColorFactor = 209;
  145. var SrcAlphaSaturateFactor = 210;
  146. var NeverDepth = 0;
  147. var AlwaysDepth = 1;
  148. var LessDepth = 2;
  149. var LessEqualDepth = 3;
  150. var EqualDepth = 4;
  151. var GreaterEqualDepth = 5;
  152. var GreaterDepth = 6;
  153. var NotEqualDepth = 7;
  154. var MultiplyOperation = 0;
  155. var MixOperation = 1;
  156. var AddOperation = 2;
  157. var NoToneMapping = 0;
  158. var LinearToneMapping = 1;
  159. var ReinhardToneMapping = 2;
  160. var Uncharted2ToneMapping = 3;
  161. var CineonToneMapping = 4;
  162. var UVMapping = 300;
  163. var CubeReflectionMapping = 301;
  164. var CubeRefractionMapping = 302;
  165. var EquirectangularReflectionMapping = 303;
  166. var EquirectangularRefractionMapping = 304;
  167. var SphericalReflectionMapping = 305;
  168. var CubeUVReflectionMapping = 306;
  169. var CubeUVRefractionMapping = 307;
  170. var RepeatWrapping = 1000;
  171. var ClampToEdgeWrapping = 1001;
  172. var MirroredRepeatWrapping = 1002;
  173. var NearestFilter = 1003;
  174. var NearestMipMapNearestFilter = 1004;
  175. var NearestMipMapLinearFilter = 1005;
  176. var LinearFilter = 1006;
  177. var LinearMipMapNearestFilter = 1007;
  178. var LinearMipMapLinearFilter = 1008;
  179. var UnsignedByteType = 1009;
  180. var ByteType = 1010;
  181. var ShortType = 1011;
  182. var UnsignedShortType = 1012;
  183. var IntType = 1013;
  184. var UnsignedIntType = 1014;
  185. var FloatType = 1015;
  186. var HalfFloatType = 1016;
  187. var UnsignedShort4444Type = 1017;
  188. var UnsignedShort5551Type = 1018;
  189. var UnsignedShort565Type = 1019;
  190. var UnsignedInt248Type = 1020;
  191. var AlphaFormat = 1021;
  192. var RGBFormat = 1022;
  193. var RGBAFormat = 1023;
  194. var LuminanceFormat = 1024;
  195. var LuminanceAlphaFormat = 1025;
  196. var RGBEFormat = RGBAFormat;
  197. var DepthFormat = 1026;
  198. var DepthStencilFormat = 1027;
  199. var RGB_S3TC_DXT1_Format = 2001;
  200. var RGBA_S3TC_DXT1_Format = 2002;
  201. var RGBA_S3TC_DXT3_Format = 2003;
  202. var RGBA_S3TC_DXT5_Format = 2004;
  203. var RGB_PVRTC_4BPPV1_Format = 2100;
  204. var RGB_PVRTC_2BPPV1_Format = 2101;
  205. var RGBA_PVRTC_4BPPV1_Format = 2102;
  206. var RGBA_PVRTC_2BPPV1_Format = 2103;
  207. var RGB_ETC1_Format = 2151;
  208. var LoopOnce = 2200;
  209. var LoopRepeat = 2201;
  210. var LoopPingPong = 2202;
  211. var InterpolateDiscrete = 2300;
  212. var InterpolateLinear = 2301;
  213. var InterpolateSmooth = 2302;
  214. var ZeroCurvatureEnding = 2400;
  215. var ZeroSlopeEnding = 2401;
  216. var WrapAroundEnding = 2402;
  217. var TrianglesDrawMode = 0;
  218. var TriangleStripDrawMode = 1;
  219. var TriangleFanDrawMode = 2;
  220. var LinearEncoding = 3000;
  221. var sRGBEncoding = 3001;
  222. var GammaEncoding = 3007;
  223. var RGBEEncoding = 3002;
  224. var LogLuvEncoding = 3003;
  225. var RGBM7Encoding = 3004;
  226. var RGBM16Encoding = 3005;
  227. var RGBDEncoding = 3006;
  228. var BasicDepthPacking = 3200;
  229. var RGBADepthPacking = 3201;
  230. /**
  231. * @author alteredq / http://alteredqualia.com/
  232. * @author mrdoob / http://mrdoob.com/
  233. */
  234. var _Math = {
  235. DEG2RAD: Math.PI / 180,
  236. RAD2DEG: 180 / Math.PI,
  237. generateUUID: function () {
  238. // http://www.broofa.com/Tools/Math.uuid.htm
  239. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  240. var uuid = new Array( 36 );
  241. var rnd = 0, r;
  242. return function generateUUID() {
  243. for ( var i = 0; i < 36; i ++ ) {
  244. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  245. uuid[ i ] = '-';
  246. } else if ( i === 14 ) {
  247. uuid[ i ] = '4';
  248. } else {
  249. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  250. r = rnd & 0xf;
  251. rnd = rnd >> 4;
  252. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  253. }
  254. }
  255. return uuid.join( '' );
  256. };
  257. }(),
  258. clamp: function ( value, min, max ) {
  259. return Math.max( min, Math.min( max, value ) );
  260. },
  261. // compute euclidian modulo of m % n
  262. // https://en.wikipedia.org/wiki/Modulo_operation
  263. euclideanModulo: function ( n, m ) {
  264. return ( ( n % m ) + m ) % m;
  265. },
  266. // Linear mapping from range <a1, a2> to range <b1, b2>
  267. mapLinear: function ( x, a1, a2, b1, b2 ) {
  268. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  269. },
  270. // https://en.wikipedia.org/wiki/Linear_interpolation
  271. lerp: function ( x, y, t ) {
  272. return ( 1 - t ) * x + t * y;
  273. },
  274. // http://en.wikipedia.org/wiki/Smoothstep
  275. smoothstep: function ( x, min, max ) {
  276. if ( x <= min ) return 0;
  277. if ( x >= max ) return 1;
  278. x = ( x - min ) / ( max - min );
  279. return x * x * ( 3 - 2 * x );
  280. },
  281. smootherstep: function ( x, min, max ) {
  282. if ( x <= min ) return 0;
  283. if ( x >= max ) return 1;
  284. x = ( x - min ) / ( max - min );
  285. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  286. },
  287. // Random integer from <low, high> interval
  288. randInt: function ( low, high ) {
  289. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  290. },
  291. // Random float from <low, high> interval
  292. randFloat: function ( low, high ) {
  293. return low + Math.random() * ( high - low );
  294. },
  295. // Random float from <-range/2, range/2> interval
  296. randFloatSpread: function ( range ) {
  297. return range * ( 0.5 - Math.random() );
  298. },
  299. degToRad: function ( degrees ) {
  300. return degrees * _Math.DEG2RAD;
  301. },
  302. radToDeg: function ( radians ) {
  303. return radians * _Math.RAD2DEG;
  304. },
  305. isPowerOfTwo: function ( value ) {
  306. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  307. },
  308. nearestPowerOfTwo: function ( value ) {
  309. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  310. },
  311. nextPowerOfTwo: function ( value ) {
  312. value --;
  313. value |= value >> 1;
  314. value |= value >> 2;
  315. value |= value >> 4;
  316. value |= value >> 8;
  317. value |= value >> 16;
  318. value ++;
  319. return value;
  320. }
  321. };
  322. /**
  323. * @author mrdoob / http://mrdoob.com/
  324. * @author philogb / http://blog.thejit.org/
  325. * @author egraether / http://egraether.com/
  326. * @author zz85 / http://www.lab4games.net/zz85/blog
  327. */
  328. function Vector2( x, y ) {
  329. this.x = x || 0;
  330. this.y = y || 0;
  331. }
  332. Object.defineProperties( Vector2.prototype, {
  333. "width" : {
  334. get: function () {
  335. return this.x;
  336. },
  337. set: function ( value ) {
  338. this.x = value;
  339. }
  340. },
  341. "height" : {
  342. get: function () {
  343. return this.y;
  344. },
  345. set: function ( value ) {
  346. this.y = value;
  347. }
  348. }
  349. } );
  350. Object.assign( Vector2.prototype, {
  351. isVector2: true,
  352. set: function ( x, y ) {
  353. this.x = x;
  354. this.y = y;
  355. return this;
  356. },
  357. setScalar: function ( scalar ) {
  358. this.x = scalar;
  359. this.y = scalar;
  360. return this;
  361. },
  362. setX: function ( x ) {
  363. this.x = x;
  364. return this;
  365. },
  366. setY: function ( y ) {
  367. this.y = y;
  368. return this;
  369. },
  370. setComponent: function ( index, value ) {
  371. switch ( index ) {
  372. case 0: this.x = value; break;
  373. case 1: this.y = value; break;
  374. default: throw new Error( 'index is out of range: ' + index );
  375. }
  376. return this;
  377. },
  378. getComponent: function ( index ) {
  379. switch ( index ) {
  380. case 0: return this.x;
  381. case 1: return this.y;
  382. default: throw new Error( 'index is out of range: ' + index );
  383. }
  384. },
  385. clone: function () {
  386. return new this.constructor( this.x, this.y );
  387. },
  388. copy: function ( v ) {
  389. this.x = v.x;
  390. this.y = v.y;
  391. return this;
  392. },
  393. add: function ( v, w ) {
  394. if ( w !== undefined ) {
  395. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  396. return this.addVectors( v, w );
  397. }
  398. this.x += v.x;
  399. this.y += v.y;
  400. return this;
  401. },
  402. addScalar: function ( s ) {
  403. this.x += s;
  404. this.y += s;
  405. return this;
  406. },
  407. addVectors: function ( a, b ) {
  408. this.x = a.x + b.x;
  409. this.y = a.y + b.y;
  410. return this;
  411. },
  412. addScaledVector: function ( v, s ) {
  413. this.x += v.x * s;
  414. this.y += v.y * s;
  415. return this;
  416. },
  417. sub: function ( v, w ) {
  418. if ( w !== undefined ) {
  419. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  420. return this.subVectors( v, w );
  421. }
  422. this.x -= v.x;
  423. this.y -= v.y;
  424. return this;
  425. },
  426. subScalar: function ( s ) {
  427. this.x -= s;
  428. this.y -= s;
  429. return this;
  430. },
  431. subVectors: function ( a, b ) {
  432. this.x = a.x - b.x;
  433. this.y = a.y - b.y;
  434. return this;
  435. },
  436. multiply: function ( v ) {
  437. this.x *= v.x;
  438. this.y *= v.y;
  439. return this;
  440. },
  441. multiplyScalar: function ( scalar ) {
  442. this.x *= scalar;
  443. this.y *= scalar;
  444. return this;
  445. },
  446. divide: function ( v ) {
  447. this.x /= v.x;
  448. this.y /= v.y;
  449. return this;
  450. },
  451. divideScalar: function ( scalar ) {
  452. return this.multiplyScalar( 1 / scalar );
  453. },
  454. min: function ( v ) {
  455. this.x = Math.min( this.x, v.x );
  456. this.y = Math.min( this.y, v.y );
  457. return this;
  458. },
  459. max: function ( v ) {
  460. this.x = Math.max( this.x, v.x );
  461. this.y = Math.max( this.y, v.y );
  462. return this;
  463. },
  464. clamp: function ( min, max ) {
  465. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  466. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  467. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  468. return this;
  469. },
  470. clampScalar: function () {
  471. var min = new Vector2();
  472. var max = new Vector2();
  473. return function clampScalar( minVal, maxVal ) {
  474. min.set( minVal, minVal );
  475. max.set( maxVal, maxVal );
  476. return this.clamp( min, max );
  477. };
  478. }(),
  479. clampLength: function ( min, max ) {
  480. var length = this.length();
  481. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  482. },
  483. floor: function () {
  484. this.x = Math.floor( this.x );
  485. this.y = Math.floor( this.y );
  486. return this;
  487. },
  488. ceil: function () {
  489. this.x = Math.ceil( this.x );
  490. this.y = Math.ceil( this.y );
  491. return this;
  492. },
  493. round: function () {
  494. this.x = Math.round( this.x );
  495. this.y = Math.round( this.y );
  496. return this;
  497. },
  498. roundToZero: function () {
  499. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  500. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  501. return this;
  502. },
  503. negate: function () {
  504. this.x = - this.x;
  505. this.y = - this.y;
  506. return this;
  507. },
  508. dot: function ( v ) {
  509. return this.x * v.x + this.y * v.y;
  510. },
  511. lengthSq: function () {
  512. return this.x * this.x + this.y * this.y;
  513. },
  514. length: function () {
  515. return Math.sqrt( this.x * this.x + this.y * this.y );
  516. },
  517. lengthManhattan: function() {
  518. return Math.abs( this.x ) + Math.abs( this.y );
  519. },
  520. normalize: function () {
  521. return this.divideScalar( this.length() );
  522. },
  523. angle: function () {
  524. // computes the angle in radians with respect to the positive x-axis
  525. var angle = Math.atan2( this.y, this.x );
  526. if ( angle < 0 ) angle += 2 * Math.PI;
  527. return angle;
  528. },
  529. distanceTo: function ( v ) {
  530. return Math.sqrt( this.distanceToSquared( v ) );
  531. },
  532. distanceToSquared: function ( v ) {
  533. var dx = this.x - v.x, dy = this.y - v.y;
  534. return dx * dx + dy * dy;
  535. },
  536. distanceToManhattan: function ( v ) {
  537. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  538. },
  539. setLength: function ( length ) {
  540. return this.multiplyScalar( length / this.length() );
  541. },
  542. lerp: function ( v, alpha ) {
  543. this.x += ( v.x - this.x ) * alpha;
  544. this.y += ( v.y - this.y ) * alpha;
  545. return this;
  546. },
  547. lerpVectors: function ( v1, v2, alpha ) {
  548. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  549. },
  550. equals: function ( v ) {
  551. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  552. },
  553. fromArray: function ( array, offset ) {
  554. if ( offset === undefined ) offset = 0;
  555. this.x = array[ offset ];
  556. this.y = array[ offset + 1 ];
  557. return this;
  558. },
  559. toArray: function ( array, offset ) {
  560. if ( array === undefined ) array = [];
  561. if ( offset === undefined ) offset = 0;
  562. array[ offset ] = this.x;
  563. array[ offset + 1 ] = this.y;
  564. return array;
  565. },
  566. fromBufferAttribute: function ( attribute, index, offset ) {
  567. if ( offset !== undefined ) {
  568. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  569. }
  570. this.x = attribute.getX( index );
  571. this.y = attribute.getY( index );
  572. return this;
  573. },
  574. rotateAround: function ( center, angle ) {
  575. var c = Math.cos( angle ), s = Math.sin( angle );
  576. var x = this.x - center.x;
  577. var y = this.y - center.y;
  578. this.x = x * c - y * s + center.x;
  579. this.y = x * s + y * c + center.y;
  580. return this;
  581. }
  582. } );
  583. /**
  584. * @author mrdoob / http://mrdoob.com/
  585. * @author alteredq / http://alteredqualia.com/
  586. * @author szimek / https://github.com/szimek/
  587. */
  588. var textureId = 0;
  589. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  590. Object.defineProperty( this, 'id', { value: textureId ++ } );
  591. this.uuid = _Math.generateUUID();
  592. this.name = '';
  593. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  594. this.mipmaps = [];
  595. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  596. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  597. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  598. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  599. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  600. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  601. this.format = format !== undefined ? format : RGBAFormat;
  602. this.type = type !== undefined ? type : UnsignedByteType;
  603. this.offset = new Vector2( 0, 0 );
  604. this.repeat = new Vector2( 1, 1 );
  605. this.generateMipmaps = true;
  606. this.premultiplyAlpha = false;
  607. this.flipY = true;
  608. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  609. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  610. //
  611. // Also changing the encoding after already used by a Material will not automatically make the Material
  612. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  613. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  614. this.version = 0;
  615. this.onUpdate = null;
  616. }
  617. Texture.DEFAULT_IMAGE = undefined;
  618. Texture.DEFAULT_MAPPING = UVMapping;
  619. Object.defineProperty( Texture.prototype, "needsUpdate", {
  620. set: function ( value ) {
  621. if ( value === true ) this.version ++;
  622. }
  623. } );
  624. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  625. constructor: Texture,
  626. isTexture: true,
  627. clone: function () {
  628. return new this.constructor().copy( this );
  629. },
  630. copy: function ( source ) {
  631. this.name = source.name;
  632. this.image = source.image;
  633. this.mipmaps = source.mipmaps.slice( 0 );
  634. this.mapping = source.mapping;
  635. this.wrapS = source.wrapS;
  636. this.wrapT = source.wrapT;
  637. this.magFilter = source.magFilter;
  638. this.minFilter = source.minFilter;
  639. this.anisotropy = source.anisotropy;
  640. this.format = source.format;
  641. this.type = source.type;
  642. this.offset.copy( source.offset );
  643. this.repeat.copy( source.repeat );
  644. this.generateMipmaps = source.generateMipmaps;
  645. this.premultiplyAlpha = source.premultiplyAlpha;
  646. this.flipY = source.flipY;
  647. this.unpackAlignment = source.unpackAlignment;
  648. this.encoding = source.encoding;
  649. return this;
  650. },
  651. toJSON: function ( meta ) {
  652. if ( meta.textures[ this.uuid ] !== undefined ) {
  653. return meta.textures[ this.uuid ];
  654. }
  655. function getDataURL( image ) {
  656. var canvas;
  657. if ( image.toDataURL !== undefined ) {
  658. canvas = image;
  659. } else {
  660. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  661. canvas.width = image.width;
  662. canvas.height = image.height;
  663. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  664. }
  665. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  666. return canvas.toDataURL( 'image/jpeg', 0.6 );
  667. } else {
  668. return canvas.toDataURL( 'image/png' );
  669. }
  670. }
  671. var output = {
  672. metadata: {
  673. version: 4.5,
  674. type: 'Texture',
  675. generator: 'Texture.toJSON'
  676. },
  677. uuid: this.uuid,
  678. name: this.name,
  679. mapping: this.mapping,
  680. repeat: [ this.repeat.x, this.repeat.y ],
  681. offset: [ this.offset.x, this.offset.y ],
  682. wrap: [ this.wrapS, this.wrapT ],
  683. minFilter: this.minFilter,
  684. magFilter: this.magFilter,
  685. anisotropy: this.anisotropy,
  686. flipY: this.flipY
  687. };
  688. if ( this.image !== undefined ) {
  689. // TODO: Move to THREE.Image
  690. var image = this.image;
  691. if ( image.uuid === undefined ) {
  692. image.uuid = _Math.generateUUID(); // UGH
  693. }
  694. if ( meta.images[ image.uuid ] === undefined ) {
  695. meta.images[ image.uuid ] = {
  696. uuid: image.uuid,
  697. url: getDataURL( image )
  698. };
  699. }
  700. output.image = image.uuid;
  701. }
  702. meta.textures[ this.uuid ] = output;
  703. return output;
  704. },
  705. dispose: function () {
  706. this.dispatchEvent( { type: 'dispose' } );
  707. },
  708. transformUv: function ( uv ) {
  709. if ( this.mapping !== UVMapping ) return;
  710. uv.multiply( this.repeat );
  711. uv.add( this.offset );
  712. if ( uv.x < 0 || uv.x > 1 ) {
  713. switch ( this.wrapS ) {
  714. case RepeatWrapping:
  715. uv.x = uv.x - Math.floor( uv.x );
  716. break;
  717. case ClampToEdgeWrapping:
  718. uv.x = uv.x < 0 ? 0 : 1;
  719. break;
  720. case MirroredRepeatWrapping:
  721. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  722. uv.x = Math.ceil( uv.x ) - uv.x;
  723. } else {
  724. uv.x = uv.x - Math.floor( uv.x );
  725. }
  726. break;
  727. }
  728. }
  729. if ( uv.y < 0 || uv.y > 1 ) {
  730. switch ( this.wrapT ) {
  731. case RepeatWrapping:
  732. uv.y = uv.y - Math.floor( uv.y );
  733. break;
  734. case ClampToEdgeWrapping:
  735. uv.y = uv.y < 0 ? 0 : 1;
  736. break;
  737. case MirroredRepeatWrapping:
  738. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  739. uv.y = Math.ceil( uv.y ) - uv.y;
  740. } else {
  741. uv.y = uv.y - Math.floor( uv.y );
  742. }
  743. break;
  744. }
  745. }
  746. if ( this.flipY ) {
  747. uv.y = 1 - uv.y;
  748. }
  749. }
  750. } );
  751. /**
  752. * @author supereggbert / http://www.paulbrunt.co.uk/
  753. * @author philogb / http://blog.thejit.org/
  754. * @author mikael emtinger / http://gomo.se/
  755. * @author egraether / http://egraether.com/
  756. * @author WestLangley / http://github.com/WestLangley
  757. */
  758. function Vector4( x, y, z, w ) {
  759. this.x = x || 0;
  760. this.y = y || 0;
  761. this.z = z || 0;
  762. this.w = ( w !== undefined ) ? w : 1;
  763. }
  764. Object.assign( Vector4.prototype, {
  765. isVector4: true,
  766. set: function ( x, y, z, w ) {
  767. this.x = x;
  768. this.y = y;
  769. this.z = z;
  770. this.w = w;
  771. return this;
  772. },
  773. setScalar: function ( scalar ) {
  774. this.x = scalar;
  775. this.y = scalar;
  776. this.z = scalar;
  777. this.w = scalar;
  778. return this;
  779. },
  780. setX: function ( x ) {
  781. this.x = x;
  782. return this;
  783. },
  784. setY: function ( y ) {
  785. this.y = y;
  786. return this;
  787. },
  788. setZ: function ( z ) {
  789. this.z = z;
  790. return this;
  791. },
  792. setW: function ( w ) {
  793. this.w = w;
  794. return this;
  795. },
  796. setComponent: function ( index, value ) {
  797. switch ( index ) {
  798. case 0: this.x = value; break;
  799. case 1: this.y = value; break;
  800. case 2: this.z = value; break;
  801. case 3: this.w = value; break;
  802. default: throw new Error( 'index is out of range: ' + index );
  803. }
  804. return this;
  805. },
  806. getComponent: function ( index ) {
  807. switch ( index ) {
  808. case 0: return this.x;
  809. case 1: return this.y;
  810. case 2: return this.z;
  811. case 3: return this.w;
  812. default: throw new Error( 'index is out of range: ' + index );
  813. }
  814. },
  815. clone: function () {
  816. return new this.constructor( this.x, this.y, this.z, this.w );
  817. },
  818. copy: function ( v ) {
  819. this.x = v.x;
  820. this.y = v.y;
  821. this.z = v.z;
  822. this.w = ( v.w !== undefined ) ? v.w : 1;
  823. return this;
  824. },
  825. add: function ( v, w ) {
  826. if ( w !== undefined ) {
  827. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  828. return this.addVectors( v, w );
  829. }
  830. this.x += v.x;
  831. this.y += v.y;
  832. this.z += v.z;
  833. this.w += v.w;
  834. return this;
  835. },
  836. addScalar: function ( s ) {
  837. this.x += s;
  838. this.y += s;
  839. this.z += s;
  840. this.w += s;
  841. return this;
  842. },
  843. addVectors: function ( a, b ) {
  844. this.x = a.x + b.x;
  845. this.y = a.y + b.y;
  846. this.z = a.z + b.z;
  847. this.w = a.w + b.w;
  848. return this;
  849. },
  850. addScaledVector: function ( v, s ) {
  851. this.x += v.x * s;
  852. this.y += v.y * s;
  853. this.z += v.z * s;
  854. this.w += v.w * s;
  855. return this;
  856. },
  857. sub: function ( v, w ) {
  858. if ( w !== undefined ) {
  859. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  860. return this.subVectors( v, w );
  861. }
  862. this.x -= v.x;
  863. this.y -= v.y;
  864. this.z -= v.z;
  865. this.w -= v.w;
  866. return this;
  867. },
  868. subScalar: function ( s ) {
  869. this.x -= s;
  870. this.y -= s;
  871. this.z -= s;
  872. this.w -= s;
  873. return this;
  874. },
  875. subVectors: function ( a, b ) {
  876. this.x = a.x - b.x;
  877. this.y = a.y - b.y;
  878. this.z = a.z - b.z;
  879. this.w = a.w - b.w;
  880. return this;
  881. },
  882. multiplyScalar: function ( scalar ) {
  883. this.x *= scalar;
  884. this.y *= scalar;
  885. this.z *= scalar;
  886. this.w *= scalar;
  887. return this;
  888. },
  889. applyMatrix4: function ( m ) {
  890. var x = this.x, y = this.y, z = this.z, w = this.w;
  891. var e = m.elements;
  892. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  893. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  894. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  895. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  896. return this;
  897. },
  898. divideScalar: function ( scalar ) {
  899. return this.multiplyScalar( 1 / scalar );
  900. },
  901. setAxisAngleFromQuaternion: function ( q ) {
  902. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  903. // q is assumed to be normalized
  904. this.w = 2 * Math.acos( q.w );
  905. var s = Math.sqrt( 1 - q.w * q.w );
  906. if ( s < 0.0001 ) {
  907. this.x = 1;
  908. this.y = 0;
  909. this.z = 0;
  910. } else {
  911. this.x = q.x / s;
  912. this.y = q.y / s;
  913. this.z = q.z / s;
  914. }
  915. return this;
  916. },
  917. setAxisAngleFromRotationMatrix: function ( m ) {
  918. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  919. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  920. var angle, x, y, z, // variables for result
  921. epsilon = 0.01, // margin to allow for rounding errors
  922. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  923. te = m.elements,
  924. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  925. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  926. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  927. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  928. ( Math.abs( m13 - m31 ) < epsilon ) &&
  929. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  930. // singularity found
  931. // first check for identity matrix which must have +1 for all terms
  932. // in leading diagonal and zero in other terms
  933. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  934. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  935. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  936. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  937. // this singularity is identity matrix so angle = 0
  938. this.set( 1, 0, 0, 0 );
  939. return this; // zero angle, arbitrary axis
  940. }
  941. // otherwise this singularity is angle = 180
  942. angle = Math.PI;
  943. var xx = ( m11 + 1 ) / 2;
  944. var yy = ( m22 + 1 ) / 2;
  945. var zz = ( m33 + 1 ) / 2;
  946. var xy = ( m12 + m21 ) / 4;
  947. var xz = ( m13 + m31 ) / 4;
  948. var yz = ( m23 + m32 ) / 4;
  949. if ( ( xx > yy ) && ( xx > zz ) ) {
  950. // m11 is the largest diagonal term
  951. if ( xx < epsilon ) {
  952. x = 0;
  953. y = 0.707106781;
  954. z = 0.707106781;
  955. } else {
  956. x = Math.sqrt( xx );
  957. y = xy / x;
  958. z = xz / x;
  959. }
  960. } else if ( yy > zz ) {
  961. // m22 is the largest diagonal term
  962. if ( yy < epsilon ) {
  963. x = 0.707106781;
  964. y = 0;
  965. z = 0.707106781;
  966. } else {
  967. y = Math.sqrt( yy );
  968. x = xy / y;
  969. z = yz / y;
  970. }
  971. } else {
  972. // m33 is the largest diagonal term so base result on this
  973. if ( zz < epsilon ) {
  974. x = 0.707106781;
  975. y = 0.707106781;
  976. z = 0;
  977. } else {
  978. z = Math.sqrt( zz );
  979. x = xz / z;
  980. y = yz / z;
  981. }
  982. }
  983. this.set( x, y, z, angle );
  984. return this; // return 180 deg rotation
  985. }
  986. // as we have reached here there are no singularities so we can handle normally
  987. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  988. ( m13 - m31 ) * ( m13 - m31 ) +
  989. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  990. if ( Math.abs( s ) < 0.001 ) s = 1;
  991. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  992. // caught by singularity test above, but I've left it in just in case
  993. this.x = ( m32 - m23 ) / s;
  994. this.y = ( m13 - m31 ) / s;
  995. this.z = ( m21 - m12 ) / s;
  996. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  997. return this;
  998. },
  999. min: function ( v ) {
  1000. this.x = Math.min( this.x, v.x );
  1001. this.y = Math.min( this.y, v.y );
  1002. this.z = Math.min( this.z, v.z );
  1003. this.w = Math.min( this.w, v.w );
  1004. return this;
  1005. },
  1006. max: function ( v ) {
  1007. this.x = Math.max( this.x, v.x );
  1008. this.y = Math.max( this.y, v.y );
  1009. this.z = Math.max( this.z, v.z );
  1010. this.w = Math.max( this.w, v.w );
  1011. return this;
  1012. },
  1013. clamp: function ( min, max ) {
  1014. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1015. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1016. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1017. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1018. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1019. return this;
  1020. },
  1021. clampScalar: function () {
  1022. var min = new Vector4();
  1023. var max = new Vector4();
  1024. return function clampScalar( minVal, maxVal ) {
  1025. min.set( minVal, minVal, minVal, minVal );
  1026. max.set( maxVal, maxVal, maxVal, maxVal );
  1027. return this.clamp( min, max );
  1028. };
  1029. }(),
  1030. floor: function () {
  1031. this.x = Math.floor( this.x );
  1032. this.y = Math.floor( this.y );
  1033. this.z = Math.floor( this.z );
  1034. this.w = Math.floor( this.w );
  1035. return this;
  1036. },
  1037. ceil: function () {
  1038. this.x = Math.ceil( this.x );
  1039. this.y = Math.ceil( this.y );
  1040. this.z = Math.ceil( this.z );
  1041. this.w = Math.ceil( this.w );
  1042. return this;
  1043. },
  1044. round: function () {
  1045. this.x = Math.round( this.x );
  1046. this.y = Math.round( this.y );
  1047. this.z = Math.round( this.z );
  1048. this.w = Math.round( this.w );
  1049. return this;
  1050. },
  1051. roundToZero: function () {
  1052. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1053. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1054. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1055. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1056. return this;
  1057. },
  1058. negate: function () {
  1059. this.x = - this.x;
  1060. this.y = - this.y;
  1061. this.z = - this.z;
  1062. this.w = - this.w;
  1063. return this;
  1064. },
  1065. dot: function ( v ) {
  1066. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1067. },
  1068. lengthSq: function () {
  1069. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1070. },
  1071. length: function () {
  1072. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1073. },
  1074. lengthManhattan: function () {
  1075. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1076. },
  1077. normalize: function () {
  1078. return this.divideScalar( this.length() );
  1079. },
  1080. setLength: function ( length ) {
  1081. return this.multiplyScalar( length / this.length() );
  1082. },
  1083. lerp: function ( v, alpha ) {
  1084. this.x += ( v.x - this.x ) * alpha;
  1085. this.y += ( v.y - this.y ) * alpha;
  1086. this.z += ( v.z - this.z ) * alpha;
  1087. this.w += ( v.w - this.w ) * alpha;
  1088. return this;
  1089. },
  1090. lerpVectors: function ( v1, v2, alpha ) {
  1091. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1092. },
  1093. equals: function ( v ) {
  1094. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1095. },
  1096. fromArray: function ( array, offset ) {
  1097. if ( offset === undefined ) offset = 0;
  1098. this.x = array[ offset ];
  1099. this.y = array[ offset + 1 ];
  1100. this.z = array[ offset + 2 ];
  1101. this.w = array[ offset + 3 ];
  1102. return this;
  1103. },
  1104. toArray: function ( array, offset ) {
  1105. if ( array === undefined ) array = [];
  1106. if ( offset === undefined ) offset = 0;
  1107. array[ offset ] = this.x;
  1108. array[ offset + 1 ] = this.y;
  1109. array[ offset + 2 ] = this.z;
  1110. array[ offset + 3 ] = this.w;
  1111. return array;
  1112. },
  1113. fromBufferAttribute: function ( attribute, index, offset ) {
  1114. if ( offset !== undefined ) {
  1115. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1116. }
  1117. this.x = attribute.getX( index );
  1118. this.y = attribute.getY( index );
  1119. this.z = attribute.getZ( index );
  1120. this.w = attribute.getW( index );
  1121. return this;
  1122. }
  1123. } );
  1124. /**
  1125. * @author szimek / https://github.com/szimek/
  1126. * @author alteredq / http://alteredqualia.com/
  1127. * @author Marius Kintel / https://github.com/kintel
  1128. */
  1129. /*
  1130. In options, we can specify:
  1131. * Texture parameters for an auto-generated target texture
  1132. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1133. */
  1134. function WebGLRenderTarget( width, height, options ) {
  1135. this.uuid = _Math.generateUUID();
  1136. this.width = width;
  1137. this.height = height;
  1138. this.scissor = new Vector4( 0, 0, width, height );
  1139. this.scissorTest = false;
  1140. this.viewport = new Vector4( 0, 0, width, height );
  1141. options = options || {};
  1142. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1143. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1144. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1145. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1146. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1147. }
  1148. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  1149. isWebGLRenderTarget: true,
  1150. setSize: function ( width, height ) {
  1151. if ( this.width !== width || this.height !== height ) {
  1152. this.width = width;
  1153. this.height = height;
  1154. this.dispose();
  1155. }
  1156. this.viewport.set( 0, 0, width, height );
  1157. this.scissor.set( 0, 0, width, height );
  1158. },
  1159. clone: function () {
  1160. return new this.constructor().copy( this );
  1161. },
  1162. copy: function ( source ) {
  1163. this.width = source.width;
  1164. this.height = source.height;
  1165. this.viewport.copy( source.viewport );
  1166. this.texture = source.texture.clone();
  1167. this.depthBuffer = source.depthBuffer;
  1168. this.stencilBuffer = source.stencilBuffer;
  1169. this.depthTexture = source.depthTexture;
  1170. return this;
  1171. },
  1172. dispose: function () {
  1173. this.dispatchEvent( { type: 'dispose' } );
  1174. }
  1175. } );
  1176. /**
  1177. * @author alteredq / http://alteredqualia.com
  1178. */
  1179. function WebGLRenderTargetCube( width, height, options ) {
  1180. WebGLRenderTarget.call( this, width, height, options );
  1181. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1182. this.activeMipMapLevel = 0;
  1183. }
  1184. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1185. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1186. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1187. /**
  1188. * @author mikael emtinger / http://gomo.se/
  1189. * @author alteredq / http://alteredqualia.com/
  1190. * @author WestLangley / http://github.com/WestLangley
  1191. * @author bhouston / http://clara.io
  1192. */
  1193. function Quaternion( x, y, z, w ) {
  1194. this._x = x || 0;
  1195. this._y = y || 0;
  1196. this._z = z || 0;
  1197. this._w = ( w !== undefined ) ? w : 1;
  1198. }
  1199. Object.assign( Quaternion, {
  1200. slerp: function ( qa, qb, qm, t ) {
  1201. return qm.copy( qa ).slerp( qb, t );
  1202. },
  1203. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1204. // fuzz-free, array-based Quaternion SLERP operation
  1205. var x0 = src0[ srcOffset0 + 0 ],
  1206. y0 = src0[ srcOffset0 + 1 ],
  1207. z0 = src0[ srcOffset0 + 2 ],
  1208. w0 = src0[ srcOffset0 + 3 ],
  1209. x1 = src1[ srcOffset1 + 0 ],
  1210. y1 = src1[ srcOffset1 + 1 ],
  1211. z1 = src1[ srcOffset1 + 2 ],
  1212. w1 = src1[ srcOffset1 + 3 ];
  1213. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1214. var s = 1 - t,
  1215. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1216. dir = ( cos >= 0 ? 1 : - 1 ),
  1217. sqrSin = 1 - cos * cos;
  1218. // Skip the Slerp for tiny steps to avoid numeric problems:
  1219. if ( sqrSin > Number.EPSILON ) {
  1220. var sin = Math.sqrt( sqrSin ),
  1221. len = Math.atan2( sin, cos * dir );
  1222. s = Math.sin( s * len ) / sin;
  1223. t = Math.sin( t * len ) / sin;
  1224. }
  1225. var tDir = t * dir;
  1226. x0 = x0 * s + x1 * tDir;
  1227. y0 = y0 * s + y1 * tDir;
  1228. z0 = z0 * s + z1 * tDir;
  1229. w0 = w0 * s + w1 * tDir;
  1230. // Normalize in case we just did a lerp:
  1231. if ( s === 1 - t ) {
  1232. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1233. x0 *= f;
  1234. y0 *= f;
  1235. z0 *= f;
  1236. w0 *= f;
  1237. }
  1238. }
  1239. dst[ dstOffset ] = x0;
  1240. dst[ dstOffset + 1 ] = y0;
  1241. dst[ dstOffset + 2 ] = z0;
  1242. dst[ dstOffset + 3 ] = w0;
  1243. }
  1244. } );
  1245. Object.defineProperties( Quaternion.prototype, {
  1246. x: {
  1247. get: function () {
  1248. return this._x;
  1249. },
  1250. set: function ( value ) {
  1251. this._x = value;
  1252. this.onChangeCallback();
  1253. }
  1254. },
  1255. y: {
  1256. get: function () {
  1257. return this._y;
  1258. },
  1259. set: function ( value ) {
  1260. this._y = value;
  1261. this.onChangeCallback();
  1262. }
  1263. },
  1264. z: {
  1265. get: function () {
  1266. return this._z;
  1267. },
  1268. set: function ( value ) {
  1269. this._z = value;
  1270. this.onChangeCallback();
  1271. }
  1272. },
  1273. w: {
  1274. get: function () {
  1275. return this._w;
  1276. },
  1277. set: function ( value ) {
  1278. this._w = value;
  1279. this.onChangeCallback();
  1280. }
  1281. }
  1282. } );
  1283. Object.assign( Quaternion.prototype, {
  1284. set: function ( x, y, z, w ) {
  1285. this._x = x;
  1286. this._y = y;
  1287. this._z = z;
  1288. this._w = w;
  1289. this.onChangeCallback();
  1290. return this;
  1291. },
  1292. clone: function () {
  1293. return new this.constructor( this._x, this._y, this._z, this._w );
  1294. },
  1295. copy: function ( quaternion ) {
  1296. this._x = quaternion.x;
  1297. this._y = quaternion.y;
  1298. this._z = quaternion.z;
  1299. this._w = quaternion.w;
  1300. this.onChangeCallback();
  1301. return this;
  1302. },
  1303. setFromEuler: function ( euler, update ) {
  1304. if ( ( euler && euler.isEuler ) === false ) {
  1305. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1306. }
  1307. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  1308. // http://www.mathworks.com/matlabcentral/fileexchange/
  1309. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1310. // content/SpinCalc.m
  1311. var cos = Math.cos;
  1312. var sin = Math.sin;
  1313. var c1 = cos( x / 2 );
  1314. var c2 = cos( y / 2 );
  1315. var c3 = cos( z / 2 );
  1316. var s1 = sin( x / 2 );
  1317. var s2 = sin( y / 2 );
  1318. var s3 = sin( z / 2 );
  1319. if ( order === 'XYZ' ) {
  1320. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1321. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1322. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1323. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1324. } else if ( order === 'YXZ' ) {
  1325. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1326. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1327. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1328. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1329. } else if ( order === 'ZXY' ) {
  1330. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1331. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1332. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1333. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1334. } else if ( order === 'ZYX' ) {
  1335. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1336. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1337. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1338. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1339. } else if ( order === 'YZX' ) {
  1340. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1341. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1342. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1344. } else if ( order === 'XZY' ) {
  1345. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1346. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1347. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1349. }
  1350. if ( update !== false ) this.onChangeCallback();
  1351. return this;
  1352. },
  1353. setFromAxisAngle: function ( axis, angle ) {
  1354. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1355. // assumes axis is normalized
  1356. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1357. this._x = axis.x * s;
  1358. this._y = axis.y * s;
  1359. this._z = axis.z * s;
  1360. this._w = Math.cos( halfAngle );
  1361. this.onChangeCallback();
  1362. return this;
  1363. },
  1364. setFromRotationMatrix: function ( m ) {
  1365. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1366. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1367. var te = m.elements,
  1368. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1369. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1370. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1371. trace = m11 + m22 + m33,
  1372. s;
  1373. if ( trace > 0 ) {
  1374. s = 0.5 / Math.sqrt( trace + 1.0 );
  1375. this._w = 0.25 / s;
  1376. this._x = ( m32 - m23 ) * s;
  1377. this._y = ( m13 - m31 ) * s;
  1378. this._z = ( m21 - m12 ) * s;
  1379. } else if ( m11 > m22 && m11 > m33 ) {
  1380. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1381. this._w = ( m32 - m23 ) / s;
  1382. this._x = 0.25 * s;
  1383. this._y = ( m12 + m21 ) / s;
  1384. this._z = ( m13 + m31 ) / s;
  1385. } else if ( m22 > m33 ) {
  1386. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1387. this._w = ( m13 - m31 ) / s;
  1388. this._x = ( m12 + m21 ) / s;
  1389. this._y = 0.25 * s;
  1390. this._z = ( m23 + m32 ) / s;
  1391. } else {
  1392. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1393. this._w = ( m21 - m12 ) / s;
  1394. this._x = ( m13 + m31 ) / s;
  1395. this._y = ( m23 + m32 ) / s;
  1396. this._z = 0.25 * s;
  1397. }
  1398. this.onChangeCallback();
  1399. return this;
  1400. },
  1401. setFromUnitVectors: function () {
  1402. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1403. // assumes direction vectors vFrom and vTo are normalized
  1404. var v1 = new Vector3();
  1405. var r;
  1406. var EPS = 0.000001;
  1407. return function setFromUnitVectors( vFrom, vTo ) {
  1408. if ( v1 === undefined ) v1 = new Vector3();
  1409. r = vFrom.dot( vTo ) + 1;
  1410. if ( r < EPS ) {
  1411. r = 0;
  1412. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1413. v1.set( - vFrom.y, vFrom.x, 0 );
  1414. } else {
  1415. v1.set( 0, - vFrom.z, vFrom.y );
  1416. }
  1417. } else {
  1418. v1.crossVectors( vFrom, vTo );
  1419. }
  1420. this._x = v1.x;
  1421. this._y = v1.y;
  1422. this._z = v1.z;
  1423. this._w = r;
  1424. return this.normalize();
  1425. };
  1426. }(),
  1427. inverse: function () {
  1428. return this.conjugate().normalize();
  1429. },
  1430. conjugate: function () {
  1431. this._x *= - 1;
  1432. this._y *= - 1;
  1433. this._z *= - 1;
  1434. this.onChangeCallback();
  1435. return this;
  1436. },
  1437. dot: function ( v ) {
  1438. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1439. },
  1440. lengthSq: function () {
  1441. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1442. },
  1443. length: function () {
  1444. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1445. },
  1446. normalize: function () {
  1447. var l = this.length();
  1448. if ( l === 0 ) {
  1449. this._x = 0;
  1450. this._y = 0;
  1451. this._z = 0;
  1452. this._w = 1;
  1453. } else {
  1454. l = 1 / l;
  1455. this._x = this._x * l;
  1456. this._y = this._y * l;
  1457. this._z = this._z * l;
  1458. this._w = this._w * l;
  1459. }
  1460. this.onChangeCallback();
  1461. return this;
  1462. },
  1463. multiply: function ( q, p ) {
  1464. if ( p !== undefined ) {
  1465. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1466. return this.multiplyQuaternions( q, p );
  1467. }
  1468. return this.multiplyQuaternions( this, q );
  1469. },
  1470. premultiply: function ( q ) {
  1471. return this.multiplyQuaternions( q, this );
  1472. },
  1473. multiplyQuaternions: function ( a, b ) {
  1474. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1475. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1476. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1477. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1478. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1479. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1480. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1481. this.onChangeCallback();
  1482. return this;
  1483. },
  1484. slerp: function ( qb, t ) {
  1485. if ( t === 0 ) return this;
  1486. if ( t === 1 ) return this.copy( qb );
  1487. var x = this._x, y = this._y, z = this._z, w = this._w;
  1488. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1489. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1490. if ( cosHalfTheta < 0 ) {
  1491. this._w = - qb._w;
  1492. this._x = - qb._x;
  1493. this._y = - qb._y;
  1494. this._z = - qb._z;
  1495. cosHalfTheta = - cosHalfTheta;
  1496. } else {
  1497. this.copy( qb );
  1498. }
  1499. if ( cosHalfTheta >= 1.0 ) {
  1500. this._w = w;
  1501. this._x = x;
  1502. this._y = y;
  1503. this._z = z;
  1504. return this;
  1505. }
  1506. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1507. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1508. this._w = 0.5 * ( w + this._w );
  1509. this._x = 0.5 * ( x + this._x );
  1510. this._y = 0.5 * ( y + this._y );
  1511. this._z = 0.5 * ( z + this._z );
  1512. return this;
  1513. }
  1514. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1515. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1516. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1517. this._w = ( w * ratioA + this._w * ratioB );
  1518. this._x = ( x * ratioA + this._x * ratioB );
  1519. this._y = ( y * ratioA + this._y * ratioB );
  1520. this._z = ( z * ratioA + this._z * ratioB );
  1521. this.onChangeCallback();
  1522. return this;
  1523. },
  1524. equals: function ( quaternion ) {
  1525. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1526. },
  1527. fromArray: function ( array, offset ) {
  1528. if ( offset === undefined ) offset = 0;
  1529. this._x = array[ offset ];
  1530. this._y = array[ offset + 1 ];
  1531. this._z = array[ offset + 2 ];
  1532. this._w = array[ offset + 3 ];
  1533. this.onChangeCallback();
  1534. return this;
  1535. },
  1536. toArray: function ( array, offset ) {
  1537. if ( array === undefined ) array = [];
  1538. if ( offset === undefined ) offset = 0;
  1539. array[ offset ] = this._x;
  1540. array[ offset + 1 ] = this._y;
  1541. array[ offset + 2 ] = this._z;
  1542. array[ offset + 3 ] = this._w;
  1543. return array;
  1544. },
  1545. onChange: function ( callback ) {
  1546. this.onChangeCallback = callback;
  1547. return this;
  1548. },
  1549. onChangeCallback: function () {}
  1550. } );
  1551. /**
  1552. * @author mrdoob / http://mrdoob.com/
  1553. * @author *kile / http://kile.stravaganza.org/
  1554. * @author philogb / http://blog.thejit.org/
  1555. * @author mikael emtinger / http://gomo.se/
  1556. * @author egraether / http://egraether.com/
  1557. * @author WestLangley / http://github.com/WestLangley
  1558. */
  1559. function Vector3( x, y, z ) {
  1560. this.x = x || 0;
  1561. this.y = y || 0;
  1562. this.z = z || 0;
  1563. }
  1564. Object.assign( Vector3.prototype, {
  1565. isVector3: true,
  1566. set: function ( x, y, z ) {
  1567. this.x = x;
  1568. this.y = y;
  1569. this.z = z;
  1570. return this;
  1571. },
  1572. setScalar: function ( scalar ) {
  1573. this.x = scalar;
  1574. this.y = scalar;
  1575. this.z = scalar;
  1576. return this;
  1577. },
  1578. setX: function ( x ) {
  1579. this.x = x;
  1580. return this;
  1581. },
  1582. setY: function ( y ) {
  1583. this.y = y;
  1584. return this;
  1585. },
  1586. setZ: function ( z ) {
  1587. this.z = z;
  1588. return this;
  1589. },
  1590. setComponent: function ( index, value ) {
  1591. switch ( index ) {
  1592. case 0: this.x = value; break;
  1593. case 1: this.y = value; break;
  1594. case 2: this.z = value; break;
  1595. default: throw new Error( 'index is out of range: ' + index );
  1596. }
  1597. return this;
  1598. },
  1599. getComponent: function ( index ) {
  1600. switch ( index ) {
  1601. case 0: return this.x;
  1602. case 1: return this.y;
  1603. case 2: return this.z;
  1604. default: throw new Error( 'index is out of range: ' + index );
  1605. }
  1606. },
  1607. clone: function () {
  1608. return new this.constructor( this.x, this.y, this.z );
  1609. },
  1610. copy: function ( v ) {
  1611. this.x = v.x;
  1612. this.y = v.y;
  1613. this.z = v.z;
  1614. return this;
  1615. },
  1616. add: function ( v, w ) {
  1617. if ( w !== undefined ) {
  1618. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1619. return this.addVectors( v, w );
  1620. }
  1621. this.x += v.x;
  1622. this.y += v.y;
  1623. this.z += v.z;
  1624. return this;
  1625. },
  1626. addScalar: function ( s ) {
  1627. this.x += s;
  1628. this.y += s;
  1629. this.z += s;
  1630. return this;
  1631. },
  1632. addVectors: function ( a, b ) {
  1633. this.x = a.x + b.x;
  1634. this.y = a.y + b.y;
  1635. this.z = a.z + b.z;
  1636. return this;
  1637. },
  1638. addScaledVector: function ( v, s ) {
  1639. this.x += v.x * s;
  1640. this.y += v.y * s;
  1641. this.z += v.z * s;
  1642. return this;
  1643. },
  1644. sub: function ( v, w ) {
  1645. if ( w !== undefined ) {
  1646. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1647. return this.subVectors( v, w );
  1648. }
  1649. this.x -= v.x;
  1650. this.y -= v.y;
  1651. this.z -= v.z;
  1652. return this;
  1653. },
  1654. subScalar: function ( s ) {
  1655. this.x -= s;
  1656. this.y -= s;
  1657. this.z -= s;
  1658. return this;
  1659. },
  1660. subVectors: function ( a, b ) {
  1661. this.x = a.x - b.x;
  1662. this.y = a.y - b.y;
  1663. this.z = a.z - b.z;
  1664. return this;
  1665. },
  1666. multiply: function ( v, w ) {
  1667. if ( w !== undefined ) {
  1668. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1669. return this.multiplyVectors( v, w );
  1670. }
  1671. this.x *= v.x;
  1672. this.y *= v.y;
  1673. this.z *= v.z;
  1674. return this;
  1675. },
  1676. multiplyScalar: function ( scalar ) {
  1677. this.x *= scalar;
  1678. this.y *= scalar;
  1679. this.z *= scalar;
  1680. return this;
  1681. },
  1682. multiplyVectors: function ( a, b ) {
  1683. this.x = a.x * b.x;
  1684. this.y = a.y * b.y;
  1685. this.z = a.z * b.z;
  1686. return this;
  1687. },
  1688. applyEuler: function () {
  1689. var quaternion = new Quaternion();
  1690. return function applyEuler( euler ) {
  1691. if ( ( euler && euler.isEuler ) === false ) {
  1692. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1693. }
  1694. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1695. };
  1696. }(),
  1697. applyAxisAngle: function () {
  1698. var quaternion = new Quaternion();
  1699. return function applyAxisAngle( axis, angle ) {
  1700. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1701. };
  1702. }(),
  1703. applyMatrix3: function ( m ) {
  1704. var x = this.x, y = this.y, z = this.z;
  1705. var e = m.elements;
  1706. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1707. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1708. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1709. return this;
  1710. },
  1711. applyMatrix4: function ( m ) {
  1712. var x = this.x, y = this.y, z = this.z;
  1713. var e = m.elements;
  1714. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1715. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1716. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1717. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  1718. return this.divideScalar( w );
  1719. },
  1720. applyQuaternion: function ( q ) {
  1721. var x = this.x, y = this.y, z = this.z;
  1722. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1723. // calculate quat * vector
  1724. var ix = qw * x + qy * z - qz * y;
  1725. var iy = qw * y + qz * x - qx * z;
  1726. var iz = qw * z + qx * y - qy * x;
  1727. var iw = - qx * x - qy * y - qz * z;
  1728. // calculate result * inverse quat
  1729. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1730. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1731. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1732. return this;
  1733. },
  1734. project: function () {
  1735. var matrix = new Matrix4();
  1736. return function project( camera ) {
  1737. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1738. return this.applyMatrix4( matrix );
  1739. };
  1740. }(),
  1741. unproject: function () {
  1742. var matrix = new Matrix4();
  1743. return function unproject( camera ) {
  1744. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1745. return this.applyMatrix4( matrix );
  1746. };
  1747. }(),
  1748. transformDirection: function ( m ) {
  1749. // input: THREE.Matrix4 affine matrix
  1750. // vector interpreted as a direction
  1751. var x = this.x, y = this.y, z = this.z;
  1752. var e = m.elements;
  1753. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1754. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1755. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1756. return this.normalize();
  1757. },
  1758. divide: function ( v ) {
  1759. this.x /= v.x;
  1760. this.y /= v.y;
  1761. this.z /= v.z;
  1762. return this;
  1763. },
  1764. divideScalar: function ( scalar ) {
  1765. return this.multiplyScalar( 1 / scalar );
  1766. },
  1767. min: function ( v ) {
  1768. this.x = Math.min( this.x, v.x );
  1769. this.y = Math.min( this.y, v.y );
  1770. this.z = Math.min( this.z, v.z );
  1771. return this;
  1772. },
  1773. max: function ( v ) {
  1774. this.x = Math.max( this.x, v.x );
  1775. this.y = Math.max( this.y, v.y );
  1776. this.z = Math.max( this.z, v.z );
  1777. return this;
  1778. },
  1779. clamp: function ( min, max ) {
  1780. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1781. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1782. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1783. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1784. return this;
  1785. },
  1786. clampScalar: function () {
  1787. var min = new Vector3();
  1788. var max = new Vector3();
  1789. return function clampScalar( minVal, maxVal ) {
  1790. min.set( minVal, minVal, minVal );
  1791. max.set( maxVal, maxVal, maxVal );
  1792. return this.clamp( min, max );
  1793. };
  1794. }(),
  1795. clampLength: function ( min, max ) {
  1796. var length = this.length();
  1797. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1798. },
  1799. floor: function () {
  1800. this.x = Math.floor( this.x );
  1801. this.y = Math.floor( this.y );
  1802. this.z = Math.floor( this.z );
  1803. return this;
  1804. },
  1805. ceil: function () {
  1806. this.x = Math.ceil( this.x );
  1807. this.y = Math.ceil( this.y );
  1808. this.z = Math.ceil( this.z );
  1809. return this;
  1810. },
  1811. round: function () {
  1812. this.x = Math.round( this.x );
  1813. this.y = Math.round( this.y );
  1814. this.z = Math.round( this.z );
  1815. return this;
  1816. },
  1817. roundToZero: function () {
  1818. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1819. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1820. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1821. return this;
  1822. },
  1823. negate: function () {
  1824. this.x = - this.x;
  1825. this.y = - this.y;
  1826. this.z = - this.z;
  1827. return this;
  1828. },
  1829. dot: function ( v ) {
  1830. return this.x * v.x + this.y * v.y + this.z * v.z;
  1831. },
  1832. // TODO lengthSquared?
  1833. lengthSq: function () {
  1834. return this.x * this.x + this.y * this.y + this.z * this.z;
  1835. },
  1836. length: function () {
  1837. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1838. },
  1839. lengthManhattan: function () {
  1840. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1841. },
  1842. normalize: function () {
  1843. return this.divideScalar( this.length() );
  1844. },
  1845. setLength: function ( length ) {
  1846. return this.multiplyScalar( length / this.length() );
  1847. },
  1848. lerp: function ( v, alpha ) {
  1849. this.x += ( v.x - this.x ) * alpha;
  1850. this.y += ( v.y - this.y ) * alpha;
  1851. this.z += ( v.z - this.z ) * alpha;
  1852. return this;
  1853. },
  1854. lerpVectors: function ( v1, v2, alpha ) {
  1855. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1856. },
  1857. cross: function ( v, w ) {
  1858. if ( w !== undefined ) {
  1859. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1860. return this.crossVectors( v, w );
  1861. }
  1862. var x = this.x, y = this.y, z = this.z;
  1863. this.x = y * v.z - z * v.y;
  1864. this.y = z * v.x - x * v.z;
  1865. this.z = x * v.y - y * v.x;
  1866. return this;
  1867. },
  1868. crossVectors: function ( a, b ) {
  1869. var ax = a.x, ay = a.y, az = a.z;
  1870. var bx = b.x, by = b.y, bz = b.z;
  1871. this.x = ay * bz - az * by;
  1872. this.y = az * bx - ax * bz;
  1873. this.z = ax * by - ay * bx;
  1874. return this;
  1875. },
  1876. projectOnVector: function ( vector ) {
  1877. var scalar = vector.dot( this ) / vector.lengthSq();
  1878. return this.copy( vector ).multiplyScalar( scalar );
  1879. },
  1880. projectOnPlane: function () {
  1881. var v1 = new Vector3();
  1882. return function projectOnPlane( planeNormal ) {
  1883. v1.copy( this ).projectOnVector( planeNormal );
  1884. return this.sub( v1 );
  1885. };
  1886. }(),
  1887. reflect: function () {
  1888. // reflect incident vector off plane orthogonal to normal
  1889. // normal is assumed to have unit length
  1890. var v1 = new Vector3();
  1891. return function reflect( normal ) {
  1892. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1893. };
  1894. }(),
  1895. angleTo: function ( v ) {
  1896. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1897. // clamp, to handle numerical problems
  1898. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1899. },
  1900. distanceTo: function ( v ) {
  1901. return Math.sqrt( this.distanceToSquared( v ) );
  1902. },
  1903. distanceToSquared: function ( v ) {
  1904. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1905. return dx * dx + dy * dy + dz * dz;
  1906. },
  1907. distanceToManhattan: function ( v ) {
  1908. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1909. },
  1910. setFromSpherical: function ( s ) {
  1911. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1912. this.x = sinPhiRadius * Math.sin( s.theta );
  1913. this.y = Math.cos( s.phi ) * s.radius;
  1914. this.z = sinPhiRadius * Math.cos( s.theta );
  1915. return this;
  1916. },
  1917. setFromCylindrical: function ( c ) {
  1918. this.x = c.radius * Math.sin( c.theta );
  1919. this.y = c.y;
  1920. this.z = c.radius * Math.cos( c.theta );
  1921. return this;
  1922. },
  1923. setFromMatrixPosition: function ( m ) {
  1924. return this.setFromMatrixColumn( m, 3 );
  1925. },
  1926. setFromMatrixScale: function ( m ) {
  1927. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1928. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1929. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1930. this.x = sx;
  1931. this.y = sy;
  1932. this.z = sz;
  1933. return this;
  1934. },
  1935. setFromMatrixColumn: function ( m, index ) {
  1936. return this.fromArray( m.elements, index * 4 );
  1937. },
  1938. equals: function ( v ) {
  1939. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1940. },
  1941. fromArray: function ( array, offset ) {
  1942. if ( offset === undefined ) offset = 0;
  1943. this.x = array[ offset ];
  1944. this.y = array[ offset + 1 ];
  1945. this.z = array[ offset + 2 ];
  1946. return this;
  1947. },
  1948. toArray: function ( array, offset ) {
  1949. if ( array === undefined ) array = [];
  1950. if ( offset === undefined ) offset = 0;
  1951. array[ offset ] = this.x;
  1952. array[ offset + 1 ] = this.y;
  1953. array[ offset + 2 ] = this.z;
  1954. return array;
  1955. },
  1956. fromBufferAttribute: function ( attribute, index, offset ) {
  1957. if ( offset !== undefined ) {
  1958. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1959. }
  1960. this.x = attribute.getX( index );
  1961. this.y = attribute.getY( index );
  1962. this.z = attribute.getZ( index );
  1963. return this;
  1964. }
  1965. } );
  1966. /**
  1967. * @author mrdoob / http://mrdoob.com/
  1968. * @author supereggbert / http://www.paulbrunt.co.uk/
  1969. * @author philogb / http://blog.thejit.org/
  1970. * @author jordi_ros / http://plattsoft.com
  1971. * @author D1plo1d / http://github.com/D1plo1d
  1972. * @author alteredq / http://alteredqualia.com/
  1973. * @author mikael emtinger / http://gomo.se/
  1974. * @author timknip / http://www.floorplanner.com/
  1975. * @author bhouston / http://clara.io
  1976. * @author WestLangley / http://github.com/WestLangley
  1977. */
  1978. function Matrix4() {
  1979. this.elements = [
  1980. 1, 0, 0, 0,
  1981. 0, 1, 0, 0,
  1982. 0, 0, 1, 0,
  1983. 0, 0, 0, 1
  1984. ];
  1985. if ( arguments.length > 0 ) {
  1986. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  1987. }
  1988. }
  1989. Object.assign( Matrix4.prototype, {
  1990. isMatrix4: true,
  1991. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1992. var te = this.elements;
  1993. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  1994. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  1995. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  1996. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  1997. return this;
  1998. },
  1999. identity: function () {
  2000. this.set(
  2001. 1, 0, 0, 0,
  2002. 0, 1, 0, 0,
  2003. 0, 0, 1, 0,
  2004. 0, 0, 0, 1
  2005. );
  2006. return this;
  2007. },
  2008. clone: function () {
  2009. return new Matrix4().fromArray( this.elements );
  2010. },
  2011. copy: function ( m ) {
  2012. var te = this.elements;
  2013. var me = m.elements;
  2014. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  2015. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  2016. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  2017. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  2018. return this;
  2019. },
  2020. copyPosition: function ( m ) {
  2021. var te = this.elements, me = m.elements;
  2022. te[ 12 ] = me[ 12 ];
  2023. te[ 13 ] = me[ 13 ];
  2024. te[ 14 ] = me[ 14 ];
  2025. return this;
  2026. },
  2027. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2028. xAxis.setFromMatrixColumn( this, 0 );
  2029. yAxis.setFromMatrixColumn( this, 1 );
  2030. zAxis.setFromMatrixColumn( this, 2 );
  2031. return this;
  2032. },
  2033. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2034. this.set(
  2035. xAxis.x, yAxis.x, zAxis.x, 0,
  2036. xAxis.y, yAxis.y, zAxis.y, 0,
  2037. xAxis.z, yAxis.z, zAxis.z, 0,
  2038. 0, 0, 0, 1
  2039. );
  2040. return this;
  2041. },
  2042. extractRotation: function () {
  2043. var v1 = new Vector3();
  2044. return function extractRotation( m ) {
  2045. var te = this.elements;
  2046. var me = m.elements;
  2047. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2048. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2049. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2050. te[ 0 ] = me[ 0 ] * scaleX;
  2051. te[ 1 ] = me[ 1 ] * scaleX;
  2052. te[ 2 ] = me[ 2 ] * scaleX;
  2053. te[ 4 ] = me[ 4 ] * scaleY;
  2054. te[ 5 ] = me[ 5 ] * scaleY;
  2055. te[ 6 ] = me[ 6 ] * scaleY;
  2056. te[ 8 ] = me[ 8 ] * scaleZ;
  2057. te[ 9 ] = me[ 9 ] * scaleZ;
  2058. te[ 10 ] = me[ 10 ] * scaleZ;
  2059. return this;
  2060. };
  2061. }(),
  2062. makeRotationFromEuler: function ( euler ) {
  2063. if ( ( euler && euler.isEuler ) === false ) {
  2064. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2065. }
  2066. var te = this.elements;
  2067. var x = euler.x, y = euler.y, z = euler.z;
  2068. var a = Math.cos( x ), b = Math.sin( x );
  2069. var c = Math.cos( y ), d = Math.sin( y );
  2070. var e = Math.cos( z ), f = Math.sin( z );
  2071. if ( euler.order === 'XYZ' ) {
  2072. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2073. te[ 0 ] = c * e;
  2074. te[ 4 ] = - c * f;
  2075. te[ 8 ] = d;
  2076. te[ 1 ] = af + be * d;
  2077. te[ 5 ] = ae - bf * d;
  2078. te[ 9 ] = - b * c;
  2079. te[ 2 ] = bf - ae * d;
  2080. te[ 6 ] = be + af * d;
  2081. te[ 10 ] = a * c;
  2082. } else if ( euler.order === 'YXZ' ) {
  2083. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2084. te[ 0 ] = ce + df * b;
  2085. te[ 4 ] = de * b - cf;
  2086. te[ 8 ] = a * d;
  2087. te[ 1 ] = a * f;
  2088. te[ 5 ] = a * e;
  2089. te[ 9 ] = - b;
  2090. te[ 2 ] = cf * b - de;
  2091. te[ 6 ] = df + ce * b;
  2092. te[ 10 ] = a * c;
  2093. } else if ( euler.order === 'ZXY' ) {
  2094. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2095. te[ 0 ] = ce - df * b;
  2096. te[ 4 ] = - a * f;
  2097. te[ 8 ] = de + cf * b;
  2098. te[ 1 ] = cf + de * b;
  2099. te[ 5 ] = a * e;
  2100. te[ 9 ] = df - ce * b;
  2101. te[ 2 ] = - a * d;
  2102. te[ 6 ] = b;
  2103. te[ 10 ] = a * c;
  2104. } else if ( euler.order === 'ZYX' ) {
  2105. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2106. te[ 0 ] = c * e;
  2107. te[ 4 ] = be * d - af;
  2108. te[ 8 ] = ae * d + bf;
  2109. te[ 1 ] = c * f;
  2110. te[ 5 ] = bf * d + ae;
  2111. te[ 9 ] = af * d - be;
  2112. te[ 2 ] = - d;
  2113. te[ 6 ] = b * c;
  2114. te[ 10 ] = a * c;
  2115. } else if ( euler.order === 'YZX' ) {
  2116. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2117. te[ 0 ] = c * e;
  2118. te[ 4 ] = bd - ac * f;
  2119. te[ 8 ] = bc * f + ad;
  2120. te[ 1 ] = f;
  2121. te[ 5 ] = a * e;
  2122. te[ 9 ] = - b * e;
  2123. te[ 2 ] = - d * e;
  2124. te[ 6 ] = ad * f + bc;
  2125. te[ 10 ] = ac - bd * f;
  2126. } else if ( euler.order === 'XZY' ) {
  2127. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2128. te[ 0 ] = c * e;
  2129. te[ 4 ] = - f;
  2130. te[ 8 ] = d * e;
  2131. te[ 1 ] = ac * f + bd;
  2132. te[ 5 ] = a * e;
  2133. te[ 9 ] = ad * f - bc;
  2134. te[ 2 ] = bc * f - ad;
  2135. te[ 6 ] = b * e;
  2136. te[ 10 ] = bd * f + ac;
  2137. }
  2138. // last column
  2139. te[ 3 ] = 0;
  2140. te[ 7 ] = 0;
  2141. te[ 11 ] = 0;
  2142. // bottom row
  2143. te[ 12 ] = 0;
  2144. te[ 13 ] = 0;
  2145. te[ 14 ] = 0;
  2146. te[ 15 ] = 1;
  2147. return this;
  2148. },
  2149. makeRotationFromQuaternion: function ( q ) {
  2150. var te = this.elements;
  2151. var x = q._x, y = q._y, z = q._z, w = q._w;
  2152. var x2 = x + x, y2 = y + y, z2 = z + z;
  2153. var xx = x * x2, xy = x * y2, xz = x * z2;
  2154. var yy = y * y2, yz = y * z2, zz = z * z2;
  2155. var wx = w * x2, wy = w * y2, wz = w * z2;
  2156. te[ 0 ] = 1 - ( yy + zz );
  2157. te[ 4 ] = xy - wz;
  2158. te[ 8 ] = xz + wy;
  2159. te[ 1 ] = xy + wz;
  2160. te[ 5 ] = 1 - ( xx + zz );
  2161. te[ 9 ] = yz - wx;
  2162. te[ 2 ] = xz - wy;
  2163. te[ 6 ] = yz + wx;
  2164. te[ 10 ] = 1 - ( xx + yy );
  2165. // last column
  2166. te[ 3 ] = 0;
  2167. te[ 7 ] = 0;
  2168. te[ 11 ] = 0;
  2169. // bottom row
  2170. te[ 12 ] = 0;
  2171. te[ 13 ] = 0;
  2172. te[ 14 ] = 0;
  2173. te[ 15 ] = 1;
  2174. return this;
  2175. },
  2176. lookAt: function () {
  2177. var x = new Vector3();
  2178. var y = new Vector3();
  2179. var z = new Vector3();
  2180. return function lookAt( eye, target, up ) {
  2181. var te = this.elements;
  2182. z.subVectors( eye, target );
  2183. if ( z.lengthSq() === 0 ) {
  2184. // eye and target are in the same position
  2185. z.z = 1;
  2186. }
  2187. z.normalize();
  2188. x.crossVectors( up, z );
  2189. if ( x.lengthSq() === 0 ) {
  2190. // eye and target are in the same vertical
  2191. z.z += 0.0001;
  2192. x.crossVectors( up, z );
  2193. }
  2194. x.normalize();
  2195. y.crossVectors( z, x );
  2196. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2197. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2198. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2199. return this;
  2200. };
  2201. }(),
  2202. multiply: function ( m, n ) {
  2203. if ( n !== undefined ) {
  2204. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2205. return this.multiplyMatrices( m, n );
  2206. }
  2207. return this.multiplyMatrices( this, m );
  2208. },
  2209. premultiply: function ( m ) {
  2210. return this.multiplyMatrices( m, this );
  2211. },
  2212. multiplyMatrices: function ( a, b ) {
  2213. var ae = a.elements;
  2214. var be = b.elements;
  2215. var te = this.elements;
  2216. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2217. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2218. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2219. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2220. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2221. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2222. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2223. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2224. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2225. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2226. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2227. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2228. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2229. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2230. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2231. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2232. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2233. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2234. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2235. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2236. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2237. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2238. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2239. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2240. return this;
  2241. },
  2242. multiplyScalar: function ( s ) {
  2243. var te = this.elements;
  2244. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2245. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2246. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2247. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2248. return this;
  2249. },
  2250. applyToBufferAttribute: function () {
  2251. var v1 = new Vector3();
  2252. return function applyToBufferAttribute( attribute ) {
  2253. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2254. v1.x = attribute.getX( i );
  2255. v1.y = attribute.getY( i );
  2256. v1.z = attribute.getZ( i );
  2257. v1.applyMatrix4( this );
  2258. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2259. }
  2260. return attribute;
  2261. };
  2262. }(),
  2263. determinant: function () {
  2264. var te = this.elements;
  2265. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2266. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2267. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2268. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2269. //TODO: make this more efficient
  2270. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2271. return (
  2272. n41 * (
  2273. + n14 * n23 * n32
  2274. - n13 * n24 * n32
  2275. - n14 * n22 * n33
  2276. + n12 * n24 * n33
  2277. + n13 * n22 * n34
  2278. - n12 * n23 * n34
  2279. ) +
  2280. n42 * (
  2281. + n11 * n23 * n34
  2282. - n11 * n24 * n33
  2283. + n14 * n21 * n33
  2284. - n13 * n21 * n34
  2285. + n13 * n24 * n31
  2286. - n14 * n23 * n31
  2287. ) +
  2288. n43 * (
  2289. + n11 * n24 * n32
  2290. - n11 * n22 * n34
  2291. - n14 * n21 * n32
  2292. + n12 * n21 * n34
  2293. + n14 * n22 * n31
  2294. - n12 * n24 * n31
  2295. ) +
  2296. n44 * (
  2297. - n13 * n22 * n31
  2298. - n11 * n23 * n32
  2299. + n11 * n22 * n33
  2300. + n13 * n21 * n32
  2301. - n12 * n21 * n33
  2302. + n12 * n23 * n31
  2303. )
  2304. );
  2305. },
  2306. transpose: function () {
  2307. var te = this.elements;
  2308. var tmp;
  2309. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2310. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2311. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2312. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2313. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2314. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2315. return this;
  2316. },
  2317. setPosition: function ( v ) {
  2318. var te = this.elements;
  2319. te[ 12 ] = v.x;
  2320. te[ 13 ] = v.y;
  2321. te[ 14 ] = v.z;
  2322. return this;
  2323. },
  2324. getInverse: function ( m, throwOnDegenerate ) {
  2325. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2326. var te = this.elements,
  2327. me = m.elements,
  2328. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2329. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2330. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2331. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2332. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2333. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2334. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2335. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2336. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2337. if ( det === 0 ) {
  2338. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2339. if ( throwOnDegenerate === true ) {
  2340. throw new Error( msg );
  2341. } else {
  2342. console.warn( msg );
  2343. }
  2344. return this.identity();
  2345. }
  2346. var detInv = 1 / det;
  2347. te[ 0 ] = t11 * detInv;
  2348. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2349. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2350. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2351. te[ 4 ] = t12 * detInv;
  2352. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2353. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2354. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2355. te[ 8 ] = t13 * detInv;
  2356. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2357. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2358. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2359. te[ 12 ] = t14 * detInv;
  2360. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2361. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2362. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2363. return this;
  2364. },
  2365. scale: function ( v ) {
  2366. var te = this.elements;
  2367. var x = v.x, y = v.y, z = v.z;
  2368. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2369. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2370. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2371. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2372. return this;
  2373. },
  2374. getMaxScaleOnAxis: function () {
  2375. var te = this.elements;
  2376. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2377. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2378. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2379. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2380. },
  2381. makeTranslation: function ( x, y, z ) {
  2382. this.set(
  2383. 1, 0, 0, x,
  2384. 0, 1, 0, y,
  2385. 0, 0, 1, z,
  2386. 0, 0, 0, 1
  2387. );
  2388. return this;
  2389. },
  2390. makeRotationX: function ( theta ) {
  2391. var c = Math.cos( theta ), s = Math.sin( theta );
  2392. this.set(
  2393. 1, 0, 0, 0,
  2394. 0, c, - s, 0,
  2395. 0, s, c, 0,
  2396. 0, 0, 0, 1
  2397. );
  2398. return this;
  2399. },
  2400. makeRotationY: function ( theta ) {
  2401. var c = Math.cos( theta ), s = Math.sin( theta );
  2402. this.set(
  2403. c, 0, s, 0,
  2404. 0, 1, 0, 0,
  2405. - s, 0, c, 0,
  2406. 0, 0, 0, 1
  2407. );
  2408. return this;
  2409. },
  2410. makeRotationZ: function ( theta ) {
  2411. var c = Math.cos( theta ), s = Math.sin( theta );
  2412. this.set(
  2413. c, - s, 0, 0,
  2414. s, c, 0, 0,
  2415. 0, 0, 1, 0,
  2416. 0, 0, 0, 1
  2417. );
  2418. return this;
  2419. },
  2420. makeRotationAxis: function ( axis, angle ) {
  2421. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2422. var c = Math.cos( angle );
  2423. var s = Math.sin( angle );
  2424. var t = 1 - c;
  2425. var x = axis.x, y = axis.y, z = axis.z;
  2426. var tx = t * x, ty = t * y;
  2427. this.set(
  2428. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2429. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2430. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2431. 0, 0, 0, 1
  2432. );
  2433. return this;
  2434. },
  2435. makeScale: function ( x, y, z ) {
  2436. this.set(
  2437. x, 0, 0, 0,
  2438. 0, y, 0, 0,
  2439. 0, 0, z, 0,
  2440. 0, 0, 0, 1
  2441. );
  2442. return this;
  2443. },
  2444. makeShear: function ( x, y, z ) {
  2445. this.set(
  2446. 1, y, z, 0,
  2447. x, 1, z, 0,
  2448. x, y, 1, 0,
  2449. 0, 0, 0, 1
  2450. );
  2451. return this;
  2452. },
  2453. compose: function ( position, quaternion, scale ) {
  2454. this.makeRotationFromQuaternion( quaternion );
  2455. this.scale( scale );
  2456. this.setPosition( position );
  2457. return this;
  2458. },
  2459. decompose: function () {
  2460. var vector = new Vector3();
  2461. var matrix = new Matrix4();
  2462. return function decompose( position, quaternion, scale ) {
  2463. var te = this.elements;
  2464. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2465. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2466. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2467. // if determine is negative, we need to invert one scale
  2468. var det = this.determinant();
  2469. if ( det < 0 ) sx = - sx;
  2470. position.x = te[ 12 ];
  2471. position.y = te[ 13 ];
  2472. position.z = te[ 14 ];
  2473. // scale the rotation part
  2474. matrix.copy( this );
  2475. var invSX = 1 / sx;
  2476. var invSY = 1 / sy;
  2477. var invSZ = 1 / sz;
  2478. matrix.elements[ 0 ] *= invSX;
  2479. matrix.elements[ 1 ] *= invSX;
  2480. matrix.elements[ 2 ] *= invSX;
  2481. matrix.elements[ 4 ] *= invSY;
  2482. matrix.elements[ 5 ] *= invSY;
  2483. matrix.elements[ 6 ] *= invSY;
  2484. matrix.elements[ 8 ] *= invSZ;
  2485. matrix.elements[ 9 ] *= invSZ;
  2486. matrix.elements[ 10 ] *= invSZ;
  2487. quaternion.setFromRotationMatrix( matrix );
  2488. scale.x = sx;
  2489. scale.y = sy;
  2490. scale.z = sz;
  2491. return this;
  2492. };
  2493. }(),
  2494. makePerspective: function ( left, right, top, bottom, near, far ) {
  2495. if ( far === undefined ) {
  2496. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2497. }
  2498. var te = this.elements;
  2499. var x = 2 * near / ( right - left );
  2500. var y = 2 * near / ( top - bottom );
  2501. var a = ( right + left ) / ( right - left );
  2502. var b = ( top + bottom ) / ( top - bottom );
  2503. var c = - ( far + near ) / ( far - near );
  2504. var d = - 2 * far * near / ( far - near );
  2505. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2506. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2507. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2508. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2509. return this;
  2510. },
  2511. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2512. var te = this.elements;
  2513. var w = 1.0 / ( right - left );
  2514. var h = 1.0 / ( top - bottom );
  2515. var p = 1.0 / ( far - near );
  2516. var x = ( right + left ) * w;
  2517. var y = ( top + bottom ) * h;
  2518. var z = ( far + near ) * p;
  2519. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2520. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2521. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2522. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2523. return this;
  2524. },
  2525. equals: function ( matrix ) {
  2526. var te = this.elements;
  2527. var me = matrix.elements;
  2528. for ( var i = 0; i < 16; i ++ ) {
  2529. if ( te[ i ] !== me[ i ] ) return false;
  2530. }
  2531. return true;
  2532. },
  2533. fromArray: function ( array, offset ) {
  2534. if ( offset === undefined ) offset = 0;
  2535. for ( var i = 0; i < 16; i ++ ) {
  2536. this.elements[ i ] = array[ i + offset ];
  2537. }
  2538. return this;
  2539. },
  2540. toArray: function ( array, offset ) {
  2541. if ( array === undefined ) array = [];
  2542. if ( offset === undefined ) offset = 0;
  2543. var te = this.elements;
  2544. array[ offset ] = te[ 0 ];
  2545. array[ offset + 1 ] = te[ 1 ];
  2546. array[ offset + 2 ] = te[ 2 ];
  2547. array[ offset + 3 ] = te[ 3 ];
  2548. array[ offset + 4 ] = te[ 4 ];
  2549. array[ offset + 5 ] = te[ 5 ];
  2550. array[ offset + 6 ] = te[ 6 ];
  2551. array[ offset + 7 ] = te[ 7 ];
  2552. array[ offset + 8 ] = te[ 8 ];
  2553. array[ offset + 9 ] = te[ 9 ];
  2554. array[ offset + 10 ] = te[ 10 ];
  2555. array[ offset + 11 ] = te[ 11 ];
  2556. array[ offset + 12 ] = te[ 12 ];
  2557. array[ offset + 13 ] = te[ 13 ];
  2558. array[ offset + 14 ] = te[ 14 ];
  2559. array[ offset + 15 ] = te[ 15 ];
  2560. return array;
  2561. }
  2562. } );
  2563. /**
  2564. * @author alteredq / http://alteredqualia.com/
  2565. */
  2566. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  2567. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2568. this.image = { data: data, width: width, height: height };
  2569. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  2570. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  2571. this.generateMipmaps = false;
  2572. this.flipY = false;
  2573. this.unpackAlignment = 1;
  2574. }
  2575. DataTexture.prototype = Object.create( Texture.prototype );
  2576. DataTexture.prototype.constructor = DataTexture;
  2577. DataTexture.prototype.isDataTexture = true;
  2578. /**
  2579. * @author mrdoob / http://mrdoob.com/
  2580. */
  2581. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2582. images = images !== undefined ? images : [];
  2583. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2584. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2585. this.flipY = false;
  2586. }
  2587. CubeTexture.prototype = Object.create( Texture.prototype );
  2588. CubeTexture.prototype.constructor = CubeTexture;
  2589. CubeTexture.prototype.isCubeTexture = true;
  2590. Object.defineProperty( CubeTexture.prototype, 'images', {
  2591. get: function () {
  2592. return this.image;
  2593. },
  2594. set: function ( value ) {
  2595. this.image = value;
  2596. }
  2597. } );
  2598. /**
  2599. * @author tschw
  2600. *
  2601. * Uniforms of a program.
  2602. * Those form a tree structure with a special top-level container for the root,
  2603. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2604. *
  2605. *
  2606. * Properties of inner nodes including the top-level container:
  2607. *
  2608. * .seq - array of nested uniforms
  2609. * .map - nested uniforms by name
  2610. *
  2611. *
  2612. * Methods of all nodes except the top-level container:
  2613. *
  2614. * .setValue( gl, value, [renderer] )
  2615. *
  2616. * uploads a uniform value(s)
  2617. * the 'renderer' parameter is needed for sampler uniforms
  2618. *
  2619. *
  2620. * Static methods of the top-level container (renderer factorizations):
  2621. *
  2622. * .upload( gl, seq, values, renderer )
  2623. *
  2624. * sets uniforms in 'seq' to 'values[id].value'
  2625. *
  2626. * .seqWithValue( seq, values ) : filteredSeq
  2627. *
  2628. * filters 'seq' entries with corresponding entry in values
  2629. *
  2630. *
  2631. * Methods of the top-level container (renderer factorizations):
  2632. *
  2633. * .setValue( gl, name, value )
  2634. *
  2635. * sets uniform with name 'name' to 'value'
  2636. *
  2637. * .set( gl, obj, prop )
  2638. *
  2639. * sets uniform from object and property with same name than uniform
  2640. *
  2641. * .setOptional( gl, obj, prop )
  2642. *
  2643. * like .set for an optional property of the object
  2644. *
  2645. */
  2646. var emptyTexture = new Texture();
  2647. var emptyCubeTexture = new CubeTexture();
  2648. // --- Base for inner nodes (including the root) ---
  2649. function UniformContainer() {
  2650. this.seq = [];
  2651. this.map = {};
  2652. }
  2653. // --- Utilities ---
  2654. // Array Caches (provide typed arrays for temporary by size)
  2655. var arrayCacheF32 = [];
  2656. var arrayCacheI32 = [];
  2657. // Float32Array caches used for uploading Matrix uniforms
  2658. var mat4array = new Float32Array( 16 );
  2659. var mat3array = new Float32Array( 9 );
  2660. // Flattening for arrays of vectors and matrices
  2661. function flatten( array, nBlocks, blockSize ) {
  2662. var firstElem = array[ 0 ];
  2663. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2664. // unoptimized: ! isNaN( firstElem )
  2665. // see http://jacksondunstan.com/articles/983
  2666. var n = nBlocks * blockSize,
  2667. r = arrayCacheF32[ n ];
  2668. if ( r === undefined ) {
  2669. r = new Float32Array( n );
  2670. arrayCacheF32[ n ] = r;
  2671. }
  2672. if ( nBlocks !== 0 ) {
  2673. firstElem.toArray( r, 0 );
  2674. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2675. offset += blockSize;
  2676. array[ i ].toArray( r, offset );
  2677. }
  2678. }
  2679. return r;
  2680. }
  2681. // Texture unit allocation
  2682. function allocTexUnits( renderer, n ) {
  2683. var r = arrayCacheI32[ n ];
  2684. if ( r === undefined ) {
  2685. r = new Int32Array( n );
  2686. arrayCacheI32[ n ] = r;
  2687. }
  2688. for ( var i = 0; i !== n; ++ i )
  2689. r[ i ] = renderer.allocTextureUnit();
  2690. return r;
  2691. }
  2692. // --- Setters ---
  2693. // Note: Defining these methods externally, because they come in a bunch
  2694. // and this way their names minify.
  2695. // Single scalar
  2696. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2697. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2698. // Single float vector (from flat array or THREE.VectorN)
  2699. function setValue2fv( gl, v ) {
  2700. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2701. else gl.uniform2f( this.addr, v.x, v.y );
  2702. }
  2703. function setValue3fv( gl, v ) {
  2704. if ( v.x !== undefined )
  2705. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2706. else if ( v.r !== undefined )
  2707. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2708. else
  2709. gl.uniform3fv( this.addr, v );
  2710. }
  2711. function setValue4fv( gl, v ) {
  2712. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2713. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2714. }
  2715. // Single matrix (from flat array or MatrixN)
  2716. function setValue2fm( gl, v ) {
  2717. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2718. }
  2719. function setValue3fm( gl, v ) {
  2720. if ( v.elements === undefined ) {
  2721. gl.uniformMatrix3fv( this.addr, false, v );
  2722. } else {
  2723. mat3array.set( v.elements );
  2724. gl.uniformMatrix3fv( this.addr, false, mat3array );
  2725. }
  2726. }
  2727. function setValue4fm( gl, v ) {
  2728. if ( v.elements === undefined ) {
  2729. gl.uniformMatrix4fv( this.addr, false, v );
  2730. } else {
  2731. mat4array.set( v.elements );
  2732. gl.uniformMatrix4fv( this.addr, false, mat4array );
  2733. }
  2734. }
  2735. // Single texture (2D / Cube)
  2736. function setValueT1( gl, v, renderer ) {
  2737. var unit = renderer.allocTextureUnit();
  2738. gl.uniform1i( this.addr, unit );
  2739. renderer.setTexture2D( v || emptyTexture, unit );
  2740. }
  2741. function setValueT6( gl, v, renderer ) {
  2742. var unit = renderer.allocTextureUnit();
  2743. gl.uniform1i( this.addr, unit );
  2744. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2745. }
  2746. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2747. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2748. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2749. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2750. // Helper to pick the right setter for the singular case
  2751. function getSingularSetter( type ) {
  2752. switch ( type ) {
  2753. case 0x1406: return setValue1f; // FLOAT
  2754. case 0x8b50: return setValue2fv; // _VEC2
  2755. case 0x8b51: return setValue3fv; // _VEC3
  2756. case 0x8b52: return setValue4fv; // _VEC4
  2757. case 0x8b5a: return setValue2fm; // _MAT2
  2758. case 0x8b5b: return setValue3fm; // _MAT3
  2759. case 0x8b5c: return setValue4fm; // _MAT4
  2760. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2761. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2762. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2763. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2764. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2765. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2766. }
  2767. }
  2768. // Array of scalars
  2769. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2770. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2771. // Array of vectors (flat or from THREE classes)
  2772. function setValueV2a( gl, v ) {
  2773. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2774. }
  2775. function setValueV3a( gl, v ) {
  2776. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2777. }
  2778. function setValueV4a( gl, v ) {
  2779. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2780. }
  2781. // Array of matrices (flat or from THREE clases)
  2782. function setValueM2a( gl, v ) {
  2783. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2784. }
  2785. function setValueM3a( gl, v ) {
  2786. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2787. }
  2788. function setValueM4a( gl, v ) {
  2789. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2790. }
  2791. // Array of textures (2D / Cube)
  2792. function setValueT1a( gl, v, renderer ) {
  2793. var n = v.length,
  2794. units = allocTexUnits( renderer, n );
  2795. gl.uniform1iv( this.addr, units );
  2796. for ( var i = 0; i !== n; ++ i ) {
  2797. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2798. }
  2799. }
  2800. function setValueT6a( gl, v, renderer ) {
  2801. var n = v.length,
  2802. units = allocTexUnits( renderer, n );
  2803. gl.uniform1iv( this.addr, units );
  2804. for ( var i = 0; i !== n; ++ i ) {
  2805. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2806. }
  2807. }
  2808. // Helper to pick the right setter for a pure (bottom-level) array
  2809. function getPureArraySetter( type ) {
  2810. switch ( type ) {
  2811. case 0x1406: return setValue1fv; // FLOAT
  2812. case 0x8b50: return setValueV2a; // _VEC2
  2813. case 0x8b51: return setValueV3a; // _VEC3
  2814. case 0x8b52: return setValueV4a; // _VEC4
  2815. case 0x8b5a: return setValueM2a; // _MAT2
  2816. case 0x8b5b: return setValueM3a; // _MAT3
  2817. case 0x8b5c: return setValueM4a; // _MAT4
  2818. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2819. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2820. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2821. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2822. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2823. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2824. }
  2825. }
  2826. // --- Uniform Classes ---
  2827. function SingleUniform( id, activeInfo, addr ) {
  2828. this.id = id;
  2829. this.addr = addr;
  2830. this.setValue = getSingularSetter( activeInfo.type );
  2831. // this.path = activeInfo.name; // DEBUG
  2832. }
  2833. function PureArrayUniform( id, activeInfo, addr ) {
  2834. this.id = id;
  2835. this.addr = addr;
  2836. this.size = activeInfo.size;
  2837. this.setValue = getPureArraySetter( activeInfo.type );
  2838. // this.path = activeInfo.name; // DEBUG
  2839. }
  2840. function StructuredUniform( id ) {
  2841. this.id = id;
  2842. UniformContainer.call( this ); // mix-in
  2843. }
  2844. StructuredUniform.prototype.setValue = function ( gl, value ) {
  2845. // Note: Don't need an extra 'renderer' parameter, since samplers
  2846. // are not allowed in structured uniforms.
  2847. var seq = this.seq;
  2848. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2849. var u = seq[ i ];
  2850. u.setValue( gl, value[ u.id ] );
  2851. }
  2852. };
  2853. // --- Top-level ---
  2854. // Parser - builds up the property tree from the path strings
  2855. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2856. // extracts
  2857. // - the identifier (member name or array index)
  2858. // - followed by an optional right bracket (found when array index)
  2859. // - followed by an optional left bracket or dot (type of subscript)
  2860. //
  2861. // Note: These portions can be read in a non-overlapping fashion and
  2862. // allow straightforward parsing of the hierarchy that WebGL encodes
  2863. // in the uniform names.
  2864. function addUniform( container, uniformObject ) {
  2865. container.seq.push( uniformObject );
  2866. container.map[ uniformObject.id ] = uniformObject;
  2867. }
  2868. function parseUniform( activeInfo, addr, container ) {
  2869. var path = activeInfo.name,
  2870. pathLength = path.length;
  2871. // reset RegExp object, because of the early exit of a previous run
  2872. RePathPart.lastIndex = 0;
  2873. for ( ; ; ) {
  2874. var match = RePathPart.exec( path ),
  2875. matchEnd = RePathPart.lastIndex,
  2876. id = match[ 1 ],
  2877. idIsIndex = match[ 2 ] === ']',
  2878. subscript = match[ 3 ];
  2879. if ( idIsIndex ) id = id | 0; // convert to integer
  2880. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  2881. // bare name or "pure" bottom-level array "[0]" suffix
  2882. addUniform( container, subscript === undefined ?
  2883. new SingleUniform( id, activeInfo, addr ) :
  2884. new PureArrayUniform( id, activeInfo, addr ) );
  2885. break;
  2886. } else {
  2887. // step into inner node / create it in case it doesn't exist
  2888. var map = container.map, next = map[ id ];
  2889. if ( next === undefined ) {
  2890. next = new StructuredUniform( id );
  2891. addUniform( container, next );
  2892. }
  2893. container = next;
  2894. }
  2895. }
  2896. }
  2897. // Root Container
  2898. function WebGLUniforms( gl, program, renderer ) {
  2899. UniformContainer.call( this );
  2900. this.renderer = renderer;
  2901. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2902. for ( var i = 0; i < n; ++ i ) {
  2903. var info = gl.getActiveUniform( program, i ),
  2904. path = info.name,
  2905. addr = gl.getUniformLocation( program, path );
  2906. parseUniform( info, addr, this );
  2907. }
  2908. }
  2909. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  2910. var u = this.map[ name ];
  2911. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2912. };
  2913. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  2914. var v = object[ name ];
  2915. if ( v !== undefined ) this.setValue( gl, name, v );
  2916. };
  2917. // Static interface
  2918. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  2919. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2920. var u = seq[ i ],
  2921. v = values[ u.id ];
  2922. if ( v.needsUpdate !== false ) {
  2923. // note: always updating when .needsUpdate is undefined
  2924. u.setValue( gl, v.value, renderer );
  2925. }
  2926. }
  2927. };
  2928. WebGLUniforms.seqWithValue = function ( seq, values ) {
  2929. var r = [];
  2930. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2931. var u = seq[ i ];
  2932. if ( u.id in values ) r.push( u );
  2933. }
  2934. return r;
  2935. };
  2936. /**
  2937. * @author mrdoob / http://mrdoob.com/
  2938. */
  2939. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  2940. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  2941. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  2942. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  2943. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  2944. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  2945. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  2946. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  2947. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  2948. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  2949. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  2950. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  2951. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  2952. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  2953. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  2954. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  2955. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  2956. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  2957. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  2958. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  2959. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  2960. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  2961. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  2962. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  2963. function Color( r, g, b ) {
  2964. if ( g === undefined && b === undefined ) {
  2965. // r is THREE.Color, hex or string
  2966. return this.set( r );
  2967. }
  2968. return this.setRGB( r, g, b );
  2969. }
  2970. Object.assign( Color.prototype, {
  2971. isColor: true,
  2972. r: 1, g: 1, b: 1,
  2973. set: function ( value ) {
  2974. if ( value && value.isColor ) {
  2975. this.copy( value );
  2976. } else if ( typeof value === 'number' ) {
  2977. this.setHex( value );
  2978. } else if ( typeof value === 'string' ) {
  2979. this.setStyle( value );
  2980. }
  2981. return this;
  2982. },
  2983. setScalar: function ( scalar ) {
  2984. this.r = scalar;
  2985. this.g = scalar;
  2986. this.b = scalar;
  2987. return this;
  2988. },
  2989. setHex: function ( hex ) {
  2990. hex = Math.floor( hex );
  2991. this.r = ( hex >> 16 & 255 ) / 255;
  2992. this.g = ( hex >> 8 & 255 ) / 255;
  2993. this.b = ( hex & 255 ) / 255;
  2994. return this;
  2995. },
  2996. setRGB: function ( r, g, b ) {
  2997. this.r = r;
  2998. this.g = g;
  2999. this.b = b;
  3000. return this;
  3001. },
  3002. setHSL: function () {
  3003. function hue2rgb( p, q, t ) {
  3004. if ( t < 0 ) t += 1;
  3005. if ( t > 1 ) t -= 1;
  3006. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3007. if ( t < 1 / 2 ) return q;
  3008. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3009. return p;
  3010. }
  3011. return function setHSL( h, s, l ) {
  3012. // h,s,l ranges are in 0.0 - 1.0
  3013. h = _Math.euclideanModulo( h, 1 );
  3014. s = _Math.clamp( s, 0, 1 );
  3015. l = _Math.clamp( l, 0, 1 );
  3016. if ( s === 0 ) {
  3017. this.r = this.g = this.b = l;
  3018. } else {
  3019. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3020. var q = ( 2 * l ) - p;
  3021. this.r = hue2rgb( q, p, h + 1 / 3 );
  3022. this.g = hue2rgb( q, p, h );
  3023. this.b = hue2rgb( q, p, h - 1 / 3 );
  3024. }
  3025. return this;
  3026. };
  3027. }(),
  3028. setStyle: function ( style ) {
  3029. function handleAlpha( string ) {
  3030. if ( string === undefined ) return;
  3031. if ( parseFloat( string ) < 1 ) {
  3032. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3033. }
  3034. }
  3035. var m;
  3036. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3037. // rgb / hsl
  3038. var color;
  3039. var name = m[ 1 ];
  3040. var components = m[ 2 ];
  3041. switch ( name ) {
  3042. case 'rgb':
  3043. case 'rgba':
  3044. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3045. // rgb(255,0,0) rgba(255,0,0,0.5)
  3046. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3047. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3048. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3049. handleAlpha( color[ 5 ] );
  3050. return this;
  3051. }
  3052. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3053. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3054. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3055. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3056. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3057. handleAlpha( color[ 5 ] );
  3058. return this;
  3059. }
  3060. break;
  3061. case 'hsl':
  3062. case 'hsla':
  3063. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3064. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3065. var h = parseFloat( color[ 1 ] ) / 360;
  3066. var s = parseInt( color[ 2 ], 10 ) / 100;
  3067. var l = parseInt( color[ 3 ], 10 ) / 100;
  3068. handleAlpha( color[ 5 ] );
  3069. return this.setHSL( h, s, l );
  3070. }
  3071. break;
  3072. }
  3073. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3074. // hex color
  3075. var hex = m[ 1 ];
  3076. var size = hex.length;
  3077. if ( size === 3 ) {
  3078. // #ff0
  3079. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3080. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3081. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3082. return this;
  3083. } else if ( size === 6 ) {
  3084. // #ff0000
  3085. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3086. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3087. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3088. return this;
  3089. }
  3090. }
  3091. if ( style && style.length > 0 ) {
  3092. // color keywords
  3093. var hex = ColorKeywords[ style ];
  3094. if ( hex !== undefined ) {
  3095. // red
  3096. this.setHex( hex );
  3097. } else {
  3098. // unknown color
  3099. console.warn( 'THREE.Color: Unknown color ' + style );
  3100. }
  3101. }
  3102. return this;
  3103. },
  3104. clone: function () {
  3105. return new this.constructor( this.r, this.g, this.b );
  3106. },
  3107. copy: function ( color ) {
  3108. this.r = color.r;
  3109. this.g = color.g;
  3110. this.b = color.b;
  3111. return this;
  3112. },
  3113. copyGammaToLinear: function ( color, gammaFactor ) {
  3114. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3115. this.r = Math.pow( color.r, gammaFactor );
  3116. this.g = Math.pow( color.g, gammaFactor );
  3117. this.b = Math.pow( color.b, gammaFactor );
  3118. return this;
  3119. },
  3120. copyLinearToGamma: function ( color, gammaFactor ) {
  3121. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3122. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3123. this.r = Math.pow( color.r, safeInverse );
  3124. this.g = Math.pow( color.g, safeInverse );
  3125. this.b = Math.pow( color.b, safeInverse );
  3126. return this;
  3127. },
  3128. convertGammaToLinear: function () {
  3129. var r = this.r, g = this.g, b = this.b;
  3130. this.r = r * r;
  3131. this.g = g * g;
  3132. this.b = b * b;
  3133. return this;
  3134. },
  3135. convertLinearToGamma: function () {
  3136. this.r = Math.sqrt( this.r );
  3137. this.g = Math.sqrt( this.g );
  3138. this.b = Math.sqrt( this.b );
  3139. return this;
  3140. },
  3141. getHex: function () {
  3142. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3143. },
  3144. getHexString: function () {
  3145. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3146. },
  3147. getHSL: function ( optionalTarget ) {
  3148. // h,s,l ranges are in 0.0 - 1.0
  3149. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3150. var r = this.r, g = this.g, b = this.b;
  3151. var max = Math.max( r, g, b );
  3152. var min = Math.min( r, g, b );
  3153. var hue, saturation;
  3154. var lightness = ( min + max ) / 2.0;
  3155. if ( min === max ) {
  3156. hue = 0;
  3157. saturation = 0;
  3158. } else {
  3159. var delta = max - min;
  3160. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3161. switch ( max ) {
  3162. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3163. case g: hue = ( b - r ) / delta + 2; break;
  3164. case b: hue = ( r - g ) / delta + 4; break;
  3165. }
  3166. hue /= 6;
  3167. }
  3168. hsl.h = hue;
  3169. hsl.s = saturation;
  3170. hsl.l = lightness;
  3171. return hsl;
  3172. },
  3173. getStyle: function () {
  3174. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3175. },
  3176. offsetHSL: function ( h, s, l ) {
  3177. var hsl = this.getHSL();
  3178. hsl.h += h; hsl.s += s; hsl.l += l;
  3179. this.setHSL( hsl.h, hsl.s, hsl.l );
  3180. return this;
  3181. },
  3182. add: function ( color ) {
  3183. this.r += color.r;
  3184. this.g += color.g;
  3185. this.b += color.b;
  3186. return this;
  3187. },
  3188. addColors: function ( color1, color2 ) {
  3189. this.r = color1.r + color2.r;
  3190. this.g = color1.g + color2.g;
  3191. this.b = color1.b + color2.b;
  3192. return this;
  3193. },
  3194. addScalar: function ( s ) {
  3195. this.r += s;
  3196. this.g += s;
  3197. this.b += s;
  3198. return this;
  3199. },
  3200. sub: function( color ) {
  3201. this.r = Math.max( 0, this.r - color.r );
  3202. this.g = Math.max( 0, this.g - color.g );
  3203. this.b = Math.max( 0, this.b - color.b );
  3204. return this;
  3205. },
  3206. multiply: function ( color ) {
  3207. this.r *= color.r;
  3208. this.g *= color.g;
  3209. this.b *= color.b;
  3210. return this;
  3211. },
  3212. multiplyScalar: function ( s ) {
  3213. this.r *= s;
  3214. this.g *= s;
  3215. this.b *= s;
  3216. return this;
  3217. },
  3218. lerp: function ( color, alpha ) {
  3219. this.r += ( color.r - this.r ) * alpha;
  3220. this.g += ( color.g - this.g ) * alpha;
  3221. this.b += ( color.b - this.b ) * alpha;
  3222. return this;
  3223. },
  3224. equals: function ( c ) {
  3225. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3226. },
  3227. fromArray: function ( array, offset ) {
  3228. if ( offset === undefined ) offset = 0;
  3229. this.r = array[ offset ];
  3230. this.g = array[ offset + 1 ];
  3231. this.b = array[ offset + 2 ];
  3232. return this;
  3233. },
  3234. toArray: function ( array, offset ) {
  3235. if ( array === undefined ) array = [];
  3236. if ( offset === undefined ) offset = 0;
  3237. array[ offset ] = this.r;
  3238. array[ offset + 1 ] = this.g;
  3239. array[ offset + 2 ] = this.b;
  3240. return array;
  3241. },
  3242. toJSON: function () {
  3243. return this.getHex();
  3244. }
  3245. } );
  3246. /**
  3247. * Uniforms library for shared webgl shaders
  3248. */
  3249. var UniformsLib = {
  3250. common: {
  3251. diffuse: { value: new Color( 0xeeeeee ) },
  3252. opacity: { value: 1.0 },
  3253. map: { value: null },
  3254. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3255. specularMap: { value: null },
  3256. alphaMap: { value: null },
  3257. envMap: { value: null },
  3258. flipEnvMap: { value: - 1 },
  3259. reflectivity: { value: 1.0 },
  3260. refractionRatio: { value: 0.98 }
  3261. },
  3262. aomap: {
  3263. aoMap: { value: null },
  3264. aoMapIntensity: { value: 1 }
  3265. },
  3266. lightmap: {
  3267. lightMap: { value: null },
  3268. lightMapIntensity: { value: 1 }
  3269. },
  3270. emissivemap: {
  3271. emissiveMap: { value: null }
  3272. },
  3273. bumpmap: {
  3274. bumpMap: { value: null },
  3275. bumpScale: { value: 1 }
  3276. },
  3277. normalmap: {
  3278. normalMap: { value: null },
  3279. normalScale: { value: new Vector2( 1, 1 ) }
  3280. },
  3281. displacementmap: {
  3282. displacementMap: { value: null },
  3283. displacementScale: { value: 1 },
  3284. displacementBias: { value: 0 }
  3285. },
  3286. roughnessmap: {
  3287. roughnessMap: { value: null }
  3288. },
  3289. metalnessmap: {
  3290. metalnessMap: { value: null }
  3291. },
  3292. gradientmap: {
  3293. gradientMap: { value: null }
  3294. },
  3295. fog: {
  3296. fogDensity: { value: 0.00025 },
  3297. fogNear: { value: 1 },
  3298. fogFar: { value: 2000 },
  3299. fogColor: { value: new Color( 0xffffff ) }
  3300. },
  3301. lights: {
  3302. ambientLightColor: { value: [] },
  3303. directionalLights: { value: [], properties: {
  3304. direction: {},
  3305. color: {},
  3306. shadow: {},
  3307. shadowBias: {},
  3308. shadowRadius: {},
  3309. shadowMapSize: {}
  3310. } },
  3311. directionalShadowMap: { value: [] },
  3312. directionalShadowMatrix: { value: [] },
  3313. spotLights: { value: [], properties: {
  3314. color: {},
  3315. position: {},
  3316. direction: {},
  3317. distance: {},
  3318. coneCos: {},
  3319. penumbraCos: {},
  3320. decay: {},
  3321. shadow: {},
  3322. shadowBias: {},
  3323. shadowRadius: {},
  3324. shadowMapSize: {}
  3325. } },
  3326. spotShadowMap: { value: [] },
  3327. spotShadowMatrix: { value: [] },
  3328. pointLights: { value: [], properties: {
  3329. color: {},
  3330. position: {},
  3331. decay: {},
  3332. distance: {},
  3333. shadow: {},
  3334. shadowBias: {},
  3335. shadowRadius: {},
  3336. shadowMapSize: {}
  3337. } },
  3338. pointShadowMap: { value: [] },
  3339. pointShadowMatrix: { value: [] },
  3340. hemisphereLights: { value: [], properties: {
  3341. direction: {},
  3342. skyColor: {},
  3343. groundColor: {}
  3344. } },
  3345. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3346. rectAreaLights: { value: [], properties: {
  3347. color: {},
  3348. position: {},
  3349. width: {},
  3350. height: {}
  3351. } }
  3352. },
  3353. points: {
  3354. diffuse: { value: new Color( 0xeeeeee ) },
  3355. opacity: { value: 1.0 },
  3356. size: { value: 1.0 },
  3357. scale: { value: 1.0 },
  3358. map: { value: null },
  3359. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3360. }
  3361. };
  3362. /**
  3363. * Uniform Utilities
  3364. */
  3365. var UniformsUtils = {
  3366. merge: function ( uniforms ) {
  3367. var merged = {};
  3368. for ( var u = 0; u < uniforms.length; u ++ ) {
  3369. var tmp = this.clone( uniforms[ u ] );
  3370. for ( var p in tmp ) {
  3371. merged[ p ] = tmp[ p ];
  3372. }
  3373. }
  3374. return merged;
  3375. },
  3376. clone: function ( uniforms_src ) {
  3377. var uniforms_dst = {};
  3378. for ( var u in uniforms_src ) {
  3379. uniforms_dst[ u ] = {};
  3380. for ( var p in uniforms_src[ u ] ) {
  3381. var parameter_src = uniforms_src[ u ][ p ];
  3382. if ( parameter_src && ( parameter_src.isColor ||
  3383. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  3384. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  3385. parameter_src.isTexture ) ) {
  3386. uniforms_dst[ u ][ p ] = parameter_src.clone();
  3387. } else if ( Array.isArray( parameter_src ) ) {
  3388. uniforms_dst[ u ][ p ] = parameter_src.slice();
  3389. } else {
  3390. uniforms_dst[ u ][ p ] = parameter_src;
  3391. }
  3392. }
  3393. }
  3394. return uniforms_dst;
  3395. }
  3396. };
  3397. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  3398. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  3399. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  3400. 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";
  3401. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  3402. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  3403. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  3404. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 ltcTextureCoords( const in GeometricContext geometry, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = (LUT_SIZE - 1.0)/LUT_SIZE;\n\tconst float LUT_BIAS = 0.5/LUT_SIZE;\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i/(2.0 * PI);\n}\nfloat ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length(f);\n\treturn max((l*l + f.z)/(l+1.0), 0.0);\n}\nvec3 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 integrateLtcBrdfOverRectOptimized( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[4];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tvec3 v1 = clippedRect[1] - clippedRect[0];\n\tvec3 v2 = clippedRect[3] - clippedRect[0];\n\tvec3 lightNormal = cross(v1, v2);\n\tbool bSameSide = dot(lightNormal, clippedRect[0]) > 0.0;\n\tif( !bSameSide )\n\t\treturn vec3(0.0);\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tvec3 edgeVectorFormFactor = vec3(0.0);\n\tedgeVectorFormFactor += EdgeVectorFormFactor( clippedRect[0], clippedRect[1] );\n\tedgeVectorFormFactor += EdgeVectorFormFactor( clippedRect[1], clippedRect[2] );\n\tedgeVectorFormFactor += EdgeVectorFormFactor( clippedRect[2], clippedRect[3] );\n\tedgeVectorFormFactor += EdgeVectorFormFactor( clippedRect[3], clippedRect[0] );\n\tvec3 Lo_i = vec3( ClippedSphereFormFactor( edgeVectorFormFactor ) );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRectOptimized( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRectOptimized( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  3405. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  3406. 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";
  3407. 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";
  3408. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  3409. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  3410. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  3411. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  3412. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  3413. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  3414. 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";
  3415. 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";
  3416. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  3417. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3418. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3419. 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";
  3420. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3421. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3422. 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";
  3423. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  3424. 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";
  3425. 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";
  3426. 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";
  3427. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  3428. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  3429. 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";
  3430. 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";
  3431. 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";
  3432. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3433. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3434. 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";
  3435. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  3436. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3437. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 matDiffColor = material.diffuseColor;\n\t\tvec3 matSpecColor = material.specularColor;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n\t\t\t\troughness,\n\t\t\t\tltcMat, ltcMag );\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec;\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff;\n\t}\n#endif\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3438. 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";
  3439. 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 matDiffColor = material.diffuseColor;\n\t\tvec3 matSpecColor = material.specularColor;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n\t\t\t\troughness,\n\t\t\t\tltcMat, ltcMag );\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec;\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff;\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";
  3440. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3441. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3442. 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";
  3443. 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";
  3444. 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";
  3445. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3446. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3447. 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";
  3448. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3449. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  3450. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3451. 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";
  3452. 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";
  3453. 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";
  3454. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  3455. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  3456. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  3457. 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";
  3458. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3459. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  3460. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  3461. 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";
  3462. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  3463. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3464. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3465. 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";
  3466. 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";
  3467. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3468. 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";
  3469. 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";
  3470. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  3471. 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";
  3472. 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";
  3473. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3474. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3475. 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";
  3476. 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";
  3477. 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";
  3478. 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";
  3479. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3480. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3481. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3482. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  3483. 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";
  3484. 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";
  3485. 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";
  3486. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3487. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  3488. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  3489. 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";
  3490. 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";
  3491. 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";
  3492. 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";
  3493. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3494. 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";
  3495. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3496. 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";
  3497. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  3498. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3499. 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 <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <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";
  3500. 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 <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3501. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  3502. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3503. 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";
  3504. 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";
  3505. 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";
  3506. 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";
  3507. var ShaderChunk = {
  3508. alphamap_fragment: alphamap_fragment,
  3509. alphamap_pars_fragment: alphamap_pars_fragment,
  3510. alphatest_fragment: alphatest_fragment,
  3511. aomap_fragment: aomap_fragment,
  3512. aomap_pars_fragment: aomap_pars_fragment,
  3513. begin_vertex: begin_vertex,
  3514. beginnormal_vertex: beginnormal_vertex,
  3515. bsdfs: bsdfs,
  3516. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3517. clipping_planes_fragment: clipping_planes_fragment,
  3518. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3519. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3520. clipping_planes_vertex: clipping_planes_vertex,
  3521. color_fragment: color_fragment,
  3522. color_pars_fragment: color_pars_fragment,
  3523. color_pars_vertex: color_pars_vertex,
  3524. color_vertex: color_vertex,
  3525. common: common,
  3526. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3527. defaultnormal_vertex: defaultnormal_vertex,
  3528. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3529. displacementmap_vertex: displacementmap_vertex,
  3530. emissivemap_fragment: emissivemap_fragment,
  3531. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3532. encodings_fragment: encodings_fragment,
  3533. encodings_pars_fragment: encodings_pars_fragment,
  3534. envmap_fragment: envmap_fragment,
  3535. envmap_pars_fragment: envmap_pars_fragment,
  3536. envmap_pars_vertex: envmap_pars_vertex,
  3537. envmap_vertex: envmap_vertex,
  3538. fog_vertex: fog_vertex,
  3539. fog_pars_vertex: fog_pars_vertex,
  3540. fog_fragment: fog_fragment,
  3541. fog_pars_fragment: fog_pars_fragment,
  3542. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3543. lightmap_fragment: lightmap_fragment,
  3544. lightmap_pars_fragment: lightmap_pars_fragment,
  3545. lights_lambert_vertex: lights_lambert_vertex,
  3546. lights_pars: lights_pars,
  3547. lights_phong_fragment: lights_phong_fragment,
  3548. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3549. lights_physical_fragment: lights_physical_fragment,
  3550. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3551. lights_template: lights_template,
  3552. logdepthbuf_fragment: logdepthbuf_fragment,
  3553. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3554. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3555. logdepthbuf_vertex: logdepthbuf_vertex,
  3556. map_fragment: map_fragment,
  3557. map_pars_fragment: map_pars_fragment,
  3558. map_particle_fragment: map_particle_fragment,
  3559. map_particle_pars_fragment: map_particle_pars_fragment,
  3560. metalnessmap_fragment: metalnessmap_fragment,
  3561. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3562. morphnormal_vertex: morphnormal_vertex,
  3563. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3564. morphtarget_vertex: morphtarget_vertex,
  3565. normal_flip: normal_flip,
  3566. normal_fragment: normal_fragment,
  3567. normalmap_pars_fragment: normalmap_pars_fragment,
  3568. packing: packing,
  3569. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3570. project_vertex: project_vertex,
  3571. dithering_fragment: dithering_fragment,
  3572. dithering_pars_fragment: dithering_pars_fragment,
  3573. roughnessmap_fragment: roughnessmap_fragment,
  3574. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3575. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3576. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3577. shadowmap_vertex: shadowmap_vertex,
  3578. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3579. skinbase_vertex: skinbase_vertex,
  3580. skinning_pars_vertex: skinning_pars_vertex,
  3581. skinning_vertex: skinning_vertex,
  3582. skinnormal_vertex: skinnormal_vertex,
  3583. specularmap_fragment: specularmap_fragment,
  3584. specularmap_pars_fragment: specularmap_pars_fragment,
  3585. tonemapping_fragment: tonemapping_fragment,
  3586. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3587. uv_pars_fragment: uv_pars_fragment,
  3588. uv_pars_vertex: uv_pars_vertex,
  3589. uv_vertex: uv_vertex,
  3590. uv2_pars_fragment: uv2_pars_fragment,
  3591. uv2_pars_vertex: uv2_pars_vertex,
  3592. uv2_vertex: uv2_vertex,
  3593. worldpos_vertex: worldpos_vertex,
  3594. cube_frag: cube_frag,
  3595. cube_vert: cube_vert,
  3596. depth_frag: depth_frag,
  3597. depth_vert: depth_vert,
  3598. distanceRGBA_frag: distanceRGBA_frag,
  3599. distanceRGBA_vert: distanceRGBA_vert,
  3600. equirect_frag: equirect_frag,
  3601. equirect_vert: equirect_vert,
  3602. linedashed_frag: linedashed_frag,
  3603. linedashed_vert: linedashed_vert,
  3604. meshbasic_frag: meshbasic_frag,
  3605. meshbasic_vert: meshbasic_vert,
  3606. meshlambert_frag: meshlambert_frag,
  3607. meshlambert_vert: meshlambert_vert,
  3608. meshphong_frag: meshphong_frag,
  3609. meshphong_vert: meshphong_vert,
  3610. meshphysical_frag: meshphysical_frag,
  3611. meshphysical_vert: meshphysical_vert,
  3612. normal_frag: normal_frag,
  3613. normal_vert: normal_vert,
  3614. points_frag: points_frag,
  3615. points_vert: points_vert,
  3616. shadow_frag: shadow_frag,
  3617. shadow_vert: shadow_vert
  3618. };
  3619. /**
  3620. * @author alteredq / http://alteredqualia.com/
  3621. * @author mrdoob / http://mrdoob.com/
  3622. * @author mikael emtinger / http://gomo.se/
  3623. */
  3624. var ShaderLib = {
  3625. basic: {
  3626. uniforms: UniformsUtils.merge( [
  3627. UniformsLib.common,
  3628. UniformsLib.aomap,
  3629. UniformsLib.lightmap,
  3630. UniformsLib.fog
  3631. ] ),
  3632. vertexShader: ShaderChunk.meshbasic_vert,
  3633. fragmentShader: ShaderChunk.meshbasic_frag
  3634. },
  3635. lambert: {
  3636. uniforms: UniformsUtils.merge( [
  3637. UniformsLib.common,
  3638. UniformsLib.aomap,
  3639. UniformsLib.lightmap,
  3640. UniformsLib.emissivemap,
  3641. UniformsLib.fog,
  3642. UniformsLib.lights,
  3643. {
  3644. emissive: { value: new Color( 0x000000 ) }
  3645. }
  3646. ] ),
  3647. vertexShader: ShaderChunk.meshlambert_vert,
  3648. fragmentShader: ShaderChunk.meshlambert_frag
  3649. },
  3650. phong: {
  3651. uniforms: UniformsUtils.merge( [
  3652. UniformsLib.common,
  3653. UniformsLib.aomap,
  3654. UniformsLib.lightmap,
  3655. UniformsLib.emissivemap,
  3656. UniformsLib.bumpmap,
  3657. UniformsLib.normalmap,
  3658. UniformsLib.displacementmap,
  3659. UniformsLib.gradientmap,
  3660. UniformsLib.fog,
  3661. UniformsLib.lights,
  3662. {
  3663. emissive: { value: new Color( 0x000000 ) },
  3664. specular: { value: new Color( 0x111111 ) },
  3665. shininess: { value: 30 }
  3666. }
  3667. ] ),
  3668. vertexShader: ShaderChunk.meshphong_vert,
  3669. fragmentShader: ShaderChunk.meshphong_frag
  3670. },
  3671. standard: {
  3672. uniforms: UniformsUtils.merge( [
  3673. UniformsLib.common,
  3674. UniformsLib.aomap,
  3675. UniformsLib.lightmap,
  3676. UniformsLib.emissivemap,
  3677. UniformsLib.bumpmap,
  3678. UniformsLib.normalmap,
  3679. UniformsLib.displacementmap,
  3680. UniformsLib.roughnessmap,
  3681. UniformsLib.metalnessmap,
  3682. UniformsLib.fog,
  3683. UniformsLib.lights,
  3684. {
  3685. emissive: { value: new Color( 0x000000 ) },
  3686. roughness: { value: 0.5 },
  3687. metalness: { value: 0.5 },
  3688. envMapIntensity: { value: 1 } // temporary
  3689. }
  3690. ] ),
  3691. vertexShader: ShaderChunk.meshphysical_vert,
  3692. fragmentShader: ShaderChunk.meshphysical_frag
  3693. },
  3694. points: {
  3695. uniforms: UniformsUtils.merge( [
  3696. UniformsLib.points,
  3697. UniformsLib.fog
  3698. ] ),
  3699. vertexShader: ShaderChunk.points_vert,
  3700. fragmentShader: ShaderChunk.points_frag
  3701. },
  3702. dashed: {
  3703. uniforms: UniformsUtils.merge( [
  3704. UniformsLib.common,
  3705. UniformsLib.fog,
  3706. {
  3707. scale: { value: 1 },
  3708. dashSize: { value: 1 },
  3709. totalSize: { value: 2 }
  3710. }
  3711. ] ),
  3712. vertexShader: ShaderChunk.linedashed_vert,
  3713. fragmentShader: ShaderChunk.linedashed_frag
  3714. },
  3715. depth: {
  3716. uniforms: UniformsUtils.merge( [
  3717. UniformsLib.common,
  3718. UniformsLib.displacementmap
  3719. ] ),
  3720. vertexShader: ShaderChunk.depth_vert,
  3721. fragmentShader: ShaderChunk.depth_frag
  3722. },
  3723. normal: {
  3724. uniforms: UniformsUtils.merge( [
  3725. UniformsLib.common,
  3726. UniformsLib.bumpmap,
  3727. UniformsLib.normalmap,
  3728. UniformsLib.displacementmap,
  3729. {
  3730. opacity: { value: 1.0 }
  3731. }
  3732. ] ),
  3733. vertexShader: ShaderChunk.normal_vert,
  3734. fragmentShader: ShaderChunk.normal_frag
  3735. },
  3736. /* -------------------------------------------------------------------------
  3737. // Cube map shader
  3738. ------------------------------------------------------------------------- */
  3739. cube: {
  3740. uniforms: {
  3741. tCube: { value: null },
  3742. tFlip: { value: - 1 },
  3743. opacity: { value: 1.0 }
  3744. },
  3745. vertexShader: ShaderChunk.cube_vert,
  3746. fragmentShader: ShaderChunk.cube_frag
  3747. },
  3748. /* -------------------------------------------------------------------------
  3749. // Cube map shader
  3750. ------------------------------------------------------------------------- */
  3751. equirect: {
  3752. uniforms: {
  3753. tEquirect: { value: null },
  3754. tFlip: { value: - 1 }
  3755. },
  3756. vertexShader: ShaderChunk.equirect_vert,
  3757. fragmentShader: ShaderChunk.equirect_frag
  3758. },
  3759. distanceRGBA: {
  3760. uniforms: {
  3761. lightPos: { value: new Vector3() }
  3762. },
  3763. vertexShader: ShaderChunk.distanceRGBA_vert,
  3764. fragmentShader: ShaderChunk.distanceRGBA_frag
  3765. }
  3766. };
  3767. ShaderLib.physical = {
  3768. uniforms: UniformsUtils.merge( [
  3769. ShaderLib.standard.uniforms,
  3770. {
  3771. clearCoat: { value: 0 },
  3772. clearCoatRoughness: { value: 0 }
  3773. }
  3774. ] ),
  3775. vertexShader: ShaderChunk.meshphysical_vert,
  3776. fragmentShader: ShaderChunk.meshphysical_frag
  3777. };
  3778. /**
  3779. * @author bhouston / http://clara.io
  3780. */
  3781. function Box2( min, max ) {
  3782. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3783. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3784. }
  3785. Object.assign( Box2.prototype, {
  3786. set: function ( min, max ) {
  3787. this.min.copy( min );
  3788. this.max.copy( max );
  3789. return this;
  3790. },
  3791. setFromPoints: function ( points ) {
  3792. this.makeEmpty();
  3793. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3794. this.expandByPoint( points[ i ] );
  3795. }
  3796. return this;
  3797. },
  3798. setFromCenterAndSize: function () {
  3799. var v1 = new Vector2();
  3800. return function setFromCenterAndSize( center, size ) {
  3801. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3802. this.min.copy( center ).sub( halfSize );
  3803. this.max.copy( center ).add( halfSize );
  3804. return this;
  3805. };
  3806. }(),
  3807. clone: function () {
  3808. return new this.constructor().copy( this );
  3809. },
  3810. copy: function ( box ) {
  3811. this.min.copy( box.min );
  3812. this.max.copy( box.max );
  3813. return this;
  3814. },
  3815. makeEmpty: function () {
  3816. this.min.x = this.min.y = + Infinity;
  3817. this.max.x = this.max.y = - Infinity;
  3818. return this;
  3819. },
  3820. isEmpty: function () {
  3821. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3822. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3823. },
  3824. getCenter: function ( optionalTarget ) {
  3825. var result = optionalTarget || new Vector2();
  3826. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3827. },
  3828. getSize: function ( optionalTarget ) {
  3829. var result = optionalTarget || new Vector2();
  3830. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3831. },
  3832. expandByPoint: function ( point ) {
  3833. this.min.min( point );
  3834. this.max.max( point );
  3835. return this;
  3836. },
  3837. expandByVector: function ( vector ) {
  3838. this.min.sub( vector );
  3839. this.max.add( vector );
  3840. return this;
  3841. },
  3842. expandByScalar: function ( scalar ) {
  3843. this.min.addScalar( - scalar );
  3844. this.max.addScalar( scalar );
  3845. return this;
  3846. },
  3847. containsPoint: function ( point ) {
  3848. return point.x < this.min.x || point.x > this.max.x ||
  3849. point.y < this.min.y || point.y > this.max.y ? false : true;
  3850. },
  3851. containsBox: function ( box ) {
  3852. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3853. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3854. },
  3855. getParameter: function ( point, optionalTarget ) {
  3856. // This can potentially have a divide by zero if the box
  3857. // has a size dimension of 0.
  3858. var result = optionalTarget || new Vector2();
  3859. return result.set(
  3860. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3861. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3862. );
  3863. },
  3864. intersectsBox: function ( box ) {
  3865. // using 4 splitting planes to rule out intersections
  3866. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3867. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3868. },
  3869. clampPoint: function ( point, optionalTarget ) {
  3870. var result = optionalTarget || new Vector2();
  3871. return result.copy( point ).clamp( this.min, this.max );
  3872. },
  3873. distanceToPoint: function () {
  3874. var v1 = new Vector2();
  3875. return function distanceToPoint( point ) {
  3876. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3877. return clampedPoint.sub( point ).length();
  3878. };
  3879. }(),
  3880. intersect: function ( box ) {
  3881. this.min.max( box.min );
  3882. this.max.min( box.max );
  3883. return this;
  3884. },
  3885. union: function ( box ) {
  3886. this.min.min( box.min );
  3887. this.max.max( box.max );
  3888. return this;
  3889. },
  3890. translate: function ( offset ) {
  3891. this.min.add( offset );
  3892. this.max.add( offset );
  3893. return this;
  3894. },
  3895. equals: function ( box ) {
  3896. return box.min.equals( this.min ) && box.max.equals( this.max );
  3897. }
  3898. } );
  3899. /**
  3900. * @author mikael emtinger / http://gomo.se/
  3901. * @author alteredq / http://alteredqualia.com/
  3902. */
  3903. function LensFlarePlugin( renderer, flares ) {
  3904. var gl = renderer.context;
  3905. var state = renderer.state;
  3906. var vertexBuffer, elementBuffer;
  3907. var shader, program, attributes, uniforms;
  3908. var tempTexture, occlusionTexture;
  3909. function init() {
  3910. var vertices = new Float32Array( [
  3911. - 1, - 1, 0, 0,
  3912. 1, - 1, 1, 0,
  3913. 1, 1, 1, 1,
  3914. - 1, 1, 0, 1
  3915. ] );
  3916. var faces = new Uint16Array( [
  3917. 0, 1, 2,
  3918. 0, 2, 3
  3919. ] );
  3920. // buffers
  3921. vertexBuffer = gl.createBuffer();
  3922. elementBuffer = gl.createBuffer();
  3923. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3924. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3925. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3926. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3927. // textures
  3928. tempTexture = gl.createTexture();
  3929. occlusionTexture = gl.createTexture();
  3930. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3931. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3932. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3933. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3934. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3935. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3936. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3937. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3938. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3939. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3940. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3941. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3942. shader = {
  3943. vertexShader: [
  3944. "uniform lowp int renderType;",
  3945. "uniform vec3 screenPosition;",
  3946. "uniform vec2 scale;",
  3947. "uniform float rotation;",
  3948. "uniform sampler2D occlusionMap;",
  3949. "attribute vec2 position;",
  3950. "attribute vec2 uv;",
  3951. "varying vec2 vUV;",
  3952. "varying float vVisibility;",
  3953. "void main() {",
  3954. "vUV = uv;",
  3955. "vec2 pos = position;",
  3956. "if ( renderType == 2 ) {",
  3957. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3958. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3959. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3960. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3961. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3962. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3963. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3964. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3965. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3966. "vVisibility = visibility.r / 9.0;",
  3967. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3968. "vVisibility *= visibility.b / 9.0;",
  3969. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3970. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3971. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3972. "}",
  3973. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3974. "}"
  3975. ].join( "\n" ),
  3976. fragmentShader: [
  3977. "uniform lowp int renderType;",
  3978. "uniform sampler2D map;",
  3979. "uniform float opacity;",
  3980. "uniform vec3 color;",
  3981. "varying vec2 vUV;",
  3982. "varying float vVisibility;",
  3983. "void main() {",
  3984. // pink square
  3985. "if ( renderType == 0 ) {",
  3986. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  3987. // restore
  3988. "} else if ( renderType == 1 ) {",
  3989. "gl_FragColor = texture2D( map, vUV );",
  3990. // flare
  3991. "} else {",
  3992. "vec4 texture = texture2D( map, vUV );",
  3993. "texture.a *= opacity * vVisibility;",
  3994. "gl_FragColor = texture;",
  3995. "gl_FragColor.rgb *= color;",
  3996. "}",
  3997. "}"
  3998. ].join( "\n" )
  3999. };
  4000. program = createProgram( shader );
  4001. attributes = {
  4002. vertex: gl.getAttribLocation ( program, "position" ),
  4003. uv: gl.getAttribLocation ( program, "uv" )
  4004. };
  4005. uniforms = {
  4006. renderType: gl.getUniformLocation( program, "renderType" ),
  4007. map: gl.getUniformLocation( program, "map" ),
  4008. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4009. opacity: gl.getUniformLocation( program, "opacity" ),
  4010. color: gl.getUniformLocation( program, "color" ),
  4011. scale: gl.getUniformLocation( program, "scale" ),
  4012. rotation: gl.getUniformLocation( program, "rotation" ),
  4013. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4014. };
  4015. }
  4016. /*
  4017. * Render lens flares
  4018. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4019. * reads these back and calculates occlusion.
  4020. */
  4021. this.render = function ( scene, camera, viewport ) {
  4022. if ( flares.length === 0 ) return;
  4023. var tempPosition = new Vector3();
  4024. var invAspect = viewport.w / viewport.z,
  4025. halfViewportWidth = viewport.z * 0.5,
  4026. halfViewportHeight = viewport.w * 0.5;
  4027. var size = 16 / viewport.w,
  4028. scale = new Vector2( size * invAspect, size );
  4029. var screenPosition = new Vector3( 1, 1, 0 ),
  4030. screenPositionPixels = new Vector2( 1, 1 );
  4031. var validArea = new Box2();
  4032. validArea.min.set( viewport.x, viewport.y );
  4033. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4034. if ( program === undefined ) {
  4035. init();
  4036. }
  4037. gl.useProgram( program );
  4038. state.initAttributes();
  4039. state.enableAttribute( attributes.vertex );
  4040. state.enableAttribute( attributes.uv );
  4041. state.disableUnusedAttributes();
  4042. // loop through all lens flares to update their occlusion and positions
  4043. // setup gl and common used attribs/uniforms
  4044. gl.uniform1i( uniforms.occlusionMap, 0 );
  4045. gl.uniform1i( uniforms.map, 1 );
  4046. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4047. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4048. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4049. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4050. state.disable( gl.CULL_FACE );
  4051. state.buffers.depth.setMask( false );
  4052. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4053. size = 16 / viewport.w;
  4054. scale.set( size * invAspect, size );
  4055. // calc object screen position
  4056. var flare = flares[ i ];
  4057. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4058. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4059. tempPosition.applyMatrix4( camera.projectionMatrix );
  4060. // setup arrays for gl programs
  4061. screenPosition.copy( tempPosition );
  4062. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4063. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4064. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4065. // screen cull
  4066. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4067. // save current RGB to temp texture
  4068. state.activeTexture( gl.TEXTURE0 );
  4069. state.bindTexture( gl.TEXTURE_2D, null );
  4070. state.activeTexture( gl.TEXTURE1 );
  4071. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4072. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4073. // render pink quad
  4074. gl.uniform1i( uniforms.renderType, 0 );
  4075. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4076. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4077. state.disable( gl.BLEND );
  4078. state.enable( gl.DEPTH_TEST );
  4079. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4080. // copy result to occlusionMap
  4081. state.activeTexture( gl.TEXTURE0 );
  4082. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4083. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4084. // restore graphics
  4085. gl.uniform1i( uniforms.renderType, 1 );
  4086. state.disable( gl.DEPTH_TEST );
  4087. state.activeTexture( gl.TEXTURE1 );
  4088. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4089. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4090. // update object positions
  4091. flare.positionScreen.copy( screenPosition );
  4092. if ( flare.customUpdateCallback ) {
  4093. flare.customUpdateCallback( flare );
  4094. } else {
  4095. flare.updateLensFlares();
  4096. }
  4097. // render flares
  4098. gl.uniform1i( uniforms.renderType, 2 );
  4099. state.enable( gl.BLEND );
  4100. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4101. var sprite = flare.lensFlares[ j ];
  4102. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4103. screenPosition.x = sprite.x;
  4104. screenPosition.y = sprite.y;
  4105. screenPosition.z = sprite.z;
  4106. size = sprite.size * sprite.scale / viewport.w;
  4107. scale.x = size * invAspect;
  4108. scale.y = size;
  4109. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4110. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4111. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4112. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4113. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4114. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4115. renderer.setTexture2D( sprite.texture, 1 );
  4116. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4117. }
  4118. }
  4119. }
  4120. }
  4121. // restore gl
  4122. state.enable( gl.CULL_FACE );
  4123. state.enable( gl.DEPTH_TEST );
  4124. state.buffers.depth.setMask( true );
  4125. renderer.resetGLState();
  4126. };
  4127. function createProgram( shader ) {
  4128. var program = gl.createProgram();
  4129. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4130. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4131. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4132. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4133. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4134. gl.compileShader( fragmentShader );
  4135. gl.compileShader( vertexShader );
  4136. gl.attachShader( program, fragmentShader );
  4137. gl.attachShader( program, vertexShader );
  4138. gl.linkProgram( program );
  4139. return program;
  4140. }
  4141. }
  4142. /**
  4143. * @author mikael emtinger / http://gomo.se/
  4144. * @author alteredq / http://alteredqualia.com/
  4145. */
  4146. function SpritePlugin( renderer, sprites ) {
  4147. var gl = renderer.context;
  4148. var state = renderer.state;
  4149. var vertexBuffer, elementBuffer;
  4150. var program, attributes, uniforms;
  4151. var texture;
  4152. // decompose matrixWorld
  4153. var spritePosition = new Vector3();
  4154. var spriteRotation = new Quaternion();
  4155. var spriteScale = new Vector3();
  4156. function init() {
  4157. var vertices = new Float32Array( [
  4158. - 0.5, - 0.5, 0, 0,
  4159. 0.5, - 0.5, 1, 0,
  4160. 0.5, 0.5, 1, 1,
  4161. - 0.5, 0.5, 0, 1
  4162. ] );
  4163. var faces = new Uint16Array( [
  4164. 0, 1, 2,
  4165. 0, 2, 3
  4166. ] );
  4167. vertexBuffer = gl.createBuffer();
  4168. elementBuffer = gl.createBuffer();
  4169. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4170. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4171. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4172. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4173. program = createProgram();
  4174. attributes = {
  4175. position: gl.getAttribLocation ( program, 'position' ),
  4176. uv: gl.getAttribLocation ( program, 'uv' )
  4177. };
  4178. uniforms = {
  4179. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4180. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4181. rotation: gl.getUniformLocation( program, 'rotation' ),
  4182. scale: gl.getUniformLocation( program, 'scale' ),
  4183. color: gl.getUniformLocation( program, 'color' ),
  4184. map: gl.getUniformLocation( program, 'map' ),
  4185. opacity: gl.getUniformLocation( program, 'opacity' ),
  4186. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4187. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4188. fogType: gl.getUniformLocation( program, 'fogType' ),
  4189. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4190. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4191. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4192. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4193. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4194. };
  4195. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4196. canvas.width = 8;
  4197. canvas.height = 8;
  4198. var context = canvas.getContext( '2d' );
  4199. context.fillStyle = 'white';
  4200. context.fillRect( 0, 0, 8, 8 );
  4201. texture = new Texture( canvas );
  4202. texture.needsUpdate = true;
  4203. }
  4204. this.render = function ( scene, camera ) {
  4205. if ( sprites.length === 0 ) return;
  4206. // setup gl
  4207. if ( program === undefined ) {
  4208. init();
  4209. }
  4210. gl.useProgram( program );
  4211. state.initAttributes();
  4212. state.enableAttribute( attributes.position );
  4213. state.enableAttribute( attributes.uv );
  4214. state.disableUnusedAttributes();
  4215. state.disable( gl.CULL_FACE );
  4216. state.enable( gl.BLEND );
  4217. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4218. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4219. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4220. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4221. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4222. state.activeTexture( gl.TEXTURE0 );
  4223. gl.uniform1i( uniforms.map, 0 );
  4224. var oldFogType = 0;
  4225. var sceneFogType = 0;
  4226. var fog = scene.fog;
  4227. if ( fog ) {
  4228. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4229. if ( fog.isFog ) {
  4230. gl.uniform1f( uniforms.fogNear, fog.near );
  4231. gl.uniform1f( uniforms.fogFar, fog.far );
  4232. gl.uniform1i( uniforms.fogType, 1 );
  4233. oldFogType = 1;
  4234. sceneFogType = 1;
  4235. } else if ( fog.isFogExp2 ) {
  4236. gl.uniform1f( uniforms.fogDensity, fog.density );
  4237. gl.uniform1i( uniforms.fogType, 2 );
  4238. oldFogType = 2;
  4239. sceneFogType = 2;
  4240. }
  4241. } else {
  4242. gl.uniform1i( uniforms.fogType, 0 );
  4243. oldFogType = 0;
  4244. sceneFogType = 0;
  4245. }
  4246. // update positions and sort
  4247. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4248. var sprite = sprites[ i ];
  4249. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4250. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4251. }
  4252. sprites.sort( painterSortStable );
  4253. // render all sprites
  4254. var scale = [];
  4255. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4256. var sprite = sprites[ i ];
  4257. var material = sprite.material;
  4258. if ( material.visible === false ) continue;
  4259. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4260. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4261. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4262. scale[ 0 ] = spriteScale.x;
  4263. scale[ 1 ] = spriteScale.y;
  4264. var fogType = 0;
  4265. if ( scene.fog && material.fog ) {
  4266. fogType = sceneFogType;
  4267. }
  4268. if ( oldFogType !== fogType ) {
  4269. gl.uniform1i( uniforms.fogType, fogType );
  4270. oldFogType = fogType;
  4271. }
  4272. if ( material.map !== null ) {
  4273. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4274. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4275. } else {
  4276. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4277. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4278. }
  4279. gl.uniform1f( uniforms.opacity, material.opacity );
  4280. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4281. gl.uniform1f( uniforms.rotation, material.rotation );
  4282. gl.uniform2fv( uniforms.scale, scale );
  4283. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4284. state.buffers.depth.setTest( material.depthTest );
  4285. state.buffers.depth.setMask( material.depthWrite );
  4286. if ( material.map ) {
  4287. renderer.setTexture2D( material.map, 0 );
  4288. } else {
  4289. renderer.setTexture2D( texture, 0 );
  4290. }
  4291. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4292. }
  4293. // restore gl
  4294. state.enable( gl.CULL_FACE );
  4295. renderer.resetGLState();
  4296. };
  4297. function createProgram() {
  4298. var program = gl.createProgram();
  4299. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4300. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4301. gl.shaderSource( vertexShader, [
  4302. 'precision ' + renderer.getPrecision() + ' float;',
  4303. 'uniform mat4 modelViewMatrix;',
  4304. 'uniform mat4 projectionMatrix;',
  4305. 'uniform float rotation;',
  4306. 'uniform vec2 scale;',
  4307. 'uniform vec2 uvOffset;',
  4308. 'uniform vec2 uvScale;',
  4309. 'attribute vec2 position;',
  4310. 'attribute vec2 uv;',
  4311. 'varying vec2 vUV;',
  4312. 'void main() {',
  4313. 'vUV = uvOffset + uv * uvScale;',
  4314. 'vec2 alignedPosition = position * scale;',
  4315. 'vec2 rotatedPosition;',
  4316. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4317. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4318. 'vec4 finalPosition;',
  4319. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4320. 'finalPosition.xy += rotatedPosition;',
  4321. 'finalPosition = projectionMatrix * finalPosition;',
  4322. 'gl_Position = finalPosition;',
  4323. '}'
  4324. ].join( '\n' ) );
  4325. gl.shaderSource( fragmentShader, [
  4326. 'precision ' + renderer.getPrecision() + ' float;',
  4327. 'uniform vec3 color;',
  4328. 'uniform sampler2D map;',
  4329. 'uniform float opacity;',
  4330. 'uniform int fogType;',
  4331. 'uniform vec3 fogColor;',
  4332. 'uniform float fogDensity;',
  4333. 'uniform float fogNear;',
  4334. 'uniform float fogFar;',
  4335. 'uniform float alphaTest;',
  4336. 'varying vec2 vUV;',
  4337. 'void main() {',
  4338. 'vec4 texture = texture2D( map, vUV );',
  4339. 'if ( texture.a < alphaTest ) discard;',
  4340. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4341. 'if ( fogType > 0 ) {',
  4342. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4343. 'float fogFactor = 0.0;',
  4344. 'if ( fogType == 1 ) {',
  4345. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4346. '} else {',
  4347. 'const float LOG2 = 1.442695;',
  4348. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4349. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4350. '}',
  4351. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4352. '}',
  4353. '}'
  4354. ].join( '\n' ) );
  4355. gl.compileShader( vertexShader );
  4356. gl.compileShader( fragmentShader );
  4357. gl.attachShader( program, vertexShader );
  4358. gl.attachShader( program, fragmentShader );
  4359. gl.linkProgram( program );
  4360. return program;
  4361. }
  4362. function painterSortStable( a, b ) {
  4363. if ( a.renderOrder !== b.renderOrder ) {
  4364. return a.renderOrder - b.renderOrder;
  4365. } else if ( a.z !== b.z ) {
  4366. return b.z - a.z;
  4367. } else {
  4368. return b.id - a.id;
  4369. }
  4370. }
  4371. }
  4372. /**
  4373. * @author mrdoob / http://mrdoob.com/
  4374. * @author alteredq / http://alteredqualia.com/
  4375. */
  4376. var materialId = 0;
  4377. function Material() {
  4378. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4379. this.uuid = _Math.generateUUID();
  4380. this.name = '';
  4381. this.type = 'Material';
  4382. this.fog = true;
  4383. this.lights = true;
  4384. this.blending = NormalBlending;
  4385. this.side = FrontSide;
  4386. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4387. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4388. this.opacity = 1;
  4389. this.transparent = false;
  4390. this.blendSrc = SrcAlphaFactor;
  4391. this.blendDst = OneMinusSrcAlphaFactor;
  4392. this.blendEquation = AddEquation;
  4393. this.blendSrcAlpha = null;
  4394. this.blendDstAlpha = null;
  4395. this.blendEquationAlpha = null;
  4396. this.depthFunc = LessEqualDepth;
  4397. this.depthTest = true;
  4398. this.depthWrite = true;
  4399. this.clippingPlanes = null;
  4400. this.clipIntersection = false;
  4401. this.clipShadows = false;
  4402. this.colorWrite = true;
  4403. this.precision = null; // override the renderer's default precision for this material
  4404. this.polygonOffset = false;
  4405. this.polygonOffsetFactor = 0;
  4406. this.polygonOffsetUnits = 0;
  4407. this.dithering = false;
  4408. this.alphaTest = 0;
  4409. this.premultipliedAlpha = false;
  4410. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4411. this.visible = true;
  4412. this.needsUpdate = true;
  4413. }
  4414. Object.assign( Material.prototype, EventDispatcher.prototype, {
  4415. isMaterial: true,
  4416. setValues: function ( values ) {
  4417. if ( values === undefined ) return;
  4418. for ( var key in values ) {
  4419. var newValue = values[ key ];
  4420. if ( newValue === undefined ) {
  4421. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4422. continue;
  4423. }
  4424. var currentValue = this[ key ];
  4425. if ( currentValue === undefined ) {
  4426. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4427. continue;
  4428. }
  4429. if ( currentValue && currentValue.isColor ) {
  4430. currentValue.set( newValue );
  4431. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4432. currentValue.copy( newValue );
  4433. } else if ( key === 'overdraw' ) {
  4434. // ensure overdraw is backwards-compatible with legacy boolean type
  4435. this[ key ] = Number( newValue );
  4436. } else {
  4437. this[ key ] = newValue;
  4438. }
  4439. }
  4440. },
  4441. toJSON: function ( meta ) {
  4442. var isRoot = meta === undefined;
  4443. if ( isRoot ) {
  4444. meta = {
  4445. textures: {},
  4446. images: {}
  4447. };
  4448. }
  4449. var data = {
  4450. metadata: {
  4451. version: 4.5,
  4452. type: 'Material',
  4453. generator: 'Material.toJSON'
  4454. }
  4455. };
  4456. // standard Material serialization
  4457. data.uuid = this.uuid;
  4458. data.type = this.type;
  4459. if ( this.name !== '' ) data.name = this.name;
  4460. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4461. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4462. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4463. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4464. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4465. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4466. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4467. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4468. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4469. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4470. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4471. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4472. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4473. data.bumpScale = this.bumpScale;
  4474. }
  4475. if ( this.normalMap && this.normalMap.isTexture ) {
  4476. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4477. data.normalScale = this.normalScale.toArray();
  4478. }
  4479. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4480. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4481. data.displacementScale = this.displacementScale;
  4482. data.displacementBias = this.displacementBias;
  4483. }
  4484. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4485. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4486. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4487. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4488. if ( this.envMap && this.envMap.isTexture ) {
  4489. data.envMap = this.envMap.toJSON( meta ).uuid;
  4490. data.reflectivity = this.reflectivity; // Scale behind envMap
  4491. }
  4492. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4493. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4494. }
  4495. if ( this.size !== undefined ) data.size = this.size;
  4496. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4497. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4498. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4499. if ( this.side !== FrontSide ) data.side = this.side;
  4500. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4501. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4502. if ( this.transparent === true ) data.transparent = this.transparent;
  4503. data.depthFunc = this.depthFunc;
  4504. data.depthTest = this.depthTest;
  4505. data.depthWrite = this.depthWrite;
  4506. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4507. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4508. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4509. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4510. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4511. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4512. data.skinning = this.skinning;
  4513. data.morphTargets = this.morphTargets;
  4514. data.dithering = this.dithering;
  4515. // TODO: Copied from Object3D.toJSON
  4516. function extractFromCache( cache ) {
  4517. var values = [];
  4518. for ( var key in cache ) {
  4519. var data = cache[ key ];
  4520. delete data.metadata;
  4521. values.push( data );
  4522. }
  4523. return values;
  4524. }
  4525. if ( isRoot ) {
  4526. var textures = extractFromCache( meta.textures );
  4527. var images = extractFromCache( meta.images );
  4528. if ( textures.length > 0 ) data.textures = textures;
  4529. if ( images.length > 0 ) data.images = images;
  4530. }
  4531. return data;
  4532. },
  4533. clone: function () {
  4534. return new this.constructor().copy( this );
  4535. },
  4536. copy: function ( source ) {
  4537. this.name = source.name;
  4538. this.fog = source.fog;
  4539. this.lights = source.lights;
  4540. this.blending = source.blending;
  4541. this.side = source.side;
  4542. this.shading = source.shading;
  4543. this.vertexColors = source.vertexColors;
  4544. this.opacity = source.opacity;
  4545. this.transparent = source.transparent;
  4546. this.blendSrc = source.blendSrc;
  4547. this.blendDst = source.blendDst;
  4548. this.blendEquation = source.blendEquation;
  4549. this.blendSrcAlpha = source.blendSrcAlpha;
  4550. this.blendDstAlpha = source.blendDstAlpha;
  4551. this.blendEquationAlpha = source.blendEquationAlpha;
  4552. this.depthFunc = source.depthFunc;
  4553. this.depthTest = source.depthTest;
  4554. this.depthWrite = source.depthWrite;
  4555. this.colorWrite = source.colorWrite;
  4556. this.precision = source.precision;
  4557. this.polygonOffset = source.polygonOffset;
  4558. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4559. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4560. this.dithering = source.dithering;
  4561. this.alphaTest = source.alphaTest;
  4562. this.premultipliedAlpha = source.premultipliedAlpha;
  4563. this.overdraw = source.overdraw;
  4564. this.visible = source.visible;
  4565. this.clipShadows = source.clipShadows;
  4566. this.clipIntersection = source.clipIntersection;
  4567. var srcPlanes = source.clippingPlanes,
  4568. dstPlanes = null;
  4569. if ( srcPlanes !== null ) {
  4570. var n = srcPlanes.length;
  4571. dstPlanes = new Array( n );
  4572. for ( var i = 0; i !== n; ++ i )
  4573. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4574. }
  4575. this.clippingPlanes = dstPlanes;
  4576. return this;
  4577. },
  4578. dispose: function () {
  4579. this.dispatchEvent( { type: 'dispose' } );
  4580. }
  4581. } );
  4582. /**
  4583. * @author alteredq / http://alteredqualia.com/
  4584. *
  4585. * parameters = {
  4586. * defines: { "label" : "value" },
  4587. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4588. *
  4589. * fragmentShader: <string>,
  4590. * vertexShader: <string>,
  4591. *
  4592. * wireframe: <boolean>,
  4593. * wireframeLinewidth: <float>,
  4594. *
  4595. * lights: <bool>,
  4596. *
  4597. * skinning: <bool>,
  4598. * morphTargets: <bool>,
  4599. * morphNormals: <bool>
  4600. * }
  4601. */
  4602. function ShaderMaterial( parameters ) {
  4603. Material.call( this );
  4604. this.type = 'ShaderMaterial';
  4605. this.defines = {};
  4606. this.uniforms = {};
  4607. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4608. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4609. this.linewidth = 1;
  4610. this.wireframe = false;
  4611. this.wireframeLinewidth = 1;
  4612. this.fog = false; // set to use scene fog
  4613. this.lights = false; // set to use scene lights
  4614. this.clipping = false; // set to use user-defined clipping planes
  4615. this.skinning = false; // set to use skinning attribute streams
  4616. this.morphTargets = false; // set to use morph targets
  4617. this.morphNormals = false; // set to use morph normals
  4618. this.extensions = {
  4619. derivatives: false, // set to use derivatives
  4620. fragDepth: false, // set to use fragment depth values
  4621. drawBuffers: false, // set to use draw buffers
  4622. shaderTextureLOD: false // set to use shader texture LOD
  4623. };
  4624. // When rendered geometry doesn't include these attributes but the material does,
  4625. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4626. this.defaultAttributeValues = {
  4627. 'color': [ 1, 1, 1 ],
  4628. 'uv': [ 0, 0 ],
  4629. 'uv2': [ 0, 0 ]
  4630. };
  4631. this.index0AttributeName = undefined;
  4632. if ( parameters !== undefined ) {
  4633. if ( parameters.attributes !== undefined ) {
  4634. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4635. }
  4636. this.setValues( parameters );
  4637. }
  4638. }
  4639. ShaderMaterial.prototype = Object.create( Material.prototype );
  4640. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4641. ShaderMaterial.prototype.isShaderMaterial = true;
  4642. ShaderMaterial.prototype.copy = function ( source ) {
  4643. Material.prototype.copy.call( this, source );
  4644. this.fragmentShader = source.fragmentShader;
  4645. this.vertexShader = source.vertexShader;
  4646. this.uniforms = UniformsUtils.clone( source.uniforms );
  4647. this.defines = source.defines;
  4648. this.wireframe = source.wireframe;
  4649. this.wireframeLinewidth = source.wireframeLinewidth;
  4650. this.lights = source.lights;
  4651. this.clipping = source.clipping;
  4652. this.skinning = source.skinning;
  4653. this.morphTargets = source.morphTargets;
  4654. this.morphNormals = source.morphNormals;
  4655. this.extensions = source.extensions;
  4656. return this;
  4657. };
  4658. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4659. var data = Material.prototype.toJSON.call( this, meta );
  4660. data.uniforms = this.uniforms;
  4661. data.vertexShader = this.vertexShader;
  4662. data.fragmentShader = this.fragmentShader;
  4663. return data;
  4664. };
  4665. /**
  4666. * @author mrdoob / http://mrdoob.com/
  4667. * @author alteredq / http://alteredqualia.com/
  4668. * @author bhouston / https://clara.io
  4669. * @author WestLangley / http://github.com/WestLangley
  4670. *
  4671. * parameters = {
  4672. *
  4673. * opacity: <float>,
  4674. *
  4675. * map: new THREE.Texture( <Image> ),
  4676. *
  4677. * alphaMap: new THREE.Texture( <Image> ),
  4678. *
  4679. * displacementMap: new THREE.Texture( <Image> ),
  4680. * displacementScale: <float>,
  4681. * displacementBias: <float>,
  4682. *
  4683. * wireframe: <boolean>,
  4684. * wireframeLinewidth: <float>
  4685. * }
  4686. */
  4687. function MeshDepthMaterial( parameters ) {
  4688. Material.call( this );
  4689. this.type = 'MeshDepthMaterial';
  4690. this.depthPacking = BasicDepthPacking;
  4691. this.skinning = false;
  4692. this.morphTargets = false;
  4693. this.map = null;
  4694. this.alphaMap = null;
  4695. this.displacementMap = null;
  4696. this.displacementScale = 1;
  4697. this.displacementBias = 0;
  4698. this.wireframe = false;
  4699. this.wireframeLinewidth = 1;
  4700. this.fog = false;
  4701. this.lights = false;
  4702. this.setValues( parameters );
  4703. }
  4704. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4705. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4706. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4707. MeshDepthMaterial.prototype.copy = function ( source ) {
  4708. Material.prototype.copy.call( this, source );
  4709. this.depthPacking = source.depthPacking;
  4710. this.skinning = source.skinning;
  4711. this.morphTargets = source.morphTargets;
  4712. this.map = source.map;
  4713. this.alphaMap = source.alphaMap;
  4714. this.displacementMap = source.displacementMap;
  4715. this.displacementScale = source.displacementScale;
  4716. this.displacementBias = source.displacementBias;
  4717. this.wireframe = source.wireframe;
  4718. this.wireframeLinewidth = source.wireframeLinewidth;
  4719. return this;
  4720. };
  4721. /**
  4722. * @author bhouston / http://clara.io
  4723. * @author WestLangley / http://github.com/WestLangley
  4724. */
  4725. function Box3( min, max ) {
  4726. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4727. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4728. }
  4729. Object.assign( Box3.prototype, {
  4730. isBox3: true,
  4731. set: function ( min, max ) {
  4732. this.min.copy( min );
  4733. this.max.copy( max );
  4734. return this;
  4735. },
  4736. setFromArray: function ( array ) {
  4737. var minX = + Infinity;
  4738. var minY = + Infinity;
  4739. var minZ = + Infinity;
  4740. var maxX = - Infinity;
  4741. var maxY = - Infinity;
  4742. var maxZ = - Infinity;
  4743. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4744. var x = array[ i ];
  4745. var y = array[ i + 1 ];
  4746. var z = array[ i + 2 ];
  4747. if ( x < minX ) minX = x;
  4748. if ( y < minY ) minY = y;
  4749. if ( z < minZ ) minZ = z;
  4750. if ( x > maxX ) maxX = x;
  4751. if ( y > maxY ) maxY = y;
  4752. if ( z > maxZ ) maxZ = z;
  4753. }
  4754. this.min.set( minX, minY, minZ );
  4755. this.max.set( maxX, maxY, maxZ );
  4756. return this;
  4757. },
  4758. setFromBufferAttribute: function ( attribute ) {
  4759. var minX = + Infinity;
  4760. var minY = + Infinity;
  4761. var minZ = + Infinity;
  4762. var maxX = - Infinity;
  4763. var maxY = - Infinity;
  4764. var maxZ = - Infinity;
  4765. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4766. var x = attribute.getX( i );
  4767. var y = attribute.getY( i );
  4768. var z = attribute.getZ( i );
  4769. if ( x < minX ) minX = x;
  4770. if ( y < minY ) minY = y;
  4771. if ( z < minZ ) minZ = z;
  4772. if ( x > maxX ) maxX = x;
  4773. if ( y > maxY ) maxY = y;
  4774. if ( z > maxZ ) maxZ = z;
  4775. }
  4776. this.min.set( minX, minY, minZ );
  4777. this.max.set( maxX, maxY, maxZ );
  4778. return this;
  4779. },
  4780. setFromPoints: function ( points ) {
  4781. this.makeEmpty();
  4782. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4783. this.expandByPoint( points[ i ] );
  4784. }
  4785. return this;
  4786. },
  4787. setFromCenterAndSize: function () {
  4788. var v1 = new Vector3();
  4789. return function setFromCenterAndSize( center, size ) {
  4790. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4791. this.min.copy( center ).sub( halfSize );
  4792. this.max.copy( center ).add( halfSize );
  4793. return this;
  4794. };
  4795. }(),
  4796. setFromObject: function ( object ) {
  4797. this.makeEmpty();
  4798. return this.expandByObject( object );
  4799. },
  4800. clone: function () {
  4801. return new this.constructor().copy( this );
  4802. },
  4803. copy: function ( box ) {
  4804. this.min.copy( box.min );
  4805. this.max.copy( box.max );
  4806. return this;
  4807. },
  4808. makeEmpty: function () {
  4809. this.min.x = this.min.y = this.min.z = + Infinity;
  4810. this.max.x = this.max.y = this.max.z = - Infinity;
  4811. return this;
  4812. },
  4813. isEmpty: function () {
  4814. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4815. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4816. },
  4817. getCenter: function ( optionalTarget ) {
  4818. var result = optionalTarget || new Vector3();
  4819. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4820. },
  4821. getSize: function ( optionalTarget ) {
  4822. var result = optionalTarget || new Vector3();
  4823. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4824. },
  4825. expandByPoint: function ( point ) {
  4826. this.min.min( point );
  4827. this.max.max( point );
  4828. return this;
  4829. },
  4830. expandByVector: function ( vector ) {
  4831. this.min.sub( vector );
  4832. this.max.add( vector );
  4833. return this;
  4834. },
  4835. expandByScalar: function ( scalar ) {
  4836. this.min.addScalar( - scalar );
  4837. this.max.addScalar( scalar );
  4838. return this;
  4839. },
  4840. expandByObject: function () {
  4841. // Computes the world-axis-aligned bounding box of an object (including its children),
  4842. // accounting for both the object's, and children's, world transforms
  4843. var v1 = new Vector3();
  4844. return function expandByObject( object ) {
  4845. var scope = this;
  4846. object.updateMatrixWorld( true );
  4847. object.traverse( function ( node ) {
  4848. var i, l;
  4849. var geometry = node.geometry;
  4850. if ( geometry !== undefined ) {
  4851. if ( geometry.isGeometry ) {
  4852. var vertices = geometry.vertices;
  4853. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4854. v1.copy( vertices[ i ] );
  4855. v1.applyMatrix4( node.matrixWorld );
  4856. scope.expandByPoint( v1 );
  4857. }
  4858. } else if ( geometry.isBufferGeometry ) {
  4859. var attribute = geometry.attributes.position;
  4860. if ( attribute !== undefined ) {
  4861. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4862. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4863. scope.expandByPoint( v1 );
  4864. }
  4865. }
  4866. }
  4867. }
  4868. } );
  4869. return this;
  4870. };
  4871. }(),
  4872. containsPoint: function ( point ) {
  4873. return point.x < this.min.x || point.x > this.max.x ||
  4874. point.y < this.min.y || point.y > this.max.y ||
  4875. point.z < this.min.z || point.z > this.max.z ? false : true;
  4876. },
  4877. containsBox: function ( box ) {
  4878. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4879. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4880. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4881. },
  4882. getParameter: function ( point, optionalTarget ) {
  4883. // This can potentially have a divide by zero if the box
  4884. // has a size dimension of 0.
  4885. var result = optionalTarget || new Vector3();
  4886. return result.set(
  4887. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4888. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4889. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4890. );
  4891. },
  4892. intersectsBox: function ( box ) {
  4893. // using 6 splitting planes to rule out intersections.
  4894. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4895. box.max.y < this.min.y || box.min.y > this.max.y ||
  4896. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4897. },
  4898. intersectsSphere: ( function () {
  4899. var closestPoint = new Vector3();
  4900. return function intersectsSphere( sphere ) {
  4901. // Find the point on the AABB closest to the sphere center.
  4902. this.clampPoint( sphere.center, closestPoint );
  4903. // If that point is inside the sphere, the AABB and sphere intersect.
  4904. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4905. };
  4906. } )(),
  4907. intersectsPlane: function ( plane ) {
  4908. // We compute the minimum and maximum dot product values. If those values
  4909. // are on the same side (back or front) of the plane, then there is no intersection.
  4910. var min, max;
  4911. if ( plane.normal.x > 0 ) {
  4912. min = plane.normal.x * this.min.x;
  4913. max = plane.normal.x * this.max.x;
  4914. } else {
  4915. min = plane.normal.x * this.max.x;
  4916. max = plane.normal.x * this.min.x;
  4917. }
  4918. if ( plane.normal.y > 0 ) {
  4919. min += plane.normal.y * this.min.y;
  4920. max += plane.normal.y * this.max.y;
  4921. } else {
  4922. min += plane.normal.y * this.max.y;
  4923. max += plane.normal.y * this.min.y;
  4924. }
  4925. if ( plane.normal.z > 0 ) {
  4926. min += plane.normal.z * this.min.z;
  4927. max += plane.normal.z * this.max.z;
  4928. } else {
  4929. min += plane.normal.z * this.max.z;
  4930. max += plane.normal.z * this.min.z;
  4931. }
  4932. return ( min <= plane.constant && max >= plane.constant );
  4933. },
  4934. clampPoint: function ( point, optionalTarget ) {
  4935. var result = optionalTarget || new Vector3();
  4936. return result.copy( point ).clamp( this.min, this.max );
  4937. },
  4938. distanceToPoint: function () {
  4939. var v1 = new Vector3();
  4940. return function distanceToPoint( point ) {
  4941. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4942. return clampedPoint.sub( point ).length();
  4943. };
  4944. }(),
  4945. getBoundingSphere: function () {
  4946. var v1 = new Vector3();
  4947. return function getBoundingSphere( optionalTarget ) {
  4948. var result = optionalTarget || new Sphere();
  4949. this.getCenter( result.center );
  4950. result.radius = this.getSize( v1 ).length() * 0.5;
  4951. return result;
  4952. };
  4953. }(),
  4954. intersect: function ( box ) {
  4955. this.min.max( box.min );
  4956. this.max.min( box.max );
  4957. // 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.
  4958. if( this.isEmpty() ) this.makeEmpty();
  4959. return this;
  4960. },
  4961. union: function ( box ) {
  4962. this.min.min( box.min );
  4963. this.max.max( box.max );
  4964. return this;
  4965. },
  4966. applyMatrix4: function () {
  4967. var points = [
  4968. new Vector3(),
  4969. new Vector3(),
  4970. new Vector3(),
  4971. new Vector3(),
  4972. new Vector3(),
  4973. new Vector3(),
  4974. new Vector3(),
  4975. new Vector3()
  4976. ];
  4977. return function applyMatrix4( matrix ) {
  4978. // transform of empty box is an empty box.
  4979. if( this.isEmpty() ) return this;
  4980. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4981. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4982. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4983. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4984. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4985. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  4986. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  4987. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  4988. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  4989. this.setFromPoints( points );
  4990. return this;
  4991. };
  4992. }(),
  4993. translate: function ( offset ) {
  4994. this.min.add( offset );
  4995. this.max.add( offset );
  4996. return this;
  4997. },
  4998. equals: function ( box ) {
  4999. return box.min.equals( this.min ) && box.max.equals( this.max );
  5000. }
  5001. } );
  5002. /**
  5003. * @author bhouston / http://clara.io
  5004. * @author mrdoob / http://mrdoob.com/
  5005. */
  5006. function Sphere( center, radius ) {
  5007. this.center = ( center !== undefined ) ? center : new Vector3();
  5008. this.radius = ( radius !== undefined ) ? radius : 0;
  5009. }
  5010. Object.assign( Sphere.prototype, {
  5011. set: function ( center, radius ) {
  5012. this.center.copy( center );
  5013. this.radius = radius;
  5014. return this;
  5015. },
  5016. setFromPoints: function () {
  5017. var box = new Box3();
  5018. return function setFromPoints( points, optionalCenter ) {
  5019. var center = this.center;
  5020. if ( optionalCenter !== undefined ) {
  5021. center.copy( optionalCenter );
  5022. } else {
  5023. box.setFromPoints( points ).getCenter( center );
  5024. }
  5025. var maxRadiusSq = 0;
  5026. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5027. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5028. }
  5029. this.radius = Math.sqrt( maxRadiusSq );
  5030. return this;
  5031. };
  5032. }(),
  5033. clone: function () {
  5034. return new this.constructor().copy( this );
  5035. },
  5036. copy: function ( sphere ) {
  5037. this.center.copy( sphere.center );
  5038. this.radius = sphere.radius;
  5039. return this;
  5040. },
  5041. empty: function () {
  5042. return ( this.radius <= 0 );
  5043. },
  5044. containsPoint: function ( point ) {
  5045. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5046. },
  5047. distanceToPoint: function ( point ) {
  5048. return ( point.distanceTo( this.center ) - this.radius );
  5049. },
  5050. intersectsSphere: function ( sphere ) {
  5051. var radiusSum = this.radius + sphere.radius;
  5052. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5053. },
  5054. intersectsBox: function ( box ) {
  5055. return box.intersectsSphere( this );
  5056. },
  5057. intersectsPlane: function ( plane ) {
  5058. // We use the following equation to compute the signed distance from
  5059. // the center of the sphere to the plane.
  5060. //
  5061. // distance = q * n - d
  5062. //
  5063. // If this distance is greater than the radius of the sphere,
  5064. // then there is no intersection.
  5065. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5066. },
  5067. clampPoint: function ( point, optionalTarget ) {
  5068. var deltaLengthSq = this.center.distanceToSquared( point );
  5069. var result = optionalTarget || new Vector3();
  5070. result.copy( point );
  5071. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5072. result.sub( this.center ).normalize();
  5073. result.multiplyScalar( this.radius ).add( this.center );
  5074. }
  5075. return result;
  5076. },
  5077. getBoundingBox: function ( optionalTarget ) {
  5078. var box = optionalTarget || new Box3();
  5079. box.set( this.center, this.center );
  5080. box.expandByScalar( this.radius );
  5081. return box;
  5082. },
  5083. applyMatrix4: function ( matrix ) {
  5084. this.center.applyMatrix4( matrix );
  5085. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5086. return this;
  5087. },
  5088. translate: function ( offset ) {
  5089. this.center.add( offset );
  5090. return this;
  5091. },
  5092. equals: function ( sphere ) {
  5093. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5094. }
  5095. } );
  5096. /**
  5097. * @author alteredq / http://alteredqualia.com/
  5098. * @author WestLangley / http://github.com/WestLangley
  5099. * @author bhouston / http://clara.io
  5100. * @author tschw
  5101. */
  5102. function Matrix3() {
  5103. this.elements = [
  5104. 1, 0, 0,
  5105. 0, 1, 0,
  5106. 0, 0, 1
  5107. ];
  5108. if ( arguments.length > 0 ) {
  5109. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5110. }
  5111. }
  5112. Object.assign( Matrix3.prototype, {
  5113. isMatrix3: true,
  5114. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5115. var te = this.elements;
  5116. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5117. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5118. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5119. return this;
  5120. },
  5121. identity: function () {
  5122. this.set(
  5123. 1, 0, 0,
  5124. 0, 1, 0,
  5125. 0, 0, 1
  5126. );
  5127. return this;
  5128. },
  5129. clone: function () {
  5130. return new this.constructor().fromArray( this.elements );
  5131. },
  5132. copy: function ( m ) {
  5133. var te = this.elements;
  5134. var me = m.elements;
  5135. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5136. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5137. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5138. return this;
  5139. },
  5140. setFromMatrix4: function ( m ) {
  5141. var me = m.elements;
  5142. this.set(
  5143. me[ 0 ], me[ 4 ], me[ 8 ],
  5144. me[ 1 ], me[ 5 ], me[ 9 ],
  5145. me[ 2 ], me[ 6 ], me[ 10 ]
  5146. );
  5147. return this;
  5148. },
  5149. applyToBufferAttribute: function () {
  5150. var v1 = new Vector3();
  5151. return function applyToBufferAttribute( attribute ) {
  5152. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5153. v1.x = attribute.getX( i );
  5154. v1.y = attribute.getY( i );
  5155. v1.z = attribute.getZ( i );
  5156. v1.applyMatrix3( this );
  5157. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5158. }
  5159. return attribute;
  5160. };
  5161. }(),
  5162. multiply: function ( m ) {
  5163. return this.multiplyMatrices( this, m );
  5164. },
  5165. premultiply: function ( m ) {
  5166. return this.multiplyMatrices( m, this );
  5167. },
  5168. multiplyMatrices: function ( a, b ) {
  5169. var ae = a.elements;
  5170. var be = b.elements;
  5171. var te = this.elements;
  5172. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5173. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5174. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5175. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5176. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5177. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5178. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5179. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5180. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5181. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5182. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5183. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5184. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5185. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5186. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5187. return this;
  5188. },
  5189. multiplyScalar: function ( s ) {
  5190. var te = this.elements;
  5191. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5192. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5193. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5194. return this;
  5195. },
  5196. determinant: function () {
  5197. var te = this.elements;
  5198. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5199. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5200. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5201. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5202. },
  5203. getInverse: function ( matrix, throwOnDegenerate ) {
  5204. if ( matrix && matrix.isMatrix4 ) {
  5205. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  5206. }
  5207. var me = matrix.elements,
  5208. te = this.elements,
  5209. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5210. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5211. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5212. t11 = n33 * n22 - n32 * n23,
  5213. t12 = n32 * n13 - n33 * n12,
  5214. t13 = n23 * n12 - n22 * n13,
  5215. det = n11 * t11 + n21 * t12 + n31 * t13;
  5216. if ( det === 0 ) {
  5217. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  5218. if ( throwOnDegenerate === true ) {
  5219. throw new Error( msg );
  5220. } else {
  5221. console.warn( msg );
  5222. }
  5223. return this.identity();
  5224. }
  5225. var detInv = 1 / det;
  5226. te[ 0 ] = t11 * detInv;
  5227. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5228. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5229. te[ 3 ] = t12 * detInv;
  5230. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5231. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5232. te[ 6 ] = t13 * detInv;
  5233. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5234. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5235. return this;
  5236. },
  5237. transpose: function () {
  5238. var tmp, m = this.elements;
  5239. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5240. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5241. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5242. return this;
  5243. },
  5244. getNormalMatrix: function ( matrix4 ) {
  5245. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5246. },
  5247. transposeIntoArray: function ( r ) {
  5248. var m = this.elements;
  5249. r[ 0 ] = m[ 0 ];
  5250. r[ 1 ] = m[ 3 ];
  5251. r[ 2 ] = m[ 6 ];
  5252. r[ 3 ] = m[ 1 ];
  5253. r[ 4 ] = m[ 4 ];
  5254. r[ 5 ] = m[ 7 ];
  5255. r[ 6 ] = m[ 2 ];
  5256. r[ 7 ] = m[ 5 ];
  5257. r[ 8 ] = m[ 8 ];
  5258. return this;
  5259. },
  5260. equals: function ( matrix ) {
  5261. var te = this.elements;
  5262. var me = matrix.elements;
  5263. for ( var i = 0; i < 9; i ++ ) {
  5264. if ( te[ i ] !== me[ i ] ) return false;
  5265. }
  5266. return true;
  5267. },
  5268. fromArray: function ( array, offset ) {
  5269. if ( offset === undefined ) offset = 0;
  5270. for ( var i = 0; i < 9; i ++ ) {
  5271. this.elements[ i ] = array[ i + offset ];
  5272. }
  5273. return this;
  5274. },
  5275. toArray: function ( array, offset ) {
  5276. if ( array === undefined ) array = [];
  5277. if ( offset === undefined ) offset = 0;
  5278. var te = this.elements;
  5279. array[ offset ] = te[ 0 ];
  5280. array[ offset + 1 ] = te[ 1 ];
  5281. array[ offset + 2 ] = te[ 2 ];
  5282. array[ offset + 3 ] = te[ 3 ];
  5283. array[ offset + 4 ] = te[ 4 ];
  5284. array[ offset + 5 ] = te[ 5 ];
  5285. array[ offset + 6 ] = te[ 6 ];
  5286. array[ offset + 7 ] = te[ 7 ];
  5287. array[ offset + 8 ] = te[ 8 ];
  5288. return array;
  5289. }
  5290. } );
  5291. /**
  5292. * @author bhouston / http://clara.io
  5293. */
  5294. function Plane( normal, constant ) {
  5295. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5296. this.constant = ( constant !== undefined ) ? constant : 0;
  5297. }
  5298. Object.assign( Plane.prototype, {
  5299. set: function ( normal, constant ) {
  5300. this.normal.copy( normal );
  5301. this.constant = constant;
  5302. return this;
  5303. },
  5304. setComponents: function ( x, y, z, w ) {
  5305. this.normal.set( x, y, z );
  5306. this.constant = w;
  5307. return this;
  5308. },
  5309. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5310. this.normal.copy( normal );
  5311. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5312. return this;
  5313. },
  5314. setFromCoplanarPoints: function () {
  5315. var v1 = new Vector3();
  5316. var v2 = new Vector3();
  5317. return function setFromCoplanarPoints( a, b, c ) {
  5318. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5319. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5320. this.setFromNormalAndCoplanarPoint( normal, a );
  5321. return this;
  5322. };
  5323. }(),
  5324. clone: function () {
  5325. return new this.constructor().copy( this );
  5326. },
  5327. copy: function ( plane ) {
  5328. this.normal.copy( plane.normal );
  5329. this.constant = plane.constant;
  5330. return this;
  5331. },
  5332. normalize: function () {
  5333. // Note: will lead to a divide by zero if the plane is invalid.
  5334. var inverseNormalLength = 1.0 / this.normal.length();
  5335. this.normal.multiplyScalar( inverseNormalLength );
  5336. this.constant *= inverseNormalLength;
  5337. return this;
  5338. },
  5339. negate: function () {
  5340. this.constant *= - 1;
  5341. this.normal.negate();
  5342. return this;
  5343. },
  5344. distanceToPoint: function ( point ) {
  5345. return this.normal.dot( point ) + this.constant;
  5346. },
  5347. distanceToSphere: function ( sphere ) {
  5348. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5349. },
  5350. projectPoint: function ( point, optionalTarget ) {
  5351. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5352. },
  5353. orthoPoint: function ( point, optionalTarget ) {
  5354. var perpendicularMagnitude = this.distanceToPoint( point );
  5355. var result = optionalTarget || new Vector3();
  5356. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5357. },
  5358. intersectLine: function () {
  5359. var v1 = new Vector3();
  5360. return function intersectLine( line, optionalTarget ) {
  5361. var result = optionalTarget || new Vector3();
  5362. var direction = line.delta( v1 );
  5363. var denominator = this.normal.dot( direction );
  5364. if ( denominator === 0 ) {
  5365. // line is coplanar, return origin
  5366. if ( this.distanceToPoint( line.start ) === 0 ) {
  5367. return result.copy( line.start );
  5368. }
  5369. // Unsure if this is the correct method to handle this case.
  5370. return undefined;
  5371. }
  5372. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5373. if ( t < 0 || t > 1 ) {
  5374. return undefined;
  5375. }
  5376. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5377. };
  5378. }(),
  5379. intersectsLine: function ( line ) {
  5380. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5381. var startSign = this.distanceToPoint( line.start );
  5382. var endSign = this.distanceToPoint( line.end );
  5383. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5384. },
  5385. intersectsBox: function ( box ) {
  5386. return box.intersectsPlane( this );
  5387. },
  5388. intersectsSphere: function ( sphere ) {
  5389. return sphere.intersectsPlane( this );
  5390. },
  5391. coplanarPoint: function ( optionalTarget ) {
  5392. var result = optionalTarget || new Vector3();
  5393. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5394. },
  5395. applyMatrix4: function () {
  5396. var v1 = new Vector3();
  5397. var m1 = new Matrix3();
  5398. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5399. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5400. // transform normal based on theory here:
  5401. // http://www.songho.ca/opengl/gl_normaltransform.html
  5402. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5403. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5404. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5405. this.constant = - referencePoint.dot( normal );
  5406. return this;
  5407. };
  5408. }(),
  5409. translate: function ( offset ) {
  5410. this.constant = this.constant - offset.dot( this.normal );
  5411. return this;
  5412. },
  5413. equals: function ( plane ) {
  5414. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5415. }
  5416. } );
  5417. /**
  5418. * @author mrdoob / http://mrdoob.com/
  5419. * @author alteredq / http://alteredqualia.com/
  5420. * @author bhouston / http://clara.io
  5421. */
  5422. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5423. this.planes = [
  5424. ( p0 !== undefined ) ? p0 : new Plane(),
  5425. ( p1 !== undefined ) ? p1 : new Plane(),
  5426. ( p2 !== undefined ) ? p2 : new Plane(),
  5427. ( p3 !== undefined ) ? p3 : new Plane(),
  5428. ( p4 !== undefined ) ? p4 : new Plane(),
  5429. ( p5 !== undefined ) ? p5 : new Plane()
  5430. ];
  5431. }
  5432. Object.assign( Frustum.prototype, {
  5433. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5434. var planes = this.planes;
  5435. planes[ 0 ].copy( p0 );
  5436. planes[ 1 ].copy( p1 );
  5437. planes[ 2 ].copy( p2 );
  5438. planes[ 3 ].copy( p3 );
  5439. planes[ 4 ].copy( p4 );
  5440. planes[ 5 ].copy( p5 );
  5441. return this;
  5442. },
  5443. clone: function () {
  5444. return new this.constructor().copy( this );
  5445. },
  5446. copy: function ( frustum ) {
  5447. var planes = this.planes;
  5448. for ( var i = 0; i < 6; i ++ ) {
  5449. planes[ i ].copy( frustum.planes[ i ] );
  5450. }
  5451. return this;
  5452. },
  5453. setFromMatrix: function ( m ) {
  5454. var planes = this.planes;
  5455. var me = m.elements;
  5456. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5457. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5458. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5459. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5460. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5461. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5462. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5463. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5464. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5465. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5466. return this;
  5467. },
  5468. intersectsObject: function () {
  5469. var sphere = new Sphere();
  5470. return function intersectsObject( object ) {
  5471. var geometry = object.geometry;
  5472. if ( geometry.boundingSphere === null )
  5473. geometry.computeBoundingSphere();
  5474. sphere.copy( geometry.boundingSphere )
  5475. .applyMatrix4( object.matrixWorld );
  5476. return this.intersectsSphere( sphere );
  5477. };
  5478. }(),
  5479. intersectsSprite: function () {
  5480. var sphere = new Sphere();
  5481. return function intersectsSprite( sprite ) {
  5482. sphere.center.set( 0, 0, 0 );
  5483. sphere.radius = 0.7071067811865476;
  5484. sphere.applyMatrix4( sprite.matrixWorld );
  5485. return this.intersectsSphere( sphere );
  5486. };
  5487. }(),
  5488. intersectsSphere: function ( sphere ) {
  5489. var planes = this.planes;
  5490. var center = sphere.center;
  5491. var negRadius = - sphere.radius;
  5492. for ( var i = 0; i < 6; i ++ ) {
  5493. var distance = planes[ i ].distanceToPoint( center );
  5494. if ( distance < negRadius ) {
  5495. return false;
  5496. }
  5497. }
  5498. return true;
  5499. },
  5500. intersectsBox: function () {
  5501. var p1 = new Vector3(),
  5502. p2 = new Vector3();
  5503. return function intersectsBox( box ) {
  5504. var planes = this.planes;
  5505. for ( var i = 0; i < 6; i ++ ) {
  5506. var plane = planes[ i ];
  5507. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5508. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5509. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5510. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5511. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5512. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5513. var d1 = plane.distanceToPoint( p1 );
  5514. var d2 = plane.distanceToPoint( p2 );
  5515. // if both outside plane, no intersection
  5516. if ( d1 < 0 && d2 < 0 ) {
  5517. return false;
  5518. }
  5519. }
  5520. return true;
  5521. };
  5522. }(),
  5523. containsPoint: function ( point ) {
  5524. var planes = this.planes;
  5525. for ( var i = 0; i < 6; i ++ ) {
  5526. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5527. return false;
  5528. }
  5529. }
  5530. return true;
  5531. }
  5532. } );
  5533. /**
  5534. * @author alteredq / http://alteredqualia.com/
  5535. * @author mrdoob / http://mrdoob.com/
  5536. */
  5537. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5538. var _gl = _renderer.context,
  5539. _state = _renderer.state,
  5540. _frustum = new Frustum(),
  5541. _projScreenMatrix = new Matrix4(),
  5542. _lightShadows = _lights.shadows,
  5543. _shadowMapSize = new Vector2(),
  5544. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5545. _lookTarget = new Vector3(),
  5546. _lightPositionWorld = new Vector3(),
  5547. _MorphingFlag = 1,
  5548. _SkinningFlag = 2,
  5549. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5550. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5551. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5552. _materialCache = {};
  5553. var cubeDirections = [
  5554. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5555. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5556. ];
  5557. var cubeUps = [
  5558. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5559. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5560. ];
  5561. var cube2DViewPorts = [
  5562. new Vector4(), new Vector4(), new Vector4(),
  5563. new Vector4(), new Vector4(), new Vector4()
  5564. ];
  5565. // init
  5566. var depthMaterialTemplate = new MeshDepthMaterial();
  5567. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5568. depthMaterialTemplate.clipping = true;
  5569. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5570. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  5571. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5572. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5573. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5574. var depthMaterial = depthMaterialTemplate.clone();
  5575. depthMaterial.morphTargets = useMorphing;
  5576. depthMaterial.skinning = useSkinning;
  5577. _depthMaterials[ i ] = depthMaterial;
  5578. var distanceMaterial = new ShaderMaterial( {
  5579. defines: {
  5580. 'USE_SHADOWMAP': ''
  5581. },
  5582. uniforms: distanceUniforms,
  5583. vertexShader: distanceShader.vertexShader,
  5584. fragmentShader: distanceShader.fragmentShader,
  5585. morphTargets: useMorphing,
  5586. skinning: useSkinning,
  5587. clipping: true
  5588. } );
  5589. _distanceMaterials[ i ] = distanceMaterial;
  5590. }
  5591. //
  5592. var scope = this;
  5593. this.enabled = false;
  5594. this.autoUpdate = true;
  5595. this.needsUpdate = false;
  5596. this.type = PCFShadowMap;
  5597. this.renderReverseSided = true;
  5598. this.renderSingleSided = true;
  5599. this.render = function ( scene, camera ) {
  5600. if ( scope.enabled === false ) return;
  5601. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5602. if ( _lightShadows.length === 0 ) return;
  5603. // Set GL state for depth map.
  5604. _state.disable( _gl.BLEND );
  5605. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5606. _state.buffers.depth.setTest( true );
  5607. _state.setScissorTest( false );
  5608. // render depth map
  5609. var faceCount, isPointLight;
  5610. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5611. var light = _lightShadows[ i ];
  5612. var shadow = light.shadow;
  5613. if ( shadow === undefined ) {
  5614. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5615. continue;
  5616. }
  5617. var shadowCamera = shadow.camera;
  5618. var shadowMatrix = shadow.matrix;
  5619. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5620. shadowCamera.position.copy( _lightPositionWorld );
  5621. _shadowMapSize.copy( shadow.mapSize );
  5622. _shadowMapSize.min( _maxShadowMapSize );
  5623. if ( light && light.isPointLight ) {
  5624. faceCount = 6;
  5625. isPointLight = true;
  5626. var vpWidth = _shadowMapSize.x;
  5627. var vpHeight = _shadowMapSize.y;
  5628. // These viewports map a cube-map onto a 2D texture with the
  5629. // following orientation:
  5630. //
  5631. // xzXZ
  5632. // y Y
  5633. //
  5634. // X - Positive x direction
  5635. // x - Negative x direction
  5636. // Y - Positive y direction
  5637. // y - Negative y direction
  5638. // Z - Positive z direction
  5639. // z - Negative z direction
  5640. // positive X
  5641. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5642. // negative X
  5643. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5644. // positive Z
  5645. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5646. // negative Z
  5647. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5648. // positive Y
  5649. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5650. // negative Y
  5651. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5652. _shadowMapSize.x *= 4.0;
  5653. _shadowMapSize.y *= 2.0;
  5654. // for point lights we set the shadow matrix to be a translation-only matrix
  5655. // equal to inverse of the light's position
  5656. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5657. } else {
  5658. faceCount = 1;
  5659. isPointLight = false;
  5660. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5661. shadowCamera.lookAt( _lookTarget );
  5662. shadowCamera.updateMatrixWorld();
  5663. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5664. // compute shadow matrix
  5665. shadowMatrix.set(
  5666. 0.5, 0.0, 0.0, 0.5,
  5667. 0.0, 0.5, 0.0, 0.5,
  5668. 0.0, 0.0, 0.5, 0.5,
  5669. 0.0, 0.0, 0.0, 1.0
  5670. );
  5671. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5672. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5673. }
  5674. if ( shadow.map === null ) {
  5675. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5676. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5677. shadow.map.texture.name = light.name + ".shadowMap";
  5678. shadowCamera.updateProjectionMatrix();
  5679. }
  5680. if ( shadow.isSpotLightShadow ) {
  5681. shadow.update( light );
  5682. }
  5683. var shadowMap = shadow.map;
  5684. _renderer.setRenderTarget( shadowMap );
  5685. _renderer.clear();
  5686. // render shadow map for each cube face (if omni-directional) or
  5687. // run a single pass if not
  5688. for ( var face = 0; face < faceCount; face ++ ) {
  5689. if ( isPointLight ) {
  5690. _lookTarget.copy( shadowCamera.position );
  5691. _lookTarget.add( cubeDirections[ face ] );
  5692. shadowCamera.up.copy( cubeUps[ face ] );
  5693. shadowCamera.lookAt( _lookTarget );
  5694. shadowCamera.updateMatrixWorld();
  5695. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5696. var vpDimensions = cube2DViewPorts[ face ];
  5697. _state.viewport( vpDimensions );
  5698. }
  5699. // update camera matrices and frustum
  5700. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5701. _frustum.setFromMatrix( _projScreenMatrix );
  5702. // set object matrices & frustum culling
  5703. renderObject( scene, camera, shadowCamera, isPointLight );
  5704. }
  5705. }
  5706. // Restore GL state.
  5707. var clearColor = _renderer.getClearColor();
  5708. var clearAlpha = _renderer.getClearAlpha();
  5709. _renderer.setClearColor( clearColor, clearAlpha );
  5710. scope.needsUpdate = false;
  5711. };
  5712. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5713. var geometry = object.geometry;
  5714. var result = null;
  5715. var materialVariants = _depthMaterials;
  5716. var customMaterial = object.customDepthMaterial;
  5717. if ( isPointLight ) {
  5718. materialVariants = _distanceMaterials;
  5719. customMaterial = object.customDistanceMaterial;
  5720. }
  5721. if ( ! customMaterial ) {
  5722. var useMorphing = false;
  5723. if ( material.morphTargets ) {
  5724. if ( geometry && geometry.isBufferGeometry ) {
  5725. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5726. } else if ( geometry && geometry.isGeometry ) {
  5727. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5728. }
  5729. }
  5730. if ( object.isSkinnedMesh && material.skinning === false ) {
  5731. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  5732. }
  5733. var useSkinning = object.isSkinnedMesh && material.skinning;
  5734. var variantIndex = 0;
  5735. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5736. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5737. result = materialVariants[ variantIndex ];
  5738. } else {
  5739. result = customMaterial;
  5740. }
  5741. if ( _renderer.localClippingEnabled &&
  5742. material.clipShadows === true &&
  5743. material.clippingPlanes.length !== 0 ) {
  5744. // in this case we need a unique material instance reflecting the
  5745. // appropriate state
  5746. var keyA = result.uuid, keyB = material.uuid;
  5747. var materialsForVariant = _materialCache[ keyA ];
  5748. if ( materialsForVariant === undefined ) {
  5749. materialsForVariant = {};
  5750. _materialCache[ keyA ] = materialsForVariant;
  5751. }
  5752. var cachedMaterial = materialsForVariant[ keyB ];
  5753. if ( cachedMaterial === undefined ) {
  5754. cachedMaterial = result.clone();
  5755. materialsForVariant[ keyB ] = cachedMaterial;
  5756. }
  5757. result = cachedMaterial;
  5758. }
  5759. result.visible = material.visible;
  5760. result.wireframe = material.wireframe;
  5761. var side = material.side;
  5762. if ( scope.renderSingleSided && side == DoubleSide ) {
  5763. side = FrontSide;
  5764. }
  5765. if ( scope.renderReverseSided ) {
  5766. if ( side === FrontSide ) side = BackSide;
  5767. else if ( side === BackSide ) side = FrontSide;
  5768. }
  5769. result.side = side;
  5770. result.clipShadows = material.clipShadows;
  5771. result.clippingPlanes = material.clippingPlanes;
  5772. result.wireframeLinewidth = material.wireframeLinewidth;
  5773. result.linewidth = material.linewidth;
  5774. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5775. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5776. }
  5777. return result;
  5778. }
  5779. function renderObject( object, camera, shadowCamera, isPointLight ) {
  5780. if ( object.visible === false ) return;
  5781. var visible = object.layers.test( camera.layers );
  5782. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5783. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5784. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5785. var geometry = _objects.update( object );
  5786. var material = object.material;
  5787. if ( Array.isArray( material ) ) {
  5788. var groups = geometry.groups;
  5789. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5790. var group = groups[ k ];
  5791. var groupMaterial = material[ group.materialIndex ];
  5792. if ( groupMaterial && groupMaterial.visible ) {
  5793. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5794. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5795. }
  5796. }
  5797. } else if ( material.visible ) {
  5798. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5799. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5800. }
  5801. }
  5802. }
  5803. var children = object.children;
  5804. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5805. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  5806. }
  5807. }
  5808. }
  5809. /**
  5810. * @author bhouston / http://clara.io
  5811. */
  5812. function Ray( origin, direction ) {
  5813. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5814. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5815. }
  5816. Object.assign( Ray.prototype, {
  5817. set: function ( origin, direction ) {
  5818. this.origin.copy( origin );
  5819. this.direction.copy( direction );
  5820. return this;
  5821. },
  5822. clone: function () {
  5823. return new this.constructor().copy( this );
  5824. },
  5825. copy: function ( ray ) {
  5826. this.origin.copy( ray.origin );
  5827. this.direction.copy( ray.direction );
  5828. return this;
  5829. },
  5830. at: function ( t, optionalTarget ) {
  5831. var result = optionalTarget || new Vector3();
  5832. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5833. },
  5834. lookAt: function ( v ) {
  5835. this.direction.copy( v ).sub( this.origin ).normalize();
  5836. return this;
  5837. },
  5838. recast: function () {
  5839. var v1 = new Vector3();
  5840. return function recast( t ) {
  5841. this.origin.copy( this.at( t, v1 ) );
  5842. return this;
  5843. };
  5844. }(),
  5845. closestPointToPoint: function ( point, optionalTarget ) {
  5846. var result = optionalTarget || new Vector3();
  5847. result.subVectors( point, this.origin );
  5848. var directionDistance = result.dot( this.direction );
  5849. if ( directionDistance < 0 ) {
  5850. return result.copy( this.origin );
  5851. }
  5852. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5853. },
  5854. distanceToPoint: function ( point ) {
  5855. return Math.sqrt( this.distanceSqToPoint( point ) );
  5856. },
  5857. distanceSqToPoint: function () {
  5858. var v1 = new Vector3();
  5859. return function distanceSqToPoint( point ) {
  5860. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5861. // point behind the ray
  5862. if ( directionDistance < 0 ) {
  5863. return this.origin.distanceToSquared( point );
  5864. }
  5865. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5866. return v1.distanceToSquared( point );
  5867. };
  5868. }(),
  5869. distanceSqToSegment: function () {
  5870. var segCenter = new Vector3();
  5871. var segDir = new Vector3();
  5872. var diff = new Vector3();
  5873. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5874. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5875. // It returns the min distance between the ray and the segment
  5876. // defined by v0 and v1
  5877. // It can also set two optional targets :
  5878. // - The closest point on the ray
  5879. // - The closest point on the segment
  5880. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5881. segDir.copy( v1 ).sub( v0 ).normalize();
  5882. diff.copy( this.origin ).sub( segCenter );
  5883. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5884. var a01 = - this.direction.dot( segDir );
  5885. var b0 = diff.dot( this.direction );
  5886. var b1 = - diff.dot( segDir );
  5887. var c = diff.lengthSq();
  5888. var det = Math.abs( 1 - a01 * a01 );
  5889. var s0, s1, sqrDist, extDet;
  5890. if ( det > 0 ) {
  5891. // The ray and segment are not parallel.
  5892. s0 = a01 * b1 - b0;
  5893. s1 = a01 * b0 - b1;
  5894. extDet = segExtent * det;
  5895. if ( s0 >= 0 ) {
  5896. if ( s1 >= - extDet ) {
  5897. if ( s1 <= extDet ) {
  5898. // region 0
  5899. // Minimum at interior points of ray and segment.
  5900. var invDet = 1 / det;
  5901. s0 *= invDet;
  5902. s1 *= invDet;
  5903. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5904. } else {
  5905. // region 1
  5906. s1 = segExtent;
  5907. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5908. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5909. }
  5910. } else {
  5911. // region 5
  5912. s1 = - segExtent;
  5913. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5914. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5915. }
  5916. } else {
  5917. if ( s1 <= - extDet ) {
  5918. // region 4
  5919. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5920. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5921. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5922. } else if ( s1 <= extDet ) {
  5923. // region 3
  5924. s0 = 0;
  5925. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5926. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5927. } else {
  5928. // region 2
  5929. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5930. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5931. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5932. }
  5933. }
  5934. } else {
  5935. // Ray and segment are parallel.
  5936. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  5937. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5938. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5939. }
  5940. if ( optionalPointOnRay ) {
  5941. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  5942. }
  5943. if ( optionalPointOnSegment ) {
  5944. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  5945. }
  5946. return sqrDist;
  5947. };
  5948. }(),
  5949. intersectSphere: function () {
  5950. var v1 = new Vector3();
  5951. return function intersectSphere( sphere, optionalTarget ) {
  5952. v1.subVectors( sphere.center, this.origin );
  5953. var tca = v1.dot( this.direction );
  5954. var d2 = v1.dot( v1 ) - tca * tca;
  5955. var radius2 = sphere.radius * sphere.radius;
  5956. if ( d2 > radius2 ) return null;
  5957. var thc = Math.sqrt( radius2 - d2 );
  5958. // t0 = first intersect point - entrance on front of sphere
  5959. var t0 = tca - thc;
  5960. // t1 = second intersect point - exit point on back of sphere
  5961. var t1 = tca + thc;
  5962. // test to see if both t0 and t1 are behind the ray - if so, return null
  5963. if ( t0 < 0 && t1 < 0 ) return null;
  5964. // test to see if t0 is behind the ray:
  5965. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5966. // in order to always return an intersect point that is in front of the ray.
  5967. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  5968. // else t0 is in front of the ray, so return the first collision point scaled by t0
  5969. return this.at( t0, optionalTarget );
  5970. };
  5971. }(),
  5972. intersectsSphere: function ( sphere ) {
  5973. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  5974. },
  5975. distanceToPlane: function ( plane ) {
  5976. var denominator = plane.normal.dot( this.direction );
  5977. if ( denominator === 0 ) {
  5978. // line is coplanar, return origin
  5979. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  5980. return 0;
  5981. }
  5982. // Null is preferable to undefined since undefined means.... it is undefined
  5983. return null;
  5984. }
  5985. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  5986. // Return if the ray never intersects the plane
  5987. return t >= 0 ? t : null;
  5988. },
  5989. intersectPlane: function ( plane, optionalTarget ) {
  5990. var t = this.distanceToPlane( plane );
  5991. if ( t === null ) {
  5992. return null;
  5993. }
  5994. return this.at( t, optionalTarget );
  5995. },
  5996. intersectsPlane: function ( plane ) {
  5997. // check if the ray lies on the plane first
  5998. var distToPoint = plane.distanceToPoint( this.origin );
  5999. if ( distToPoint === 0 ) {
  6000. return true;
  6001. }
  6002. var denominator = plane.normal.dot( this.direction );
  6003. if ( denominator * distToPoint < 0 ) {
  6004. return true;
  6005. }
  6006. // ray origin is behind the plane (and is pointing behind it)
  6007. return false;
  6008. },
  6009. intersectBox: function ( box, optionalTarget ) {
  6010. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6011. var invdirx = 1 / this.direction.x,
  6012. invdiry = 1 / this.direction.y,
  6013. invdirz = 1 / this.direction.z;
  6014. var origin = this.origin;
  6015. if ( invdirx >= 0 ) {
  6016. tmin = ( box.min.x - origin.x ) * invdirx;
  6017. tmax = ( box.max.x - origin.x ) * invdirx;
  6018. } else {
  6019. tmin = ( box.max.x - origin.x ) * invdirx;
  6020. tmax = ( box.min.x - origin.x ) * invdirx;
  6021. }
  6022. if ( invdiry >= 0 ) {
  6023. tymin = ( box.min.y - origin.y ) * invdiry;
  6024. tymax = ( box.max.y - origin.y ) * invdiry;
  6025. } else {
  6026. tymin = ( box.max.y - origin.y ) * invdiry;
  6027. tymax = ( box.min.y - origin.y ) * invdiry;
  6028. }
  6029. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6030. // These lines also handle the case where tmin or tmax is NaN
  6031. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6032. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6033. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6034. if ( invdirz >= 0 ) {
  6035. tzmin = ( box.min.z - origin.z ) * invdirz;
  6036. tzmax = ( box.max.z - origin.z ) * invdirz;
  6037. } else {
  6038. tzmin = ( box.max.z - origin.z ) * invdirz;
  6039. tzmax = ( box.min.z - origin.z ) * invdirz;
  6040. }
  6041. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6042. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6043. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6044. //return point closest to the ray (positive side)
  6045. if ( tmax < 0 ) return null;
  6046. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6047. },
  6048. intersectsBox: ( function () {
  6049. var v = new Vector3();
  6050. return function intersectsBox( box ) {
  6051. return this.intersectBox( box, v ) !== null;
  6052. };
  6053. } )(),
  6054. intersectTriangle: function () {
  6055. // Compute the offset origin, edges, and normal.
  6056. var diff = new Vector3();
  6057. var edge1 = new Vector3();
  6058. var edge2 = new Vector3();
  6059. var normal = new Vector3();
  6060. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6061. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6062. edge1.subVectors( b, a );
  6063. edge2.subVectors( c, a );
  6064. normal.crossVectors( edge1, edge2 );
  6065. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6066. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6067. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6068. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6069. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6070. var DdN = this.direction.dot( normal );
  6071. var sign;
  6072. if ( DdN > 0 ) {
  6073. if ( backfaceCulling ) return null;
  6074. sign = 1;
  6075. } else if ( DdN < 0 ) {
  6076. sign = - 1;
  6077. DdN = - DdN;
  6078. } else {
  6079. return null;
  6080. }
  6081. diff.subVectors( this.origin, a );
  6082. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6083. // b1 < 0, no intersection
  6084. if ( DdQxE2 < 0 ) {
  6085. return null;
  6086. }
  6087. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6088. // b2 < 0, no intersection
  6089. if ( DdE1xQ < 0 ) {
  6090. return null;
  6091. }
  6092. // b1+b2 > 1, no intersection
  6093. if ( DdQxE2 + DdE1xQ > DdN ) {
  6094. return null;
  6095. }
  6096. // Line intersects triangle, check if ray does.
  6097. var QdN = - sign * diff.dot( normal );
  6098. // t < 0, no intersection
  6099. if ( QdN < 0 ) {
  6100. return null;
  6101. }
  6102. // Ray intersects triangle.
  6103. return this.at( QdN / DdN, optionalTarget );
  6104. };
  6105. }(),
  6106. applyMatrix4: function ( matrix4 ) {
  6107. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6108. this.origin.applyMatrix4( matrix4 );
  6109. this.direction.sub( this.origin );
  6110. this.direction.normalize();
  6111. return this;
  6112. },
  6113. equals: function ( ray ) {
  6114. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6115. }
  6116. } );
  6117. /**
  6118. * @author mrdoob / http://mrdoob.com/
  6119. * @author WestLangley / http://github.com/WestLangley
  6120. * @author bhouston / http://clara.io
  6121. */
  6122. function Euler( x, y, z, order ) {
  6123. this._x = x || 0;
  6124. this._y = y || 0;
  6125. this._z = z || 0;
  6126. this._order = order || Euler.DefaultOrder;
  6127. }
  6128. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6129. Euler.DefaultOrder = 'XYZ';
  6130. Object.defineProperties( Euler.prototype, {
  6131. x: {
  6132. get: function () {
  6133. return this._x;
  6134. },
  6135. set: function ( value ) {
  6136. this._x = value;
  6137. this.onChangeCallback();
  6138. }
  6139. },
  6140. y: {
  6141. get: function () {
  6142. return this._y;
  6143. },
  6144. set: function ( value ) {
  6145. this._y = value;
  6146. this.onChangeCallback();
  6147. }
  6148. },
  6149. z: {
  6150. get: function () {
  6151. return this._z;
  6152. },
  6153. set: function ( value ) {
  6154. this._z = value;
  6155. this.onChangeCallback();
  6156. }
  6157. },
  6158. order: {
  6159. get: function () {
  6160. return this._order;
  6161. },
  6162. set: function ( value ) {
  6163. this._order = value;
  6164. this.onChangeCallback();
  6165. }
  6166. }
  6167. } );
  6168. Object.assign( Euler.prototype, {
  6169. isEuler: true,
  6170. set: function ( x, y, z, order ) {
  6171. this._x = x;
  6172. this._y = y;
  6173. this._z = z;
  6174. this._order = order || this._order;
  6175. this.onChangeCallback();
  6176. return this;
  6177. },
  6178. clone: function () {
  6179. return new this.constructor( this._x, this._y, this._z, this._order );
  6180. },
  6181. copy: function ( euler ) {
  6182. this._x = euler._x;
  6183. this._y = euler._y;
  6184. this._z = euler._z;
  6185. this._order = euler._order;
  6186. this.onChangeCallback();
  6187. return this;
  6188. },
  6189. setFromRotationMatrix: function ( m, order, update ) {
  6190. var clamp = _Math.clamp;
  6191. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6192. var te = m.elements;
  6193. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6194. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6195. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6196. order = order || this._order;
  6197. if ( order === 'XYZ' ) {
  6198. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6199. if ( Math.abs( m13 ) < 0.99999 ) {
  6200. this._x = Math.atan2( - m23, m33 );
  6201. this._z = Math.atan2( - m12, m11 );
  6202. } else {
  6203. this._x = Math.atan2( m32, m22 );
  6204. this._z = 0;
  6205. }
  6206. } else if ( order === 'YXZ' ) {
  6207. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6208. if ( Math.abs( m23 ) < 0.99999 ) {
  6209. this._y = Math.atan2( m13, m33 );
  6210. this._z = Math.atan2( m21, m22 );
  6211. } else {
  6212. this._y = Math.atan2( - m31, m11 );
  6213. this._z = 0;
  6214. }
  6215. } else if ( order === 'ZXY' ) {
  6216. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6217. if ( Math.abs( m32 ) < 0.99999 ) {
  6218. this._y = Math.atan2( - m31, m33 );
  6219. this._z = Math.atan2( - m12, m22 );
  6220. } else {
  6221. this._y = 0;
  6222. this._z = Math.atan2( m21, m11 );
  6223. }
  6224. } else if ( order === 'ZYX' ) {
  6225. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6226. if ( Math.abs( m31 ) < 0.99999 ) {
  6227. this._x = Math.atan2( m32, m33 );
  6228. this._z = Math.atan2( m21, m11 );
  6229. } else {
  6230. this._x = 0;
  6231. this._z = Math.atan2( - m12, m22 );
  6232. }
  6233. } else if ( order === 'YZX' ) {
  6234. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6235. if ( Math.abs( m21 ) < 0.99999 ) {
  6236. this._x = Math.atan2( - m23, m22 );
  6237. this._y = Math.atan2( - m31, m11 );
  6238. } else {
  6239. this._x = 0;
  6240. this._y = Math.atan2( m13, m33 );
  6241. }
  6242. } else if ( order === 'XZY' ) {
  6243. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6244. if ( Math.abs( m12 ) < 0.99999 ) {
  6245. this._x = Math.atan2( m32, m22 );
  6246. this._y = Math.atan2( m13, m11 );
  6247. } else {
  6248. this._x = Math.atan2( - m23, m33 );
  6249. this._y = 0;
  6250. }
  6251. } else {
  6252. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6253. }
  6254. this._order = order;
  6255. if ( update !== false ) this.onChangeCallback();
  6256. return this;
  6257. },
  6258. setFromQuaternion: function () {
  6259. var matrix = new Matrix4();
  6260. return function setFromQuaternion( q, order, update ) {
  6261. matrix.makeRotationFromQuaternion( q );
  6262. return this.setFromRotationMatrix( matrix, order, update );
  6263. };
  6264. }(),
  6265. setFromVector3: function ( v, order ) {
  6266. return this.set( v.x, v.y, v.z, order || this._order );
  6267. },
  6268. reorder: function () {
  6269. // WARNING: this discards revolution information -bhouston
  6270. var q = new Quaternion();
  6271. return function reorder( newOrder ) {
  6272. q.setFromEuler( this );
  6273. return this.setFromQuaternion( q, newOrder );
  6274. };
  6275. }(),
  6276. equals: function ( euler ) {
  6277. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6278. },
  6279. fromArray: function ( array ) {
  6280. this._x = array[ 0 ];
  6281. this._y = array[ 1 ];
  6282. this._z = array[ 2 ];
  6283. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6284. this.onChangeCallback();
  6285. return this;
  6286. },
  6287. toArray: function ( array, offset ) {
  6288. if ( array === undefined ) array = [];
  6289. if ( offset === undefined ) offset = 0;
  6290. array[ offset ] = this._x;
  6291. array[ offset + 1 ] = this._y;
  6292. array[ offset + 2 ] = this._z;
  6293. array[ offset + 3 ] = this._order;
  6294. return array;
  6295. },
  6296. toVector3: function ( optionalResult ) {
  6297. if ( optionalResult ) {
  6298. return optionalResult.set( this._x, this._y, this._z );
  6299. } else {
  6300. return new Vector3( this._x, this._y, this._z );
  6301. }
  6302. },
  6303. onChange: function ( callback ) {
  6304. this.onChangeCallback = callback;
  6305. return this;
  6306. },
  6307. onChangeCallback: function () {}
  6308. } );
  6309. /**
  6310. * @author mrdoob / http://mrdoob.com/
  6311. */
  6312. function Layers() {
  6313. this.mask = 1 | 0;
  6314. }
  6315. Object.assign( Layers.prototype, {
  6316. set: function ( channel ) {
  6317. this.mask = 1 << channel | 0;
  6318. },
  6319. enable: function ( channel ) {
  6320. this.mask |= 1 << channel | 0;
  6321. },
  6322. toggle: function ( channel ) {
  6323. this.mask ^= 1 << channel | 0;
  6324. },
  6325. disable: function ( channel ) {
  6326. this.mask &= ~ ( 1 << channel | 0 );
  6327. },
  6328. test: function ( layers ) {
  6329. return ( this.mask & layers.mask ) !== 0;
  6330. }
  6331. } );
  6332. /**
  6333. * @author mrdoob / http://mrdoob.com/
  6334. * @author mikael emtinger / http://gomo.se/
  6335. * @author alteredq / http://alteredqualia.com/
  6336. * @author WestLangley / http://github.com/WestLangley
  6337. * @author elephantatwork / www.elephantatwork.ch
  6338. */
  6339. var object3DId = 0;
  6340. function Object3D() {
  6341. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6342. this.uuid = _Math.generateUUID();
  6343. this.name = '';
  6344. this.type = 'Object3D';
  6345. this.parent = null;
  6346. this.children = [];
  6347. this.up = Object3D.DefaultUp.clone();
  6348. var position = new Vector3();
  6349. var rotation = new Euler();
  6350. var quaternion = new Quaternion();
  6351. var scale = new Vector3( 1, 1, 1 );
  6352. function onRotationChange() {
  6353. quaternion.setFromEuler( rotation, false );
  6354. }
  6355. function onQuaternionChange() {
  6356. rotation.setFromQuaternion( quaternion, undefined, false );
  6357. }
  6358. rotation.onChange( onRotationChange );
  6359. quaternion.onChange( onQuaternionChange );
  6360. Object.defineProperties( this, {
  6361. position: {
  6362. enumerable: true,
  6363. value: position
  6364. },
  6365. rotation: {
  6366. enumerable: true,
  6367. value: rotation
  6368. },
  6369. quaternion: {
  6370. enumerable: true,
  6371. value: quaternion
  6372. },
  6373. scale: {
  6374. enumerable: true,
  6375. value: scale
  6376. },
  6377. modelViewMatrix: {
  6378. value: new Matrix4()
  6379. },
  6380. normalMatrix: {
  6381. value: new Matrix3()
  6382. }
  6383. } );
  6384. this.matrix = new Matrix4();
  6385. this.matrixWorld = new Matrix4();
  6386. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6387. this.matrixWorldNeedsUpdate = false;
  6388. this.layers = new Layers();
  6389. this.visible = true;
  6390. this.castShadow = false;
  6391. this.receiveShadow = false;
  6392. this.frustumCulled = true;
  6393. this.renderOrder = 0;
  6394. this.userData = {};
  6395. this.onBeforeRender = function () {};
  6396. this.onAfterRender = function () {};
  6397. }
  6398. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6399. Object3D.DefaultMatrixAutoUpdate = true;
  6400. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  6401. isObject3D: true,
  6402. applyMatrix: function ( matrix ) {
  6403. this.matrix.multiplyMatrices( matrix, this.matrix );
  6404. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6405. },
  6406. setRotationFromAxisAngle: function ( axis, angle ) {
  6407. // assumes axis is normalized
  6408. this.quaternion.setFromAxisAngle( axis, angle );
  6409. },
  6410. setRotationFromEuler: function ( euler ) {
  6411. this.quaternion.setFromEuler( euler, true );
  6412. },
  6413. setRotationFromMatrix: function ( m ) {
  6414. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6415. this.quaternion.setFromRotationMatrix( m );
  6416. },
  6417. setRotationFromQuaternion: function ( q ) {
  6418. // assumes q is normalized
  6419. this.quaternion.copy( q );
  6420. },
  6421. rotateOnAxis: function () {
  6422. // rotate object on axis in object space
  6423. // axis is assumed to be normalized
  6424. var q1 = new Quaternion();
  6425. return function rotateOnAxis( axis, angle ) {
  6426. q1.setFromAxisAngle( axis, angle );
  6427. this.quaternion.multiply( q1 );
  6428. return this;
  6429. };
  6430. }(),
  6431. rotateX: function () {
  6432. var v1 = new Vector3( 1, 0, 0 );
  6433. return function rotateX( angle ) {
  6434. return this.rotateOnAxis( v1, angle );
  6435. };
  6436. }(),
  6437. rotateY: function () {
  6438. var v1 = new Vector3( 0, 1, 0 );
  6439. return function rotateY( angle ) {
  6440. return this.rotateOnAxis( v1, angle );
  6441. };
  6442. }(),
  6443. rotateZ: function () {
  6444. var v1 = new Vector3( 0, 0, 1 );
  6445. return function rotateZ( angle ) {
  6446. return this.rotateOnAxis( v1, angle );
  6447. };
  6448. }(),
  6449. translateOnAxis: function () {
  6450. // translate object by distance along axis in object space
  6451. // axis is assumed to be normalized
  6452. var v1 = new Vector3();
  6453. return function translateOnAxis( axis, distance ) {
  6454. v1.copy( axis ).applyQuaternion( this.quaternion );
  6455. this.position.add( v1.multiplyScalar( distance ) );
  6456. return this;
  6457. };
  6458. }(),
  6459. translateX: function () {
  6460. var v1 = new Vector3( 1, 0, 0 );
  6461. return function translateX( distance ) {
  6462. return this.translateOnAxis( v1, distance );
  6463. };
  6464. }(),
  6465. translateY: function () {
  6466. var v1 = new Vector3( 0, 1, 0 );
  6467. return function translateY( distance ) {
  6468. return this.translateOnAxis( v1, distance );
  6469. };
  6470. }(),
  6471. translateZ: function () {
  6472. var v1 = new Vector3( 0, 0, 1 );
  6473. return function translateZ( distance ) {
  6474. return this.translateOnAxis( v1, distance );
  6475. };
  6476. }(),
  6477. localToWorld: function ( vector ) {
  6478. return vector.applyMatrix4( this.matrixWorld );
  6479. },
  6480. worldToLocal: function () {
  6481. var m1 = new Matrix4();
  6482. return function worldToLocal( vector ) {
  6483. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6484. };
  6485. }(),
  6486. lookAt: function () {
  6487. // This routine does not support objects with rotated and/or translated parent(s)
  6488. var m1 = new Matrix4();
  6489. return function lookAt( vector ) {
  6490. if ( this.isCamera ) {
  6491. m1.lookAt( this.position, vector, this.up );
  6492. } else {
  6493. m1.lookAt( vector, this.position, this.up );
  6494. }
  6495. this.quaternion.setFromRotationMatrix( m1 );
  6496. };
  6497. }(),
  6498. add: function ( object ) {
  6499. if ( arguments.length > 1 ) {
  6500. for ( var i = 0; i < arguments.length; i ++ ) {
  6501. this.add( arguments[ i ] );
  6502. }
  6503. return this;
  6504. }
  6505. if ( object === this ) {
  6506. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6507. return this;
  6508. }
  6509. if ( ( object && object.isObject3D ) ) {
  6510. if ( object.parent !== null ) {
  6511. object.parent.remove( object );
  6512. }
  6513. object.parent = this;
  6514. object.dispatchEvent( { type: 'added' } );
  6515. this.children.push( object );
  6516. } else {
  6517. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6518. }
  6519. return this;
  6520. },
  6521. remove: function ( object ) {
  6522. if ( arguments.length > 1 ) {
  6523. for ( var i = 0; i < arguments.length; i ++ ) {
  6524. this.remove( arguments[ i ] );
  6525. }
  6526. }
  6527. var index = this.children.indexOf( object );
  6528. if ( index !== - 1 ) {
  6529. object.parent = null;
  6530. object.dispatchEvent( { type: 'removed' } );
  6531. this.children.splice( index, 1 );
  6532. }
  6533. },
  6534. getObjectById: function ( id ) {
  6535. return this.getObjectByProperty( 'id', id );
  6536. },
  6537. getObjectByName: function ( name ) {
  6538. return this.getObjectByProperty( 'name', name );
  6539. },
  6540. getObjectByProperty: function ( name, value ) {
  6541. if ( this[ name ] === value ) return this;
  6542. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6543. var child = this.children[ i ];
  6544. var object = child.getObjectByProperty( name, value );
  6545. if ( object !== undefined ) {
  6546. return object;
  6547. }
  6548. }
  6549. return undefined;
  6550. },
  6551. getWorldPosition: function ( optionalTarget ) {
  6552. var result = optionalTarget || new Vector3();
  6553. this.updateMatrixWorld( true );
  6554. return result.setFromMatrixPosition( this.matrixWorld );
  6555. },
  6556. getWorldQuaternion: function () {
  6557. var position = new Vector3();
  6558. var scale = new Vector3();
  6559. return function getWorldQuaternion( optionalTarget ) {
  6560. var result = optionalTarget || new Quaternion();
  6561. this.updateMatrixWorld( true );
  6562. this.matrixWorld.decompose( position, result, scale );
  6563. return result;
  6564. };
  6565. }(),
  6566. getWorldRotation: function () {
  6567. var quaternion = new Quaternion();
  6568. return function getWorldRotation( optionalTarget ) {
  6569. var result = optionalTarget || new Euler();
  6570. this.getWorldQuaternion( quaternion );
  6571. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6572. };
  6573. }(),
  6574. getWorldScale: function () {
  6575. var position = new Vector3();
  6576. var quaternion = new Quaternion();
  6577. return function getWorldScale( optionalTarget ) {
  6578. var result = optionalTarget || new Vector3();
  6579. this.updateMatrixWorld( true );
  6580. this.matrixWorld.decompose( position, quaternion, result );
  6581. return result;
  6582. };
  6583. }(),
  6584. getWorldDirection: function () {
  6585. var quaternion = new Quaternion();
  6586. return function getWorldDirection( optionalTarget ) {
  6587. var result = optionalTarget || new Vector3();
  6588. this.getWorldQuaternion( quaternion );
  6589. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6590. };
  6591. }(),
  6592. raycast: function () {},
  6593. traverse: function ( callback ) {
  6594. callback( this );
  6595. var children = this.children;
  6596. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6597. children[ i ].traverse( callback );
  6598. }
  6599. },
  6600. traverseVisible: function ( callback ) {
  6601. if ( this.visible === false ) return;
  6602. callback( this );
  6603. var children = this.children;
  6604. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6605. children[ i ].traverseVisible( callback );
  6606. }
  6607. },
  6608. traverseAncestors: function ( callback ) {
  6609. var parent = this.parent;
  6610. if ( parent !== null ) {
  6611. callback( parent );
  6612. parent.traverseAncestors( callback );
  6613. }
  6614. },
  6615. updateMatrix: function () {
  6616. this.matrix.compose( this.position, this.quaternion, this.scale );
  6617. this.matrixWorldNeedsUpdate = true;
  6618. },
  6619. updateMatrixWorld: function ( force ) {
  6620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  6621. if ( this.matrixWorldNeedsUpdate || force ) {
  6622. if ( this.parent === null ) {
  6623. this.matrixWorld.copy( this.matrix );
  6624. } else {
  6625. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6626. }
  6627. this.matrixWorldNeedsUpdate = false;
  6628. force = true;
  6629. }
  6630. // update children
  6631. var children = this.children;
  6632. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6633. children[ i ].updateMatrixWorld( force );
  6634. }
  6635. },
  6636. toJSON: function ( meta ) {
  6637. // meta is '' when called from JSON.stringify
  6638. var isRootObject = ( meta === undefined || meta === '' );
  6639. var output = {};
  6640. // meta is a hash used to collect geometries, materials.
  6641. // not providing it implies that this is the root object
  6642. // being serialized.
  6643. if ( isRootObject ) {
  6644. // initialize meta obj
  6645. meta = {
  6646. geometries: {},
  6647. materials: {},
  6648. textures: {},
  6649. images: {}
  6650. };
  6651. output.metadata = {
  6652. version: 4.5,
  6653. type: 'Object',
  6654. generator: 'Object3D.toJSON'
  6655. };
  6656. }
  6657. // standard Object3D serialization
  6658. var object = {};
  6659. object.uuid = this.uuid;
  6660. object.type = this.type;
  6661. if ( this.name !== '' ) object.name = this.name;
  6662. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6663. if ( this.castShadow === true ) object.castShadow = true;
  6664. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6665. if ( this.visible === false ) object.visible = false;
  6666. object.matrix = this.matrix.toArray();
  6667. //
  6668. function serialize( library, element ) {
  6669. if ( library[ element.uuid ] === undefined ) {
  6670. library[ element.uuid ] = element.toJSON( meta );
  6671. }
  6672. return element.uuid;
  6673. }
  6674. if ( this.geometry !== undefined ) {
  6675. object.geometry = serialize( meta.geometries, this.geometry );
  6676. }
  6677. if ( this.material !== undefined ) {
  6678. if ( Array.isArray( this.material ) ) {
  6679. var uuids = [];
  6680. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  6681. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6682. }
  6683. object.material = uuids;
  6684. } else {
  6685. object.material = serialize( meta.materials, this.material );
  6686. }
  6687. }
  6688. //
  6689. if ( this.children.length > 0 ) {
  6690. object.children = [];
  6691. for ( var i = 0; i < this.children.length; i ++ ) {
  6692. object.children.push( this.children[ i ].toJSON( meta ).object );
  6693. }
  6694. }
  6695. if ( isRootObject ) {
  6696. var geometries = extractFromCache( meta.geometries );
  6697. var materials = extractFromCache( meta.materials );
  6698. var textures = extractFromCache( meta.textures );
  6699. var images = extractFromCache( meta.images );
  6700. if ( geometries.length > 0 ) output.geometries = geometries;
  6701. if ( materials.length > 0 ) output.materials = materials;
  6702. if ( textures.length > 0 ) output.textures = textures;
  6703. if ( images.length > 0 ) output.images = images;
  6704. }
  6705. output.object = object;
  6706. return output;
  6707. // extract data from the cache hash
  6708. // remove metadata on each item
  6709. // and return as array
  6710. function extractFromCache( cache ) {
  6711. var values = [];
  6712. for ( var key in cache ) {
  6713. var data = cache[ key ];
  6714. delete data.metadata;
  6715. values.push( data );
  6716. }
  6717. return values;
  6718. }
  6719. },
  6720. clone: function ( recursive ) {
  6721. return new this.constructor().copy( this, recursive );
  6722. },
  6723. copy: function ( source, recursive ) {
  6724. if ( recursive === undefined ) recursive = true;
  6725. this.name = source.name;
  6726. this.up.copy( source.up );
  6727. this.position.copy( source.position );
  6728. this.quaternion.copy( source.quaternion );
  6729. this.scale.copy( source.scale );
  6730. this.matrix.copy( source.matrix );
  6731. this.matrixWorld.copy( source.matrixWorld );
  6732. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6733. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6734. this.layers.mask = source.layers.mask;
  6735. this.visible = source.visible;
  6736. this.castShadow = source.castShadow;
  6737. this.receiveShadow = source.receiveShadow;
  6738. this.frustumCulled = source.frustumCulled;
  6739. this.renderOrder = source.renderOrder;
  6740. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6741. if ( recursive === true ) {
  6742. for ( var i = 0; i < source.children.length; i ++ ) {
  6743. var child = source.children[ i ];
  6744. this.add( child.clone() );
  6745. }
  6746. }
  6747. return this;
  6748. }
  6749. } );
  6750. /**
  6751. * @author bhouston / http://clara.io
  6752. */
  6753. function Line3( start, end ) {
  6754. this.start = ( start !== undefined ) ? start : new Vector3();
  6755. this.end = ( end !== undefined ) ? end : new Vector3();
  6756. }
  6757. Object.assign( Line3.prototype, {
  6758. set: function ( start, end ) {
  6759. this.start.copy( start );
  6760. this.end.copy( end );
  6761. return this;
  6762. },
  6763. clone: function () {
  6764. return new this.constructor().copy( this );
  6765. },
  6766. copy: function ( line ) {
  6767. this.start.copy( line.start );
  6768. this.end.copy( line.end );
  6769. return this;
  6770. },
  6771. getCenter: function ( optionalTarget ) {
  6772. var result = optionalTarget || new Vector3();
  6773. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6774. },
  6775. delta: function ( optionalTarget ) {
  6776. var result = optionalTarget || new Vector3();
  6777. return result.subVectors( this.end, this.start );
  6778. },
  6779. distanceSq: function () {
  6780. return this.start.distanceToSquared( this.end );
  6781. },
  6782. distance: function () {
  6783. return this.start.distanceTo( this.end );
  6784. },
  6785. at: function ( t, optionalTarget ) {
  6786. var result = optionalTarget || new Vector3();
  6787. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6788. },
  6789. closestPointToPointParameter: function () {
  6790. var startP = new Vector3();
  6791. var startEnd = new Vector3();
  6792. return function closestPointToPointParameter( point, clampToLine ) {
  6793. startP.subVectors( point, this.start );
  6794. startEnd.subVectors( this.end, this.start );
  6795. var startEnd2 = startEnd.dot( startEnd );
  6796. var startEnd_startP = startEnd.dot( startP );
  6797. var t = startEnd_startP / startEnd2;
  6798. if ( clampToLine ) {
  6799. t = _Math.clamp( t, 0, 1 );
  6800. }
  6801. return t;
  6802. };
  6803. }(),
  6804. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6805. var t = this.closestPointToPointParameter( point, clampToLine );
  6806. var result = optionalTarget || new Vector3();
  6807. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6808. },
  6809. applyMatrix4: function ( matrix ) {
  6810. this.start.applyMatrix4( matrix );
  6811. this.end.applyMatrix4( matrix );
  6812. return this;
  6813. },
  6814. equals: function ( line ) {
  6815. return line.start.equals( this.start ) && line.end.equals( this.end );
  6816. }
  6817. } );
  6818. /**
  6819. * @author bhouston / http://clara.io
  6820. * @author mrdoob / http://mrdoob.com/
  6821. */
  6822. function Triangle( a, b, c ) {
  6823. this.a = ( a !== undefined ) ? a : new Vector3();
  6824. this.b = ( b !== undefined ) ? b : new Vector3();
  6825. this.c = ( c !== undefined ) ? c : new Vector3();
  6826. }
  6827. Object.assign( Triangle, {
  6828. normal: function () {
  6829. var v0 = new Vector3();
  6830. return function normal( a, b, c, optionalTarget ) {
  6831. var result = optionalTarget || new Vector3();
  6832. result.subVectors( c, b );
  6833. v0.subVectors( a, b );
  6834. result.cross( v0 );
  6835. var resultLengthSq = result.lengthSq();
  6836. if ( resultLengthSq > 0 ) {
  6837. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6838. }
  6839. return result.set( 0, 0, 0 );
  6840. };
  6841. }(),
  6842. // static/instance method to calculate barycentric coordinates
  6843. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6844. barycoordFromPoint: function () {
  6845. var v0 = new Vector3();
  6846. var v1 = new Vector3();
  6847. var v2 = new Vector3();
  6848. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6849. v0.subVectors( c, a );
  6850. v1.subVectors( b, a );
  6851. v2.subVectors( point, a );
  6852. var dot00 = v0.dot( v0 );
  6853. var dot01 = v0.dot( v1 );
  6854. var dot02 = v0.dot( v2 );
  6855. var dot11 = v1.dot( v1 );
  6856. var dot12 = v1.dot( v2 );
  6857. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6858. var result = optionalTarget || new Vector3();
  6859. // collinear or singular triangle
  6860. if ( denom === 0 ) {
  6861. // arbitrary location outside of triangle?
  6862. // not sure if this is the best idea, maybe should be returning undefined
  6863. return result.set( - 2, - 1, - 1 );
  6864. }
  6865. var invDenom = 1 / denom;
  6866. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6867. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6868. // barycentric coordinates must always sum to 1
  6869. return result.set( 1 - u - v, v, u );
  6870. };
  6871. }(),
  6872. containsPoint: function () {
  6873. var v1 = new Vector3();
  6874. return function containsPoint( point, a, b, c ) {
  6875. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6876. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6877. };
  6878. }()
  6879. } );
  6880. Object.assign( Triangle.prototype, {
  6881. set: function ( a, b, c ) {
  6882. this.a.copy( a );
  6883. this.b.copy( b );
  6884. this.c.copy( c );
  6885. return this;
  6886. },
  6887. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6888. this.a.copy( points[ i0 ] );
  6889. this.b.copy( points[ i1 ] );
  6890. this.c.copy( points[ i2 ] );
  6891. return this;
  6892. },
  6893. clone: function () {
  6894. return new this.constructor().copy( this );
  6895. },
  6896. copy: function ( triangle ) {
  6897. this.a.copy( triangle.a );
  6898. this.b.copy( triangle.b );
  6899. this.c.copy( triangle.c );
  6900. return this;
  6901. },
  6902. area: function () {
  6903. var v0 = new Vector3();
  6904. var v1 = new Vector3();
  6905. return function area() {
  6906. v0.subVectors( this.c, this.b );
  6907. v1.subVectors( this.a, this.b );
  6908. return v0.cross( v1 ).length() * 0.5;
  6909. };
  6910. }(),
  6911. midpoint: function ( optionalTarget ) {
  6912. var result = optionalTarget || new Vector3();
  6913. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6914. },
  6915. normal: function ( optionalTarget ) {
  6916. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6917. },
  6918. plane: function ( optionalTarget ) {
  6919. var result = optionalTarget || new Plane();
  6920. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6921. },
  6922. barycoordFromPoint: function ( point, optionalTarget ) {
  6923. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6924. },
  6925. containsPoint: function ( point ) {
  6926. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6927. },
  6928. closestPointToPoint: function () {
  6929. var plane = new Plane();
  6930. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  6931. var projectedPoint = new Vector3();
  6932. var closestPoint = new Vector3();
  6933. return function closestPointToPoint( point, optionalTarget ) {
  6934. var result = optionalTarget || new Vector3();
  6935. var minDistance = Infinity;
  6936. // project the point onto the plane of the triangle
  6937. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6938. plane.projectPoint( point, projectedPoint );
  6939. // check if the projection lies within the triangle
  6940. if( this.containsPoint( projectedPoint ) === true ) {
  6941. // if so, this is the closest point
  6942. result.copy( projectedPoint );
  6943. } else {
  6944. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6945. edgeList[ 0 ].set( this.a, this.b );
  6946. edgeList[ 1 ].set( this.b, this.c );
  6947. edgeList[ 2 ].set( this.c, this.a );
  6948. for( var i = 0; i < edgeList.length; i ++ ) {
  6949. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  6950. var distance = projectedPoint.distanceToSquared( closestPoint );
  6951. if( distance < minDistance ) {
  6952. minDistance = distance;
  6953. result.copy( closestPoint );
  6954. }
  6955. }
  6956. }
  6957. return result;
  6958. };
  6959. }(),
  6960. equals: function ( triangle ) {
  6961. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6962. }
  6963. } );
  6964. /**
  6965. * @author mrdoob / http://mrdoob.com/
  6966. * @author alteredq / http://alteredqualia.com/
  6967. */
  6968. function Face3( a, b, c, normal, color, materialIndex ) {
  6969. this.a = a;
  6970. this.b = b;
  6971. this.c = c;
  6972. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  6973. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6974. this.color = ( color && color.isColor ) ? color : new Color();
  6975. this.vertexColors = Array.isArray( color ) ? color : [];
  6976. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6977. }
  6978. Object.assign( Face3.prototype, {
  6979. clone: function () {
  6980. return new this.constructor().copy( this );
  6981. },
  6982. copy: function ( source ) {
  6983. this.a = source.a;
  6984. this.b = source.b;
  6985. this.c = source.c;
  6986. this.normal.copy( source.normal );
  6987. this.color.copy( source.color );
  6988. this.materialIndex = source.materialIndex;
  6989. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6990. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6991. }
  6992. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6993. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6994. }
  6995. return this;
  6996. }
  6997. } );
  6998. /**
  6999. * @author mrdoob / http://mrdoob.com/
  7000. * @author alteredq / http://alteredqualia.com/
  7001. *
  7002. * parameters = {
  7003. * color: <hex>,
  7004. * opacity: <float>,
  7005. * map: new THREE.Texture( <Image> ),
  7006. *
  7007. * lightMap: new THREE.Texture( <Image> ),
  7008. * lightMapIntensity: <float>
  7009. *
  7010. * aoMap: new THREE.Texture( <Image> ),
  7011. * aoMapIntensity: <float>
  7012. *
  7013. * specularMap: new THREE.Texture( <Image> ),
  7014. *
  7015. * alphaMap: new THREE.Texture( <Image> ),
  7016. *
  7017. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7018. * combine: THREE.Multiply,
  7019. * reflectivity: <float>,
  7020. * refractionRatio: <float>,
  7021. *
  7022. * shading: THREE.SmoothShading,
  7023. * depthTest: <bool>,
  7024. * depthWrite: <bool>,
  7025. *
  7026. * wireframe: <boolean>,
  7027. * wireframeLinewidth: <float>,
  7028. *
  7029. * skinning: <bool>,
  7030. * morphTargets: <bool>
  7031. * }
  7032. */
  7033. function MeshBasicMaterial( parameters ) {
  7034. Material.call( this );
  7035. this.type = 'MeshBasicMaterial';
  7036. this.color = new Color( 0xffffff ); // emissive
  7037. this.map = null;
  7038. this.lightMap = null;
  7039. this.lightMapIntensity = 1.0;
  7040. this.aoMap = null;
  7041. this.aoMapIntensity = 1.0;
  7042. this.specularMap = null;
  7043. this.alphaMap = null;
  7044. this.envMap = null;
  7045. this.combine = MultiplyOperation;
  7046. this.reflectivity = 1;
  7047. this.refractionRatio = 0.98;
  7048. this.wireframe = false;
  7049. this.wireframeLinewidth = 1;
  7050. this.wireframeLinecap = 'round';
  7051. this.wireframeLinejoin = 'round';
  7052. this.skinning = false;
  7053. this.morphTargets = false;
  7054. this.lights = false;
  7055. this.setValues( parameters );
  7056. }
  7057. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7058. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7059. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7060. MeshBasicMaterial.prototype.copy = function ( source ) {
  7061. Material.prototype.copy.call( this, source );
  7062. this.color.copy( source.color );
  7063. this.map = source.map;
  7064. this.lightMap = source.lightMap;
  7065. this.lightMapIntensity = source.lightMapIntensity;
  7066. this.aoMap = source.aoMap;
  7067. this.aoMapIntensity = source.aoMapIntensity;
  7068. this.specularMap = source.specularMap;
  7069. this.alphaMap = source.alphaMap;
  7070. this.envMap = source.envMap;
  7071. this.combine = source.combine;
  7072. this.reflectivity = source.reflectivity;
  7073. this.refractionRatio = source.refractionRatio;
  7074. this.wireframe = source.wireframe;
  7075. this.wireframeLinewidth = source.wireframeLinewidth;
  7076. this.wireframeLinecap = source.wireframeLinecap;
  7077. this.wireframeLinejoin = source.wireframeLinejoin;
  7078. this.skinning = source.skinning;
  7079. this.morphTargets = source.morphTargets;
  7080. return this;
  7081. };
  7082. /**
  7083. * @author mrdoob / http://mrdoob.com/
  7084. */
  7085. function BufferAttribute( array, itemSize, normalized ) {
  7086. if ( Array.isArray( array ) ) {
  7087. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7088. }
  7089. this.uuid = _Math.generateUUID();
  7090. this.array = array;
  7091. this.itemSize = itemSize;
  7092. this.count = array !== undefined ? array.length / itemSize : 0;
  7093. this.normalized = normalized === true;
  7094. this.dynamic = false;
  7095. this.updateRange = { offset: 0, count: - 1 };
  7096. this.onUploadCallback = function () {};
  7097. this.version = 0;
  7098. }
  7099. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  7100. set: function ( value ) {
  7101. if ( value === true ) this.version ++;
  7102. }
  7103. } );
  7104. Object.assign( BufferAttribute.prototype, {
  7105. isBufferAttribute: true,
  7106. setArray: function ( array ) {
  7107. if ( Array.isArray( array ) ) {
  7108. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7109. }
  7110. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7111. this.array = array;
  7112. },
  7113. setDynamic: function ( value ) {
  7114. this.dynamic = value;
  7115. return this;
  7116. },
  7117. copy: function ( source ) {
  7118. this.array = new source.array.constructor( source.array );
  7119. this.itemSize = source.itemSize;
  7120. this.count = source.count;
  7121. this.normalized = source.normalized;
  7122. this.dynamic = source.dynamic;
  7123. return this;
  7124. },
  7125. copyAt: function ( index1, attribute, index2 ) {
  7126. index1 *= this.itemSize;
  7127. index2 *= attribute.itemSize;
  7128. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7129. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7130. }
  7131. return this;
  7132. },
  7133. copyArray: function ( array ) {
  7134. this.array.set( array );
  7135. return this;
  7136. },
  7137. copyColorsArray: function ( colors ) {
  7138. var array = this.array, offset = 0;
  7139. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7140. var color = colors[ i ];
  7141. if ( color === undefined ) {
  7142. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7143. color = new Color();
  7144. }
  7145. array[ offset ++ ] = color.r;
  7146. array[ offset ++ ] = color.g;
  7147. array[ offset ++ ] = color.b;
  7148. }
  7149. return this;
  7150. },
  7151. copyIndicesArray: function ( indices ) {
  7152. var array = this.array, offset = 0;
  7153. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7154. var index = indices[ i ];
  7155. array[ offset ++ ] = index.a;
  7156. array[ offset ++ ] = index.b;
  7157. array[ offset ++ ] = index.c;
  7158. }
  7159. return this;
  7160. },
  7161. copyVector2sArray: function ( vectors ) {
  7162. var array = this.array, offset = 0;
  7163. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7164. var vector = vectors[ i ];
  7165. if ( vector === undefined ) {
  7166. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7167. vector = new Vector2();
  7168. }
  7169. array[ offset ++ ] = vector.x;
  7170. array[ offset ++ ] = vector.y;
  7171. }
  7172. return this;
  7173. },
  7174. copyVector3sArray: function ( vectors ) {
  7175. var array = this.array, offset = 0;
  7176. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7177. var vector = vectors[ i ];
  7178. if ( vector === undefined ) {
  7179. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7180. vector = new Vector3();
  7181. }
  7182. array[ offset ++ ] = vector.x;
  7183. array[ offset ++ ] = vector.y;
  7184. array[ offset ++ ] = vector.z;
  7185. }
  7186. return this;
  7187. },
  7188. copyVector4sArray: function ( vectors ) {
  7189. var array = this.array, offset = 0;
  7190. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7191. var vector = vectors[ i ];
  7192. if ( vector === undefined ) {
  7193. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7194. vector = new Vector4();
  7195. }
  7196. array[ offset ++ ] = vector.x;
  7197. array[ offset ++ ] = vector.y;
  7198. array[ offset ++ ] = vector.z;
  7199. array[ offset ++ ] = vector.w;
  7200. }
  7201. return this;
  7202. },
  7203. set: function ( value, offset ) {
  7204. if ( offset === undefined ) offset = 0;
  7205. this.array.set( value, offset );
  7206. return this;
  7207. },
  7208. getX: function ( index ) {
  7209. return this.array[ index * this.itemSize ];
  7210. },
  7211. setX: function ( index, x ) {
  7212. this.array[ index * this.itemSize ] = x;
  7213. return this;
  7214. },
  7215. getY: function ( index ) {
  7216. return this.array[ index * this.itemSize + 1 ];
  7217. },
  7218. setY: function ( index, y ) {
  7219. this.array[ index * this.itemSize + 1 ] = y;
  7220. return this;
  7221. },
  7222. getZ: function ( index ) {
  7223. return this.array[ index * this.itemSize + 2 ];
  7224. },
  7225. setZ: function ( index, z ) {
  7226. this.array[ index * this.itemSize + 2 ] = z;
  7227. return this;
  7228. },
  7229. getW: function ( index ) {
  7230. return this.array[ index * this.itemSize + 3 ];
  7231. },
  7232. setW: function ( index, w ) {
  7233. this.array[ index * this.itemSize + 3 ] = w;
  7234. return this;
  7235. },
  7236. setXY: function ( index, x, y ) {
  7237. index *= this.itemSize;
  7238. this.array[ index + 0 ] = x;
  7239. this.array[ index + 1 ] = y;
  7240. return this;
  7241. },
  7242. setXYZ: function ( index, x, y, z ) {
  7243. index *= this.itemSize;
  7244. this.array[ index + 0 ] = x;
  7245. this.array[ index + 1 ] = y;
  7246. this.array[ index + 2 ] = z;
  7247. return this;
  7248. },
  7249. setXYZW: function ( index, x, y, z, w ) {
  7250. index *= this.itemSize;
  7251. this.array[ index + 0 ] = x;
  7252. this.array[ index + 1 ] = y;
  7253. this.array[ index + 2 ] = z;
  7254. this.array[ index + 3 ] = w;
  7255. return this;
  7256. },
  7257. onUpload: function ( callback ) {
  7258. this.onUploadCallback = callback;
  7259. return this;
  7260. },
  7261. clone: function () {
  7262. return new this.constructor( this.array, this.itemSize ).copy( this );
  7263. }
  7264. } );
  7265. //
  7266. function Int8BufferAttribute( array, itemSize ) {
  7267. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7268. }
  7269. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7270. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7271. function Uint8BufferAttribute( array, itemSize ) {
  7272. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7273. }
  7274. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7275. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7276. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7277. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7278. }
  7279. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7280. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7281. function Int16BufferAttribute( array, itemSize ) {
  7282. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7283. }
  7284. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7285. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7286. function Uint16BufferAttribute( array, itemSize ) {
  7287. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7288. }
  7289. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7290. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7291. function Int32BufferAttribute( array, itemSize ) {
  7292. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7293. }
  7294. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7295. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7296. function Uint32BufferAttribute( array, itemSize ) {
  7297. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7298. }
  7299. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7300. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7301. function Float32BufferAttribute( array, itemSize ) {
  7302. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7303. }
  7304. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7305. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7306. function Float64BufferAttribute( array, itemSize ) {
  7307. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7308. }
  7309. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7310. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7311. /**
  7312. * @author mrdoob / http://mrdoob.com/
  7313. */
  7314. function DirectGeometry() {
  7315. this.indices = [];
  7316. this.vertices = [];
  7317. this.normals = [];
  7318. this.colors = [];
  7319. this.uvs = [];
  7320. this.uvs2 = [];
  7321. this.groups = [];
  7322. this.morphTargets = {};
  7323. this.skinWeights = [];
  7324. this.skinIndices = [];
  7325. // this.lineDistances = [];
  7326. this.boundingBox = null;
  7327. this.boundingSphere = null;
  7328. // update flags
  7329. this.verticesNeedUpdate = false;
  7330. this.normalsNeedUpdate = false;
  7331. this.colorsNeedUpdate = false;
  7332. this.uvsNeedUpdate = false;
  7333. this.groupsNeedUpdate = false;
  7334. }
  7335. Object.assign( DirectGeometry.prototype, {
  7336. computeGroups: function ( geometry ) {
  7337. var group;
  7338. var groups = [];
  7339. var materialIndex = undefined;
  7340. var faces = geometry.faces;
  7341. for ( var i = 0; i < faces.length; i ++ ) {
  7342. var face = faces[ i ];
  7343. // materials
  7344. if ( face.materialIndex !== materialIndex ) {
  7345. materialIndex = face.materialIndex;
  7346. if ( group !== undefined ) {
  7347. group.count = ( i * 3 ) - group.start;
  7348. groups.push( group );
  7349. }
  7350. group = {
  7351. start: i * 3,
  7352. materialIndex: materialIndex
  7353. };
  7354. }
  7355. }
  7356. if ( group !== undefined ) {
  7357. group.count = ( i * 3 ) - group.start;
  7358. groups.push( group );
  7359. }
  7360. this.groups = groups;
  7361. },
  7362. fromGeometry: function ( geometry ) {
  7363. var faces = geometry.faces;
  7364. var vertices = geometry.vertices;
  7365. var faceVertexUvs = geometry.faceVertexUvs;
  7366. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7367. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7368. // morphs
  7369. var morphTargets = geometry.morphTargets;
  7370. var morphTargetsLength = morphTargets.length;
  7371. var morphTargetsPosition;
  7372. if ( morphTargetsLength > 0 ) {
  7373. morphTargetsPosition = [];
  7374. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7375. morphTargetsPosition[ i ] = [];
  7376. }
  7377. this.morphTargets.position = morphTargetsPosition;
  7378. }
  7379. var morphNormals = geometry.morphNormals;
  7380. var morphNormalsLength = morphNormals.length;
  7381. var morphTargetsNormal;
  7382. if ( morphNormalsLength > 0 ) {
  7383. morphTargetsNormal = [];
  7384. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7385. morphTargetsNormal[ i ] = [];
  7386. }
  7387. this.morphTargets.normal = morphTargetsNormal;
  7388. }
  7389. // skins
  7390. var skinIndices = geometry.skinIndices;
  7391. var skinWeights = geometry.skinWeights;
  7392. var hasSkinIndices = skinIndices.length === vertices.length;
  7393. var hasSkinWeights = skinWeights.length === vertices.length;
  7394. //
  7395. for ( var i = 0; i < faces.length; i ++ ) {
  7396. var face = faces[ i ];
  7397. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7398. var vertexNormals = face.vertexNormals;
  7399. if ( vertexNormals.length === 3 ) {
  7400. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7401. } else {
  7402. var normal = face.normal;
  7403. this.normals.push( normal, normal, normal );
  7404. }
  7405. var vertexColors = face.vertexColors;
  7406. if ( vertexColors.length === 3 ) {
  7407. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7408. } else {
  7409. var color = face.color;
  7410. this.colors.push( color, color, color );
  7411. }
  7412. if ( hasFaceVertexUv === true ) {
  7413. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7414. if ( vertexUvs !== undefined ) {
  7415. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7416. } else {
  7417. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7418. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7419. }
  7420. }
  7421. if ( hasFaceVertexUv2 === true ) {
  7422. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7423. if ( vertexUvs !== undefined ) {
  7424. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7425. } else {
  7426. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7427. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7428. }
  7429. }
  7430. // morphs
  7431. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7432. var morphTarget = morphTargets[ j ].vertices;
  7433. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7434. }
  7435. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7436. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7437. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7438. }
  7439. // skins
  7440. if ( hasSkinIndices ) {
  7441. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7442. }
  7443. if ( hasSkinWeights ) {
  7444. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7445. }
  7446. }
  7447. this.computeGroups( geometry );
  7448. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7449. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7450. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7451. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7452. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7453. return this;
  7454. }
  7455. } );
  7456. function arrayMax( array ) {
  7457. if ( array.length === 0 ) return - Infinity;
  7458. var max = array[ 0 ];
  7459. for ( var i = 1, l = array.length; i < l; ++ i ) {
  7460. if ( array[ i ] > max ) max = array[ i ];
  7461. }
  7462. return max;
  7463. }
  7464. /**
  7465. * @author mrdoob / http://mrdoob.com/
  7466. * @author kile / http://kile.stravaganza.org/
  7467. * @author alteredq / http://alteredqualia.com/
  7468. * @author mikael emtinger / http://gomo.se/
  7469. * @author zz85 / http://www.lab4games.net/zz85/blog
  7470. * @author bhouston / http://clara.io
  7471. */
  7472. var count = 0;
  7473. function GeometryIdCount() { return count++; }
  7474. function Geometry() {
  7475. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7476. this.uuid = _Math.generateUUID();
  7477. this.name = '';
  7478. this.type = 'Geometry';
  7479. this.vertices = [];
  7480. this.colors = [];
  7481. this.faces = [];
  7482. this.faceVertexUvs = [[]];
  7483. this.morphTargets = [];
  7484. this.morphNormals = [];
  7485. this.skinWeights = [];
  7486. this.skinIndices = [];
  7487. this.lineDistances = [];
  7488. this.boundingBox = null;
  7489. this.boundingSphere = null;
  7490. // update flags
  7491. this.elementsNeedUpdate = false;
  7492. this.verticesNeedUpdate = false;
  7493. this.uvsNeedUpdate = false;
  7494. this.normalsNeedUpdate = false;
  7495. this.colorsNeedUpdate = false;
  7496. this.lineDistancesNeedUpdate = false;
  7497. this.groupsNeedUpdate = false;
  7498. }
  7499. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  7500. isGeometry: true,
  7501. applyMatrix: function ( matrix ) {
  7502. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7503. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7504. var vertex = this.vertices[ i ];
  7505. vertex.applyMatrix4( matrix );
  7506. }
  7507. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7508. var face = this.faces[ i ];
  7509. face.normal.applyMatrix3( normalMatrix ).normalize();
  7510. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7511. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7512. }
  7513. }
  7514. if ( this.boundingBox !== null ) {
  7515. this.computeBoundingBox();
  7516. }
  7517. if ( this.boundingSphere !== null ) {
  7518. this.computeBoundingSphere();
  7519. }
  7520. this.verticesNeedUpdate = true;
  7521. this.normalsNeedUpdate = true;
  7522. return this;
  7523. },
  7524. rotateX: function () {
  7525. // rotate geometry around world x-axis
  7526. var m1 = new Matrix4();
  7527. return function rotateX( angle ) {
  7528. m1.makeRotationX( angle );
  7529. this.applyMatrix( m1 );
  7530. return this;
  7531. };
  7532. }(),
  7533. rotateY: function () {
  7534. // rotate geometry around world y-axis
  7535. var m1 = new Matrix4();
  7536. return function rotateY( angle ) {
  7537. m1.makeRotationY( angle );
  7538. this.applyMatrix( m1 );
  7539. return this;
  7540. };
  7541. }(),
  7542. rotateZ: function () {
  7543. // rotate geometry around world z-axis
  7544. var m1 = new Matrix4();
  7545. return function rotateZ( angle ) {
  7546. m1.makeRotationZ( angle );
  7547. this.applyMatrix( m1 );
  7548. return this;
  7549. };
  7550. }(),
  7551. translate: function () {
  7552. // translate geometry
  7553. var m1 = new Matrix4();
  7554. return function translate( x, y, z ) {
  7555. m1.makeTranslation( x, y, z );
  7556. this.applyMatrix( m1 );
  7557. return this;
  7558. };
  7559. }(),
  7560. scale: function () {
  7561. // scale geometry
  7562. var m1 = new Matrix4();
  7563. return function scale( x, y, z ) {
  7564. m1.makeScale( x, y, z );
  7565. this.applyMatrix( m1 );
  7566. return this;
  7567. };
  7568. }(),
  7569. lookAt: function () {
  7570. var obj = new Object3D();
  7571. return function lookAt( vector ) {
  7572. obj.lookAt( vector );
  7573. obj.updateMatrix();
  7574. this.applyMatrix( obj.matrix );
  7575. };
  7576. }(),
  7577. fromBufferGeometry: function ( geometry ) {
  7578. var scope = this;
  7579. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7580. var attributes = geometry.attributes;
  7581. var positions = attributes.position.array;
  7582. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7583. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7584. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7585. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7586. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7587. var tempNormals = [];
  7588. var tempUVs = [];
  7589. var tempUVs2 = [];
  7590. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7591. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7592. if ( normals !== undefined ) {
  7593. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7594. }
  7595. if ( colors !== undefined ) {
  7596. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7597. }
  7598. if ( uvs !== undefined ) {
  7599. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7600. }
  7601. if ( uvs2 !== undefined ) {
  7602. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7603. }
  7604. }
  7605. function addFace( a, b, c, materialIndex ) {
  7606. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7607. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7608. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7609. scope.faces.push( face );
  7610. if ( uvs !== undefined ) {
  7611. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7612. }
  7613. if ( uvs2 !== undefined ) {
  7614. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7615. }
  7616. }
  7617. var groups = geometry.groups;
  7618. if ( groups.length > 0 ) {
  7619. for ( var i = 0; i < groups.length; i ++ ) {
  7620. var group = groups[ i ];
  7621. var start = group.start;
  7622. var count = group.count;
  7623. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7624. if ( indices !== undefined ) {
  7625. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7626. } else {
  7627. addFace( j, j + 1, j + 2, group.materialIndex );
  7628. }
  7629. }
  7630. }
  7631. } else {
  7632. if ( indices !== undefined ) {
  7633. for ( var i = 0; i < indices.length; i += 3 ) {
  7634. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7635. }
  7636. } else {
  7637. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7638. addFace( i, i + 1, i + 2 );
  7639. }
  7640. }
  7641. }
  7642. this.computeFaceNormals();
  7643. if ( geometry.boundingBox !== null ) {
  7644. this.boundingBox = geometry.boundingBox.clone();
  7645. }
  7646. if ( geometry.boundingSphere !== null ) {
  7647. this.boundingSphere = geometry.boundingSphere.clone();
  7648. }
  7649. return this;
  7650. },
  7651. center: function () {
  7652. this.computeBoundingBox();
  7653. var offset = this.boundingBox.getCenter().negate();
  7654. this.translate( offset.x, offset.y, offset.z );
  7655. return offset;
  7656. },
  7657. normalize: function () {
  7658. this.computeBoundingSphere();
  7659. var center = this.boundingSphere.center;
  7660. var radius = this.boundingSphere.radius;
  7661. var s = radius === 0 ? 1 : 1.0 / radius;
  7662. var matrix = new Matrix4();
  7663. matrix.set(
  7664. s, 0, 0, - s * center.x,
  7665. 0, s, 0, - s * center.y,
  7666. 0, 0, s, - s * center.z,
  7667. 0, 0, 0, 1
  7668. );
  7669. this.applyMatrix( matrix );
  7670. return this;
  7671. },
  7672. computeFaceNormals: function () {
  7673. var cb = new Vector3(), ab = new Vector3();
  7674. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7675. var face = this.faces[ f ];
  7676. var vA = this.vertices[ face.a ];
  7677. var vB = this.vertices[ face.b ];
  7678. var vC = this.vertices[ face.c ];
  7679. cb.subVectors( vC, vB );
  7680. ab.subVectors( vA, vB );
  7681. cb.cross( ab );
  7682. cb.normalize();
  7683. face.normal.copy( cb );
  7684. }
  7685. },
  7686. computeVertexNormals: function ( areaWeighted ) {
  7687. if ( areaWeighted === undefined ) areaWeighted = true;
  7688. var v, vl, f, fl, face, vertices;
  7689. vertices = new Array( this.vertices.length );
  7690. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7691. vertices[ v ] = new Vector3();
  7692. }
  7693. if ( areaWeighted ) {
  7694. // vertex normals weighted by triangle areas
  7695. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7696. var vA, vB, vC;
  7697. var cb = new Vector3(), ab = new Vector3();
  7698. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7699. face = this.faces[ f ];
  7700. vA = this.vertices[ face.a ];
  7701. vB = this.vertices[ face.b ];
  7702. vC = this.vertices[ face.c ];
  7703. cb.subVectors( vC, vB );
  7704. ab.subVectors( vA, vB );
  7705. cb.cross( ab );
  7706. vertices[ face.a ].add( cb );
  7707. vertices[ face.b ].add( cb );
  7708. vertices[ face.c ].add( cb );
  7709. }
  7710. } else {
  7711. this.computeFaceNormals();
  7712. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7713. face = this.faces[ f ];
  7714. vertices[ face.a ].add( face.normal );
  7715. vertices[ face.b ].add( face.normal );
  7716. vertices[ face.c ].add( face.normal );
  7717. }
  7718. }
  7719. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7720. vertices[ v ].normalize();
  7721. }
  7722. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7723. face = this.faces[ f ];
  7724. var vertexNormals = face.vertexNormals;
  7725. if ( vertexNormals.length === 3 ) {
  7726. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7727. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7728. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7729. } else {
  7730. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7731. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7732. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7733. }
  7734. }
  7735. if ( this.faces.length > 0 ) {
  7736. this.normalsNeedUpdate = true;
  7737. }
  7738. },
  7739. computeFlatVertexNormals: function () {
  7740. var f, fl, face;
  7741. this.computeFaceNormals();
  7742. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7743. face = this.faces[ f ];
  7744. var vertexNormals = face.vertexNormals;
  7745. if ( vertexNormals.length === 3 ) {
  7746. vertexNormals[ 0 ].copy( face.normal );
  7747. vertexNormals[ 1 ].copy( face.normal );
  7748. vertexNormals[ 2 ].copy( face.normal );
  7749. } else {
  7750. vertexNormals[ 0 ] = face.normal.clone();
  7751. vertexNormals[ 1 ] = face.normal.clone();
  7752. vertexNormals[ 2 ] = face.normal.clone();
  7753. }
  7754. }
  7755. if ( this.faces.length > 0 ) {
  7756. this.normalsNeedUpdate = true;
  7757. }
  7758. },
  7759. computeMorphNormals: function () {
  7760. var i, il, f, fl, face;
  7761. // save original normals
  7762. // - create temp variables on first access
  7763. // otherwise just copy (for faster repeated calls)
  7764. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7765. face = this.faces[ f ];
  7766. if ( ! face.__originalFaceNormal ) {
  7767. face.__originalFaceNormal = face.normal.clone();
  7768. } else {
  7769. face.__originalFaceNormal.copy( face.normal );
  7770. }
  7771. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7772. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7773. if ( ! face.__originalVertexNormals[ i ] ) {
  7774. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7775. } else {
  7776. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7777. }
  7778. }
  7779. }
  7780. // use temp geometry to compute face and vertex normals for each morph
  7781. var tmpGeo = new Geometry();
  7782. tmpGeo.faces = this.faces;
  7783. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7784. // create on first access
  7785. if ( ! this.morphNormals[ i ] ) {
  7786. this.morphNormals[ i ] = {};
  7787. this.morphNormals[ i ].faceNormals = [];
  7788. this.morphNormals[ i ].vertexNormals = [];
  7789. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7790. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7791. var faceNormal, vertexNormals;
  7792. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7793. faceNormal = new Vector3();
  7794. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7795. dstNormalsFace.push( faceNormal );
  7796. dstNormalsVertex.push( vertexNormals );
  7797. }
  7798. }
  7799. var morphNormals = this.morphNormals[ i ];
  7800. // set vertices to morph target
  7801. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7802. // compute morph normals
  7803. tmpGeo.computeFaceNormals();
  7804. tmpGeo.computeVertexNormals();
  7805. // store morph normals
  7806. var faceNormal, vertexNormals;
  7807. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7808. face = this.faces[ f ];
  7809. faceNormal = morphNormals.faceNormals[ f ];
  7810. vertexNormals = morphNormals.vertexNormals[ f ];
  7811. faceNormal.copy( face.normal );
  7812. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7813. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7814. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7815. }
  7816. }
  7817. // restore original normals
  7818. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7819. face = this.faces[ f ];
  7820. face.normal = face.__originalFaceNormal;
  7821. face.vertexNormals = face.__originalVertexNormals;
  7822. }
  7823. },
  7824. computeLineDistances: function () {
  7825. var d = 0;
  7826. var vertices = this.vertices;
  7827. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7828. if ( i > 0 ) {
  7829. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7830. }
  7831. this.lineDistances[ i ] = d;
  7832. }
  7833. },
  7834. computeBoundingBox: function () {
  7835. if ( this.boundingBox === null ) {
  7836. this.boundingBox = new Box3();
  7837. }
  7838. this.boundingBox.setFromPoints( this.vertices );
  7839. },
  7840. computeBoundingSphere: function () {
  7841. if ( this.boundingSphere === null ) {
  7842. this.boundingSphere = new Sphere();
  7843. }
  7844. this.boundingSphere.setFromPoints( this.vertices );
  7845. },
  7846. merge: function ( geometry, matrix, materialIndexOffset ) {
  7847. if ( ( geometry && geometry.isGeometry ) === false ) {
  7848. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7849. return;
  7850. }
  7851. var normalMatrix,
  7852. vertexOffset = this.vertices.length,
  7853. vertices1 = this.vertices,
  7854. vertices2 = geometry.vertices,
  7855. faces1 = this.faces,
  7856. faces2 = geometry.faces,
  7857. uvs1 = this.faceVertexUvs[ 0 ],
  7858. uvs2 = geometry.faceVertexUvs[ 0 ],
  7859. colors1 = this.colors,
  7860. colors2 = geometry.colors;
  7861. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7862. if ( matrix !== undefined ) {
  7863. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7864. }
  7865. // vertices
  7866. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7867. var vertex = vertices2[ i ];
  7868. var vertexCopy = vertex.clone();
  7869. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7870. vertices1.push( vertexCopy );
  7871. }
  7872. // colors
  7873. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7874. colors1.push( colors2[ i ].clone() );
  7875. }
  7876. // faces
  7877. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7878. var face = faces2[ i ], faceCopy, normal, color,
  7879. faceVertexNormals = face.vertexNormals,
  7880. faceVertexColors = face.vertexColors;
  7881. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7882. faceCopy.normal.copy( face.normal );
  7883. if ( normalMatrix !== undefined ) {
  7884. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7885. }
  7886. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7887. normal = faceVertexNormals[ j ].clone();
  7888. if ( normalMatrix !== undefined ) {
  7889. normal.applyMatrix3( normalMatrix ).normalize();
  7890. }
  7891. faceCopy.vertexNormals.push( normal );
  7892. }
  7893. faceCopy.color.copy( face.color );
  7894. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7895. color = faceVertexColors[ j ];
  7896. faceCopy.vertexColors.push( color.clone() );
  7897. }
  7898. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7899. faces1.push( faceCopy );
  7900. }
  7901. // uvs
  7902. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7903. var uv = uvs2[ i ], uvCopy = [];
  7904. if ( uv === undefined ) {
  7905. continue;
  7906. }
  7907. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7908. uvCopy.push( uv[ j ].clone() );
  7909. }
  7910. uvs1.push( uvCopy );
  7911. }
  7912. },
  7913. mergeMesh: function ( mesh ) {
  7914. if ( ( mesh && mesh.isMesh ) === false ) {
  7915. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7916. return;
  7917. }
  7918. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7919. this.merge( mesh.geometry, mesh.matrix );
  7920. },
  7921. /*
  7922. * Checks for duplicate vertices with hashmap.
  7923. * Duplicated vertices are removed
  7924. * and faces' vertices are updated.
  7925. */
  7926. mergeVertices: function () {
  7927. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7928. var unique = [], changes = [];
  7929. var v, key;
  7930. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7931. var precision = Math.pow( 10, precisionPoints );
  7932. var i, il, face;
  7933. var indices, j, jl;
  7934. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7935. v = this.vertices[ i ];
  7936. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7937. if ( verticesMap[ key ] === undefined ) {
  7938. verticesMap[ key ] = i;
  7939. unique.push( this.vertices[ i ] );
  7940. changes[ i ] = unique.length - 1;
  7941. } else {
  7942. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7943. changes[ i ] = changes[ verticesMap[ key ] ];
  7944. }
  7945. }
  7946. // if faces are completely degenerate after merging vertices, we
  7947. // have to remove them from the geometry.
  7948. var faceIndicesToRemove = [];
  7949. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7950. face = this.faces[ i ];
  7951. face.a = changes[ face.a ];
  7952. face.b = changes[ face.b ];
  7953. face.c = changes[ face.c ];
  7954. indices = [ face.a, face.b, face.c ];
  7955. // if any duplicate vertices are found in a Face3
  7956. // we have to remove the face as nothing can be saved
  7957. for ( var n = 0; n < 3; n ++ ) {
  7958. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7959. faceIndicesToRemove.push( i );
  7960. break;
  7961. }
  7962. }
  7963. }
  7964. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7965. var idx = faceIndicesToRemove[ i ];
  7966. this.faces.splice( idx, 1 );
  7967. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7968. this.faceVertexUvs[ j ].splice( idx, 1 );
  7969. }
  7970. }
  7971. // Use unique set of vertices
  7972. var diff = this.vertices.length - unique.length;
  7973. this.vertices = unique;
  7974. return diff;
  7975. },
  7976. sortFacesByMaterialIndex: function () {
  7977. var faces = this.faces;
  7978. var length = faces.length;
  7979. // tag faces
  7980. for ( var i = 0; i < length; i ++ ) {
  7981. faces[ i ]._id = i;
  7982. }
  7983. // sort faces
  7984. function materialIndexSort( a, b ) {
  7985. return a.materialIndex - b.materialIndex;
  7986. }
  7987. faces.sort( materialIndexSort );
  7988. // sort uvs
  7989. var uvs1 = this.faceVertexUvs[ 0 ];
  7990. var uvs2 = this.faceVertexUvs[ 1 ];
  7991. var newUvs1, newUvs2;
  7992. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7993. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7994. for ( var i = 0; i < length; i ++ ) {
  7995. var id = faces[ i ]._id;
  7996. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7997. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7998. }
  7999. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8000. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8001. },
  8002. toJSON: function () {
  8003. var data = {
  8004. metadata: {
  8005. version: 4.5,
  8006. type: 'Geometry',
  8007. generator: 'Geometry.toJSON'
  8008. }
  8009. };
  8010. // standard Geometry serialization
  8011. data.uuid = this.uuid;
  8012. data.type = this.type;
  8013. if ( this.name !== '' ) data.name = this.name;
  8014. if ( this.parameters !== undefined ) {
  8015. var parameters = this.parameters;
  8016. for ( var key in parameters ) {
  8017. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8018. }
  8019. return data;
  8020. }
  8021. var vertices = [];
  8022. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8023. var vertex = this.vertices[ i ];
  8024. vertices.push( vertex.x, vertex.y, vertex.z );
  8025. }
  8026. var faces = [];
  8027. var normals = [];
  8028. var normalsHash = {};
  8029. var colors = [];
  8030. var colorsHash = {};
  8031. var uvs = [];
  8032. var uvsHash = {};
  8033. for ( var i = 0; i < this.faces.length; i ++ ) {
  8034. var face = this.faces[ i ];
  8035. var hasMaterial = true;
  8036. var hasFaceUv = false; // deprecated
  8037. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8038. var hasFaceNormal = face.normal.length() > 0;
  8039. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8040. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8041. var hasFaceVertexColor = face.vertexColors.length > 0;
  8042. var faceType = 0;
  8043. faceType = setBit( faceType, 0, 0 ); // isQuad
  8044. faceType = setBit( faceType, 1, hasMaterial );
  8045. faceType = setBit( faceType, 2, hasFaceUv );
  8046. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8047. faceType = setBit( faceType, 4, hasFaceNormal );
  8048. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8049. faceType = setBit( faceType, 6, hasFaceColor );
  8050. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8051. faces.push( faceType );
  8052. faces.push( face.a, face.b, face.c );
  8053. faces.push( face.materialIndex );
  8054. if ( hasFaceVertexUv ) {
  8055. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8056. faces.push(
  8057. getUvIndex( faceVertexUvs[ 0 ] ),
  8058. getUvIndex( faceVertexUvs[ 1 ] ),
  8059. getUvIndex( faceVertexUvs[ 2 ] )
  8060. );
  8061. }
  8062. if ( hasFaceNormal ) {
  8063. faces.push( getNormalIndex( face.normal ) );
  8064. }
  8065. if ( hasFaceVertexNormal ) {
  8066. var vertexNormals = face.vertexNormals;
  8067. faces.push(
  8068. getNormalIndex( vertexNormals[ 0 ] ),
  8069. getNormalIndex( vertexNormals[ 1 ] ),
  8070. getNormalIndex( vertexNormals[ 2 ] )
  8071. );
  8072. }
  8073. if ( hasFaceColor ) {
  8074. faces.push( getColorIndex( face.color ) );
  8075. }
  8076. if ( hasFaceVertexColor ) {
  8077. var vertexColors = face.vertexColors;
  8078. faces.push(
  8079. getColorIndex( vertexColors[ 0 ] ),
  8080. getColorIndex( vertexColors[ 1 ] ),
  8081. getColorIndex( vertexColors[ 2 ] )
  8082. );
  8083. }
  8084. }
  8085. function setBit( value, position, enabled ) {
  8086. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8087. }
  8088. function getNormalIndex( normal ) {
  8089. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8090. if ( normalsHash[ hash ] !== undefined ) {
  8091. return normalsHash[ hash ];
  8092. }
  8093. normalsHash[ hash ] = normals.length / 3;
  8094. normals.push( normal.x, normal.y, normal.z );
  8095. return normalsHash[ hash ];
  8096. }
  8097. function getColorIndex( color ) {
  8098. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8099. if ( colorsHash[ hash ] !== undefined ) {
  8100. return colorsHash[ hash ];
  8101. }
  8102. colorsHash[ hash ] = colors.length;
  8103. colors.push( color.getHex() );
  8104. return colorsHash[ hash ];
  8105. }
  8106. function getUvIndex( uv ) {
  8107. var hash = uv.x.toString() + uv.y.toString();
  8108. if ( uvsHash[ hash ] !== undefined ) {
  8109. return uvsHash[ hash ];
  8110. }
  8111. uvsHash[ hash ] = uvs.length / 2;
  8112. uvs.push( uv.x, uv.y );
  8113. return uvsHash[ hash ];
  8114. }
  8115. data.data = {};
  8116. data.data.vertices = vertices;
  8117. data.data.normals = normals;
  8118. if ( colors.length > 0 ) data.data.colors = colors;
  8119. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8120. data.data.faces = faces;
  8121. return data;
  8122. },
  8123. clone: function () {
  8124. /*
  8125. // Handle primitives
  8126. var parameters = this.parameters;
  8127. if ( parameters !== undefined ) {
  8128. var values = [];
  8129. for ( var key in parameters ) {
  8130. values.push( parameters[ key ] );
  8131. }
  8132. var geometry = Object.create( this.constructor.prototype );
  8133. this.constructor.apply( geometry, values );
  8134. return geometry;
  8135. }
  8136. return new this.constructor().copy( this );
  8137. */
  8138. return new Geometry().copy( this );
  8139. },
  8140. copy: function ( source ) {
  8141. var i, il, j, jl, k, kl;
  8142. // reset
  8143. this.vertices = [];
  8144. this.colors = [];
  8145. this.faces = [];
  8146. this.faceVertexUvs = [[]];
  8147. this.morphTargets = [];
  8148. this.morphNormals = [];
  8149. this.skinWeights = [];
  8150. this.skinIndices = [];
  8151. this.lineDistances = [];
  8152. this.boundingBox = null;
  8153. this.boundingSphere = null;
  8154. // name
  8155. this.name = source.name;
  8156. // vertices
  8157. var vertices = source.vertices;
  8158. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  8159. this.vertices.push( vertices[ i ].clone() );
  8160. }
  8161. // colors
  8162. var colors = source.colors;
  8163. for ( i = 0, il = colors.length; i < il; i ++ ) {
  8164. this.colors.push( colors[ i ].clone() );
  8165. }
  8166. // faces
  8167. var faces = source.faces;
  8168. for ( i = 0, il = faces.length; i < il; i ++ ) {
  8169. this.faces.push( faces[ i ].clone() );
  8170. }
  8171. // face vertex uvs
  8172. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8173. var faceVertexUvs = source.faceVertexUvs[ i ];
  8174. if ( this.faceVertexUvs[ i ] === undefined ) {
  8175. this.faceVertexUvs[ i ] = [];
  8176. }
  8177. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8178. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8179. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  8180. var uv = uvs[ k ];
  8181. uvsCopy.push( uv.clone() );
  8182. }
  8183. this.faceVertexUvs[ i ].push( uvsCopy );
  8184. }
  8185. }
  8186. // morph targets
  8187. var morphTargets = source.morphTargets;
  8188. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  8189. var morphTarget = {};
  8190. morphTarget.name = morphTargets[ i ].name;
  8191. // vertices
  8192. if ( morphTargets[ i ].vertices !== undefined ) {
  8193. morphTarget.vertices = [];
  8194. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  8195. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  8196. }
  8197. }
  8198. // normals
  8199. if ( morphTargets[ i ].normals !== undefined ) {
  8200. morphTarget.normals = [];
  8201. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  8202. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  8203. }
  8204. }
  8205. this.morphTargets.push( morphTarget );
  8206. }
  8207. // morph normals
  8208. var morphNormals = source.morphNormals;
  8209. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  8210. var morphNormal = {};
  8211. // vertex normals
  8212. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  8213. morphNormal.vertexNormals = [];
  8214. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  8215. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  8216. var destVertexNormal = {};
  8217. destVertexNormal.a = srcVertexNormal.a.clone();
  8218. destVertexNormal.b = srcVertexNormal.b.clone();
  8219. destVertexNormal.c = srcVertexNormal.c.clone();
  8220. morphNormal.vertexNormals.push( destVertexNormal );
  8221. }
  8222. }
  8223. // face normals
  8224. if ( morphNormals[ i ].faceNormals !== undefined ) {
  8225. morphNormal.faceNormals = [];
  8226. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  8227. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  8228. }
  8229. }
  8230. this.morphNormals.push( morphNormal );
  8231. }
  8232. // skin weights
  8233. var skinWeights = source.skinWeights;
  8234. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  8235. this.skinWeights.push( skinWeights[ i ].clone() );
  8236. }
  8237. // skin indices
  8238. var skinIndices = source.skinIndices;
  8239. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  8240. this.skinIndices.push( skinIndices[ i ].clone() );
  8241. }
  8242. // line distances
  8243. var lineDistances = source.lineDistances;
  8244. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  8245. this.lineDistances.push( lineDistances[ i ] );
  8246. }
  8247. // bounding box
  8248. var boundingBox = source.boundingBox;
  8249. if ( boundingBox !== null ) {
  8250. this.boundingBox = boundingBox.clone();
  8251. }
  8252. // bounding sphere
  8253. var boundingSphere = source.boundingSphere;
  8254. if ( boundingSphere !== null ) {
  8255. this.boundingSphere = boundingSphere.clone();
  8256. }
  8257. // update flags
  8258. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8259. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8260. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8261. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8262. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8263. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8264. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8265. return this;
  8266. },
  8267. dispose: function () {
  8268. this.dispatchEvent( { type: 'dispose' } );
  8269. }
  8270. } );
  8271. /**
  8272. * @author alteredq / http://alteredqualia.com/
  8273. * @author mrdoob / http://mrdoob.com/
  8274. */
  8275. function BufferGeometry() {
  8276. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8277. this.uuid = _Math.generateUUID();
  8278. this.name = '';
  8279. this.type = 'BufferGeometry';
  8280. this.index = null;
  8281. this.attributes = {};
  8282. this.morphAttributes = {};
  8283. this.groups = [];
  8284. this.boundingBox = null;
  8285. this.boundingSphere = null;
  8286. this.drawRange = { start: 0, count: Infinity };
  8287. }
  8288. BufferGeometry.MaxIndex = 65535;
  8289. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  8290. isBufferGeometry: true,
  8291. getIndex: function () {
  8292. return this.index;
  8293. },
  8294. setIndex: function ( index ) {
  8295. if ( Array.isArray( index ) ) {
  8296. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8297. } else {
  8298. this.index = index;
  8299. }
  8300. },
  8301. addAttribute: function ( name, attribute ) {
  8302. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8303. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8304. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8305. return;
  8306. }
  8307. if ( name === 'index' ) {
  8308. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8309. this.setIndex( attribute );
  8310. return;
  8311. }
  8312. this.attributes[ name ] = attribute;
  8313. return this;
  8314. },
  8315. getAttribute: function ( name ) {
  8316. return this.attributes[ name ];
  8317. },
  8318. removeAttribute: function ( name ) {
  8319. delete this.attributes[ name ];
  8320. return this;
  8321. },
  8322. addGroup: function ( start, count, materialIndex ) {
  8323. this.groups.push( {
  8324. start: start,
  8325. count: count,
  8326. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8327. } );
  8328. },
  8329. clearGroups: function () {
  8330. this.groups = [];
  8331. },
  8332. setDrawRange: function ( start, count ) {
  8333. this.drawRange.start = start;
  8334. this.drawRange.count = count;
  8335. },
  8336. applyMatrix: function ( matrix ) {
  8337. var position = this.attributes.position;
  8338. if ( position !== undefined ) {
  8339. matrix.applyToBufferAttribute( position );
  8340. position.needsUpdate = true;
  8341. }
  8342. var normal = this.attributes.normal;
  8343. if ( normal !== undefined ) {
  8344. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8345. normalMatrix.applyToBufferAttribute( normal );
  8346. normal.needsUpdate = true;
  8347. }
  8348. if ( this.boundingBox !== null ) {
  8349. this.computeBoundingBox();
  8350. }
  8351. if ( this.boundingSphere !== null ) {
  8352. this.computeBoundingSphere();
  8353. }
  8354. return this;
  8355. },
  8356. rotateX: function () {
  8357. // rotate geometry around world x-axis
  8358. var m1 = new Matrix4();
  8359. return function rotateX( angle ) {
  8360. m1.makeRotationX( angle );
  8361. this.applyMatrix( m1 );
  8362. return this;
  8363. };
  8364. }(),
  8365. rotateY: function () {
  8366. // rotate geometry around world y-axis
  8367. var m1 = new Matrix4();
  8368. return function rotateY( angle ) {
  8369. m1.makeRotationY( angle );
  8370. this.applyMatrix( m1 );
  8371. return this;
  8372. };
  8373. }(),
  8374. rotateZ: function () {
  8375. // rotate geometry around world z-axis
  8376. var m1 = new Matrix4();
  8377. return function rotateZ( angle ) {
  8378. m1.makeRotationZ( angle );
  8379. this.applyMatrix( m1 );
  8380. return this;
  8381. };
  8382. }(),
  8383. translate: function () {
  8384. // translate geometry
  8385. var m1 = new Matrix4();
  8386. return function translate( x, y, z ) {
  8387. m1.makeTranslation( x, y, z );
  8388. this.applyMatrix( m1 );
  8389. return this;
  8390. };
  8391. }(),
  8392. scale: function () {
  8393. // scale geometry
  8394. var m1 = new Matrix4();
  8395. return function scale( x, y, z ) {
  8396. m1.makeScale( x, y, z );
  8397. this.applyMatrix( m1 );
  8398. return this;
  8399. };
  8400. }(),
  8401. lookAt: function () {
  8402. var obj = new Object3D();
  8403. return function lookAt( vector ) {
  8404. obj.lookAt( vector );
  8405. obj.updateMatrix();
  8406. this.applyMatrix( obj.matrix );
  8407. };
  8408. }(),
  8409. center: function () {
  8410. this.computeBoundingBox();
  8411. var offset = this.boundingBox.getCenter().negate();
  8412. this.translate( offset.x, offset.y, offset.z );
  8413. return offset;
  8414. },
  8415. setFromObject: function ( object ) {
  8416. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8417. var geometry = object.geometry;
  8418. if ( object.isPoints || object.isLine ) {
  8419. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8420. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8421. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8422. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8423. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8424. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8425. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8426. }
  8427. if ( geometry.boundingSphere !== null ) {
  8428. this.boundingSphere = geometry.boundingSphere.clone();
  8429. }
  8430. if ( geometry.boundingBox !== null ) {
  8431. this.boundingBox = geometry.boundingBox.clone();
  8432. }
  8433. } else if ( object.isMesh ) {
  8434. if ( geometry && geometry.isGeometry ) {
  8435. this.fromGeometry( geometry );
  8436. }
  8437. }
  8438. return this;
  8439. },
  8440. updateFromObject: function ( object ) {
  8441. var geometry = object.geometry;
  8442. if ( object.isMesh ) {
  8443. var direct = geometry.__directGeometry;
  8444. if ( geometry.elementsNeedUpdate === true ) {
  8445. direct = undefined;
  8446. geometry.elementsNeedUpdate = false;
  8447. }
  8448. if ( direct === undefined ) {
  8449. return this.fromGeometry( geometry );
  8450. }
  8451. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8452. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8453. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8454. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8455. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8456. geometry.verticesNeedUpdate = false;
  8457. geometry.normalsNeedUpdate = false;
  8458. geometry.colorsNeedUpdate = false;
  8459. geometry.uvsNeedUpdate = false;
  8460. geometry.groupsNeedUpdate = false;
  8461. geometry = direct;
  8462. }
  8463. var attribute;
  8464. if ( geometry.verticesNeedUpdate === true ) {
  8465. attribute = this.attributes.position;
  8466. if ( attribute !== undefined ) {
  8467. attribute.copyVector3sArray( geometry.vertices );
  8468. attribute.needsUpdate = true;
  8469. }
  8470. geometry.verticesNeedUpdate = false;
  8471. }
  8472. if ( geometry.normalsNeedUpdate === true ) {
  8473. attribute = this.attributes.normal;
  8474. if ( attribute !== undefined ) {
  8475. attribute.copyVector3sArray( geometry.normals );
  8476. attribute.needsUpdate = true;
  8477. }
  8478. geometry.normalsNeedUpdate = false;
  8479. }
  8480. if ( geometry.colorsNeedUpdate === true ) {
  8481. attribute = this.attributes.color;
  8482. if ( attribute !== undefined ) {
  8483. attribute.copyColorsArray( geometry.colors );
  8484. attribute.needsUpdate = true;
  8485. }
  8486. geometry.colorsNeedUpdate = false;
  8487. }
  8488. if ( geometry.uvsNeedUpdate ) {
  8489. attribute = this.attributes.uv;
  8490. if ( attribute !== undefined ) {
  8491. attribute.copyVector2sArray( geometry.uvs );
  8492. attribute.needsUpdate = true;
  8493. }
  8494. geometry.uvsNeedUpdate = false;
  8495. }
  8496. if ( geometry.lineDistancesNeedUpdate ) {
  8497. attribute = this.attributes.lineDistance;
  8498. if ( attribute !== undefined ) {
  8499. attribute.copyArray( geometry.lineDistances );
  8500. attribute.needsUpdate = true;
  8501. }
  8502. geometry.lineDistancesNeedUpdate = false;
  8503. }
  8504. if ( geometry.groupsNeedUpdate ) {
  8505. geometry.computeGroups( object.geometry );
  8506. this.groups = geometry.groups;
  8507. geometry.groupsNeedUpdate = false;
  8508. }
  8509. return this;
  8510. },
  8511. fromGeometry: function ( geometry ) {
  8512. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8513. return this.fromDirectGeometry( geometry.__directGeometry );
  8514. },
  8515. fromDirectGeometry: function ( geometry ) {
  8516. var positions = new Float32Array( geometry.vertices.length * 3 );
  8517. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8518. if ( geometry.normals.length > 0 ) {
  8519. var normals = new Float32Array( geometry.normals.length * 3 );
  8520. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8521. }
  8522. if ( geometry.colors.length > 0 ) {
  8523. var colors = new Float32Array( geometry.colors.length * 3 );
  8524. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8525. }
  8526. if ( geometry.uvs.length > 0 ) {
  8527. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8528. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8529. }
  8530. if ( geometry.uvs2.length > 0 ) {
  8531. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8532. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8533. }
  8534. if ( geometry.indices.length > 0 ) {
  8535. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  8536. var indices = new TypeArray( geometry.indices.length * 3 );
  8537. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8538. }
  8539. // groups
  8540. this.groups = geometry.groups;
  8541. // morphs
  8542. for ( var name in geometry.morphTargets ) {
  8543. var array = [];
  8544. var morphTargets = geometry.morphTargets[ name ];
  8545. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8546. var morphTarget = morphTargets[ i ];
  8547. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8548. array.push( attribute.copyVector3sArray( morphTarget ) );
  8549. }
  8550. this.morphAttributes[ name ] = array;
  8551. }
  8552. // skinning
  8553. if ( geometry.skinIndices.length > 0 ) {
  8554. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8555. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8556. }
  8557. if ( geometry.skinWeights.length > 0 ) {
  8558. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8559. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8560. }
  8561. //
  8562. if ( geometry.boundingSphere !== null ) {
  8563. this.boundingSphere = geometry.boundingSphere.clone();
  8564. }
  8565. if ( geometry.boundingBox !== null ) {
  8566. this.boundingBox = geometry.boundingBox.clone();
  8567. }
  8568. return this;
  8569. },
  8570. computeBoundingBox: function () {
  8571. if ( this.boundingBox === null ) {
  8572. this.boundingBox = new Box3();
  8573. }
  8574. var position = this.attributes.position;
  8575. if ( position !== undefined ) {
  8576. this.boundingBox.setFromBufferAttribute( position );
  8577. } else {
  8578. this.boundingBox.makeEmpty();
  8579. }
  8580. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8581. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8582. }
  8583. },
  8584. computeBoundingSphere: function () {
  8585. var box = new Box3();
  8586. var vector = new Vector3();
  8587. return function computeBoundingSphere() {
  8588. if ( this.boundingSphere === null ) {
  8589. this.boundingSphere = new Sphere();
  8590. }
  8591. var position = this.attributes.position;
  8592. if ( position ) {
  8593. var center = this.boundingSphere.center;
  8594. box.setFromBufferAttribute( position );
  8595. box.getCenter( center );
  8596. // hoping to find a boundingSphere with a radius smaller than the
  8597. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8598. var maxRadiusSq = 0;
  8599. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8600. vector.x = position.getX( i );
  8601. vector.y = position.getY( i );
  8602. vector.z = position.getZ( i );
  8603. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8604. }
  8605. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8606. if ( isNaN( this.boundingSphere.radius ) ) {
  8607. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8608. }
  8609. }
  8610. };
  8611. }(),
  8612. computeFaceNormals: function () {
  8613. // backwards compatibility
  8614. },
  8615. computeVertexNormals: function () {
  8616. var index = this.index;
  8617. var attributes = this.attributes;
  8618. var groups = this.groups;
  8619. if ( attributes.position ) {
  8620. var positions = attributes.position.array;
  8621. if ( attributes.normal === undefined ) {
  8622. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8623. } else {
  8624. // reset existing normals to zero
  8625. var array = attributes.normal.array;
  8626. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8627. array[ i ] = 0;
  8628. }
  8629. }
  8630. var normals = attributes.normal.array;
  8631. var vA, vB, vC;
  8632. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8633. var cb = new Vector3(), ab = new Vector3();
  8634. // indexed elements
  8635. if ( index ) {
  8636. var indices = index.array;
  8637. if ( groups.length === 0 ) {
  8638. this.addGroup( 0, indices.length );
  8639. }
  8640. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8641. var group = groups[ j ];
  8642. var start = group.start;
  8643. var count = group.count;
  8644. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8645. vA = indices[ i + 0 ] * 3;
  8646. vB = indices[ i + 1 ] * 3;
  8647. vC = indices[ i + 2 ] * 3;
  8648. pA.fromArray( positions, vA );
  8649. pB.fromArray( positions, vB );
  8650. pC.fromArray( positions, vC );
  8651. cb.subVectors( pC, pB );
  8652. ab.subVectors( pA, pB );
  8653. cb.cross( ab );
  8654. normals[ vA ] += cb.x;
  8655. normals[ vA + 1 ] += cb.y;
  8656. normals[ vA + 2 ] += cb.z;
  8657. normals[ vB ] += cb.x;
  8658. normals[ vB + 1 ] += cb.y;
  8659. normals[ vB + 2 ] += cb.z;
  8660. normals[ vC ] += cb.x;
  8661. normals[ vC + 1 ] += cb.y;
  8662. normals[ vC + 2 ] += cb.z;
  8663. }
  8664. }
  8665. } else {
  8666. // non-indexed elements (unconnected triangle soup)
  8667. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8668. pA.fromArray( positions, i );
  8669. pB.fromArray( positions, i + 3 );
  8670. pC.fromArray( positions, i + 6 );
  8671. cb.subVectors( pC, pB );
  8672. ab.subVectors( pA, pB );
  8673. cb.cross( ab );
  8674. normals[ i ] = cb.x;
  8675. normals[ i + 1 ] = cb.y;
  8676. normals[ i + 2 ] = cb.z;
  8677. normals[ i + 3 ] = cb.x;
  8678. normals[ i + 4 ] = cb.y;
  8679. normals[ i + 5 ] = cb.z;
  8680. normals[ i + 6 ] = cb.x;
  8681. normals[ i + 7 ] = cb.y;
  8682. normals[ i + 8 ] = cb.z;
  8683. }
  8684. }
  8685. this.normalizeNormals();
  8686. attributes.normal.needsUpdate = true;
  8687. }
  8688. },
  8689. merge: function ( geometry, offset ) {
  8690. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8691. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8692. return;
  8693. }
  8694. if ( offset === undefined ) offset = 0;
  8695. var attributes = this.attributes;
  8696. for ( var key in attributes ) {
  8697. if ( geometry.attributes[ key ] === undefined ) continue;
  8698. var attribute1 = attributes[ key ];
  8699. var attributeArray1 = attribute1.array;
  8700. var attribute2 = geometry.attributes[ key ];
  8701. var attributeArray2 = attribute2.array;
  8702. var attributeSize = attribute2.itemSize;
  8703. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8704. attributeArray1[ j ] = attributeArray2[ i ];
  8705. }
  8706. }
  8707. return this;
  8708. },
  8709. normalizeNormals: function () {
  8710. var normals = this.attributes.normal;
  8711. var x, y, z, n;
  8712. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  8713. x = normals.getX( i );
  8714. y = normals.getY( i );
  8715. z = normals.getZ( i );
  8716. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8717. normals.setXYZ( i, x * n, y * n, z * n );
  8718. }
  8719. },
  8720. toNonIndexed: function () {
  8721. if ( this.index === null ) {
  8722. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8723. return this;
  8724. }
  8725. var geometry2 = new BufferGeometry();
  8726. var indices = this.index.array;
  8727. var attributes = this.attributes;
  8728. for ( var name in attributes ) {
  8729. var attribute = attributes[ name ];
  8730. var array = attribute.array;
  8731. var itemSize = attribute.itemSize;
  8732. var array2 = new array.constructor( indices.length * itemSize );
  8733. var index = 0, index2 = 0;
  8734. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8735. index = indices[ i ] * itemSize;
  8736. for ( var j = 0; j < itemSize; j ++ ) {
  8737. array2[ index2 ++ ] = array[ index ++ ];
  8738. }
  8739. }
  8740. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8741. }
  8742. return geometry2;
  8743. },
  8744. toJSON: function () {
  8745. var data = {
  8746. metadata: {
  8747. version: 4.5,
  8748. type: 'BufferGeometry',
  8749. generator: 'BufferGeometry.toJSON'
  8750. }
  8751. };
  8752. // standard BufferGeometry serialization
  8753. data.uuid = this.uuid;
  8754. data.type = this.type;
  8755. if ( this.name !== '' ) data.name = this.name;
  8756. if ( this.parameters !== undefined ) {
  8757. var parameters = this.parameters;
  8758. for ( var key in parameters ) {
  8759. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8760. }
  8761. return data;
  8762. }
  8763. data.data = { attributes: {} };
  8764. var index = this.index;
  8765. if ( index !== null ) {
  8766. var array = Array.prototype.slice.call( index.array );
  8767. data.data.index = {
  8768. type: index.array.constructor.name,
  8769. array: array
  8770. };
  8771. }
  8772. var attributes = this.attributes;
  8773. for ( var key in attributes ) {
  8774. var attribute = attributes[ key ];
  8775. var array = Array.prototype.slice.call( attribute.array );
  8776. data.data.attributes[ key ] = {
  8777. itemSize: attribute.itemSize,
  8778. type: attribute.array.constructor.name,
  8779. array: array,
  8780. normalized: attribute.normalized
  8781. };
  8782. }
  8783. var groups = this.groups;
  8784. if ( groups.length > 0 ) {
  8785. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8786. }
  8787. var boundingSphere = this.boundingSphere;
  8788. if ( boundingSphere !== null ) {
  8789. data.data.boundingSphere = {
  8790. center: boundingSphere.center.toArray(),
  8791. radius: boundingSphere.radius
  8792. };
  8793. }
  8794. return data;
  8795. },
  8796. clone: function () {
  8797. /*
  8798. // Handle primitives
  8799. var parameters = this.parameters;
  8800. if ( parameters !== undefined ) {
  8801. var values = [];
  8802. for ( var key in parameters ) {
  8803. values.push( parameters[ key ] );
  8804. }
  8805. var geometry = Object.create( this.constructor.prototype );
  8806. this.constructor.apply( geometry, values );
  8807. return geometry;
  8808. }
  8809. return new this.constructor().copy( this );
  8810. */
  8811. return new BufferGeometry().copy( this );
  8812. },
  8813. copy: function ( source ) {
  8814. var name, i, l;
  8815. // reset
  8816. this.index = null;
  8817. this.attributes = {};
  8818. this.morphAttributes = {};
  8819. this.groups = [];
  8820. this.boundingBox = null;
  8821. this.boundingSphere = null;
  8822. // name
  8823. this.name = source.name;
  8824. // index
  8825. var index = source.index;
  8826. if ( index !== null ) {
  8827. this.setIndex( index.clone() );
  8828. }
  8829. // attributes
  8830. var attributes = source.attributes;
  8831. for ( name in attributes ) {
  8832. var attribute = attributes[ name ];
  8833. this.addAttribute( name, attribute.clone() );
  8834. }
  8835. // morph attributes
  8836. var morphAttributes = source.morphAttributes;
  8837. for ( name in morphAttributes ) {
  8838. var array = [];
  8839. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8840. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8841. array.push( morphAttribute[ i ].clone() );
  8842. }
  8843. this.morphAttributes[ name ] = array;
  8844. }
  8845. // groups
  8846. var groups = source.groups;
  8847. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8848. var group = groups[ i ];
  8849. this.addGroup( group.start, group.count, group.materialIndex );
  8850. }
  8851. // bounding box
  8852. var boundingBox = source.boundingBox;
  8853. if ( boundingBox !== null ) {
  8854. this.boundingBox = boundingBox.clone();
  8855. }
  8856. // bounding sphere
  8857. var boundingSphere = source.boundingSphere;
  8858. if ( boundingSphere !== null ) {
  8859. this.boundingSphere = boundingSphere.clone();
  8860. }
  8861. // draw range
  8862. this.drawRange.start = source.drawRange.start;
  8863. this.drawRange.count = source.drawRange.count;
  8864. return this;
  8865. },
  8866. dispose: function () {
  8867. this.dispatchEvent( { type: 'dispose' } );
  8868. }
  8869. } );
  8870. /**
  8871. * @author mrdoob / http://mrdoob.com/
  8872. * @author alteredq / http://alteredqualia.com/
  8873. * @author mikael emtinger / http://gomo.se/
  8874. * @author jonobr1 / http://jonobr1.com/
  8875. */
  8876. function Mesh( geometry, material ) {
  8877. Object3D.call( this );
  8878. this.type = 'Mesh';
  8879. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8880. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8881. this.drawMode = TrianglesDrawMode;
  8882. this.updateMorphTargets();
  8883. }
  8884. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8885. constructor: Mesh,
  8886. isMesh: true,
  8887. setDrawMode: function ( value ) {
  8888. this.drawMode = value;
  8889. },
  8890. copy: function ( source ) {
  8891. Object3D.prototype.copy.call( this, source );
  8892. this.drawMode = source.drawMode;
  8893. return this;
  8894. },
  8895. updateMorphTargets: function () {
  8896. var morphTargets = this.geometry.morphTargets;
  8897. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8898. this.morphTargetInfluences = [];
  8899. this.morphTargetDictionary = {};
  8900. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8901. this.morphTargetInfluences.push( 0 );
  8902. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8903. }
  8904. }
  8905. },
  8906. raycast: ( function () {
  8907. var inverseMatrix = new Matrix4();
  8908. var ray = new Ray();
  8909. var sphere = new Sphere();
  8910. var vA = new Vector3();
  8911. var vB = new Vector3();
  8912. var vC = new Vector3();
  8913. var tempA = new Vector3();
  8914. var tempB = new Vector3();
  8915. var tempC = new Vector3();
  8916. var uvA = new Vector2();
  8917. var uvB = new Vector2();
  8918. var uvC = new Vector2();
  8919. var barycoord = new Vector3();
  8920. var intersectionPoint = new Vector3();
  8921. var intersectionPointWorld = new Vector3();
  8922. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8923. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8924. uv1.multiplyScalar( barycoord.x );
  8925. uv2.multiplyScalar( barycoord.y );
  8926. uv3.multiplyScalar( barycoord.z );
  8927. uv1.add( uv2 ).add( uv3 );
  8928. return uv1.clone();
  8929. }
  8930. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8931. var intersect;
  8932. var material = object.material;
  8933. if ( material.side === BackSide ) {
  8934. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8935. } else {
  8936. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8937. }
  8938. if ( intersect === null ) return null;
  8939. intersectionPointWorld.copy( point );
  8940. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8941. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8942. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8943. return {
  8944. distance: distance,
  8945. point: intersectionPointWorld.clone(),
  8946. object: object
  8947. };
  8948. }
  8949. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  8950. vA.fromBufferAttribute( position, a );
  8951. vB.fromBufferAttribute( position, b );
  8952. vC.fromBufferAttribute( position, c );
  8953. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8954. if ( intersection ) {
  8955. if ( uv ) {
  8956. uvA.fromBufferAttribute( uv, a );
  8957. uvB.fromBufferAttribute( uv, b );
  8958. uvC.fromBufferAttribute( uv, c );
  8959. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8960. }
  8961. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8962. intersection.faceIndex = a;
  8963. }
  8964. return intersection;
  8965. }
  8966. return function raycast( raycaster, intersects ) {
  8967. var geometry = this.geometry;
  8968. var material = this.material;
  8969. var matrixWorld = this.matrixWorld;
  8970. if ( material === undefined ) return;
  8971. // Checking boundingSphere distance to ray
  8972. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8973. sphere.copy( geometry.boundingSphere );
  8974. sphere.applyMatrix4( matrixWorld );
  8975. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8976. //
  8977. inverseMatrix.getInverse( matrixWorld );
  8978. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8979. // Check boundingBox before continuing
  8980. if ( geometry.boundingBox !== null ) {
  8981. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8982. }
  8983. var intersection;
  8984. if ( geometry.isBufferGeometry ) {
  8985. var a, b, c;
  8986. var index = geometry.index;
  8987. var position = geometry.attributes.position;
  8988. var uv = geometry.attributes.uv;
  8989. var i, l;
  8990. if ( index !== null ) {
  8991. // indexed buffer geometry
  8992. for ( i = 0, l = index.count; i < l; i += 3 ) {
  8993. a = index.getX( i );
  8994. b = index.getX( i + 1 );
  8995. c = index.getX( i + 2 );
  8996. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  8997. if ( intersection ) {
  8998. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8999. intersects.push( intersection );
  9000. }
  9001. }
  9002. } else {
  9003. // non-indexed buffer geometry
  9004. for ( i = 0, l = position.count; i < l; i += 3 ) {
  9005. a = i;
  9006. b = i + 1;
  9007. c = i + 2;
  9008. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  9009. if ( intersection ) {
  9010. intersection.index = a; // triangle number in positions buffer semantics
  9011. intersects.push( intersection );
  9012. }
  9013. }
  9014. }
  9015. } else if ( geometry.isGeometry ) {
  9016. var fvA, fvB, fvC;
  9017. var isMultiMaterial = Array.isArray( material );
  9018. var vertices = geometry.vertices;
  9019. var faces = geometry.faces;
  9020. var uvs;
  9021. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  9022. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  9023. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9024. var face = faces[ f ];
  9025. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  9026. if ( faceMaterial === undefined ) continue;
  9027. fvA = vertices[ face.a ];
  9028. fvB = vertices[ face.b ];
  9029. fvC = vertices[ face.c ];
  9030. if ( faceMaterial.morphTargets === true ) {
  9031. var morphTargets = geometry.morphTargets;
  9032. var morphInfluences = this.morphTargetInfluences;
  9033. vA.set( 0, 0, 0 );
  9034. vB.set( 0, 0, 0 );
  9035. vC.set( 0, 0, 0 );
  9036. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9037. var influence = morphInfluences[ t ];
  9038. if ( influence === 0 ) continue;
  9039. var targets = morphTargets[ t ].vertices;
  9040. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  9041. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  9042. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  9043. }
  9044. vA.add( fvA );
  9045. vB.add( fvB );
  9046. vC.add( fvC );
  9047. fvA = vA;
  9048. fvB = vB;
  9049. fvC = vC;
  9050. }
  9051. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  9052. if ( intersection ) {
  9053. if ( uvs && uvs[ f ] ) {
  9054. var uvs_f = uvs[ f ];
  9055. uvA.copy( uvs_f[ 0 ] );
  9056. uvB.copy( uvs_f[ 1 ] );
  9057. uvC.copy( uvs_f[ 2 ] );
  9058. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  9059. }
  9060. intersection.face = face;
  9061. intersection.faceIndex = f;
  9062. intersects.push( intersection );
  9063. }
  9064. }
  9065. }
  9066. };
  9067. }() ),
  9068. clone: function () {
  9069. return new this.constructor( this.geometry, this.material ).copy( this );
  9070. }
  9071. } );
  9072. /**
  9073. * @author mrdoob / http://mrdoob.com/
  9074. * @author Mugen87 / https://github.com/Mugen87
  9075. *
  9076. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  9077. */
  9078. // BoxGeometry
  9079. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9080. Geometry.call( this );
  9081. this.type = 'BoxGeometry';
  9082. this.parameters = {
  9083. width: width,
  9084. height: height,
  9085. depth: depth,
  9086. widthSegments: widthSegments,
  9087. heightSegments: heightSegments,
  9088. depthSegments: depthSegments
  9089. };
  9090. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  9091. this.mergeVertices();
  9092. }
  9093. BoxGeometry.prototype = Object.create( Geometry.prototype );
  9094. BoxGeometry.prototype.constructor = BoxGeometry;
  9095. // BoxBufferGeometry
  9096. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  9097. BufferGeometry.call( this );
  9098. this.type = 'BoxBufferGeometry';
  9099. this.parameters = {
  9100. width: width,
  9101. height: height,
  9102. depth: depth,
  9103. widthSegments: widthSegments,
  9104. heightSegments: heightSegments,
  9105. depthSegments: depthSegments
  9106. };
  9107. var scope = this;
  9108. // segments
  9109. widthSegments = Math.floor( widthSegments ) || 1;
  9110. heightSegments = Math.floor( heightSegments ) || 1;
  9111. depthSegments = Math.floor( depthSegments ) || 1;
  9112. // buffers
  9113. var indices = [];
  9114. var vertices = [];
  9115. var normals = [];
  9116. var uvs = [];
  9117. // helper variables
  9118. var numberOfVertices = 0;
  9119. var groupStart = 0;
  9120. // build each side of the box geometry
  9121. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  9122. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9123. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9124. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9125. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9126. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9127. // build geometry
  9128. this.setIndex( indices );
  9129. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  9130. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  9131. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  9132. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9133. var segmentWidth = width / gridX;
  9134. var segmentHeight = height / gridY;
  9135. var widthHalf = width / 2;
  9136. var heightHalf = height / 2;
  9137. var depthHalf = depth / 2;
  9138. var gridX1 = gridX + 1;
  9139. var gridY1 = gridY + 1;
  9140. var vertexCounter = 0;
  9141. var groupCount = 0;
  9142. var ix, iy;
  9143. var vector = new Vector3();
  9144. // generate vertices, normals and uvs
  9145. for ( iy = 0; iy < gridY1; iy ++ ) {
  9146. var y = iy * segmentHeight - heightHalf;
  9147. for ( ix = 0; ix < gridX1; ix ++ ) {
  9148. var x = ix * segmentWidth - widthHalf;
  9149. // set values to correct vector component
  9150. vector[ u ] = x * udir;
  9151. vector[ v ] = y * vdir;
  9152. vector[ w ] = depthHalf;
  9153. // now apply vector to vertex buffer
  9154. vertices.push( vector.x, vector.y, vector.z );
  9155. // set values to correct vector component
  9156. vector[ u ] = 0;
  9157. vector[ v ] = 0;
  9158. vector[ w ] = depth > 0 ? 1 : - 1;
  9159. // now apply vector to normal buffer
  9160. normals.push( vector.x, vector.y, vector.z );
  9161. // uvs
  9162. uvs.push( ix / gridX );
  9163. uvs.push( 1 - ( iy / gridY ) );
  9164. // counters
  9165. vertexCounter += 1;
  9166. }
  9167. }
  9168. // indices
  9169. // 1. you need three indices to draw a single face
  9170. // 2. a single segment consists of two faces
  9171. // 3. so we need to generate six (2*3) indices per segment
  9172. for ( iy = 0; iy < gridY; iy ++ ) {
  9173. for ( ix = 0; ix < gridX; ix ++ ) {
  9174. var a = numberOfVertices + ix + gridX1 * iy;
  9175. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9176. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9177. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9178. // faces
  9179. indices.push( a, b, d );
  9180. indices.push( b, c, d );
  9181. // increase counter
  9182. groupCount += 6;
  9183. }
  9184. }
  9185. // add a group to the geometry. this will ensure multi material support
  9186. scope.addGroup( groupStart, groupCount, materialIndex );
  9187. // calculate new start value for groups
  9188. groupStart += groupCount;
  9189. // update total number of vertices
  9190. numberOfVertices += vertexCounter;
  9191. }
  9192. }
  9193. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9194. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9195. /**
  9196. * @author mrdoob / http://mrdoob.com/
  9197. * @author Mugen87 / https://github.com/Mugen87
  9198. *
  9199. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9200. */
  9201. // PlaneGeometry
  9202. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  9203. Geometry.call( this );
  9204. this.type = 'PlaneGeometry';
  9205. this.parameters = {
  9206. width: width,
  9207. height: height,
  9208. widthSegments: widthSegments,
  9209. heightSegments: heightSegments
  9210. };
  9211. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  9212. this.mergeVertices();
  9213. }
  9214. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  9215. PlaneGeometry.prototype.constructor = PlaneGeometry;
  9216. // PlaneBufferGeometry
  9217. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9218. BufferGeometry.call( this );
  9219. this.type = 'PlaneBufferGeometry';
  9220. this.parameters = {
  9221. width: width,
  9222. height: height,
  9223. widthSegments: widthSegments,
  9224. heightSegments: heightSegments
  9225. };
  9226. var width_half = width / 2;
  9227. var height_half = height / 2;
  9228. var gridX = Math.floor( widthSegments ) || 1;
  9229. var gridY = Math.floor( heightSegments ) || 1;
  9230. var gridX1 = gridX + 1;
  9231. var gridY1 = gridY + 1;
  9232. var segment_width = width / gridX;
  9233. var segment_height = height / gridY;
  9234. var ix, iy;
  9235. // buffers
  9236. var indices = [];
  9237. var vertices = [];
  9238. var normals = [];
  9239. var uvs = [];
  9240. // generate vertices, normals and uvs
  9241. for ( iy = 0; iy < gridY1; iy ++ ) {
  9242. var y = iy * segment_height - height_half;
  9243. for ( ix = 0; ix < gridX1; ix ++ ) {
  9244. var x = ix * segment_width - width_half;
  9245. vertices.push( x, - y, 0 );
  9246. normals.push( 0, 0, 1 );
  9247. uvs.push( ix / gridX );
  9248. uvs.push( 1 - ( iy / gridY ) );
  9249. }
  9250. }
  9251. // indices
  9252. for ( iy = 0; iy < gridY; iy ++ ) {
  9253. for ( ix = 0; ix < gridX; ix ++ ) {
  9254. var a = ix + gridX1 * iy;
  9255. var b = ix + gridX1 * ( iy + 1 );
  9256. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9257. var d = ( ix + 1 ) + gridX1 * iy;
  9258. // faces
  9259. indices.push( a, b, d );
  9260. indices.push( b, c, d );
  9261. }
  9262. }
  9263. // build geometry
  9264. this.setIndex( indices );
  9265. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  9266. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  9267. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  9268. }
  9269. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9270. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9271. /**
  9272. * @author mrdoob / http://mrdoob.com/
  9273. * @author mikael emtinger / http://gomo.se/
  9274. * @author WestLangley / http://github.com/WestLangley
  9275. */
  9276. function Camera() {
  9277. Object3D.call( this );
  9278. this.type = 'Camera';
  9279. this.matrixWorldInverse = new Matrix4();
  9280. this.projectionMatrix = new Matrix4();
  9281. }
  9282. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9283. constructor: Camera,
  9284. isCamera: true,
  9285. copy: function ( source ) {
  9286. Object3D.prototype.copy.call( this, source );
  9287. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9288. this.projectionMatrix.copy( source.projectionMatrix );
  9289. return this;
  9290. },
  9291. getWorldDirection: function () {
  9292. var quaternion = new Quaternion();
  9293. return function getWorldDirection( optionalTarget ) {
  9294. var result = optionalTarget || new Vector3();
  9295. this.getWorldQuaternion( quaternion );
  9296. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9297. };
  9298. }(),
  9299. clone: function () {
  9300. return new this.constructor().copy( this );
  9301. }
  9302. } );
  9303. /**
  9304. * @author mrdoob / http://mrdoob.com/
  9305. * @author greggman / http://games.greggman.com/
  9306. * @author zz85 / http://www.lab4games.net/zz85/blog
  9307. * @author tschw
  9308. */
  9309. function PerspectiveCamera( fov, aspect, near, far ) {
  9310. Camera.call( this );
  9311. this.type = 'PerspectiveCamera';
  9312. this.fov = fov !== undefined ? fov : 50;
  9313. this.zoom = 1;
  9314. this.near = near !== undefined ? near : 0.1;
  9315. this.far = far !== undefined ? far : 2000;
  9316. this.focus = 10;
  9317. this.aspect = aspect !== undefined ? aspect : 1;
  9318. this.view = null;
  9319. this.filmGauge = 35; // width of the film (default in millimeters)
  9320. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9321. this.updateProjectionMatrix();
  9322. }
  9323. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9324. constructor: PerspectiveCamera,
  9325. isPerspectiveCamera: true,
  9326. copy: function ( source ) {
  9327. Camera.prototype.copy.call( this, source );
  9328. this.fov = source.fov;
  9329. this.zoom = source.zoom;
  9330. this.near = source.near;
  9331. this.far = source.far;
  9332. this.focus = source.focus;
  9333. this.aspect = source.aspect;
  9334. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9335. this.filmGauge = source.filmGauge;
  9336. this.filmOffset = source.filmOffset;
  9337. return this;
  9338. },
  9339. /**
  9340. * Sets the FOV by focal length in respect to the current .filmGauge.
  9341. *
  9342. * The default film gauge is 35, so that the focal length can be specified for
  9343. * a 35mm (full frame) camera.
  9344. *
  9345. * Values for focal length and film gauge must have the same unit.
  9346. */
  9347. setFocalLength: function ( focalLength ) {
  9348. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9349. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9350. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9351. this.updateProjectionMatrix();
  9352. },
  9353. /**
  9354. * Calculates the focal length from the current .fov and .filmGauge.
  9355. */
  9356. getFocalLength: function () {
  9357. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9358. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9359. },
  9360. getEffectiveFOV: function () {
  9361. return _Math.RAD2DEG * 2 * Math.atan(
  9362. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9363. },
  9364. getFilmWidth: function () {
  9365. // film not completely covered in portrait format (aspect < 1)
  9366. return this.filmGauge * Math.min( this.aspect, 1 );
  9367. },
  9368. getFilmHeight: function () {
  9369. // film not completely covered in landscape format (aspect > 1)
  9370. return this.filmGauge / Math.max( this.aspect, 1 );
  9371. },
  9372. /**
  9373. * Sets an offset in a larger frustum. This is useful for multi-window or
  9374. * multi-monitor/multi-machine setups.
  9375. *
  9376. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9377. * the monitors are in grid like this
  9378. *
  9379. * +---+---+---+
  9380. * | A | B | C |
  9381. * +---+---+---+
  9382. * | D | E | F |
  9383. * +---+---+---+
  9384. *
  9385. * then for each monitor you would call it like this
  9386. *
  9387. * var w = 1920;
  9388. * var h = 1080;
  9389. * var fullWidth = w * 3;
  9390. * var fullHeight = h * 2;
  9391. *
  9392. * --A--
  9393. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9394. * --B--
  9395. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9396. * --C--
  9397. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9398. * --D--
  9399. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9400. * --E--
  9401. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9402. * --F--
  9403. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9404. *
  9405. * Note there is no reason monitors have to be the same size or in a grid.
  9406. */
  9407. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9408. this.aspect = fullWidth / fullHeight;
  9409. this.view = {
  9410. fullWidth: fullWidth,
  9411. fullHeight: fullHeight,
  9412. offsetX: x,
  9413. offsetY: y,
  9414. width: width,
  9415. height: height
  9416. };
  9417. this.updateProjectionMatrix();
  9418. },
  9419. clearViewOffset: function () {
  9420. this.view = null;
  9421. this.updateProjectionMatrix();
  9422. },
  9423. updateProjectionMatrix: function () {
  9424. var near = this.near,
  9425. top = near * Math.tan(
  9426. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9427. height = 2 * top,
  9428. width = this.aspect * height,
  9429. left = - 0.5 * width,
  9430. view = this.view;
  9431. if ( view !== null ) {
  9432. var fullWidth = view.fullWidth,
  9433. fullHeight = view.fullHeight;
  9434. left += view.offsetX * width / fullWidth;
  9435. top -= view.offsetY * height / fullHeight;
  9436. width *= view.width / fullWidth;
  9437. height *= view.height / fullHeight;
  9438. }
  9439. var skew = this.filmOffset;
  9440. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9441. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  9442. },
  9443. toJSON: function ( meta ) {
  9444. var data = Object3D.prototype.toJSON.call( this, meta );
  9445. data.object.fov = this.fov;
  9446. data.object.zoom = this.zoom;
  9447. data.object.near = this.near;
  9448. data.object.far = this.far;
  9449. data.object.focus = this.focus;
  9450. data.object.aspect = this.aspect;
  9451. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9452. data.object.filmGauge = this.filmGauge;
  9453. data.object.filmOffset = this.filmOffset;
  9454. return data;
  9455. }
  9456. } );
  9457. /**
  9458. * @author alteredq / http://alteredqualia.com/
  9459. * @author arose / http://github.com/arose
  9460. */
  9461. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9462. Camera.call( this );
  9463. this.type = 'OrthographicCamera';
  9464. this.zoom = 1;
  9465. this.view = null;
  9466. this.left = left;
  9467. this.right = right;
  9468. this.top = top;
  9469. this.bottom = bottom;
  9470. this.near = ( near !== undefined ) ? near : 0.1;
  9471. this.far = ( far !== undefined ) ? far : 2000;
  9472. this.updateProjectionMatrix();
  9473. }
  9474. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9475. constructor: OrthographicCamera,
  9476. isOrthographicCamera: true,
  9477. copy: function ( source ) {
  9478. Camera.prototype.copy.call( this, source );
  9479. this.left = source.left;
  9480. this.right = source.right;
  9481. this.top = source.top;
  9482. this.bottom = source.bottom;
  9483. this.near = source.near;
  9484. this.far = source.far;
  9485. this.zoom = source.zoom;
  9486. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9487. return this;
  9488. },
  9489. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9490. this.view = {
  9491. fullWidth: fullWidth,
  9492. fullHeight: fullHeight,
  9493. offsetX: x,
  9494. offsetY: y,
  9495. width: width,
  9496. height: height
  9497. };
  9498. this.updateProjectionMatrix();
  9499. },
  9500. clearViewOffset: function() {
  9501. this.view = null;
  9502. this.updateProjectionMatrix();
  9503. },
  9504. updateProjectionMatrix: function () {
  9505. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9506. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9507. var cx = ( this.right + this.left ) / 2;
  9508. var cy = ( this.top + this.bottom ) / 2;
  9509. var left = cx - dx;
  9510. var right = cx + dx;
  9511. var top = cy + dy;
  9512. var bottom = cy - dy;
  9513. if ( this.view !== null ) {
  9514. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9515. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9516. var scaleW = ( this.right - this.left ) / this.view.width;
  9517. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9518. left += scaleW * ( this.view.offsetX / zoomW );
  9519. right = left + scaleW * ( this.view.width / zoomW );
  9520. top -= scaleH * ( this.view.offsetY / zoomH );
  9521. bottom = top - scaleH * ( this.view.height / zoomH );
  9522. }
  9523. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9524. },
  9525. toJSON: function ( meta ) {
  9526. var data = Object3D.prototype.toJSON.call( this, meta );
  9527. data.object.zoom = this.zoom;
  9528. data.object.left = this.left;
  9529. data.object.right = this.right;
  9530. data.object.top = this.top;
  9531. data.object.bottom = this.bottom;
  9532. data.object.near = this.near;
  9533. data.object.far = this.far;
  9534. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9535. return data;
  9536. }
  9537. } );
  9538. /**
  9539. * @author mrdoob / http://mrdoob.com/
  9540. */
  9541. function WebGLAttributes( gl ) {
  9542. var buffers = {};
  9543. function createBuffer( attribute, bufferType ) {
  9544. var array = attribute.array;
  9545. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  9546. var buffer = gl.createBuffer();
  9547. gl.bindBuffer( bufferType, buffer );
  9548. gl.bufferData( bufferType, array, usage );
  9549. attribute.onUploadCallback();
  9550. var type = gl.FLOAT;
  9551. if ( array instanceof Float32Array ) {
  9552. type = gl.FLOAT;
  9553. } else if ( array instanceof Float64Array ) {
  9554. console.warn( "Unsupported data buffer format: Float64Array" );
  9555. } else if ( array instanceof Uint16Array ) {
  9556. type = gl.UNSIGNED_SHORT;
  9557. } else if ( array instanceof Int16Array ) {
  9558. type = gl.SHORT;
  9559. } else if ( array instanceof Uint32Array ) {
  9560. type = gl.UNSIGNED_INT;
  9561. } else if ( array instanceof Int32Array ) {
  9562. type = gl.INT;
  9563. } else if ( array instanceof Int8Array ) {
  9564. type = gl.BYTE;
  9565. } else if ( array instanceof Uint8Array ) {
  9566. type = gl.UNSIGNED_BYTE;
  9567. }
  9568. return {
  9569. buffer: buffer,
  9570. type: type,
  9571. bytesPerElement: array.BYTES_PER_ELEMENT,
  9572. version: attribute.version
  9573. };
  9574. }
  9575. function updateBuffer( buffer, attribute, bufferType ) {
  9576. var array = attribute.array;
  9577. var updateRange = attribute.updateRange;
  9578. gl.bindBuffer( bufferType, buffer );
  9579. if ( attribute.dynamic === false ) {
  9580. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  9581. } else if ( updateRange.count === - 1 ) {
  9582. // Not using update ranges
  9583. gl.bufferSubData( bufferType, 0, array );
  9584. } else if ( updateRange.count === 0 ) {
  9585. 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.' );
  9586. } else {
  9587. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  9588. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  9589. updateRange.count = 0; // reset range
  9590. }
  9591. }
  9592. //
  9593. function get( attribute ) {
  9594. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9595. return buffers[ attribute.uuid ];
  9596. }
  9597. function remove( attribute ) {
  9598. var data = buffers[ attribute.uuid ];
  9599. if ( data ) {
  9600. gl.deleteBuffer( data.buffer );
  9601. delete buffers[ attribute.uuid ];
  9602. }
  9603. }
  9604. function update( attribute, bufferType ) {
  9605. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9606. var data = buffers[ attribute.uuid ];
  9607. if ( data === undefined ) {
  9608. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  9609. } else if ( data.version < attribute.version ) {
  9610. updateBuffer( data.buffer, attribute, bufferType );
  9611. data.version = attribute.version;
  9612. }
  9613. }
  9614. return {
  9615. get: get,
  9616. remove: remove,
  9617. update: update
  9618. };
  9619. }
  9620. /**
  9621. * @author mrdoob / http://mrdoob.com/
  9622. */
  9623. function painterSortStable( a, b ) {
  9624. if ( a.renderOrder !== b.renderOrder ) {
  9625. return a.renderOrder - b.renderOrder;
  9626. } else if ( a.program && b.program && a.program !== b.program ) {
  9627. return a.program.id - b.program.id;
  9628. } else if ( a.material.id !== b.material.id ) {
  9629. return a.material.id - b.material.id;
  9630. } else if ( a.z !== b.z ) {
  9631. return a.z - b.z;
  9632. } else {
  9633. return a.id - b.id;
  9634. }
  9635. }
  9636. function reversePainterSortStable( a, b ) {
  9637. if ( a.renderOrder !== b.renderOrder ) {
  9638. return a.renderOrder - b.renderOrder;
  9639. } if ( a.z !== b.z ) {
  9640. return b.z - a.z;
  9641. } else {
  9642. return a.id - b.id;
  9643. }
  9644. }
  9645. function WebGLRenderList() {
  9646. var opaque = [];
  9647. var opaqueLastIndex = - 1;
  9648. var transparent = [];
  9649. var transparentLastIndex = - 1;
  9650. function init() {
  9651. opaqueLastIndex = - 1;
  9652. transparentLastIndex = - 1;
  9653. }
  9654. function push( object, geometry, material, z, group ) {
  9655. var array, index;
  9656. // allocate the next position in the appropriate array
  9657. if ( material.transparent ) {
  9658. array = transparent;
  9659. index = ++ transparentLastIndex;
  9660. } else {
  9661. array = opaque;
  9662. index = ++ opaqueLastIndex;
  9663. }
  9664. // recycle existing render item or grow the array
  9665. var renderItem = array[ index ];
  9666. if ( renderItem ) {
  9667. renderItem.id = object.id;
  9668. renderItem.object = object;
  9669. renderItem.geometry = geometry;
  9670. renderItem.material = material;
  9671. renderItem.program = material.program;
  9672. renderItem.renderOrder = object.renderOrder;
  9673. renderItem.z = z;
  9674. renderItem.group = group;
  9675. } else {
  9676. renderItem = {
  9677. id: object.id,
  9678. object: object,
  9679. geometry: geometry,
  9680. material: material,
  9681. program: material.program,
  9682. renderOrder: object.renderOrder,
  9683. z: z,
  9684. group: group
  9685. };
  9686. // assert( index === array.length );
  9687. array.push( renderItem );
  9688. }
  9689. }
  9690. function finish() {
  9691. opaque.length = opaqueLastIndex + 1;
  9692. transparent.length = transparentLastIndex + 1;
  9693. }
  9694. function sort() {
  9695. opaque.sort( painterSortStable );
  9696. transparent.sort( reversePainterSortStable );
  9697. }
  9698. return {
  9699. opaque: opaque,
  9700. transparent: transparent,
  9701. init: init,
  9702. push: push,
  9703. finish: finish,
  9704. sort: sort
  9705. };
  9706. }
  9707. function WebGLRenderLists() {
  9708. var lists = {};
  9709. function get( scene, camera ) {
  9710. var hash = scene.id + ',' + camera.id;
  9711. var list = lists[ hash ];
  9712. if ( list === undefined ) {
  9713. // console.log( 'THREE.WebGLRenderLists:', hash );
  9714. list = new WebGLRenderList();
  9715. lists[ hash ] = list;
  9716. }
  9717. return list;
  9718. }
  9719. function dispose() {
  9720. lists = {};
  9721. }
  9722. return {
  9723. get: get,
  9724. dispose: dispose
  9725. };
  9726. }
  9727. /**
  9728. * @author mrdoob / http://mrdoob.com/
  9729. */
  9730. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9731. var mode;
  9732. function setMode( value ) {
  9733. mode = value;
  9734. }
  9735. var type, size;
  9736. function setIndex( index ) {
  9737. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9738. type = gl.UNSIGNED_INT;
  9739. size = 4;
  9740. } else if ( index.array instanceof Uint16Array ) {
  9741. type = gl.UNSIGNED_SHORT;
  9742. size = 2;
  9743. } else {
  9744. type = gl.UNSIGNED_BYTE;
  9745. size = 1;
  9746. }
  9747. }
  9748. function render( start, count ) {
  9749. gl.drawElements( mode, count, type, start * size );
  9750. infoRender.calls ++;
  9751. infoRender.vertices += count;
  9752. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9753. }
  9754. function renderInstances( geometry, start, count ) {
  9755. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9756. if ( extension === null ) {
  9757. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9758. return;
  9759. }
  9760. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9761. infoRender.calls ++;
  9762. infoRender.vertices += count * geometry.maxInstancedCount;
  9763. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9764. }
  9765. //
  9766. this.setMode = setMode;
  9767. this.setIndex = setIndex;
  9768. this.render = render;
  9769. this.renderInstances = renderInstances;
  9770. }
  9771. /**
  9772. * @author mrdoob / http://mrdoob.com/
  9773. */
  9774. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9775. var mode;
  9776. function setMode( value ) {
  9777. mode = value;
  9778. }
  9779. function render( start, count ) {
  9780. gl.drawArrays( mode, start, count );
  9781. infoRender.calls ++;
  9782. infoRender.vertices += count;
  9783. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9784. }
  9785. function renderInstances( geometry, start, count ) {
  9786. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9787. if ( extension === null ) {
  9788. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9789. return;
  9790. }
  9791. var position = geometry.attributes.position;
  9792. if ( position.isInterleavedBufferAttribute ) {
  9793. count = position.data.count;
  9794. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9795. } else {
  9796. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  9797. }
  9798. infoRender.calls ++;
  9799. infoRender.vertices += count * geometry.maxInstancedCount;
  9800. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9801. }
  9802. //
  9803. this.setMode = setMode;
  9804. this.render = render;
  9805. this.renderInstances = renderInstances;
  9806. }
  9807. /**
  9808. * @author mrdoob / http://mrdoob.com/
  9809. */
  9810. function WebGLGeometries( gl, attributes, infoMemory ) {
  9811. var geometries = {};
  9812. var wireframeAttributes = {};
  9813. function onGeometryDispose( event ) {
  9814. var geometry = event.target;
  9815. var buffergeometry = geometries[ geometry.id ];
  9816. if ( buffergeometry.index !== null ) {
  9817. attributes.remove( buffergeometry.index );
  9818. }
  9819. for ( var name in buffergeometry.attributes ) {
  9820. attributes.remove( buffergeometry.attributes[ name ] );
  9821. }
  9822. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9823. delete geometries[ geometry.id ];
  9824. // TODO Remove duplicate code
  9825. var attribute = wireframeAttributes[ geometry.id ];
  9826. if ( attribute ) {
  9827. attributes.remove( attribute );
  9828. delete wireframeAttributes[ geometry.id ];
  9829. }
  9830. attribute = wireframeAttributes[ buffergeometry.id ];
  9831. if ( attribute ) {
  9832. attributes.remove( attribute );
  9833. delete wireframeAttributes[ buffergeometry.id ];
  9834. }
  9835. //
  9836. infoMemory.geometries --;
  9837. }
  9838. function get( object, geometry ) {
  9839. var buffergeometry = geometries[ geometry.id ];
  9840. if ( buffergeometry ) return buffergeometry;
  9841. geometry.addEventListener( 'dispose', onGeometryDispose );
  9842. if ( geometry.isBufferGeometry ) {
  9843. buffergeometry = geometry;
  9844. } else if ( geometry.isGeometry ) {
  9845. if ( geometry._bufferGeometry === undefined ) {
  9846. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9847. }
  9848. buffergeometry = geometry._bufferGeometry;
  9849. }
  9850. geometries[ geometry.id ] = buffergeometry;
  9851. infoMemory.geometries ++;
  9852. return buffergeometry;
  9853. }
  9854. function update( geometry ) {
  9855. var index = geometry.index;
  9856. var geometryAttributes = geometry.attributes;
  9857. if ( index !== null ) {
  9858. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9859. }
  9860. for ( var name in geometryAttributes ) {
  9861. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9862. }
  9863. // morph targets
  9864. var morphAttributes = geometry.morphAttributes;
  9865. for ( var name in morphAttributes ) {
  9866. var array = morphAttributes[ name ];
  9867. for ( var i = 0, l = array.length; i < l; i ++ ) {
  9868. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9869. }
  9870. }
  9871. }
  9872. function getWireframeAttribute( geometry ) {
  9873. var attribute = wireframeAttributes[ geometry.id ];
  9874. if ( attribute ) return attribute;
  9875. var indices = [];
  9876. var geometryIndex = geometry.index;
  9877. var geometryAttributes = geometry.attributes;
  9878. // console.time( 'wireframe' );
  9879. if ( geometryIndex !== null ) {
  9880. var array = geometryIndex.array;
  9881. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9882. var a = array[ i + 0 ];
  9883. var b = array[ i + 1 ];
  9884. var c = array[ i + 2 ];
  9885. indices.push( a, b, b, c, c, a );
  9886. }
  9887. } else {
  9888. var array = geometryAttributes.position.array;
  9889. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9890. var a = i + 0;
  9891. var b = i + 1;
  9892. var c = i + 2;
  9893. indices.push( a, b, b, c, c, a );
  9894. }
  9895. }
  9896. // console.timeEnd( 'wireframe' );
  9897. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9898. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  9899. wireframeAttributes[ geometry.id ] = attribute;
  9900. return attribute;
  9901. }
  9902. return {
  9903. get: get,
  9904. update: update,
  9905. getWireframeAttribute: getWireframeAttribute
  9906. };
  9907. }
  9908. /**
  9909. * @author mrdoob / http://mrdoob.com/
  9910. */
  9911. function WebGLLights() {
  9912. var lights = {};
  9913. return {
  9914. get: function ( light ) {
  9915. if ( lights[ light.id ] !== undefined ) {
  9916. return lights[ light.id ];
  9917. }
  9918. var uniforms;
  9919. switch ( light.type ) {
  9920. case 'DirectionalLight':
  9921. uniforms = {
  9922. direction: new Vector3(),
  9923. color: new Color(),
  9924. shadow: false,
  9925. shadowBias: 0,
  9926. shadowRadius: 1,
  9927. shadowMapSize: new Vector2()
  9928. };
  9929. break;
  9930. case 'SpotLight':
  9931. uniforms = {
  9932. position: new Vector3(),
  9933. direction: new Vector3(),
  9934. color: new Color(),
  9935. distance: 0,
  9936. coneCos: 0,
  9937. penumbraCos: 0,
  9938. decay: 0,
  9939. shadow: false,
  9940. shadowBias: 0,
  9941. shadowRadius: 1,
  9942. shadowMapSize: new Vector2()
  9943. };
  9944. break;
  9945. case 'PointLight':
  9946. uniforms = {
  9947. position: new Vector3(),
  9948. color: new Color(),
  9949. distance: 0,
  9950. decay: 0,
  9951. shadow: false,
  9952. shadowBias: 0,
  9953. shadowRadius: 1,
  9954. shadowMapSize: new Vector2()
  9955. };
  9956. break;
  9957. case 'HemisphereLight':
  9958. uniforms = {
  9959. direction: new Vector3(),
  9960. skyColor: new Color(),
  9961. groundColor: new Color()
  9962. };
  9963. break;
  9964. case 'RectAreaLight':
  9965. uniforms = {
  9966. color: new Color(),
  9967. position: new Vector3(),
  9968. halfWidth: new Vector3(),
  9969. halfHeight: new Vector3()
  9970. // TODO (abelnation): set RectAreaLight shadow uniforms
  9971. };
  9972. break;
  9973. }
  9974. lights[ light.id ] = uniforms;
  9975. return uniforms;
  9976. }
  9977. };
  9978. }
  9979. /**
  9980. * @author mrdoob / http://mrdoob.com/
  9981. */
  9982. function WebGLObjects( gl, geometries, infoRender ) {
  9983. var updateList = {};
  9984. function update( object ) {
  9985. var frame = infoRender.frame;
  9986. var geometry = object.geometry;
  9987. var buffergeometry = geometries.get( object, geometry );
  9988. // Update once per frame
  9989. if ( updateList[ buffergeometry.id ] !== frame ) {
  9990. if ( geometry.isGeometry ) {
  9991. buffergeometry.updateFromObject( object );
  9992. }
  9993. geometries.update( buffergeometry );
  9994. updateList[ buffergeometry.id ] = frame;
  9995. }
  9996. return buffergeometry;
  9997. }
  9998. function clear() {
  9999. updateList = {};
  10000. }
  10001. return {
  10002. update: update,
  10003. clear: clear
  10004. };
  10005. }
  10006. /**
  10007. * @author mrdoob / http://mrdoob.com/
  10008. */
  10009. function addLineNumbers( string ) {
  10010. var lines = string.split( '\n' );
  10011. for ( var i = 0; i < lines.length; i ++ ) {
  10012. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10013. }
  10014. return lines.join( '\n' );
  10015. }
  10016. function WebGLShader( gl, type, string ) {
  10017. var shader = gl.createShader( type );
  10018. gl.shaderSource( shader, string );
  10019. gl.compileShader( shader );
  10020. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  10021. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  10022. }
  10023. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  10024. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  10025. }
  10026. // --enable-privileged-webgl-extension
  10027. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10028. return shader;
  10029. }
  10030. /**
  10031. * @author mrdoob / http://mrdoob.com/
  10032. */
  10033. var programIdCount = 0;
  10034. function getEncodingComponents( encoding ) {
  10035. switch ( encoding ) {
  10036. case LinearEncoding:
  10037. return [ 'Linear','( value )' ];
  10038. case sRGBEncoding:
  10039. return [ 'sRGB','( value )' ];
  10040. case RGBEEncoding:
  10041. return [ 'RGBE','( value )' ];
  10042. case RGBM7Encoding:
  10043. return [ 'RGBM','( value, 7.0 )' ];
  10044. case RGBM16Encoding:
  10045. return [ 'RGBM','( value, 16.0 )' ];
  10046. case RGBDEncoding:
  10047. return [ 'RGBD','( value, 256.0 )' ];
  10048. case GammaEncoding:
  10049. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  10050. default:
  10051. throw new Error( 'unsupported encoding: ' + encoding );
  10052. }
  10053. }
  10054. function getTexelDecodingFunction( functionName, encoding ) {
  10055. var components = getEncodingComponents( encoding );
  10056. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  10057. }
  10058. function getTexelEncodingFunction( functionName, encoding ) {
  10059. var components = getEncodingComponents( encoding );
  10060. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  10061. }
  10062. function getToneMappingFunction( functionName, toneMapping ) {
  10063. var toneMappingName;
  10064. switch ( toneMapping ) {
  10065. case LinearToneMapping:
  10066. toneMappingName = "Linear";
  10067. break;
  10068. case ReinhardToneMapping:
  10069. toneMappingName = "Reinhard";
  10070. break;
  10071. case Uncharted2ToneMapping:
  10072. toneMappingName = "Uncharted2";
  10073. break;
  10074. case CineonToneMapping:
  10075. toneMappingName = "OptimizedCineon";
  10076. break;
  10077. default:
  10078. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  10079. }
  10080. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  10081. }
  10082. function generateExtensions( extensions, parameters, rendererExtensions ) {
  10083. extensions = extensions || {};
  10084. var chunks = [
  10085. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10086. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  10087. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10088. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10089. ];
  10090. return chunks.filter( filterEmptyLine ).join( '\n' );
  10091. }
  10092. function generateDefines( defines ) {
  10093. var chunks = [];
  10094. for ( var name in defines ) {
  10095. var value = defines[ name ];
  10096. if ( value === false ) continue;
  10097. chunks.push( '#define ' + name + ' ' + value );
  10098. }
  10099. return chunks.join( '\n' );
  10100. }
  10101. function fetchAttributeLocations( gl, program, identifiers ) {
  10102. var attributes = {};
  10103. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10104. for ( var i = 0; i < n; i ++ ) {
  10105. var info = gl.getActiveAttrib( program, i );
  10106. var name = info.name;
  10107. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  10108. attributes[ name ] = gl.getAttribLocation( program, name );
  10109. }
  10110. return attributes;
  10111. }
  10112. function filterEmptyLine( string ) {
  10113. return string !== '';
  10114. }
  10115. function replaceLightNums( string, parameters ) {
  10116. return string
  10117. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10118. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10119. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10120. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10121. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  10122. }
  10123. function parseIncludes( string ) {
  10124. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  10125. function replace( match, include ) {
  10126. var replace = ShaderChunk[ include ];
  10127. if ( replace === undefined ) {
  10128. throw new Error( 'Can not resolve #include <' + include + '>' );
  10129. }
  10130. return parseIncludes( replace );
  10131. }
  10132. return string.replace( pattern, replace );
  10133. }
  10134. function unrollLoops( string ) {
  10135. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10136. function replace( match, start, end, snippet ) {
  10137. var unroll = '';
  10138. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10139. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  10140. }
  10141. return unroll;
  10142. }
  10143. return string.replace( pattern, replace );
  10144. }
  10145. function WebGLProgram( renderer, code, material, parameters ) {
  10146. var gl = renderer.context;
  10147. var extensions = material.extensions;
  10148. var defines = material.defines;
  10149. var vertexShader = material.__webglShader.vertexShader;
  10150. var fragmentShader = material.__webglShader.fragmentShader;
  10151. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10152. if ( parameters.shadowMapType === PCFShadowMap ) {
  10153. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10154. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10155. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10156. }
  10157. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10158. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10159. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10160. if ( parameters.envMap ) {
  10161. switch ( material.envMap.mapping ) {
  10162. case CubeReflectionMapping:
  10163. case CubeRefractionMapping:
  10164. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10165. break;
  10166. case CubeUVReflectionMapping:
  10167. case CubeUVRefractionMapping:
  10168. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10169. break;
  10170. case EquirectangularReflectionMapping:
  10171. case EquirectangularRefractionMapping:
  10172. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  10173. break;
  10174. case SphericalReflectionMapping:
  10175. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  10176. break;
  10177. }
  10178. switch ( material.envMap.mapping ) {
  10179. case CubeRefractionMapping:
  10180. case EquirectangularRefractionMapping:
  10181. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10182. break;
  10183. }
  10184. switch ( material.combine ) {
  10185. case MultiplyOperation:
  10186. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10187. break;
  10188. case MixOperation:
  10189. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10190. break;
  10191. case AddOperation:
  10192. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10193. break;
  10194. }
  10195. }
  10196. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10197. // console.log( 'building new program ' );
  10198. //
  10199. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  10200. var customDefines = generateDefines( defines );
  10201. //
  10202. var program = gl.createProgram();
  10203. var prefixVertex, prefixFragment;
  10204. if ( material.isRawShaderMaterial ) {
  10205. prefixVertex = [
  10206. customDefines,
  10207. '\n'
  10208. ].filter( filterEmptyLine ).join( '\n' );
  10209. prefixFragment = [
  10210. customExtensions,
  10211. customDefines,
  10212. '\n'
  10213. ].filter( filterEmptyLine ).join( '\n' );
  10214. } else {
  10215. prefixVertex = [
  10216. 'precision ' + parameters.precision + ' float;',
  10217. 'precision ' + parameters.precision + ' int;',
  10218. '#define SHADER_NAME ' + material.__webglShader.name,
  10219. customDefines,
  10220. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10221. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10222. '#define MAX_BONES ' + parameters.maxBones,
  10223. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10224. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10225. parameters.map ? '#define USE_MAP' : '',
  10226. parameters.envMap ? '#define USE_ENVMAP' : '',
  10227. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10228. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10229. parameters.aoMap ? '#define USE_AOMAP' : '',
  10230. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10231. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10232. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10233. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10234. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10235. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10236. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10237. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10238. parameters.vertexColors ? '#define USE_COLOR' : '',
  10239. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10240. parameters.skinning ? '#define USE_SKINNING' : '',
  10241. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10242. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10243. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10244. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10245. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10246. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10247. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10248. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10249. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10250. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10251. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10252. 'uniform mat4 modelMatrix;',
  10253. 'uniform mat4 modelViewMatrix;',
  10254. 'uniform mat4 projectionMatrix;',
  10255. 'uniform mat4 viewMatrix;',
  10256. 'uniform mat3 normalMatrix;',
  10257. 'uniform vec3 cameraPosition;',
  10258. 'attribute vec3 position;',
  10259. 'attribute vec3 normal;',
  10260. 'attribute vec2 uv;',
  10261. '#ifdef USE_COLOR',
  10262. ' attribute vec3 color;',
  10263. '#endif',
  10264. '#ifdef USE_MORPHTARGETS',
  10265. ' attribute vec3 morphTarget0;',
  10266. ' attribute vec3 morphTarget1;',
  10267. ' attribute vec3 morphTarget2;',
  10268. ' attribute vec3 morphTarget3;',
  10269. ' #ifdef USE_MORPHNORMALS',
  10270. ' attribute vec3 morphNormal0;',
  10271. ' attribute vec3 morphNormal1;',
  10272. ' attribute vec3 morphNormal2;',
  10273. ' attribute vec3 morphNormal3;',
  10274. ' #else',
  10275. ' attribute vec3 morphTarget4;',
  10276. ' attribute vec3 morphTarget5;',
  10277. ' attribute vec3 morphTarget6;',
  10278. ' attribute vec3 morphTarget7;',
  10279. ' #endif',
  10280. '#endif',
  10281. '#ifdef USE_SKINNING',
  10282. ' attribute vec4 skinIndex;',
  10283. ' attribute vec4 skinWeight;',
  10284. '#endif',
  10285. '\n'
  10286. ].filter( filterEmptyLine ).join( '\n' );
  10287. prefixFragment = [
  10288. customExtensions,
  10289. 'precision ' + parameters.precision + ' float;',
  10290. 'precision ' + parameters.precision + ' int;',
  10291. '#define SHADER_NAME ' + material.__webglShader.name,
  10292. customDefines,
  10293. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  10294. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10295. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10296. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  10297. parameters.map ? '#define USE_MAP' : '',
  10298. parameters.envMap ? '#define USE_ENVMAP' : '',
  10299. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10300. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10301. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10302. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10303. parameters.aoMap ? '#define USE_AOMAP' : '',
  10304. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10305. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10306. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10307. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10308. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10309. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10310. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10311. parameters.vertexColors ? '#define USE_COLOR' : '',
  10312. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10313. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10314. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10315. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10316. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  10317. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  10318. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10319. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10320. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  10321. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  10322. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10323. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10324. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  10325. 'uniform mat4 viewMatrix;',
  10326. 'uniform vec3 cameraPosition;',
  10327. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  10328. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10329. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  10330. parameters.dithering ? '#define DITHERING' : '',
  10331. ( 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
  10332. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10333. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10334. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10335. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  10336. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  10337. '\n'
  10338. ].filter( filterEmptyLine ).join( '\n' );
  10339. }
  10340. vertexShader = parseIncludes( vertexShader, parameters );
  10341. vertexShader = replaceLightNums( vertexShader, parameters );
  10342. fragmentShader = parseIncludes( fragmentShader, parameters );
  10343. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10344. if ( ! material.isShaderMaterial ) {
  10345. vertexShader = unrollLoops( vertexShader );
  10346. fragmentShader = unrollLoops( fragmentShader );
  10347. }
  10348. var vertexGlsl = prefixVertex + vertexShader;
  10349. var fragmentGlsl = prefixFragment + fragmentShader;
  10350. // console.log( '*VERTEX*', vertexGlsl );
  10351. // console.log( '*FRAGMENT*', fragmentGlsl );
  10352. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  10353. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  10354. gl.attachShader( program, glVertexShader );
  10355. gl.attachShader( program, glFragmentShader );
  10356. // Force a particular attribute to index 0.
  10357. if ( material.index0AttributeName !== undefined ) {
  10358. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  10359. } else if ( parameters.morphTargets === true ) {
  10360. // programs with morphTargets displace position out of attribute 0
  10361. gl.bindAttribLocation( program, 0, 'position' );
  10362. }
  10363. gl.linkProgram( program );
  10364. var programLog = gl.getProgramInfoLog( program );
  10365. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  10366. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  10367. var runnable = true;
  10368. var haveDiagnostics = true;
  10369. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  10370. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  10371. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  10372. runnable = false;
  10373. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  10374. } else if ( programLog !== '' ) {
  10375. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10376. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10377. haveDiagnostics = false;
  10378. }
  10379. if ( haveDiagnostics ) {
  10380. this.diagnostics = {
  10381. runnable: runnable,
  10382. material: material,
  10383. programLog: programLog,
  10384. vertexShader: {
  10385. log: vertexLog,
  10386. prefix: prefixVertex
  10387. },
  10388. fragmentShader: {
  10389. log: fragmentLog,
  10390. prefix: prefixFragment
  10391. }
  10392. };
  10393. }
  10394. // clean up
  10395. gl.deleteShader( glVertexShader );
  10396. gl.deleteShader( glFragmentShader );
  10397. // set up caching for uniform locations
  10398. var cachedUniforms;
  10399. this.getUniforms = function() {
  10400. if ( cachedUniforms === undefined ) {
  10401. cachedUniforms =
  10402. new WebGLUniforms( gl, program, renderer );
  10403. }
  10404. return cachedUniforms;
  10405. };
  10406. // set up caching for attribute locations
  10407. var cachedAttributes;
  10408. this.getAttributes = function() {
  10409. if ( cachedAttributes === undefined ) {
  10410. cachedAttributes = fetchAttributeLocations( gl, program );
  10411. }
  10412. return cachedAttributes;
  10413. };
  10414. // free resource
  10415. this.destroy = function() {
  10416. gl.deleteProgram( program );
  10417. this.program = undefined;
  10418. };
  10419. // DEPRECATED
  10420. Object.defineProperties( this, {
  10421. uniforms: {
  10422. get: function() {
  10423. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10424. return this.getUniforms();
  10425. }
  10426. },
  10427. attributes: {
  10428. get: function() {
  10429. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10430. return this.getAttributes();
  10431. }
  10432. }
  10433. } );
  10434. //
  10435. this.id = programIdCount ++;
  10436. this.code = code;
  10437. this.usedTimes = 1;
  10438. this.program = program;
  10439. this.vertexShader = glVertexShader;
  10440. this.fragmentShader = glFragmentShader;
  10441. return this;
  10442. }
  10443. /**
  10444. * @author mrdoob / http://mrdoob.com/
  10445. */
  10446. function WebGLPrograms( renderer, capabilities ) {
  10447. var programs = [];
  10448. var shaderIDs = {
  10449. MeshDepthMaterial: 'depth',
  10450. MeshNormalMaterial: 'normal',
  10451. MeshBasicMaterial: 'basic',
  10452. MeshLambertMaterial: 'lambert',
  10453. MeshPhongMaterial: 'phong',
  10454. MeshToonMaterial: 'phong',
  10455. MeshStandardMaterial: 'physical',
  10456. MeshPhysicalMaterial: 'physical',
  10457. LineBasicMaterial: 'basic',
  10458. LineDashedMaterial: 'dashed',
  10459. PointsMaterial: 'points'
  10460. };
  10461. var parameterNames = [
  10462. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10463. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10464. "roughnessMap", "metalnessMap", "gradientMap",
  10465. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10466. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10467. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10468. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10469. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10470. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10471. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  10472. ];
  10473. function allocateBones( object ) {
  10474. var skeleton = object.skeleton;
  10475. var bones = skeleton.bones;
  10476. if ( capabilities.floatVertexTextures ) {
  10477. return 1024;
  10478. } else {
  10479. // default for when object is not specified
  10480. // ( for example when prebuilding shader to be used with multiple objects )
  10481. //
  10482. // - leave some extra space for other uniforms
  10483. // - limit here is ANGLE's 254 max uniform vectors
  10484. // (up to 54 should be safe)
  10485. var nVertexUniforms = capabilities.maxVertexUniforms;
  10486. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10487. var maxBones = Math.min( nVertexMatrices, bones.length );
  10488. if ( maxBones < bones.length ) {
  10489. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10490. return 0;
  10491. }
  10492. return maxBones;
  10493. }
  10494. }
  10495. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10496. var encoding;
  10497. if ( ! map ) {
  10498. encoding = LinearEncoding;
  10499. } else if ( map.isTexture ) {
  10500. encoding = map.encoding;
  10501. } else if ( map.isWebGLRenderTarget ) {
  10502. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10503. encoding = map.texture.encoding;
  10504. }
  10505. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10506. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10507. encoding = GammaEncoding;
  10508. }
  10509. return encoding;
  10510. }
  10511. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10512. var shaderID = shaderIDs[ material.type ];
  10513. // heuristics to create shader parameters according to lights in the scene
  10514. // (not to blow over maxLights budget)
  10515. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  10516. var precision = renderer.getPrecision();
  10517. if ( material.precision !== null ) {
  10518. precision = capabilities.getMaxPrecision( material.precision );
  10519. if ( precision !== material.precision ) {
  10520. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10521. }
  10522. }
  10523. var currentRenderTarget = renderer.getRenderTarget();
  10524. var parameters = {
  10525. shaderID: shaderID,
  10526. precision: precision,
  10527. supportsVertexTextures: capabilities.vertexTextures,
  10528. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10529. map: !! material.map,
  10530. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10531. envMap: !! material.envMap,
  10532. envMapMode: material.envMap && material.envMap.mapping,
  10533. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10534. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10535. lightMap: !! material.lightMap,
  10536. aoMap: !! material.aoMap,
  10537. emissiveMap: !! material.emissiveMap,
  10538. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10539. bumpMap: !! material.bumpMap,
  10540. normalMap: !! material.normalMap,
  10541. displacementMap: !! material.displacementMap,
  10542. roughnessMap: !! material.roughnessMap,
  10543. metalnessMap: !! material.metalnessMap,
  10544. specularMap: !! material.specularMap,
  10545. alphaMap: !! material.alphaMap,
  10546. gradientMap: !! material.gradientMap,
  10547. combine: material.combine,
  10548. vertexColors: material.vertexColors,
  10549. fog: !! fog,
  10550. useFog: material.fog,
  10551. fogExp: ( fog && fog.isFogExp2 ),
  10552. flatShading: material.shading === FlatShading,
  10553. sizeAttenuation: material.sizeAttenuation,
  10554. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10555. skinning: material.skinning && maxBones > 0,
  10556. maxBones: maxBones,
  10557. useVertexTexture: capabilities.floatVertexTextures,
  10558. morphTargets: material.morphTargets,
  10559. morphNormals: material.morphNormals,
  10560. maxMorphTargets: renderer.maxMorphTargets,
  10561. maxMorphNormals: renderer.maxMorphNormals,
  10562. numDirLights: lights.directional.length,
  10563. numPointLights: lights.point.length,
  10564. numSpotLights: lights.spot.length,
  10565. numRectAreaLights: lights.rectArea.length,
  10566. numHemiLights: lights.hemi.length,
  10567. numClippingPlanes: nClipPlanes,
  10568. numClipIntersection: nClipIntersection,
  10569. dithering: material.dithering,
  10570. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10571. shadowMapType: renderer.shadowMap.type,
  10572. toneMapping: renderer.toneMapping,
  10573. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10574. premultipliedAlpha: material.premultipliedAlpha,
  10575. alphaTest: material.alphaTest,
  10576. doubleSided: material.side === DoubleSide,
  10577. flipSided: material.side === BackSide,
  10578. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10579. };
  10580. return parameters;
  10581. };
  10582. this.getProgramCode = function ( material, parameters ) {
  10583. var array = [];
  10584. if ( parameters.shaderID ) {
  10585. array.push( parameters.shaderID );
  10586. } else {
  10587. array.push( material.fragmentShader );
  10588. array.push( material.vertexShader );
  10589. }
  10590. if ( material.defines !== undefined ) {
  10591. for ( var name in material.defines ) {
  10592. array.push( name );
  10593. array.push( material.defines[ name ] );
  10594. }
  10595. }
  10596. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10597. array.push( parameters[ parameterNames[ i ] ] );
  10598. }
  10599. return array.join();
  10600. };
  10601. this.acquireProgram = function ( material, parameters, code ) {
  10602. var program;
  10603. // Check if code has been already compiled
  10604. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10605. var programInfo = programs[ p ];
  10606. if ( programInfo.code === code ) {
  10607. program = programInfo;
  10608. ++ program.usedTimes;
  10609. break;
  10610. }
  10611. }
  10612. if ( program === undefined ) {
  10613. program = new WebGLProgram( renderer, code, material, parameters );
  10614. programs.push( program );
  10615. }
  10616. return program;
  10617. };
  10618. this.releaseProgram = function ( program ) {
  10619. if ( -- program.usedTimes === 0 ) {
  10620. // Remove from unordered set
  10621. var i = programs.indexOf( program );
  10622. programs[ i ] = programs[ programs.length - 1 ];
  10623. programs.pop();
  10624. // Free WebGL resources
  10625. program.destroy();
  10626. }
  10627. };
  10628. // Exposed for resource monitoring & error feedback via renderer.info:
  10629. this.programs = programs;
  10630. }
  10631. /**
  10632. * @author mrdoob / http://mrdoob.com/
  10633. */
  10634. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) {
  10635. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10636. //
  10637. function clampToMaxSize( image, maxSize ) {
  10638. if ( image.width > maxSize || image.height > maxSize ) {
  10639. // Warning: Scaling through the canvas will only work with images that use
  10640. // premultiplied alpha.
  10641. var scale = maxSize / Math.max( image.width, image.height );
  10642. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10643. canvas.width = Math.floor( image.width * scale );
  10644. canvas.height = Math.floor( image.height * scale );
  10645. var context = canvas.getContext( '2d' );
  10646. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10647. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10648. return canvas;
  10649. }
  10650. return image;
  10651. }
  10652. function isPowerOfTwo( image ) {
  10653. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10654. }
  10655. function makePowerOfTwo( image ) {
  10656. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10657. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10658. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10659. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10660. var context = canvas.getContext( '2d' );
  10661. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10662. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10663. return canvas;
  10664. }
  10665. return image;
  10666. }
  10667. function textureNeedsPowerOfTwo( texture ) {
  10668. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10669. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10670. }
  10671. // Fallback filters for non-power-of-2 textures
  10672. function filterFallback( f ) {
  10673. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10674. return _gl.NEAREST;
  10675. }
  10676. return _gl.LINEAR;
  10677. }
  10678. //
  10679. function onTextureDispose( event ) {
  10680. var texture = event.target;
  10681. texture.removeEventListener( 'dispose', onTextureDispose );
  10682. deallocateTexture( texture );
  10683. infoMemory.textures --;
  10684. }
  10685. function onRenderTargetDispose( event ) {
  10686. var renderTarget = event.target;
  10687. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10688. deallocateRenderTarget( renderTarget );
  10689. infoMemory.textures --;
  10690. }
  10691. //
  10692. function deallocateTexture( texture ) {
  10693. var textureProperties = properties.get( texture );
  10694. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10695. // cube texture
  10696. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10697. } else {
  10698. // 2D texture
  10699. if ( textureProperties.__webglInit === undefined ) return;
  10700. _gl.deleteTexture( textureProperties.__webglTexture );
  10701. }
  10702. // remove all webgl properties
  10703. properties.remove( texture );
  10704. }
  10705. function deallocateRenderTarget( renderTarget ) {
  10706. var renderTargetProperties = properties.get( renderTarget );
  10707. var textureProperties = properties.get( renderTarget.texture );
  10708. if ( ! renderTarget ) return;
  10709. if ( textureProperties.__webglTexture !== undefined ) {
  10710. _gl.deleteTexture( textureProperties.__webglTexture );
  10711. }
  10712. if ( renderTarget.depthTexture ) {
  10713. renderTarget.depthTexture.dispose();
  10714. }
  10715. if ( renderTarget.isWebGLRenderTargetCube ) {
  10716. for ( var i = 0; i < 6; i ++ ) {
  10717. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10718. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10719. }
  10720. } else {
  10721. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10722. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10723. }
  10724. properties.remove( renderTarget.texture );
  10725. properties.remove( renderTarget );
  10726. }
  10727. //
  10728. function setTexture2D( texture, slot ) {
  10729. var textureProperties = properties.get( texture );
  10730. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10731. var image = texture.image;
  10732. if ( image === undefined ) {
  10733. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10734. } else if ( image.complete === false ) {
  10735. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10736. } else {
  10737. uploadTexture( textureProperties, texture, slot );
  10738. return;
  10739. }
  10740. }
  10741. state.activeTexture( _gl.TEXTURE0 + slot );
  10742. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10743. }
  10744. function setTextureCube( texture, slot ) {
  10745. var textureProperties = properties.get( texture );
  10746. if ( texture.image.length === 6 ) {
  10747. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10748. if ( ! textureProperties.__image__webglTextureCube ) {
  10749. texture.addEventListener( 'dispose', onTextureDispose );
  10750. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10751. infoMemory.textures ++;
  10752. }
  10753. state.activeTexture( _gl.TEXTURE0 + slot );
  10754. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10755. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10756. var isCompressed = ( texture && texture.isCompressedTexture );
  10757. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  10758. var cubeImage = [];
  10759. for ( var i = 0; i < 6; i ++ ) {
  10760. if ( ! isCompressed && ! isDataTexture ) {
  10761. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10762. } else {
  10763. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10764. }
  10765. }
  10766. var image = cubeImage[ 0 ],
  10767. isPowerOfTwoImage = isPowerOfTwo( image ),
  10768. glFormat = paramThreeToGL( texture.format ),
  10769. glType = paramThreeToGL( texture.type );
  10770. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10771. for ( var i = 0; i < 6; i ++ ) {
  10772. if ( ! isCompressed ) {
  10773. if ( isDataTexture ) {
  10774. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10775. } else {
  10776. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10777. }
  10778. } else {
  10779. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10780. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10781. mipmap = mipmaps[ j ];
  10782. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10783. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10784. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10785. } else {
  10786. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10787. }
  10788. } else {
  10789. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10790. }
  10791. }
  10792. }
  10793. }
  10794. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10795. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10796. }
  10797. textureProperties.__version = texture.version;
  10798. if ( texture.onUpdate ) texture.onUpdate( texture );
  10799. } else {
  10800. state.activeTexture( _gl.TEXTURE0 + slot );
  10801. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10802. }
  10803. }
  10804. }
  10805. function setTextureCubeDynamic( texture, slot ) {
  10806. state.activeTexture( _gl.TEXTURE0 + slot );
  10807. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10808. }
  10809. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10810. var extension;
  10811. if ( isPowerOfTwoImage ) {
  10812. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10813. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10814. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10815. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10816. } else {
  10817. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10818. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10819. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10820. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10821. }
  10822. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10823. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10824. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10825. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10826. }
  10827. }
  10828. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10829. if ( extension ) {
  10830. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10831. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10832. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10833. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10834. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10835. }
  10836. }
  10837. }
  10838. function uploadTexture( textureProperties, texture, slot ) {
  10839. if ( textureProperties.__webglInit === undefined ) {
  10840. textureProperties.__webglInit = true;
  10841. texture.addEventListener( 'dispose', onTextureDispose );
  10842. textureProperties.__webglTexture = _gl.createTexture();
  10843. infoMemory.textures ++;
  10844. }
  10845. state.activeTexture( _gl.TEXTURE0 + slot );
  10846. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10847. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10848. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10849. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10850. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10851. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10852. image = makePowerOfTwo( image );
  10853. }
  10854. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10855. glFormat = paramThreeToGL( texture.format ),
  10856. glType = paramThreeToGL( texture.type );
  10857. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10858. var mipmap, mipmaps = texture.mipmaps;
  10859. if ( texture.isDepthTexture ) {
  10860. // populate depth texture with dummy data
  10861. var internalFormat = _gl.DEPTH_COMPONENT;
  10862. if ( texture.type === FloatType ) {
  10863. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10864. internalFormat = _gl.DEPTH_COMPONENT32F;
  10865. } else if ( _isWebGL2 ) {
  10866. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10867. internalFormat = _gl.DEPTH_COMPONENT16;
  10868. }
  10869. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10870. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10871. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10872. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10873. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10874. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10875. texture.type = UnsignedShortType;
  10876. glType = paramThreeToGL( texture.type );
  10877. }
  10878. }
  10879. // Depth stencil textures need the DEPTH_STENCIL internal format
  10880. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10881. if ( texture.format === DepthStencilFormat ) {
  10882. internalFormat = _gl.DEPTH_STENCIL;
  10883. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10884. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10885. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10886. if ( texture.type !== UnsignedInt248Type ) {
  10887. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10888. texture.type = UnsignedInt248Type;
  10889. glType = paramThreeToGL( texture.type );
  10890. }
  10891. }
  10892. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10893. } else if ( texture.isDataTexture ) {
  10894. // use manually created mipmaps if available
  10895. // if there are no manual mipmaps
  10896. // set 0 level mipmap and then use GL to generate other mipmap levels
  10897. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10898. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10899. mipmap = mipmaps[ i ];
  10900. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10901. }
  10902. texture.generateMipmaps = false;
  10903. } else {
  10904. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10905. }
  10906. } else if ( texture.isCompressedTexture ) {
  10907. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10908. mipmap = mipmaps[ i ];
  10909. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10910. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10911. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10912. } else {
  10913. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10914. }
  10915. } else {
  10916. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10917. }
  10918. }
  10919. } else {
  10920. // regular Texture (image, video, canvas)
  10921. // use manually created mipmaps if available
  10922. // if there are no manual mipmaps
  10923. // set 0 level mipmap and then use GL to generate other mipmap levels
  10924. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10925. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10926. mipmap = mipmaps[ i ];
  10927. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10928. }
  10929. texture.generateMipmaps = false;
  10930. } else {
  10931. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10932. }
  10933. }
  10934. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10935. textureProperties.__version = texture.version;
  10936. if ( texture.onUpdate ) texture.onUpdate( texture );
  10937. }
  10938. // Render targets
  10939. // Setup storage for target texture and bind it to correct framebuffer
  10940. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10941. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10942. var glType = paramThreeToGL( renderTarget.texture.type );
  10943. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10944. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10945. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10946. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10947. }
  10948. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10949. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10950. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10951. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10952. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10953. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10954. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10955. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10956. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10957. } else {
  10958. // FIXME: We don't support !depth !stencil
  10959. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10960. }
  10961. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10962. }
  10963. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10964. function setupDepthTexture( framebuffer, renderTarget ) {
  10965. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10966. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10967. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10968. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10969. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10970. }
  10971. // upload an empty depth texture with framebuffer size
  10972. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10973. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10974. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10975. renderTarget.depthTexture.image.width = renderTarget.width;
  10976. renderTarget.depthTexture.image.height = renderTarget.height;
  10977. renderTarget.depthTexture.needsUpdate = true;
  10978. }
  10979. setTexture2D( renderTarget.depthTexture, 0 );
  10980. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10981. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10982. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10983. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10984. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10985. } else {
  10986. throw new Error('Unknown depthTexture format')
  10987. }
  10988. }
  10989. // Setup GL resources for a non-texture depth buffer
  10990. function setupDepthRenderbuffer( renderTarget ) {
  10991. var renderTargetProperties = properties.get( renderTarget );
  10992. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10993. if ( renderTarget.depthTexture ) {
  10994. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10995. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10996. } else {
  10997. if ( isCube ) {
  10998. renderTargetProperties.__webglDepthbuffer = [];
  10999. for ( var i = 0; i < 6; i ++ ) {
  11000. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  11001. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  11002. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  11003. }
  11004. } else {
  11005. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11006. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  11007. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  11008. }
  11009. }
  11010. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  11011. }
  11012. // Set up GL resources for the render target
  11013. function setupRenderTarget( renderTarget ) {
  11014. var renderTargetProperties = properties.get( renderTarget );
  11015. var textureProperties = properties.get( renderTarget.texture );
  11016. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  11017. textureProperties.__webglTexture = _gl.createTexture();
  11018. infoMemory.textures ++;
  11019. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  11020. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  11021. // Setup framebuffer
  11022. if ( isCube ) {
  11023. renderTargetProperties.__webglFramebuffer = [];
  11024. for ( var i = 0; i < 6; i ++ ) {
  11025. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  11026. }
  11027. } else {
  11028. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  11029. }
  11030. // Setup color buffer
  11031. if ( isCube ) {
  11032. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  11033. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  11034. for ( var i = 0; i < 6; i ++ ) {
  11035. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  11036. }
  11037. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  11038. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  11039. } else {
  11040. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  11041. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  11042. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  11043. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  11044. state.bindTexture( _gl.TEXTURE_2D, null );
  11045. }
  11046. // Setup depth and stencil buffers
  11047. if ( renderTarget.depthBuffer ) {
  11048. setupDepthRenderbuffer( renderTarget );
  11049. }
  11050. }
  11051. function updateRenderTargetMipmap( renderTarget ) {
  11052. var texture = renderTarget.texture;
  11053. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  11054. texture.minFilter !== NearestFilter &&
  11055. texture.minFilter !== LinearFilter ) {
  11056. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  11057. var webglTexture = properties.get( texture ).__webglTexture;
  11058. state.bindTexture( target, webglTexture );
  11059. _gl.generateMipmap( target );
  11060. state.bindTexture( target, null );
  11061. }
  11062. }
  11063. this.setTexture2D = setTexture2D;
  11064. this.setTextureCube = setTextureCube;
  11065. this.setTextureCubeDynamic = setTextureCubeDynamic;
  11066. this.setupRenderTarget = setupRenderTarget;
  11067. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  11068. }
  11069. /**
  11070. * @author fordacious / fordacious.github.io
  11071. */
  11072. function WebGLProperties() {
  11073. var properties = {};
  11074. function get( object ) {
  11075. var uuid = object.uuid;
  11076. var map = properties[ uuid ];
  11077. if ( map === undefined ) {
  11078. map = {};
  11079. properties[ uuid ] = map;
  11080. }
  11081. return map;
  11082. }
  11083. function remove( object ) {
  11084. delete properties[ object.uuid ];
  11085. }
  11086. function clear() {
  11087. properties = {};
  11088. }
  11089. return {
  11090. get: get,
  11091. remove: remove,
  11092. clear: clear
  11093. };
  11094. }
  11095. /**
  11096. * @author mrdoob / http://mrdoob.com/
  11097. */
  11098. function WebGLState( gl, extensions, paramThreeToGL ) {
  11099. function ColorBuffer() {
  11100. var locked = false;
  11101. var color = new Vector4();
  11102. var currentColorMask = null;
  11103. var currentColorClear = new Vector4();
  11104. return {
  11105. setMask: function ( colorMask ) {
  11106. if ( currentColorMask !== colorMask && ! locked ) {
  11107. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11108. currentColorMask = colorMask;
  11109. }
  11110. },
  11111. setLocked: function ( lock ) {
  11112. locked = lock;
  11113. },
  11114. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11115. if ( premultipliedAlpha === true ) {
  11116. r *= a; g *= a; b *= a;
  11117. }
  11118. color.set( r, g, b, a );
  11119. if ( currentColorClear.equals( color ) === false ) {
  11120. gl.clearColor( r, g, b, a );
  11121. currentColorClear.copy( color );
  11122. }
  11123. },
  11124. reset: function () {
  11125. locked = false;
  11126. currentColorMask = null;
  11127. currentColorClear.set( 0, 0, 0, 1 );
  11128. }
  11129. };
  11130. }
  11131. function DepthBuffer() {
  11132. var locked = false;
  11133. var currentDepthMask = null;
  11134. var currentDepthFunc = null;
  11135. var currentDepthClear = null;
  11136. return {
  11137. setTest: function ( depthTest ) {
  11138. if ( depthTest ) {
  11139. enable( gl.DEPTH_TEST );
  11140. } else {
  11141. disable( gl.DEPTH_TEST );
  11142. }
  11143. },
  11144. setMask: function ( depthMask ) {
  11145. if ( currentDepthMask !== depthMask && ! locked ) {
  11146. gl.depthMask( depthMask );
  11147. currentDepthMask = depthMask;
  11148. }
  11149. },
  11150. setFunc: function ( depthFunc ) {
  11151. if ( currentDepthFunc !== depthFunc ) {
  11152. if ( depthFunc ) {
  11153. switch ( depthFunc ) {
  11154. case NeverDepth:
  11155. gl.depthFunc( gl.NEVER );
  11156. break;
  11157. case AlwaysDepth:
  11158. gl.depthFunc( gl.ALWAYS );
  11159. break;
  11160. case LessDepth:
  11161. gl.depthFunc( gl.LESS );
  11162. break;
  11163. case LessEqualDepth:
  11164. gl.depthFunc( gl.LEQUAL );
  11165. break;
  11166. case EqualDepth:
  11167. gl.depthFunc( gl.EQUAL );
  11168. break;
  11169. case GreaterEqualDepth:
  11170. gl.depthFunc( gl.GEQUAL );
  11171. break;
  11172. case GreaterDepth:
  11173. gl.depthFunc( gl.GREATER );
  11174. break;
  11175. case NotEqualDepth:
  11176. gl.depthFunc( gl.NOTEQUAL );
  11177. break;
  11178. default:
  11179. gl.depthFunc( gl.LEQUAL );
  11180. }
  11181. } else {
  11182. gl.depthFunc( gl.LEQUAL );
  11183. }
  11184. currentDepthFunc = depthFunc;
  11185. }
  11186. },
  11187. setLocked: function ( lock ) {
  11188. locked = lock;
  11189. },
  11190. setClear: function ( depth ) {
  11191. if ( currentDepthClear !== depth ) {
  11192. gl.clearDepth( depth );
  11193. currentDepthClear = depth;
  11194. }
  11195. },
  11196. reset: function () {
  11197. locked = false;
  11198. currentDepthMask = null;
  11199. currentDepthFunc = null;
  11200. currentDepthClear = null;
  11201. }
  11202. };
  11203. }
  11204. function StencilBuffer() {
  11205. var locked = false;
  11206. var currentStencilMask = null;
  11207. var currentStencilFunc = null;
  11208. var currentStencilRef = null;
  11209. var currentStencilFuncMask = null;
  11210. var currentStencilFail = null;
  11211. var currentStencilZFail = null;
  11212. var currentStencilZPass = null;
  11213. var currentStencilClear = null;
  11214. return {
  11215. setTest: function ( stencilTest ) {
  11216. if ( stencilTest ) {
  11217. enable( gl.STENCIL_TEST );
  11218. } else {
  11219. disable( gl.STENCIL_TEST );
  11220. }
  11221. },
  11222. setMask: function ( stencilMask ) {
  11223. if ( currentStencilMask !== stencilMask && ! locked ) {
  11224. gl.stencilMask( stencilMask );
  11225. currentStencilMask = stencilMask;
  11226. }
  11227. },
  11228. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11229. if ( currentStencilFunc !== stencilFunc ||
  11230. currentStencilRef !== stencilRef ||
  11231. currentStencilFuncMask !== stencilMask ) {
  11232. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11233. currentStencilFunc = stencilFunc;
  11234. currentStencilRef = stencilRef;
  11235. currentStencilFuncMask = stencilMask;
  11236. }
  11237. },
  11238. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11239. if ( currentStencilFail !== stencilFail ||
  11240. currentStencilZFail !== stencilZFail ||
  11241. currentStencilZPass !== stencilZPass ) {
  11242. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11243. currentStencilFail = stencilFail;
  11244. currentStencilZFail = stencilZFail;
  11245. currentStencilZPass = stencilZPass;
  11246. }
  11247. },
  11248. setLocked: function ( lock ) {
  11249. locked = lock;
  11250. },
  11251. setClear: function ( stencil ) {
  11252. if ( currentStencilClear !== stencil ) {
  11253. gl.clearStencil( stencil );
  11254. currentStencilClear = stencil;
  11255. }
  11256. },
  11257. reset: function () {
  11258. locked = false;
  11259. currentStencilMask = null;
  11260. currentStencilFunc = null;
  11261. currentStencilRef = null;
  11262. currentStencilFuncMask = null;
  11263. currentStencilFail = null;
  11264. currentStencilZFail = null;
  11265. currentStencilZPass = null;
  11266. currentStencilClear = null;
  11267. }
  11268. };
  11269. }
  11270. //
  11271. var colorBuffer = new ColorBuffer();
  11272. var depthBuffer = new DepthBuffer();
  11273. var stencilBuffer = new StencilBuffer();
  11274. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11275. var newAttributes = new Uint8Array( maxVertexAttributes );
  11276. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11277. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11278. var capabilities = {};
  11279. var compressedTextureFormats = null;
  11280. var currentBlending = null;
  11281. var currentBlendEquation = null;
  11282. var currentBlendSrc = null;
  11283. var currentBlendDst = null;
  11284. var currentBlendEquationAlpha = null;
  11285. var currentBlendSrcAlpha = null;
  11286. var currentBlendDstAlpha = null;
  11287. var currentPremultipledAlpha = false;
  11288. var currentFlipSided = null;
  11289. var currentCullFace = null;
  11290. var currentLineWidth = null;
  11291. var currentPolygonOffsetFactor = null;
  11292. var currentPolygonOffsetUnits = null;
  11293. var currentScissorTest = null;
  11294. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11295. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11296. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11297. var currentTextureSlot = null;
  11298. var currentBoundTextures = {};
  11299. var currentScissor = new Vector4();
  11300. var currentViewport = new Vector4();
  11301. function createTexture( type, target, count ) {
  11302. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11303. var texture = gl.createTexture();
  11304. gl.bindTexture( type, texture );
  11305. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11306. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11307. for ( var i = 0; i < count; i ++ ) {
  11308. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11309. }
  11310. return texture;
  11311. }
  11312. var emptyTextures = {};
  11313. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11314. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11315. //
  11316. function init() {
  11317. colorBuffer.setClear( 0, 0, 0, 1 );
  11318. depthBuffer.setClear( 1 );
  11319. stencilBuffer.setClear( 0 );
  11320. enable( gl.DEPTH_TEST );
  11321. depthBuffer.setFunc( LessEqualDepth );
  11322. setFlipSided( false );
  11323. setCullFace( CullFaceBack );
  11324. enable( gl.CULL_FACE );
  11325. enable( gl.BLEND );
  11326. setBlending( NormalBlending );
  11327. }
  11328. function initAttributes() {
  11329. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11330. newAttributes[ i ] = 0;
  11331. }
  11332. }
  11333. function enableAttribute( attribute ) {
  11334. newAttributes[ attribute ] = 1;
  11335. if ( enabledAttributes[ attribute ] === 0 ) {
  11336. gl.enableVertexAttribArray( attribute );
  11337. enabledAttributes[ attribute ] = 1;
  11338. }
  11339. if ( attributeDivisors[ attribute ] !== 0 ) {
  11340. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11341. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11342. attributeDivisors[ attribute ] = 0;
  11343. }
  11344. }
  11345. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  11346. newAttributes[ attribute ] = 1;
  11347. if ( enabledAttributes[ attribute ] === 0 ) {
  11348. gl.enableVertexAttribArray( attribute );
  11349. enabledAttributes[ attribute ] = 1;
  11350. }
  11351. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11352. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11353. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11354. attributeDivisors[ attribute ] = meshPerAttribute;
  11355. }
  11356. }
  11357. function disableUnusedAttributes() {
  11358. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11359. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11360. gl.disableVertexAttribArray( i );
  11361. enabledAttributes[ i ] = 0;
  11362. }
  11363. }
  11364. }
  11365. function enable( id ) {
  11366. if ( capabilities[ id ] !== true ) {
  11367. gl.enable( id );
  11368. capabilities[ id ] = true;
  11369. }
  11370. }
  11371. function disable( id ) {
  11372. if ( capabilities[ id ] !== false ) {
  11373. gl.disable( id );
  11374. capabilities[ id ] = false;
  11375. }
  11376. }
  11377. function getCompressedTextureFormats() {
  11378. if ( compressedTextureFormats === null ) {
  11379. compressedTextureFormats = [];
  11380. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11381. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11382. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11383. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11384. for ( var i = 0; i < formats.length; i ++ ) {
  11385. compressedTextureFormats.push( formats[ i ] );
  11386. }
  11387. }
  11388. }
  11389. return compressedTextureFormats;
  11390. }
  11391. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11392. if ( blending !== NoBlending ) {
  11393. enable( gl.BLEND );
  11394. } else {
  11395. disable( gl.BLEND );
  11396. }
  11397. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11398. if ( blending === AdditiveBlending ) {
  11399. if ( premultipliedAlpha ) {
  11400. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11401. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11402. } else {
  11403. gl.blendEquation( gl.FUNC_ADD );
  11404. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11405. }
  11406. } else if ( blending === SubtractiveBlending ) {
  11407. if ( premultipliedAlpha ) {
  11408. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11409. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11410. } else {
  11411. gl.blendEquation( gl.FUNC_ADD );
  11412. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11413. }
  11414. } else if ( blending === MultiplyBlending ) {
  11415. if ( premultipliedAlpha ) {
  11416. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11417. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11418. } else {
  11419. gl.blendEquation( gl.FUNC_ADD );
  11420. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11421. }
  11422. } else {
  11423. if ( premultipliedAlpha ) {
  11424. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11425. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11426. } else {
  11427. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11428. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11429. }
  11430. }
  11431. currentBlending = blending;
  11432. currentPremultipledAlpha = premultipliedAlpha;
  11433. }
  11434. if ( blending === CustomBlending ) {
  11435. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11436. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11437. blendDstAlpha = blendDstAlpha || blendDst;
  11438. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11439. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11440. currentBlendEquation = blendEquation;
  11441. currentBlendEquationAlpha = blendEquationAlpha;
  11442. }
  11443. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11444. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11445. currentBlendSrc = blendSrc;
  11446. currentBlendDst = blendDst;
  11447. currentBlendSrcAlpha = blendSrcAlpha;
  11448. currentBlendDstAlpha = blendDstAlpha;
  11449. }
  11450. } else {
  11451. currentBlendEquation = null;
  11452. currentBlendSrc = null;
  11453. currentBlendDst = null;
  11454. currentBlendEquationAlpha = null;
  11455. currentBlendSrcAlpha = null;
  11456. currentBlendDstAlpha = null;
  11457. }
  11458. }
  11459. function setMaterial( material ) {
  11460. material.side === DoubleSide
  11461. ? disable( gl.CULL_FACE )
  11462. : enable( gl.CULL_FACE );
  11463. setFlipSided( material.side === BackSide );
  11464. material.transparent === true
  11465. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  11466. : setBlending( NoBlending );
  11467. depthBuffer.setFunc( material.depthFunc );
  11468. depthBuffer.setTest( material.depthTest );
  11469. depthBuffer.setMask( material.depthWrite );
  11470. colorBuffer.setMask( material.colorWrite );
  11471. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11472. }
  11473. //
  11474. function setFlipSided( flipSided ) {
  11475. if ( currentFlipSided !== flipSided ) {
  11476. if ( flipSided ) {
  11477. gl.frontFace( gl.CW );
  11478. } else {
  11479. gl.frontFace( gl.CCW );
  11480. }
  11481. currentFlipSided = flipSided;
  11482. }
  11483. }
  11484. function setCullFace( cullFace ) {
  11485. if ( cullFace !== CullFaceNone ) {
  11486. enable( gl.CULL_FACE );
  11487. if ( cullFace !== currentCullFace ) {
  11488. if ( cullFace === CullFaceBack ) {
  11489. gl.cullFace( gl.BACK );
  11490. } else if ( cullFace === CullFaceFront ) {
  11491. gl.cullFace( gl.FRONT );
  11492. } else {
  11493. gl.cullFace( gl.FRONT_AND_BACK );
  11494. }
  11495. }
  11496. } else {
  11497. disable( gl.CULL_FACE );
  11498. }
  11499. currentCullFace = cullFace;
  11500. }
  11501. function setLineWidth( width ) {
  11502. if ( width !== currentLineWidth ) {
  11503. if ( lineWidthAvailable ) gl.lineWidth( width );
  11504. currentLineWidth = width;
  11505. }
  11506. }
  11507. function setPolygonOffset( polygonOffset, factor, units ) {
  11508. if ( polygonOffset ) {
  11509. enable( gl.POLYGON_OFFSET_FILL );
  11510. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11511. gl.polygonOffset( factor, units );
  11512. currentPolygonOffsetFactor = factor;
  11513. currentPolygonOffsetUnits = units;
  11514. }
  11515. } else {
  11516. disable( gl.POLYGON_OFFSET_FILL );
  11517. }
  11518. }
  11519. function getScissorTest() {
  11520. return currentScissorTest;
  11521. }
  11522. function setScissorTest( scissorTest ) {
  11523. currentScissorTest = scissorTest;
  11524. if ( scissorTest ) {
  11525. enable( gl.SCISSOR_TEST );
  11526. } else {
  11527. disable( gl.SCISSOR_TEST );
  11528. }
  11529. }
  11530. // texture
  11531. function activeTexture( webglSlot ) {
  11532. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11533. if ( currentTextureSlot !== webglSlot ) {
  11534. gl.activeTexture( webglSlot );
  11535. currentTextureSlot = webglSlot;
  11536. }
  11537. }
  11538. function bindTexture( webglType, webglTexture ) {
  11539. if ( currentTextureSlot === null ) {
  11540. activeTexture();
  11541. }
  11542. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11543. if ( boundTexture === undefined ) {
  11544. boundTexture = { type: undefined, texture: undefined };
  11545. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11546. }
  11547. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11548. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11549. boundTexture.type = webglType;
  11550. boundTexture.texture = webglTexture;
  11551. }
  11552. }
  11553. function compressedTexImage2D() {
  11554. try {
  11555. gl.compressedTexImage2D.apply( gl, arguments );
  11556. } catch ( error ) {
  11557. console.error( error );
  11558. }
  11559. }
  11560. function texImage2D() {
  11561. try {
  11562. gl.texImage2D.apply( gl, arguments );
  11563. } catch ( error ) {
  11564. console.error( error );
  11565. }
  11566. }
  11567. //
  11568. function scissor( scissor ) {
  11569. if ( currentScissor.equals( scissor ) === false ) {
  11570. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11571. currentScissor.copy( scissor );
  11572. }
  11573. }
  11574. function viewport( viewport ) {
  11575. if ( currentViewport.equals( viewport ) === false ) {
  11576. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11577. currentViewport.copy( viewport );
  11578. }
  11579. }
  11580. //
  11581. function reset() {
  11582. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11583. if ( enabledAttributes[ i ] === 1 ) {
  11584. gl.disableVertexAttribArray( i );
  11585. enabledAttributes[ i ] = 0;
  11586. }
  11587. }
  11588. capabilities = {};
  11589. compressedTextureFormats = null;
  11590. currentTextureSlot = null;
  11591. currentBoundTextures = {};
  11592. currentBlending = null;
  11593. currentFlipSided = null;
  11594. currentCullFace = null;
  11595. colorBuffer.reset();
  11596. depthBuffer.reset();
  11597. stencilBuffer.reset();
  11598. }
  11599. return {
  11600. buffers: {
  11601. color: colorBuffer,
  11602. depth: depthBuffer,
  11603. stencil: stencilBuffer
  11604. },
  11605. init: init,
  11606. initAttributes: initAttributes,
  11607. enableAttribute: enableAttribute,
  11608. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11609. disableUnusedAttributes: disableUnusedAttributes,
  11610. enable: enable,
  11611. disable: disable,
  11612. getCompressedTextureFormats: getCompressedTextureFormats,
  11613. setBlending: setBlending,
  11614. setMaterial: setMaterial,
  11615. setFlipSided: setFlipSided,
  11616. setCullFace: setCullFace,
  11617. setLineWidth: setLineWidth,
  11618. setPolygonOffset: setPolygonOffset,
  11619. getScissorTest: getScissorTest,
  11620. setScissorTest: setScissorTest,
  11621. activeTexture: activeTexture,
  11622. bindTexture: bindTexture,
  11623. compressedTexImage2D: compressedTexImage2D,
  11624. texImage2D: texImage2D,
  11625. scissor: scissor,
  11626. viewport: viewport,
  11627. reset: reset
  11628. };
  11629. }
  11630. /**
  11631. * @author mrdoob / http://mrdoob.com/
  11632. */
  11633. function WebGLCapabilities( gl, extensions, parameters ) {
  11634. var maxAnisotropy;
  11635. function getMaxAnisotropy() {
  11636. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11637. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11638. if ( extension !== null ) {
  11639. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11640. } else {
  11641. maxAnisotropy = 0;
  11642. }
  11643. return maxAnisotropy;
  11644. }
  11645. function getMaxPrecision( precision ) {
  11646. if ( precision === 'highp' ) {
  11647. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11648. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11649. return 'highp';
  11650. }
  11651. precision = 'mediump';
  11652. }
  11653. if ( precision === 'mediump' ) {
  11654. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11655. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11656. return 'mediump';
  11657. }
  11658. }
  11659. return 'lowp';
  11660. }
  11661. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11662. var maxPrecision = getMaxPrecision( precision );
  11663. if ( maxPrecision !== precision ) {
  11664. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11665. precision = maxPrecision;
  11666. }
  11667. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11668. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11669. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11670. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11671. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11672. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11673. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11674. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11675. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11676. var vertexTextures = maxVertexTextures > 0;
  11677. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11678. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11679. return {
  11680. getMaxAnisotropy: getMaxAnisotropy,
  11681. getMaxPrecision: getMaxPrecision,
  11682. precision: precision,
  11683. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11684. maxTextures: maxTextures,
  11685. maxVertexTextures: maxVertexTextures,
  11686. maxTextureSize: maxTextureSize,
  11687. maxCubemapSize: maxCubemapSize,
  11688. maxAttributes: maxAttributes,
  11689. maxVertexUniforms: maxVertexUniforms,
  11690. maxVaryings: maxVaryings,
  11691. maxFragmentUniforms: maxFragmentUniforms,
  11692. vertexTextures: vertexTextures,
  11693. floatFragmentTextures: floatFragmentTextures,
  11694. floatVertexTextures: floatVertexTextures
  11695. };
  11696. }
  11697. /**
  11698. * @author mrdoob / http://mrdoob.com/
  11699. */
  11700. function WebGLExtensions( gl ) {
  11701. var extensions = {};
  11702. return {
  11703. get: function ( name ) {
  11704. if ( extensions[ name ] !== undefined ) {
  11705. return extensions[ name ];
  11706. }
  11707. var extension;
  11708. switch ( name ) {
  11709. case 'WEBGL_depth_texture':
  11710. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11711. break;
  11712. case 'EXT_texture_filter_anisotropic':
  11713. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11714. break;
  11715. case 'WEBGL_compressed_texture_s3tc':
  11716. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11717. break;
  11718. case 'WEBGL_compressed_texture_pvrtc':
  11719. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11720. break;
  11721. case 'WEBGL_compressed_texture_etc1':
  11722. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11723. break;
  11724. default:
  11725. extension = gl.getExtension( name );
  11726. }
  11727. if ( extension === null ) {
  11728. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11729. }
  11730. extensions[ name ] = extension;
  11731. return extension;
  11732. }
  11733. };
  11734. }
  11735. /**
  11736. * @author tschw
  11737. */
  11738. function WebGLClipping() {
  11739. var scope = this,
  11740. globalState = null,
  11741. numGlobalPlanes = 0,
  11742. localClippingEnabled = false,
  11743. renderingShadows = false,
  11744. plane = new Plane(),
  11745. viewNormalMatrix = new Matrix3(),
  11746. uniform = { value: null, needsUpdate: false };
  11747. this.uniform = uniform;
  11748. this.numPlanes = 0;
  11749. this.numIntersection = 0;
  11750. this.init = function( planes, enableLocalClipping, camera ) {
  11751. var enabled =
  11752. planes.length !== 0 ||
  11753. enableLocalClipping ||
  11754. // enable state of previous frame - the clipping code has to
  11755. // run another frame in order to reset the state:
  11756. numGlobalPlanes !== 0 ||
  11757. localClippingEnabled;
  11758. localClippingEnabled = enableLocalClipping;
  11759. globalState = projectPlanes( planes, camera, 0 );
  11760. numGlobalPlanes = planes.length;
  11761. return enabled;
  11762. };
  11763. this.beginShadows = function() {
  11764. renderingShadows = true;
  11765. projectPlanes( null );
  11766. };
  11767. this.endShadows = function() {
  11768. renderingShadows = false;
  11769. resetGlobalState();
  11770. };
  11771. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11772. if ( ! localClippingEnabled ||
  11773. planes === null || planes.length === 0 ||
  11774. renderingShadows && ! clipShadows ) {
  11775. // there's no local clipping
  11776. if ( renderingShadows ) {
  11777. // there's no global clipping
  11778. projectPlanes( null );
  11779. } else {
  11780. resetGlobalState();
  11781. }
  11782. } else {
  11783. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11784. lGlobal = nGlobal * 4,
  11785. dstArray = cache.clippingState || null;
  11786. uniform.value = dstArray; // ensure unique state
  11787. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11788. for ( var i = 0; i !== lGlobal; ++ i ) {
  11789. dstArray[ i ] = globalState[ i ];
  11790. }
  11791. cache.clippingState = dstArray;
  11792. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11793. this.numPlanes += nGlobal;
  11794. }
  11795. };
  11796. function resetGlobalState() {
  11797. if ( uniform.value !== globalState ) {
  11798. uniform.value = globalState;
  11799. uniform.needsUpdate = numGlobalPlanes > 0;
  11800. }
  11801. scope.numPlanes = numGlobalPlanes;
  11802. scope.numIntersection = 0;
  11803. }
  11804. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11805. var nPlanes = planes !== null ? planes.length : 0,
  11806. dstArray = null;
  11807. if ( nPlanes !== 0 ) {
  11808. dstArray = uniform.value;
  11809. if ( skipTransform !== true || dstArray === null ) {
  11810. var flatSize = dstOffset + nPlanes * 4,
  11811. viewMatrix = camera.matrixWorldInverse;
  11812. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11813. if ( dstArray === null || dstArray.length < flatSize ) {
  11814. dstArray = new Float32Array( flatSize );
  11815. }
  11816. for ( var i = 0, i4 = dstOffset;
  11817. i !== nPlanes; ++ i, i4 += 4 ) {
  11818. plane.copy( planes[ i ] ).
  11819. applyMatrix4( viewMatrix, viewNormalMatrix );
  11820. plane.normal.toArray( dstArray, i4 );
  11821. dstArray[ i4 + 3 ] = plane.constant;
  11822. }
  11823. }
  11824. uniform.value = dstArray;
  11825. uniform.needsUpdate = true;
  11826. }
  11827. scope.numPlanes = nPlanes;
  11828. return dstArray;
  11829. }
  11830. }
  11831. // import { Sphere } from '../math/Sphere';
  11832. /**
  11833. * @author supereggbert / http://www.paulbrunt.co.uk/
  11834. * @author mrdoob / http://mrdoob.com/
  11835. * @author alteredq / http://alteredqualia.com/
  11836. * @author szimek / https://github.com/szimek/
  11837. * @author tschw
  11838. */
  11839. function WebGLRenderer( parameters ) {
  11840. console.log( 'THREE.WebGLRenderer', REVISION );
  11841. parameters = parameters || {};
  11842. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11843. _context = parameters.context !== undefined ? parameters.context : null,
  11844. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11845. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11846. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11847. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11848. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11849. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11850. var lights = [];
  11851. var currentRenderList = null;
  11852. var morphInfluences = new Float32Array( 8 );
  11853. var sprites = [];
  11854. var lensFlares = [];
  11855. // public properties
  11856. this.domElement = _canvas;
  11857. this.context = null;
  11858. // clearing
  11859. this.autoClear = true;
  11860. this.autoClearColor = true;
  11861. this.autoClearDepth = true;
  11862. this.autoClearStencil = true;
  11863. // scene graph
  11864. this.sortObjects = true;
  11865. // user-defined clipping
  11866. this.clippingPlanes = [];
  11867. this.localClippingEnabled = false;
  11868. // physically based shading
  11869. this.gammaFactor = 2.0; // for backwards compatibility
  11870. this.gammaInput = false;
  11871. this.gammaOutput = false;
  11872. // physical lights
  11873. this.physicallyCorrectLights = false;
  11874. // tone mapping
  11875. this.toneMapping = LinearToneMapping;
  11876. this.toneMappingExposure = 1.0;
  11877. this.toneMappingWhitePoint = 1.0;
  11878. // morphs
  11879. this.maxMorphTargets = 8;
  11880. this.maxMorphNormals = 4;
  11881. // internal properties
  11882. var _this = this,
  11883. // internal state cache
  11884. _currentProgram = null,
  11885. _currentRenderTarget = null,
  11886. _currentFramebuffer = null,
  11887. _currentMaterialId = - 1,
  11888. _currentGeometryProgram = '',
  11889. _currentCamera = null,
  11890. _currentScissor = new Vector4(),
  11891. _currentScissorTest = null,
  11892. _currentViewport = new Vector4(),
  11893. //
  11894. _usedTextureUnits = 0,
  11895. //
  11896. _clearColor = new Color( 0x000000 ),
  11897. _clearAlpha = 0,
  11898. _width = _canvas.width,
  11899. _height = _canvas.height,
  11900. _pixelRatio = 1,
  11901. _scissor = new Vector4( 0, 0, _width, _height ),
  11902. _scissorTest = false,
  11903. _viewport = new Vector4( 0, 0, _width, _height ),
  11904. // frustum
  11905. _frustum = new Frustum(),
  11906. // clipping
  11907. _clipping = new WebGLClipping(),
  11908. _clippingEnabled = false,
  11909. _localClippingEnabled = false,
  11910. // camera matrices cache
  11911. _projScreenMatrix = new Matrix4(),
  11912. _vector3 = new Vector3(),
  11913. _matrix4 = new Matrix4(),
  11914. _matrix42 = new Matrix4(),
  11915. // light arrays cache
  11916. _lights = {
  11917. hash: '',
  11918. ambient: [ 0, 0, 0 ],
  11919. directional: [],
  11920. directionalShadowMap: [],
  11921. directionalShadowMatrix: [],
  11922. spot: [],
  11923. spotShadowMap: [],
  11924. spotShadowMatrix: [],
  11925. rectArea: [],
  11926. point: [],
  11927. pointShadowMap: [],
  11928. pointShadowMatrix: [],
  11929. hemi: [],
  11930. shadows: []
  11931. },
  11932. // info
  11933. _infoMemory = {
  11934. geometries: 0,
  11935. textures: 0
  11936. },
  11937. _infoRender = {
  11938. frame: 0,
  11939. calls: 0,
  11940. vertices: 0,
  11941. faces: 0,
  11942. points: 0
  11943. };
  11944. this.info = {
  11945. render: _infoRender,
  11946. memory: _infoMemory,
  11947. programs: null
  11948. };
  11949. // initialize
  11950. var _gl;
  11951. try {
  11952. var contextAttributes = {
  11953. alpha: _alpha,
  11954. depth: _depth,
  11955. stencil: _stencil,
  11956. antialias: _antialias,
  11957. premultipliedAlpha: _premultipliedAlpha,
  11958. preserveDrawingBuffer: _preserveDrawingBuffer
  11959. };
  11960. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  11961. if ( _gl === null ) {
  11962. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11963. throw 'Error creating WebGL context with your selected attributes.';
  11964. } else {
  11965. throw 'Error creating WebGL context.';
  11966. }
  11967. }
  11968. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11969. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11970. _gl.getShaderPrecisionFormat = function () {
  11971. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11972. };
  11973. }
  11974. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11975. } catch ( error ) {
  11976. console.error( 'THREE.WebGLRenderer: ' + error );
  11977. }
  11978. var extensions = new WebGLExtensions( _gl );
  11979. extensions.get( 'WEBGL_depth_texture' );
  11980. extensions.get( 'OES_texture_float' );
  11981. extensions.get( 'OES_texture_float_linear' );
  11982. extensions.get( 'OES_texture_half_float' );
  11983. extensions.get( 'OES_texture_half_float_linear' );
  11984. extensions.get( 'OES_standard_derivatives' );
  11985. extensions.get( 'ANGLE_instanced_arrays' );
  11986. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11987. BufferGeometry.MaxIndex = 4294967296;
  11988. }
  11989. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11990. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11991. var properties = new WebGLProperties();
  11992. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory );
  11993. var attributes = new WebGLAttributes( _gl );
  11994. var geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  11995. var objects = new WebGLObjects( _gl, geometries, _infoRender );
  11996. var programCache = new WebGLPrograms( this, capabilities );
  11997. var lightCache = new WebGLLights();
  11998. var renderLists = new WebGLRenderLists();
  11999. this.info.programs = programCache.programs;
  12000. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  12001. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12002. //
  12003. var backgroundPlaneCamera, backgroundPlaneMesh;
  12004. var backgroundBoxCamera, backgroundBoxMesh;
  12005. //
  12006. function getTargetPixelRatio() {
  12007. return _currentRenderTarget === null ? _pixelRatio : 1;
  12008. }
  12009. function setDefaultGLState() {
  12010. state.init();
  12011. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  12012. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  12013. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12014. }
  12015. function resetGLState() {
  12016. _currentProgram = null;
  12017. _currentCamera = null;
  12018. _currentGeometryProgram = '';
  12019. _currentMaterialId = - 1;
  12020. state.reset();
  12021. }
  12022. setDefaultGLState();
  12023. this.context = _gl;
  12024. this.capabilities = capabilities;
  12025. this.extensions = extensions;
  12026. this.properties = properties;
  12027. this.state = state;
  12028. // shadow map
  12029. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  12030. this.shadowMap = shadowMap;
  12031. // Plugins
  12032. var spritePlugin = new SpritePlugin( this, sprites );
  12033. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  12034. // API
  12035. this.getContext = function () {
  12036. return _gl;
  12037. };
  12038. this.getContextAttributes = function () {
  12039. return _gl.getContextAttributes();
  12040. };
  12041. this.forceContextLoss = function () {
  12042. var extension = extensions.get( 'WEBGL_lose_context' );
  12043. if ( extension ) extension.loseContext();
  12044. };
  12045. this.getMaxAnisotropy = function () {
  12046. return capabilities.getMaxAnisotropy();
  12047. };
  12048. this.getPrecision = function () {
  12049. return capabilities.precision;
  12050. };
  12051. this.getPixelRatio = function () {
  12052. return _pixelRatio;
  12053. };
  12054. this.setPixelRatio = function ( value ) {
  12055. if ( value === undefined ) return;
  12056. _pixelRatio = value;
  12057. this.setSize( _viewport.z, _viewport.w, false );
  12058. };
  12059. this.getSize = function () {
  12060. return {
  12061. width: _width,
  12062. height: _height
  12063. };
  12064. };
  12065. this.setSize = function ( width, height, updateStyle ) {
  12066. _width = width;
  12067. _height = height;
  12068. _canvas.width = width * _pixelRatio;
  12069. _canvas.height = height * _pixelRatio;
  12070. if ( updateStyle !== false ) {
  12071. _canvas.style.width = width + 'px';
  12072. _canvas.style.height = height + 'px';
  12073. }
  12074. this.setViewport( 0, 0, width, height );
  12075. };
  12076. this.setViewport = function ( x, y, width, height ) {
  12077. state.viewport( _viewport.set( x, y, width, height ) );
  12078. };
  12079. this.setScissor = function ( x, y, width, height ) {
  12080. state.scissor( _scissor.set( x, y, width, height ) );
  12081. };
  12082. this.setScissorTest = function ( boolean ) {
  12083. state.setScissorTest( _scissorTest = boolean );
  12084. };
  12085. // Clearing
  12086. this.getClearColor = function () {
  12087. return _clearColor;
  12088. };
  12089. this.setClearColor = function ( color, alpha ) {
  12090. _clearColor.set( color );
  12091. _clearAlpha = alpha !== undefined ? alpha : 1;
  12092. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12093. };
  12094. this.getClearAlpha = function () {
  12095. return _clearAlpha;
  12096. };
  12097. this.setClearAlpha = function ( alpha ) {
  12098. _clearAlpha = alpha;
  12099. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12100. };
  12101. this.clear = function ( color, depth, stencil ) {
  12102. var bits = 0;
  12103. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12104. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12105. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12106. _gl.clear( bits );
  12107. };
  12108. this.clearColor = function () {
  12109. this.clear( true, false, false );
  12110. };
  12111. this.clearDepth = function () {
  12112. this.clear( false, true, false );
  12113. };
  12114. this.clearStencil = function () {
  12115. this.clear( false, false, true );
  12116. };
  12117. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12118. this.setRenderTarget( renderTarget );
  12119. this.clear( color, depth, stencil );
  12120. };
  12121. // Reset
  12122. this.resetGLState = resetGLState;
  12123. this.dispose = function () {
  12124. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  12125. renderLists.dispose();
  12126. };
  12127. // Events
  12128. function onContextLost( event ) {
  12129. event.preventDefault();
  12130. resetGLState();
  12131. setDefaultGLState();
  12132. properties.clear();
  12133. objects.clear();
  12134. }
  12135. function onMaterialDispose( event ) {
  12136. var material = event.target;
  12137. material.removeEventListener( 'dispose', onMaterialDispose );
  12138. deallocateMaterial( material );
  12139. }
  12140. // Buffer deallocation
  12141. function deallocateMaterial( material ) {
  12142. releaseMaterialProgramReference( material );
  12143. properties.remove( material );
  12144. }
  12145. function releaseMaterialProgramReference( material ) {
  12146. var programInfo = properties.get( material ).program;
  12147. material.program = undefined;
  12148. if ( programInfo !== undefined ) {
  12149. programCache.releaseProgram( programInfo );
  12150. }
  12151. }
  12152. // Buffer rendering
  12153. function renderObjectImmediate( object, program, material ) {
  12154. object.render( function ( object ) {
  12155. _this.renderBufferImmediate( object, program, material );
  12156. } );
  12157. }
  12158. this.renderBufferImmediate = function ( object, program, material ) {
  12159. state.initAttributes();
  12160. var buffers = properties.get( object );
  12161. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  12162. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  12163. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  12164. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  12165. var programAttributes = program.getAttributes();
  12166. if ( object.hasPositions ) {
  12167. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  12168. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12169. state.enableAttribute( programAttributes.position );
  12170. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12171. }
  12172. if ( object.hasNormals ) {
  12173. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12174. if ( ! material.isMeshPhongMaterial &&
  12175. ! material.isMeshStandardMaterial &&
  12176. ! material.isMeshNormalMaterial &&
  12177. material.shading === FlatShading ) {
  12178. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12179. var array = object.normalArray;
  12180. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12181. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12182. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12183. array[ i + 0 ] = nx;
  12184. array[ i + 1 ] = ny;
  12185. array[ i + 2 ] = nz;
  12186. array[ i + 3 ] = nx;
  12187. array[ i + 4 ] = ny;
  12188. array[ i + 5 ] = nz;
  12189. array[ i + 6 ] = nx;
  12190. array[ i + 7 ] = ny;
  12191. array[ i + 8 ] = nz;
  12192. }
  12193. }
  12194. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12195. state.enableAttribute( programAttributes.normal );
  12196. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12197. }
  12198. if ( object.hasUvs && material.map ) {
  12199. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12200. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12201. state.enableAttribute( programAttributes.uv );
  12202. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12203. }
  12204. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12205. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12206. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12207. state.enableAttribute( programAttributes.color );
  12208. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12209. }
  12210. state.disableUnusedAttributes();
  12211. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12212. object.count = 0;
  12213. };
  12214. function absNumericalSort( a, b ) {
  12215. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12216. }
  12217. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12218. state.setMaterial( material );
  12219. var program = setProgram( camera, fog, material, object );
  12220. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  12221. var updateBuffers = false;
  12222. if ( geometryProgram !== _currentGeometryProgram ) {
  12223. _currentGeometryProgram = geometryProgram;
  12224. updateBuffers = true;
  12225. }
  12226. // morph targets
  12227. var morphTargetInfluences = object.morphTargetInfluences;
  12228. if ( morphTargetInfluences !== undefined ) {
  12229. // TODO Remove allocations
  12230. var activeInfluences = [];
  12231. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12232. var influence = morphTargetInfluences[ i ];
  12233. activeInfluences.push( [ influence, i ] );
  12234. }
  12235. activeInfluences.sort( absNumericalSort );
  12236. if ( activeInfluences.length > 8 ) {
  12237. activeInfluences.length = 8;
  12238. }
  12239. var morphAttributes = geometry.morphAttributes;
  12240. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12241. var influence = activeInfluences[ i ];
  12242. morphInfluences[ i ] = influence[ 0 ];
  12243. if ( influence[ 0 ] !== 0 ) {
  12244. var index = influence[ 1 ];
  12245. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12246. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12247. } else {
  12248. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12249. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12250. }
  12251. }
  12252. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12253. morphInfluences[ i ] = 0.0;
  12254. }
  12255. program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences );
  12256. updateBuffers = true;
  12257. }
  12258. //
  12259. var index = geometry.index;
  12260. var position = geometry.attributes.position;
  12261. var rangeFactor = 1;
  12262. if ( material.wireframe === true ) {
  12263. index = geometries.getWireframeAttribute( geometry );
  12264. rangeFactor = 2;
  12265. }
  12266. var renderer = bufferRenderer;
  12267. if ( index !== null ) {
  12268. renderer = indexedBufferRenderer;
  12269. renderer.setIndex( index );
  12270. }
  12271. if ( updateBuffers ) {
  12272. setupVertexAttributes( material, program, geometry );
  12273. if ( index !== null ) {
  12274. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  12275. }
  12276. }
  12277. //
  12278. var dataCount = 0;
  12279. if ( index !== null ) {
  12280. dataCount = index.count;
  12281. } else if ( position !== undefined ) {
  12282. dataCount = position.count;
  12283. }
  12284. var rangeStart = geometry.drawRange.start * rangeFactor;
  12285. var rangeCount = geometry.drawRange.count * rangeFactor;
  12286. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12287. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12288. var drawStart = Math.max( rangeStart, groupStart );
  12289. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12290. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12291. if ( drawCount === 0 ) return;
  12292. //
  12293. if ( object.isMesh ) {
  12294. if ( material.wireframe === true ) {
  12295. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12296. renderer.setMode( _gl.LINES );
  12297. } else {
  12298. switch ( object.drawMode ) {
  12299. case TrianglesDrawMode:
  12300. renderer.setMode( _gl.TRIANGLES );
  12301. break;
  12302. case TriangleStripDrawMode:
  12303. renderer.setMode( _gl.TRIANGLE_STRIP );
  12304. break;
  12305. case TriangleFanDrawMode:
  12306. renderer.setMode( _gl.TRIANGLE_FAN );
  12307. break;
  12308. }
  12309. }
  12310. } else if ( object.isLine ) {
  12311. var lineWidth = material.linewidth;
  12312. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12313. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12314. if ( object.isLineSegments ) {
  12315. renderer.setMode( _gl.LINES );
  12316. } else if ( object.isLineLoop ) {
  12317. renderer.setMode( _gl.LINE_LOOP );
  12318. } else {
  12319. renderer.setMode( _gl.LINE_STRIP );
  12320. }
  12321. } else if ( object.isPoints ) {
  12322. renderer.setMode( _gl.POINTS );
  12323. }
  12324. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12325. if ( geometry.maxInstancedCount > 0 ) {
  12326. renderer.renderInstances( geometry, drawStart, drawCount );
  12327. }
  12328. } else {
  12329. renderer.render( drawStart, drawCount );
  12330. }
  12331. };
  12332. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12333. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12334. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  12335. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12336. return;
  12337. }
  12338. }
  12339. if ( startIndex === undefined ) startIndex = 0;
  12340. state.initAttributes();
  12341. var geometryAttributes = geometry.attributes;
  12342. var programAttributes = program.getAttributes();
  12343. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12344. for ( var name in programAttributes ) {
  12345. var programAttribute = programAttributes[ name ];
  12346. if ( programAttribute >= 0 ) {
  12347. var geometryAttribute = geometryAttributes[ name ];
  12348. if ( geometryAttribute !== undefined ) {
  12349. var normalized = geometryAttribute.normalized;
  12350. var size = geometryAttribute.itemSize;
  12351. var attributeProperties = attributes.get( geometryAttribute );
  12352. var buffer = attributeProperties.buffer;
  12353. var type = attributeProperties.type;
  12354. var bytesPerElement = attributeProperties.bytesPerElement;
  12355. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12356. var data = geometryAttribute.data;
  12357. var stride = data.stride;
  12358. var offset = geometryAttribute.offset;
  12359. if ( data && data.isInstancedInterleavedBuffer ) {
  12360. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  12361. if ( geometry.maxInstancedCount === undefined ) {
  12362. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12363. }
  12364. } else {
  12365. state.enableAttribute( programAttribute );
  12366. }
  12367. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12368. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12369. } else {
  12370. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12371. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  12372. if ( geometry.maxInstancedCount === undefined ) {
  12373. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12374. }
  12375. } else {
  12376. state.enableAttribute( programAttribute );
  12377. }
  12378. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12379. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12380. }
  12381. } else if ( materialDefaultAttributeValues !== undefined ) {
  12382. var value = materialDefaultAttributeValues[ name ];
  12383. if ( value !== undefined ) {
  12384. switch ( value.length ) {
  12385. case 2:
  12386. _gl.vertexAttrib2fv( programAttribute, value );
  12387. break;
  12388. case 3:
  12389. _gl.vertexAttrib3fv( programAttribute, value );
  12390. break;
  12391. case 4:
  12392. _gl.vertexAttrib4fv( programAttribute, value );
  12393. break;
  12394. default:
  12395. _gl.vertexAttrib1fv( programAttribute, value );
  12396. }
  12397. }
  12398. }
  12399. }
  12400. }
  12401. state.disableUnusedAttributes();
  12402. }
  12403. // Compile
  12404. this.compile = function ( scene, camera ) {
  12405. lights = [];
  12406. scene.traverse( function ( object ) {
  12407. if ( object.isLight ) {
  12408. lights.push( object );
  12409. }
  12410. } );
  12411. setupLights( lights, camera );
  12412. scene.traverse( function ( object ) {
  12413. if ( object.material ) {
  12414. if ( Array.isArray( object.material ) ) {
  12415. for ( var i = 0; i < object.material.length; i ++ ) {
  12416. initMaterial( object.material[ i ], scene.fog, object );
  12417. }
  12418. } else {
  12419. initMaterial( object.material, scene.fog, object );
  12420. }
  12421. }
  12422. } );
  12423. };
  12424. // Rendering
  12425. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12426. if ( camera !== undefined && camera.isCamera !== true ) {
  12427. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12428. return;
  12429. }
  12430. // reset caching for this frame
  12431. _currentGeometryProgram = '';
  12432. _currentMaterialId = - 1;
  12433. _currentCamera = null;
  12434. // update scene graph
  12435. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12436. // update camera matrices and frustum
  12437. camera.onBeforeRender( _this );
  12438. if ( camera.parent === null ) camera.updateMatrixWorld();
  12439. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12440. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12441. _frustum.setFromMatrix( _projScreenMatrix );
  12442. lights.length = 0;
  12443. sprites.length = 0;
  12444. lensFlares.length = 0;
  12445. _localClippingEnabled = this.localClippingEnabled;
  12446. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12447. currentRenderList = renderLists.get( scene, camera );
  12448. currentRenderList.init();
  12449. projectObject( scene, camera, _this.sortObjects );
  12450. currentRenderList.finish();
  12451. if ( _this.sortObjects === true ) {
  12452. currentRenderList.sort();
  12453. }
  12454. //
  12455. if ( _clippingEnabled ) _clipping.beginShadows();
  12456. setupShadows( lights );
  12457. shadowMap.render( scene, camera );
  12458. setupLights( lights, camera );
  12459. if ( _clippingEnabled ) _clipping.endShadows();
  12460. //
  12461. _infoRender.frame ++;
  12462. _infoRender.calls = 0;
  12463. _infoRender.vertices = 0;
  12464. _infoRender.faces = 0;
  12465. _infoRender.points = 0;
  12466. if ( renderTarget === undefined ) {
  12467. renderTarget = null;
  12468. }
  12469. this.setRenderTarget( renderTarget );
  12470. //
  12471. var background = scene.background;
  12472. if ( background === null ) {
  12473. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12474. } else if ( background && background.isColor ) {
  12475. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12476. forceClear = true;
  12477. }
  12478. if ( this.autoClear || forceClear ) {
  12479. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12480. }
  12481. if ( background && background.isCubeTexture ) {
  12482. if ( backgroundBoxCamera === undefined ) {
  12483. backgroundBoxCamera = new PerspectiveCamera();
  12484. backgroundBoxMesh = new Mesh(
  12485. new BoxBufferGeometry( 5, 5, 5 ),
  12486. new ShaderMaterial( {
  12487. uniforms: ShaderLib.cube.uniforms,
  12488. vertexShader: ShaderLib.cube.vertexShader,
  12489. fragmentShader: ShaderLib.cube.fragmentShader,
  12490. side: BackSide,
  12491. depthTest: false,
  12492. depthWrite: false,
  12493. fog: false
  12494. } )
  12495. );
  12496. }
  12497. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  12498. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  12499. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  12500. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12501. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12502. objects.update( backgroundBoxMesh );
  12503. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12504. } else if ( background && background.isTexture ) {
  12505. if ( backgroundPlaneCamera === undefined ) {
  12506. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12507. backgroundPlaneMesh = new Mesh(
  12508. new PlaneBufferGeometry( 2, 2 ),
  12509. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  12510. );
  12511. }
  12512. backgroundPlaneMesh.material.map = background;
  12513. objects.update( backgroundPlaneMesh );
  12514. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12515. }
  12516. //
  12517. var opaqueObjects = currentRenderList.opaque;
  12518. var transparentObjects = currentRenderList.transparent;
  12519. if ( scene.overrideMaterial ) {
  12520. var overrideMaterial = scene.overrideMaterial;
  12521. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12522. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12523. } else {
  12524. // opaque pass (front-to-back order)
  12525. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  12526. // transparent pass (back-to-front order)
  12527. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  12528. }
  12529. // custom render plugins (post pass)
  12530. spritePlugin.render( scene, camera );
  12531. lensFlarePlugin.render( scene, camera, _currentViewport );
  12532. // Generate mipmap if we're using any kind of mipmap filtering
  12533. if ( renderTarget ) {
  12534. textures.updateRenderTargetMipmap( renderTarget );
  12535. }
  12536. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12537. state.buffers.depth.setTest( true );
  12538. state.buffers.depth.setMask( true );
  12539. state.buffers.color.setMask( true );
  12540. if ( camera.isArrayCamera && camera.enabled ) {
  12541. _this.setScissorTest( false );
  12542. }
  12543. camera.onAfterRender( _this );
  12544. // _gl.finish();
  12545. };
  12546. /*
  12547. // TODO Duplicated code (Frustum)
  12548. var _sphere = new Sphere();
  12549. function isObjectViewable( object ) {
  12550. var geometry = object.geometry;
  12551. if ( geometry.boundingSphere === null )
  12552. geometry.computeBoundingSphere();
  12553. _sphere.copy( geometry.boundingSphere ).
  12554. applyMatrix4( object.matrixWorld );
  12555. return isSphereViewable( _sphere );
  12556. }
  12557. function isSpriteViewable( sprite ) {
  12558. _sphere.center.set( 0, 0, 0 );
  12559. _sphere.radius = 0.7071067811865476;
  12560. _sphere.applyMatrix4( sprite.matrixWorld );
  12561. return isSphereViewable( _sphere );
  12562. }
  12563. function isSphereViewable( sphere ) {
  12564. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12565. var numPlanes = _clipping.numPlanes;
  12566. if ( numPlanes === 0 ) return true;
  12567. var planes = _this.clippingPlanes,
  12568. center = sphere.center,
  12569. negRad = - sphere.radius,
  12570. i = 0;
  12571. do {
  12572. // out when deeper than radius in the negative halfspace
  12573. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12574. } while ( ++ i !== numPlanes );
  12575. return true;
  12576. }
  12577. */
  12578. function projectObject( object, camera, sortObjects ) {
  12579. if ( ! object.visible ) return;
  12580. var visible = object.layers.test( camera.layers );
  12581. if ( visible ) {
  12582. if ( object.isLight ) {
  12583. lights.push( object );
  12584. } else if ( object.isSprite ) {
  12585. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  12586. sprites.push( object );
  12587. }
  12588. } else if ( object.isLensFlare ) {
  12589. lensFlares.push( object );
  12590. } else if ( object.isImmediateRenderObject ) {
  12591. if ( sortObjects ) {
  12592. _vector3.setFromMatrixPosition( object.matrixWorld )
  12593. .applyMatrix4( _projScreenMatrix );
  12594. }
  12595. currentRenderList.push( object, null, object.material, _vector3.z, null );
  12596. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12597. if ( object.isSkinnedMesh ) {
  12598. object.skeleton.update();
  12599. }
  12600. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  12601. if ( sortObjects ) {
  12602. _vector3.setFromMatrixPosition( object.matrixWorld )
  12603. .applyMatrix4( _projScreenMatrix );
  12604. }
  12605. var geometry = objects.update( object );
  12606. var material = object.material;
  12607. if ( Array.isArray( material ) ) {
  12608. var groups = geometry.groups;
  12609. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12610. var group = groups[ i ];
  12611. var groupMaterial = material[ group.materialIndex ];
  12612. if ( groupMaterial && groupMaterial.visible ) {
  12613. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  12614. }
  12615. }
  12616. } else if ( material.visible ) {
  12617. currentRenderList.push( object, geometry, material, _vector3.z, null );
  12618. }
  12619. }
  12620. }
  12621. }
  12622. var children = object.children;
  12623. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12624. projectObject( children[ i ], camera, sortObjects );
  12625. }
  12626. }
  12627. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12628. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12629. var renderItem = renderList[ i ];
  12630. var object = renderItem.object;
  12631. var geometry = renderItem.geometry;
  12632. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12633. var group = renderItem.group;
  12634. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12635. if ( camera.isArrayCamera && camera.enabled ) {
  12636. var cameras = camera.cameras;
  12637. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  12638. var camera2 = cameras[ j ];
  12639. var bounds = camera2.bounds;
  12640. _this.setViewport(
  12641. bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
  12642. bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
  12643. );
  12644. _this.setScissor(
  12645. bounds.x * _width * _pixelRatio, bounds.y * _height * _pixelRatio,
  12646. bounds.z * _width * _pixelRatio, bounds.w * _height * _pixelRatio
  12647. );
  12648. _this.setScissorTest( true );
  12649. renderObject( object, scene, camera2, geometry, material, group );
  12650. }
  12651. } else {
  12652. renderObject( object, scene, camera, geometry, material, group );
  12653. }
  12654. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12655. }
  12656. }
  12657. function renderObject( object, scene, camera, geometry, material, group ) {
  12658. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12659. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12660. if ( object.isImmediateRenderObject ) {
  12661. state.setMaterial( material );
  12662. var program = setProgram( camera, scene.fog, material, object );
  12663. _currentGeometryProgram = '';
  12664. renderObjectImmediate( object, program, material );
  12665. } else {
  12666. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12667. }
  12668. }
  12669. function initMaterial( material, fog, object ) {
  12670. var materialProperties = properties.get( material );
  12671. var parameters = programCache.getParameters(
  12672. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12673. var code = programCache.getProgramCode( material, parameters );
  12674. var program = materialProperties.program;
  12675. var programChange = true;
  12676. if ( program === undefined ) {
  12677. // new material
  12678. material.addEventListener( 'dispose', onMaterialDispose );
  12679. } else if ( program.code !== code ) {
  12680. // changed glsl or parameters
  12681. releaseMaterialProgramReference( material );
  12682. } else if ( parameters.shaderID !== undefined ) {
  12683. // same glsl and uniform list
  12684. return;
  12685. } else {
  12686. // only rebuild uniform list
  12687. programChange = false;
  12688. }
  12689. if ( programChange ) {
  12690. if ( parameters.shaderID ) {
  12691. var shader = ShaderLib[ parameters.shaderID ];
  12692. materialProperties.__webglShader = {
  12693. name: material.type,
  12694. uniforms: UniformsUtils.clone( shader.uniforms ),
  12695. vertexShader: shader.vertexShader,
  12696. fragmentShader: shader.fragmentShader
  12697. };
  12698. } else {
  12699. materialProperties.__webglShader = {
  12700. name: material.type,
  12701. uniforms: material.uniforms,
  12702. vertexShader: material.vertexShader,
  12703. fragmentShader: material.fragmentShader
  12704. };
  12705. }
  12706. material.__webglShader = materialProperties.__webglShader;
  12707. program = programCache.acquireProgram( material, parameters, code );
  12708. materialProperties.program = program;
  12709. material.program = program;
  12710. }
  12711. var programAttributes = program.getAttributes();
  12712. if ( material.morphTargets ) {
  12713. material.numSupportedMorphTargets = 0;
  12714. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12715. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  12716. material.numSupportedMorphTargets ++;
  12717. }
  12718. }
  12719. }
  12720. if ( material.morphNormals ) {
  12721. material.numSupportedMorphNormals = 0;
  12722. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12723. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  12724. material.numSupportedMorphNormals ++;
  12725. }
  12726. }
  12727. }
  12728. var uniforms = materialProperties.__webglShader.uniforms;
  12729. if ( ! material.isShaderMaterial &&
  12730. ! material.isRawShaderMaterial ||
  12731. material.clipping === true ) {
  12732. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12733. materialProperties.numIntersection = _clipping.numIntersection;
  12734. uniforms.clippingPlanes = _clipping.uniform;
  12735. }
  12736. materialProperties.fog = fog;
  12737. // store the light setup it was created for
  12738. materialProperties.lightsHash = _lights.hash;
  12739. if ( material.lights ) {
  12740. // wire up the material to this renderer's lighting state
  12741. uniforms.ambientLightColor.value = _lights.ambient;
  12742. uniforms.directionalLights.value = _lights.directional;
  12743. uniforms.spotLights.value = _lights.spot;
  12744. uniforms.rectAreaLights.value = _lights.rectArea;
  12745. uniforms.pointLights.value = _lights.point;
  12746. uniforms.hemisphereLights.value = _lights.hemi;
  12747. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12748. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12749. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12750. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12751. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12752. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12753. // TODO (abelnation): add area lights shadow info to uniforms
  12754. }
  12755. var progUniforms = materialProperties.program.getUniforms(),
  12756. uniformsList =
  12757. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12758. materialProperties.uniformsList = uniformsList;
  12759. }
  12760. function setProgram( camera, fog, material, object ) {
  12761. _usedTextureUnits = 0;
  12762. var materialProperties = properties.get( material );
  12763. if ( _clippingEnabled ) {
  12764. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12765. var useCache =
  12766. camera === _currentCamera &&
  12767. material.id === _currentMaterialId;
  12768. // we might want to call this function with some ClippingGroup
  12769. // object instead of the material, once it becomes feasible
  12770. // (#8465, #8379)
  12771. _clipping.setState(
  12772. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12773. camera, materialProperties, useCache );
  12774. }
  12775. }
  12776. if ( material.needsUpdate === false ) {
  12777. if ( materialProperties.program === undefined ) {
  12778. material.needsUpdate = true;
  12779. } else if ( material.fog && materialProperties.fog !== fog ) {
  12780. material.needsUpdate = true;
  12781. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12782. material.needsUpdate = true;
  12783. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12784. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12785. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12786. material.needsUpdate = true;
  12787. }
  12788. }
  12789. if ( material.needsUpdate ) {
  12790. initMaterial( material, fog, object );
  12791. material.needsUpdate = false;
  12792. }
  12793. var refreshProgram = false;
  12794. var refreshMaterial = false;
  12795. var refreshLights = false;
  12796. var program = materialProperties.program,
  12797. p_uniforms = program.getUniforms(),
  12798. m_uniforms = materialProperties.__webglShader.uniforms;
  12799. if ( program.id !== _currentProgram ) {
  12800. _gl.useProgram( program.program );
  12801. _currentProgram = program.id;
  12802. refreshProgram = true;
  12803. refreshMaterial = true;
  12804. refreshLights = true;
  12805. }
  12806. if ( material.id !== _currentMaterialId ) {
  12807. _currentMaterialId = material.id;
  12808. refreshMaterial = true;
  12809. }
  12810. if ( refreshProgram || camera !== _currentCamera ) {
  12811. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  12812. if ( capabilities.logarithmicDepthBuffer ) {
  12813. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12814. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12815. }
  12816. if ( camera !== _currentCamera ) {
  12817. _currentCamera = camera;
  12818. // lighting uniforms depend on the camera so enforce an update
  12819. // now, in case this material supports lights - or later, when
  12820. // the next material that does gets activated:
  12821. refreshMaterial = true; // set to true on material change
  12822. refreshLights = true; // remains set until update done
  12823. }
  12824. // load material specific uniforms
  12825. // (shader material also gets them for the sake of genericity)
  12826. if ( material.isShaderMaterial ||
  12827. material.isMeshPhongMaterial ||
  12828. material.isMeshStandardMaterial ||
  12829. material.envMap ) {
  12830. var uCamPos = p_uniforms.map.cameraPosition;
  12831. if ( uCamPos !== undefined ) {
  12832. uCamPos.setValue( _gl,
  12833. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12834. }
  12835. }
  12836. if ( material.isMeshPhongMaterial ||
  12837. material.isMeshLambertMaterial ||
  12838. material.isMeshBasicMaterial ||
  12839. material.isMeshStandardMaterial ||
  12840. material.isShaderMaterial ||
  12841. material.skinning ) {
  12842. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12843. }
  12844. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  12845. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  12846. }
  12847. // skinning uniforms must be set even if material didn't change
  12848. // auto-setting of texture unit for bone texture must go before other textures
  12849. // not sure why, but otherwise weird things happen
  12850. if ( material.skinning ) {
  12851. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12852. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12853. var skeleton = object.skeleton;
  12854. if ( skeleton ) {
  12855. var bones = skeleton.bones;
  12856. if ( capabilities.floatVertexTextures ) {
  12857. if ( skeleton.boneTexture === undefined ) {
  12858. // layout (1 matrix = 4 pixels)
  12859. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  12860. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  12861. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  12862. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  12863. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  12864. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  12865. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  12866. size = Math.max( size, 4 );
  12867. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  12868. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  12869. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  12870. skeleton.boneMatrices = boneMatrices;
  12871. skeleton.boneTexture = boneTexture;
  12872. skeleton.boneTextureSize = size;
  12873. }
  12874. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  12875. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  12876. } else {
  12877. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12878. }
  12879. }
  12880. }
  12881. if ( refreshMaterial ) {
  12882. if ( material.lights ) {
  12883. // the current material requires lighting info
  12884. // note: all lighting uniforms are always set correctly
  12885. // they simply reference the renderer's state for their
  12886. // values
  12887. //
  12888. // use the current material's .needsUpdate flags to set
  12889. // the GL state when required
  12890. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12891. }
  12892. // refresh uniforms common to several materials
  12893. if ( fog && material.fog ) {
  12894. refreshUniformsFog( m_uniforms, fog );
  12895. }
  12896. if ( material.isMeshBasicMaterial ||
  12897. material.isMeshLambertMaterial ||
  12898. material.isMeshPhongMaterial ||
  12899. material.isMeshStandardMaterial ||
  12900. material.isMeshNormalMaterial ||
  12901. material.isMeshDepthMaterial ) {
  12902. refreshUniformsCommon( m_uniforms, material );
  12903. }
  12904. // refresh single material specific uniforms
  12905. if ( material.isLineBasicMaterial ) {
  12906. refreshUniformsLine( m_uniforms, material );
  12907. } else if ( material.isLineDashedMaterial ) {
  12908. refreshUniformsLine( m_uniforms, material );
  12909. refreshUniformsDash( m_uniforms, material );
  12910. } else if ( material.isPointsMaterial ) {
  12911. refreshUniformsPoints( m_uniforms, material );
  12912. } else if ( material.isMeshLambertMaterial ) {
  12913. refreshUniformsLambert( m_uniforms, material );
  12914. } else if ( material.isMeshToonMaterial ) {
  12915. refreshUniformsToon( m_uniforms, material );
  12916. } else if ( material.isMeshPhongMaterial ) {
  12917. refreshUniformsPhong( m_uniforms, material );
  12918. } else if ( material.isMeshPhysicalMaterial ) {
  12919. refreshUniformsPhysical( m_uniforms, material );
  12920. } else if ( material.isMeshStandardMaterial ) {
  12921. refreshUniformsStandard( m_uniforms, material );
  12922. } else if ( material.isMeshDepthMaterial ) {
  12923. if ( material.displacementMap ) {
  12924. m_uniforms.displacementMap.value = material.displacementMap;
  12925. m_uniforms.displacementScale.value = material.displacementScale;
  12926. m_uniforms.displacementBias.value = material.displacementBias;
  12927. }
  12928. } else if ( material.isMeshNormalMaterial ) {
  12929. refreshUniformsNormal( m_uniforms, material );
  12930. }
  12931. // RectAreaLight Texture
  12932. // TODO (mrdoob): Find a nicer implementation
  12933. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  12934. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  12935. WebGLUniforms.upload(
  12936. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12937. }
  12938. // common matrices
  12939. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  12940. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  12941. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12942. return program;
  12943. }
  12944. // Uniforms (refresh uniforms objects)
  12945. function refreshUniformsCommon( uniforms, material ) {
  12946. uniforms.opacity.value = material.opacity;
  12947. uniforms.diffuse.value = material.color;
  12948. if ( material.emissive ) {
  12949. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12950. }
  12951. uniforms.map.value = material.map;
  12952. uniforms.specularMap.value = material.specularMap;
  12953. uniforms.alphaMap.value = material.alphaMap;
  12954. if ( material.lightMap ) {
  12955. uniforms.lightMap.value = material.lightMap;
  12956. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12957. }
  12958. if ( material.aoMap ) {
  12959. uniforms.aoMap.value = material.aoMap;
  12960. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12961. }
  12962. // uv repeat and offset setting priorities
  12963. // 1. color map
  12964. // 2. specular map
  12965. // 3. normal map
  12966. // 4. bump map
  12967. // 5. alpha map
  12968. // 6. emissive map
  12969. var uvScaleMap;
  12970. if ( material.map ) {
  12971. uvScaleMap = material.map;
  12972. } else if ( material.specularMap ) {
  12973. uvScaleMap = material.specularMap;
  12974. } else if ( material.displacementMap ) {
  12975. uvScaleMap = material.displacementMap;
  12976. } else if ( material.normalMap ) {
  12977. uvScaleMap = material.normalMap;
  12978. } else if ( material.bumpMap ) {
  12979. uvScaleMap = material.bumpMap;
  12980. } else if ( material.roughnessMap ) {
  12981. uvScaleMap = material.roughnessMap;
  12982. } else if ( material.metalnessMap ) {
  12983. uvScaleMap = material.metalnessMap;
  12984. } else if ( material.alphaMap ) {
  12985. uvScaleMap = material.alphaMap;
  12986. } else if ( material.emissiveMap ) {
  12987. uvScaleMap = material.emissiveMap;
  12988. }
  12989. if ( uvScaleMap !== undefined ) {
  12990. // backwards compatibility
  12991. if ( uvScaleMap.isWebGLRenderTarget ) {
  12992. uvScaleMap = uvScaleMap.texture;
  12993. }
  12994. var offset = uvScaleMap.offset;
  12995. var repeat = uvScaleMap.repeat;
  12996. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12997. }
  12998. uniforms.envMap.value = material.envMap;
  12999. // don't flip CubeTexture envMaps, flip everything else:
  13000. // WebGLRenderTargetCube will be flipped for backwards compatibility
  13001. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  13002. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  13003. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  13004. uniforms.reflectivity.value = material.reflectivity;
  13005. uniforms.refractionRatio.value = material.refractionRatio;
  13006. }
  13007. function refreshUniformsLine( uniforms, material ) {
  13008. uniforms.diffuse.value = material.color;
  13009. uniforms.opacity.value = material.opacity;
  13010. }
  13011. function refreshUniformsDash( uniforms, material ) {
  13012. uniforms.dashSize.value = material.dashSize;
  13013. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13014. uniforms.scale.value = material.scale;
  13015. }
  13016. function refreshUniformsPoints( uniforms, material ) {
  13017. uniforms.diffuse.value = material.color;
  13018. uniforms.opacity.value = material.opacity;
  13019. uniforms.size.value = material.size * _pixelRatio;
  13020. uniforms.scale.value = _height * 0.5;
  13021. uniforms.map.value = material.map;
  13022. if ( material.map !== null ) {
  13023. var offset = material.map.offset;
  13024. var repeat = material.map.repeat;
  13025. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13026. }
  13027. }
  13028. function refreshUniformsFog( uniforms, fog ) {
  13029. uniforms.fogColor.value = fog.color;
  13030. if ( fog.isFog ) {
  13031. uniforms.fogNear.value = fog.near;
  13032. uniforms.fogFar.value = fog.far;
  13033. } else if ( fog.isFogExp2 ) {
  13034. uniforms.fogDensity.value = fog.density;
  13035. }
  13036. }
  13037. function refreshUniformsLambert( uniforms, material ) {
  13038. if ( material.emissiveMap ) {
  13039. uniforms.emissiveMap.value = material.emissiveMap;
  13040. }
  13041. }
  13042. function refreshUniformsPhong( uniforms, material ) {
  13043. uniforms.specular.value = material.specular;
  13044. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13045. if ( material.emissiveMap ) {
  13046. uniforms.emissiveMap.value = material.emissiveMap;
  13047. }
  13048. if ( material.bumpMap ) {
  13049. uniforms.bumpMap.value = material.bumpMap;
  13050. uniforms.bumpScale.value = material.bumpScale;
  13051. }
  13052. if ( material.normalMap ) {
  13053. uniforms.normalMap.value = material.normalMap;
  13054. uniforms.normalScale.value.copy( material.normalScale );
  13055. }
  13056. if ( material.displacementMap ) {
  13057. uniforms.displacementMap.value = material.displacementMap;
  13058. uniforms.displacementScale.value = material.displacementScale;
  13059. uniforms.displacementBias.value = material.displacementBias;
  13060. }
  13061. }
  13062. function refreshUniformsToon( uniforms, material ) {
  13063. refreshUniformsPhong( uniforms, material );
  13064. if ( material.gradientMap ) {
  13065. uniforms.gradientMap.value = material.gradientMap;
  13066. }
  13067. }
  13068. function refreshUniformsStandard( uniforms, material ) {
  13069. uniforms.roughness.value = material.roughness;
  13070. uniforms.metalness.value = material.metalness;
  13071. if ( material.roughnessMap ) {
  13072. uniforms.roughnessMap.value = material.roughnessMap;
  13073. }
  13074. if ( material.metalnessMap ) {
  13075. uniforms.metalnessMap.value = material.metalnessMap;
  13076. }
  13077. if ( material.emissiveMap ) {
  13078. uniforms.emissiveMap.value = material.emissiveMap;
  13079. }
  13080. if ( material.bumpMap ) {
  13081. uniforms.bumpMap.value = material.bumpMap;
  13082. uniforms.bumpScale.value = material.bumpScale;
  13083. }
  13084. if ( material.normalMap ) {
  13085. uniforms.normalMap.value = material.normalMap;
  13086. uniforms.normalScale.value.copy( material.normalScale );
  13087. }
  13088. if ( material.displacementMap ) {
  13089. uniforms.displacementMap.value = material.displacementMap;
  13090. uniforms.displacementScale.value = material.displacementScale;
  13091. uniforms.displacementBias.value = material.displacementBias;
  13092. }
  13093. if ( material.envMap ) {
  13094. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13095. uniforms.envMapIntensity.value = material.envMapIntensity;
  13096. }
  13097. }
  13098. function refreshUniformsPhysical( uniforms, material ) {
  13099. uniforms.clearCoat.value = material.clearCoat;
  13100. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  13101. refreshUniformsStandard( uniforms, material );
  13102. }
  13103. function refreshUniformsNormal( uniforms, material ) {
  13104. if ( material.bumpMap ) {
  13105. uniforms.bumpMap.value = material.bumpMap;
  13106. uniforms.bumpScale.value = material.bumpScale;
  13107. }
  13108. if ( material.normalMap ) {
  13109. uniforms.normalMap.value = material.normalMap;
  13110. uniforms.normalScale.value.copy( material.normalScale );
  13111. }
  13112. if ( material.displacementMap ) {
  13113. uniforms.displacementMap.value = material.displacementMap;
  13114. uniforms.displacementScale.value = material.displacementScale;
  13115. uniforms.displacementBias.value = material.displacementBias;
  13116. }
  13117. }
  13118. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13119. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  13120. uniforms.ambientLightColor.needsUpdate = value;
  13121. uniforms.directionalLights.needsUpdate = value;
  13122. uniforms.pointLights.needsUpdate = value;
  13123. uniforms.spotLights.needsUpdate = value;
  13124. uniforms.rectAreaLights.needsUpdate = value;
  13125. uniforms.hemisphereLights.needsUpdate = value;
  13126. }
  13127. // Lighting
  13128. function setupShadows( lights ) {
  13129. var lightShadowsLength = 0;
  13130. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  13131. var light = lights[ i ];
  13132. if ( light.castShadow ) {
  13133. _lights.shadows[ lightShadowsLength ] = light;
  13134. lightShadowsLength ++;
  13135. }
  13136. }
  13137. _lights.shadows.length = lightShadowsLength;
  13138. }
  13139. function setupLights( lights, camera ) {
  13140. var l, ll, light, shadow,
  13141. r = 0, g = 0, b = 0,
  13142. color,
  13143. intensity,
  13144. distance,
  13145. shadowMap,
  13146. viewMatrix = camera.matrixWorldInverse,
  13147. directionalLength = 0,
  13148. pointLength = 0,
  13149. spotLength = 0,
  13150. rectAreaLength = 0,
  13151. hemiLength = 0;
  13152. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13153. light = lights[ l ];
  13154. color = light.color;
  13155. intensity = light.intensity;
  13156. distance = light.distance;
  13157. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13158. if ( light.isAmbientLight ) {
  13159. r += color.r * intensity;
  13160. g += color.g * intensity;
  13161. b += color.b * intensity;
  13162. } else if ( light.isDirectionalLight ) {
  13163. var uniforms = lightCache.get( light );
  13164. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13165. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13166. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13167. uniforms.direction.sub( _vector3 );
  13168. uniforms.direction.transformDirection( viewMatrix );
  13169. uniforms.shadow = light.castShadow;
  13170. if ( light.castShadow ) {
  13171. shadow = light.shadow;
  13172. uniforms.shadowBias = shadow.bias;
  13173. uniforms.shadowRadius = shadow.radius;
  13174. uniforms.shadowMapSize = shadow.mapSize;
  13175. }
  13176. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  13177. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13178. _lights.directional[ directionalLength ] = uniforms;
  13179. directionalLength ++;
  13180. } else if ( light.isSpotLight ) {
  13181. var uniforms = lightCache.get( light );
  13182. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13183. uniforms.position.applyMatrix4( viewMatrix );
  13184. uniforms.color.copy( color ).multiplyScalar( intensity );
  13185. uniforms.distance = distance;
  13186. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13187. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13188. uniforms.direction.sub( _vector3 );
  13189. uniforms.direction.transformDirection( viewMatrix );
  13190. uniforms.coneCos = Math.cos( light.angle );
  13191. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13192. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13193. uniforms.shadow = light.castShadow;
  13194. if ( light.castShadow ) {
  13195. shadow = light.shadow;
  13196. uniforms.shadowBias = shadow.bias;
  13197. uniforms.shadowRadius = shadow.radius;
  13198. uniforms.shadowMapSize = shadow.mapSize;
  13199. }
  13200. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13201. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13202. _lights.spot[ spotLength ] = uniforms;
  13203. spotLength ++;
  13204. } else if ( light.isRectAreaLight ) {
  13205. var uniforms = lightCache.get( light );
  13206. // (a) intensity controls irradiance of entire light
  13207. uniforms.color
  13208. .copy( color )
  13209. .multiplyScalar( intensity / ( light.width * light.height ) );
  13210. // (b) intensity controls the radiance per light area
  13211. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13212. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13213. uniforms.position.applyMatrix4( viewMatrix );
  13214. // extract local rotation of light to derive width/height half vectors
  13215. _matrix42.identity();
  13216. _matrix4.copy( light.matrixWorld );
  13217. _matrix4.premultiply( viewMatrix );
  13218. _matrix42.extractRotation( _matrix4 );
  13219. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13220. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13221. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13222. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13223. // TODO (abelnation): RectAreaLight distance?
  13224. // uniforms.distance = distance;
  13225. _lights.rectArea[ rectAreaLength ] = uniforms;
  13226. rectAreaLength ++;
  13227. } else if ( light.isPointLight ) {
  13228. var uniforms = lightCache.get( light );
  13229. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13230. uniforms.position.applyMatrix4( viewMatrix );
  13231. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13232. uniforms.distance = light.distance;
  13233. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13234. uniforms.shadow = light.castShadow;
  13235. if ( light.castShadow ) {
  13236. shadow = light.shadow;
  13237. uniforms.shadowBias = shadow.bias;
  13238. uniforms.shadowRadius = shadow.radius;
  13239. uniforms.shadowMapSize = shadow.mapSize;
  13240. }
  13241. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13242. _lights.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13243. _lights.point[ pointLength ] = uniforms;
  13244. pointLength ++;
  13245. } else if ( light.isHemisphereLight ) {
  13246. var uniforms = lightCache.get( light );
  13247. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13248. uniforms.direction.transformDirection( viewMatrix );
  13249. uniforms.direction.normalize();
  13250. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13251. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13252. _lights.hemi[ hemiLength ] = uniforms;
  13253. hemiLength ++;
  13254. }
  13255. }
  13256. _lights.ambient[ 0 ] = r;
  13257. _lights.ambient[ 1 ] = g;
  13258. _lights.ambient[ 2 ] = b;
  13259. _lights.directional.length = directionalLength;
  13260. _lights.spot.length = spotLength;
  13261. _lights.rectArea.length = rectAreaLength;
  13262. _lights.point.length = pointLength;
  13263. _lights.hemi.length = hemiLength;
  13264. // TODO (sam-g-steel) why aren't we using join
  13265. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13266. }
  13267. // GL state setting
  13268. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13269. state.setCullFace( cullFace );
  13270. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13271. };
  13272. // Textures
  13273. function allocTextureUnit() {
  13274. var textureUnit = _usedTextureUnits;
  13275. if ( textureUnit >= capabilities.maxTextures ) {
  13276. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13277. }
  13278. _usedTextureUnits += 1;
  13279. return textureUnit;
  13280. }
  13281. this.allocTextureUnit = allocTextureUnit;
  13282. // this.setTexture2D = setTexture2D;
  13283. this.setTexture2D = ( function () {
  13284. var warned = false;
  13285. // backwards compatibility: peel texture.texture
  13286. return function setTexture2D( texture, slot ) {
  13287. if ( texture && texture.isWebGLRenderTarget ) {
  13288. if ( ! warned ) {
  13289. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13290. warned = true;
  13291. }
  13292. texture = texture.texture;
  13293. }
  13294. textures.setTexture2D( texture, slot );
  13295. };
  13296. }() );
  13297. this.setTexture = ( function () {
  13298. var warned = false;
  13299. return function setTexture( texture, slot ) {
  13300. if ( ! warned ) {
  13301. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13302. warned = true;
  13303. }
  13304. textures.setTexture2D( texture, slot );
  13305. };
  13306. }() );
  13307. this.setTextureCube = ( function () {
  13308. var warned = false;
  13309. return function setTextureCube( texture, slot ) {
  13310. // backwards compatibility: peel texture.texture
  13311. if ( texture && texture.isWebGLRenderTargetCube ) {
  13312. if ( ! warned ) {
  13313. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13314. warned = true;
  13315. }
  13316. texture = texture.texture;
  13317. }
  13318. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13319. // TODO: unify these code paths
  13320. if ( ( texture && texture.isCubeTexture ) ||
  13321. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13322. // CompressedTexture can have Array in image :/
  13323. // this function alone should take care of cube textures
  13324. textures.setTextureCube( texture, slot );
  13325. } else {
  13326. // assumed: texture property of THREE.WebGLRenderTargetCube
  13327. textures.setTextureCubeDynamic( texture, slot );
  13328. }
  13329. };
  13330. }() );
  13331. this.getRenderTarget = function () {
  13332. return _currentRenderTarget;
  13333. };
  13334. this.setRenderTarget = function ( renderTarget ) {
  13335. _currentRenderTarget = renderTarget;
  13336. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13337. textures.setupRenderTarget( renderTarget );
  13338. }
  13339. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13340. var framebuffer;
  13341. if ( renderTarget ) {
  13342. var renderTargetProperties = properties.get( renderTarget );
  13343. if ( isCube ) {
  13344. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13345. } else {
  13346. framebuffer = renderTargetProperties.__webglFramebuffer;
  13347. }
  13348. _currentScissor.copy( renderTarget.scissor );
  13349. _currentScissorTest = renderTarget.scissorTest;
  13350. _currentViewport.copy( renderTarget.viewport );
  13351. } else {
  13352. framebuffer = null;
  13353. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13354. _currentScissorTest = _scissorTest;
  13355. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13356. }
  13357. if ( _currentFramebuffer !== framebuffer ) {
  13358. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13359. _currentFramebuffer = framebuffer;
  13360. }
  13361. state.scissor( _currentScissor );
  13362. state.setScissorTest( _currentScissorTest );
  13363. state.viewport( _currentViewport );
  13364. if ( isCube ) {
  13365. var textureProperties = properties.get( renderTarget.texture );
  13366. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13367. }
  13368. };
  13369. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13370. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13371. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13372. return;
  13373. }
  13374. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13375. if ( framebuffer ) {
  13376. var restore = false;
  13377. if ( framebuffer !== _currentFramebuffer ) {
  13378. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13379. restore = true;
  13380. }
  13381. try {
  13382. var texture = renderTarget.texture;
  13383. var textureFormat = texture.format;
  13384. var textureType = texture.type;
  13385. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13386. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13387. return;
  13388. }
  13389. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13390. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13391. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13392. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13393. return;
  13394. }
  13395. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13396. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13397. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13398. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13399. }
  13400. } else {
  13401. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13402. }
  13403. } finally {
  13404. if ( restore ) {
  13405. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13406. }
  13407. }
  13408. }
  13409. };
  13410. // Map three.js constants to WebGL constants
  13411. function paramThreeToGL( p ) {
  13412. var extension;
  13413. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13414. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13415. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13416. if ( p === NearestFilter ) return _gl.NEAREST;
  13417. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13418. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13419. if ( p === LinearFilter ) return _gl.LINEAR;
  13420. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13421. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13422. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13423. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13424. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13425. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13426. if ( p === ByteType ) return _gl.BYTE;
  13427. if ( p === ShortType ) return _gl.SHORT;
  13428. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13429. if ( p === IntType ) return _gl.INT;
  13430. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13431. if ( p === FloatType ) return _gl.FLOAT;
  13432. if ( p === HalfFloatType ) {
  13433. extension = extensions.get( 'OES_texture_half_float' );
  13434. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13435. }
  13436. if ( p === AlphaFormat ) return _gl.ALPHA;
  13437. if ( p === RGBFormat ) return _gl.RGB;
  13438. if ( p === RGBAFormat ) return _gl.RGBA;
  13439. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13440. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13441. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13442. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13443. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13444. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13445. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13446. if ( p === ZeroFactor ) return _gl.ZERO;
  13447. if ( p === OneFactor ) return _gl.ONE;
  13448. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13449. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13450. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13451. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13452. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13453. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13454. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13455. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13456. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13457. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13458. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13459. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13460. if ( extension !== null ) {
  13461. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13462. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13463. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13464. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13465. }
  13466. }
  13467. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13468. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13469. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13470. if ( extension !== null ) {
  13471. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13472. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13473. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13474. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13475. }
  13476. }
  13477. if ( p === RGB_ETC1_Format ) {
  13478. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13479. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13480. }
  13481. if ( p === MinEquation || p === MaxEquation ) {
  13482. extension = extensions.get( 'EXT_blend_minmax' );
  13483. if ( extension !== null ) {
  13484. if ( p === MinEquation ) return extension.MIN_EXT;
  13485. if ( p === MaxEquation ) return extension.MAX_EXT;
  13486. }
  13487. }
  13488. if ( p === UnsignedInt248Type ) {
  13489. extension = extensions.get( 'WEBGL_depth_texture' );
  13490. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13491. }
  13492. return 0;
  13493. }
  13494. }
  13495. /**
  13496. * @author mrdoob / http://mrdoob.com/
  13497. * @author alteredq / http://alteredqualia.com/
  13498. */
  13499. function FogExp2 ( color, density ) {
  13500. this.name = '';
  13501. this.color = new Color( color );
  13502. this.density = ( density !== undefined ) ? density : 0.00025;
  13503. }
  13504. FogExp2.prototype.isFogExp2 = true;
  13505. FogExp2.prototype.clone = function () {
  13506. return new FogExp2( this.color.getHex(), this.density );
  13507. };
  13508. FogExp2.prototype.toJSON = function ( meta ) {
  13509. return {
  13510. type: 'FogExp2',
  13511. color: this.color.getHex(),
  13512. density: this.density
  13513. };
  13514. };
  13515. /**
  13516. * @author mrdoob / http://mrdoob.com/
  13517. * @author alteredq / http://alteredqualia.com/
  13518. */
  13519. function Fog ( color, near, far ) {
  13520. this.name = '';
  13521. this.color = new Color( color );
  13522. this.near = ( near !== undefined ) ? near : 1;
  13523. this.far = ( far !== undefined ) ? far : 1000;
  13524. }
  13525. Fog.prototype.isFog = true;
  13526. Fog.prototype.clone = function () {
  13527. return new Fog( this.color.getHex(), this.near, this.far );
  13528. };
  13529. Fog.prototype.toJSON = function ( meta ) {
  13530. return {
  13531. type: 'Fog',
  13532. color: this.color.getHex(),
  13533. near: this.near,
  13534. far: this.far
  13535. };
  13536. };
  13537. /**
  13538. * @author mrdoob / http://mrdoob.com/
  13539. */
  13540. function Scene () {
  13541. Object3D.call( this );
  13542. this.type = 'Scene';
  13543. this.background = null;
  13544. this.fog = null;
  13545. this.overrideMaterial = null;
  13546. this.autoUpdate = true; // checked by the renderer
  13547. }
  13548. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13549. constructor: Scene,
  13550. copy: function ( source, recursive ) {
  13551. Object3D.prototype.copy.call( this, source, recursive );
  13552. if ( source.background !== null ) this.background = source.background.clone();
  13553. if ( source.fog !== null ) this.fog = source.fog.clone();
  13554. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13555. this.autoUpdate = source.autoUpdate;
  13556. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13557. return this;
  13558. },
  13559. toJSON: function ( meta ) {
  13560. var data = Object3D.prototype.toJSON.call( this, meta );
  13561. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13562. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13563. return data;
  13564. }
  13565. } );
  13566. /**
  13567. * @author mikael emtinger / http://gomo.se/
  13568. * @author alteredq / http://alteredqualia.com/
  13569. */
  13570. function LensFlare( texture, size, distance, blending, color ) {
  13571. Object3D.call( this );
  13572. this.lensFlares = [];
  13573. this.positionScreen = new Vector3();
  13574. this.customUpdateCallback = undefined;
  13575. if ( texture !== undefined ) {
  13576. this.add( texture, size, distance, blending, color );
  13577. }
  13578. }
  13579. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13580. constructor: LensFlare,
  13581. isLensFlare: true,
  13582. copy: function ( source ) {
  13583. Object3D.prototype.copy.call( this, source );
  13584. this.positionScreen.copy( source.positionScreen );
  13585. this.customUpdateCallback = source.customUpdateCallback;
  13586. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13587. this.lensFlares.push( source.lensFlares[ i ] );
  13588. }
  13589. return this;
  13590. },
  13591. add: function ( texture, size, distance, blending, color, opacity ) {
  13592. if ( size === undefined ) size = - 1;
  13593. if ( distance === undefined ) distance = 0;
  13594. if ( opacity === undefined ) opacity = 1;
  13595. if ( color === undefined ) color = new Color( 0xffffff );
  13596. if ( blending === undefined ) blending = NormalBlending;
  13597. distance = Math.min( distance, Math.max( 0, distance ) );
  13598. this.lensFlares.push( {
  13599. texture: texture, // THREE.Texture
  13600. size: size, // size in pixels (-1 = use texture.width)
  13601. distance: distance, // distance (0-1) from light source (0=at light source)
  13602. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13603. scale: 1, // scale
  13604. rotation: 0, // rotation
  13605. opacity: opacity, // opacity
  13606. color: color, // color
  13607. blending: blending // blending
  13608. } );
  13609. },
  13610. /*
  13611. * Update lens flares update positions on all flares based on the screen position
  13612. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13613. */
  13614. updateLensFlares: function () {
  13615. var f, fl = this.lensFlares.length;
  13616. var flare;
  13617. var vecX = - this.positionScreen.x * 2;
  13618. var vecY = - this.positionScreen.y * 2;
  13619. for ( f = 0; f < fl; f ++ ) {
  13620. flare = this.lensFlares[ f ];
  13621. flare.x = this.positionScreen.x + vecX * flare.distance;
  13622. flare.y = this.positionScreen.y + vecY * flare.distance;
  13623. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13624. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13625. }
  13626. }
  13627. } );
  13628. /**
  13629. * @author alteredq / http://alteredqualia.com/
  13630. *
  13631. * parameters = {
  13632. * color: <hex>,
  13633. * opacity: <float>,
  13634. * map: new THREE.Texture( <Image> ),
  13635. *
  13636. * uvOffset: new THREE.Vector2(),
  13637. * uvScale: new THREE.Vector2()
  13638. * }
  13639. */
  13640. function SpriteMaterial( parameters ) {
  13641. Material.call( this );
  13642. this.type = 'SpriteMaterial';
  13643. this.color = new Color( 0xffffff );
  13644. this.map = null;
  13645. this.rotation = 0;
  13646. this.fog = false;
  13647. this.lights = false;
  13648. this.setValues( parameters );
  13649. }
  13650. SpriteMaterial.prototype = Object.create( Material.prototype );
  13651. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13652. SpriteMaterial.prototype.isSpriteMaterial = true;
  13653. SpriteMaterial.prototype.copy = function ( source ) {
  13654. Material.prototype.copy.call( this, source );
  13655. this.color.copy( source.color );
  13656. this.map = source.map;
  13657. this.rotation = source.rotation;
  13658. return this;
  13659. };
  13660. /**
  13661. * @author mikael emtinger / http://gomo.se/
  13662. * @author alteredq / http://alteredqualia.com/
  13663. */
  13664. function Sprite( material ) {
  13665. Object3D.call( this );
  13666. this.type = 'Sprite';
  13667. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13668. }
  13669. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13670. constructor: Sprite,
  13671. isSprite: true,
  13672. raycast: ( function () {
  13673. var intersectPoint = new Vector3();
  13674. var worldPosition = new Vector3();
  13675. var worldScale = new Vector3();
  13676. return function raycast( raycaster, intersects ) {
  13677. worldPosition.setFromMatrixPosition( this.matrixWorld );
  13678. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  13679. worldScale.setFromMatrixScale( this.matrixWorld );
  13680. var guessSizeSq = worldScale.x * worldScale.y / 4;
  13681. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  13682. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13683. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13684. intersects.push( {
  13685. distance: distance,
  13686. point: intersectPoint.clone(),
  13687. face: null,
  13688. object: this
  13689. } );
  13690. };
  13691. }() ),
  13692. clone: function () {
  13693. return new this.constructor( this.material ).copy( this );
  13694. }
  13695. } );
  13696. /**
  13697. * @author mikael emtinger / http://gomo.se/
  13698. * @author alteredq / http://alteredqualia.com/
  13699. * @author mrdoob / http://mrdoob.com/
  13700. */
  13701. function LOD() {
  13702. Object3D.call( this );
  13703. this.type = 'LOD';
  13704. Object.defineProperties( this, {
  13705. levels: {
  13706. enumerable: true,
  13707. value: []
  13708. }
  13709. } );
  13710. }
  13711. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13712. constructor: LOD,
  13713. copy: function ( source ) {
  13714. Object3D.prototype.copy.call( this, source, false );
  13715. var levels = source.levels;
  13716. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13717. var level = levels[ i ];
  13718. this.addLevel( level.object.clone(), level.distance );
  13719. }
  13720. return this;
  13721. },
  13722. addLevel: function ( object, distance ) {
  13723. if ( distance === undefined ) distance = 0;
  13724. distance = Math.abs( distance );
  13725. var levels = this.levels;
  13726. for ( var l = 0; l < levels.length; l ++ ) {
  13727. if ( distance < levels[ l ].distance ) {
  13728. break;
  13729. }
  13730. }
  13731. levels.splice( l, 0, { distance: distance, object: object } );
  13732. this.add( object );
  13733. },
  13734. getObjectForDistance: function ( distance ) {
  13735. var levels = this.levels;
  13736. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13737. if ( distance < levels[ i ].distance ) {
  13738. break;
  13739. }
  13740. }
  13741. return levels[ i - 1 ].object;
  13742. },
  13743. raycast: ( function () {
  13744. var matrixPosition = new Vector3();
  13745. return function raycast( raycaster, intersects ) {
  13746. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13747. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13748. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13749. };
  13750. }() ),
  13751. update: function () {
  13752. var v1 = new Vector3();
  13753. var v2 = new Vector3();
  13754. return function update( camera ) {
  13755. var levels = this.levels;
  13756. if ( levels.length > 1 ) {
  13757. v1.setFromMatrixPosition( camera.matrixWorld );
  13758. v2.setFromMatrixPosition( this.matrixWorld );
  13759. var distance = v1.distanceTo( v2 );
  13760. levels[ 0 ].object.visible = true;
  13761. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13762. if ( distance >= levels[ i ].distance ) {
  13763. levels[ i - 1 ].object.visible = false;
  13764. levels[ i ].object.visible = true;
  13765. } else {
  13766. break;
  13767. }
  13768. }
  13769. for ( ; i < l; i ++ ) {
  13770. levels[ i ].object.visible = false;
  13771. }
  13772. }
  13773. };
  13774. }(),
  13775. toJSON: function ( meta ) {
  13776. var data = Object3D.prototype.toJSON.call( this, meta );
  13777. data.object.levels = [];
  13778. var levels = this.levels;
  13779. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13780. var level = levels[ i ];
  13781. data.object.levels.push( {
  13782. object: level.object.uuid,
  13783. distance: level.distance
  13784. } );
  13785. }
  13786. return data;
  13787. }
  13788. } );
  13789. /**
  13790. * @author mikael emtinger / http://gomo.se/
  13791. * @author alteredq / http://alteredqualia.com/
  13792. * @author michael guerrero / http://realitymeltdown.com
  13793. * @author ikerr / http://verold.com
  13794. */
  13795. function Skeleton( bones, boneInverses ) {
  13796. // copy the bone array
  13797. bones = bones || [];
  13798. this.bones = bones.slice( 0 );
  13799. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  13800. // use the supplied bone inverses or calculate the inverses
  13801. if ( boneInverses === undefined ) {
  13802. this.calculateInverses();
  13803. } else {
  13804. if ( this.bones.length === boneInverses.length ) {
  13805. this.boneInverses = boneInverses.slice( 0 );
  13806. } else {
  13807. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  13808. this.boneInverses = [];
  13809. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  13810. this.boneInverses.push( new Matrix4() );
  13811. }
  13812. }
  13813. }
  13814. }
  13815. Object.assign( Skeleton.prototype, {
  13816. calculateInverses: function () {
  13817. this.boneInverses = [];
  13818. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  13819. var inverse = new Matrix4();
  13820. if ( this.bones[ i ] ) {
  13821. inverse.getInverse( this.bones[ i ].matrixWorld );
  13822. }
  13823. this.boneInverses.push( inverse );
  13824. }
  13825. },
  13826. pose: function () {
  13827. var bone, i, il;
  13828. // recover the bind-time world matrices
  13829. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  13830. bone = this.bones[ i ];
  13831. if ( bone ) {
  13832. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  13833. }
  13834. }
  13835. // compute the local matrices, positions, rotations and scales
  13836. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  13837. bone = this.bones[ i ];
  13838. if ( bone ) {
  13839. if ( bone.parent && bone.parent.isBone ) {
  13840. bone.matrix.getInverse( bone.parent.matrixWorld );
  13841. bone.matrix.multiply( bone.matrixWorld );
  13842. } else {
  13843. bone.matrix.copy( bone.matrixWorld );
  13844. }
  13845. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13846. }
  13847. }
  13848. },
  13849. update: ( function () {
  13850. var offsetMatrix = new Matrix4();
  13851. var identityMatrix = new Matrix4();
  13852. return function update() {
  13853. var bones = this.bones;
  13854. var boneInverses = this.boneInverses;
  13855. var boneMatrices = this.boneMatrices;
  13856. var boneTexture = this.boneTexture;
  13857. // flatten bone matrices to array
  13858. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  13859. // compute the offset between the current and the original transform
  13860. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  13861. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  13862. offsetMatrix.toArray( boneMatrices, i * 16 );
  13863. }
  13864. if ( boneTexture !== undefined ) {
  13865. boneTexture.needsUpdate = true;
  13866. }
  13867. };
  13868. } )(),
  13869. clone: function () {
  13870. return new Skeleton( this.bones, this.boneInverses );
  13871. }
  13872. } );
  13873. /**
  13874. * @author mikael emtinger / http://gomo.se/
  13875. * @author alteredq / http://alteredqualia.com/
  13876. * @author ikerr / http://verold.com
  13877. */
  13878. function Bone() {
  13879. Object3D.call( this );
  13880. this.type = 'Bone';
  13881. }
  13882. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13883. constructor: Bone,
  13884. isBone: true
  13885. } );
  13886. /**
  13887. * @author mikael emtinger / http://gomo.se/
  13888. * @author alteredq / http://alteredqualia.com/
  13889. * @author ikerr / http://verold.com
  13890. */
  13891. function SkinnedMesh( geometry, material ) {
  13892. Mesh.call( this, geometry, material );
  13893. this.type = 'SkinnedMesh';
  13894. this.bindMode = 'attached';
  13895. this.bindMatrix = new Matrix4();
  13896. this.bindMatrixInverse = new Matrix4();
  13897. var bones = this.initBones();
  13898. var skeleton = new Skeleton( bones );
  13899. this.bind( skeleton, this.matrixWorld );
  13900. this.normalizeSkinWeights();
  13901. }
  13902. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13903. constructor: SkinnedMesh,
  13904. isSkinnedMesh: true,
  13905. initBones: function () {
  13906. var bones = [], bone, gbone;
  13907. var i, il;
  13908. if ( this.geometry && this.geometry.bones !== undefined ) {
  13909. // first, create array of 'Bone' objects from geometry data
  13910. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  13911. gbone = this.geometry.bones[ i ];
  13912. // create new 'Bone' object
  13913. bone = new Bone();
  13914. bones.push( bone );
  13915. // apply values
  13916. bone.name = gbone.name;
  13917. bone.position.fromArray( gbone.pos );
  13918. bone.quaternion.fromArray( gbone.rotq );
  13919. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13920. }
  13921. // second, create bone hierarchy
  13922. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  13923. gbone = this.geometry.bones[ i ];
  13924. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  13925. // subsequent bones in the hierarchy
  13926. bones[ gbone.parent ].add( bones[ i ] );
  13927. } else {
  13928. // topmost bone, immediate child of the skinned mesh
  13929. this.add( bones[ i ] );
  13930. }
  13931. }
  13932. }
  13933. // now the bones are part of the scene graph and children of the skinned mesh.
  13934. // let's update the corresponding matrices
  13935. this.updateMatrixWorld( true );
  13936. return bones;
  13937. },
  13938. bind: function ( skeleton, bindMatrix ) {
  13939. this.skeleton = skeleton;
  13940. if ( bindMatrix === undefined ) {
  13941. this.updateMatrixWorld( true );
  13942. this.skeleton.calculateInverses();
  13943. bindMatrix = this.matrixWorld;
  13944. }
  13945. this.bindMatrix.copy( bindMatrix );
  13946. this.bindMatrixInverse.getInverse( bindMatrix );
  13947. },
  13948. pose: function () {
  13949. this.skeleton.pose();
  13950. },
  13951. normalizeSkinWeights: function () {
  13952. var scale, i;
  13953. if ( this.geometry && this.geometry.isGeometry ) {
  13954. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13955. var sw = this.geometry.skinWeights[ i ];
  13956. scale = 1.0 / sw.lengthManhattan();
  13957. if ( scale !== Infinity ) {
  13958. sw.multiplyScalar( scale );
  13959. } else {
  13960. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13961. }
  13962. }
  13963. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13964. var vec = new Vector4();
  13965. var skinWeight = this.geometry.attributes.skinWeight;
  13966. for ( i = 0; i < skinWeight.count; i ++ ) {
  13967. vec.x = skinWeight.getX( i );
  13968. vec.y = skinWeight.getY( i );
  13969. vec.z = skinWeight.getZ( i );
  13970. vec.w = skinWeight.getW( i );
  13971. scale = 1.0 / vec.lengthManhattan();
  13972. if ( scale !== Infinity ) {
  13973. vec.multiplyScalar( scale );
  13974. } else {
  13975. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13976. }
  13977. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13978. }
  13979. }
  13980. },
  13981. updateMatrixWorld: function ( force ) {
  13982. Mesh.prototype.updateMatrixWorld.call( this, force );
  13983. if ( this.bindMode === 'attached' ) {
  13984. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13985. } else if ( this.bindMode === 'detached' ) {
  13986. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13987. } else {
  13988. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  13989. }
  13990. },
  13991. clone: function () {
  13992. return new this.constructor( this.geometry, this.material ).copy( this );
  13993. }
  13994. } );
  13995. /**
  13996. * @author mrdoob / http://mrdoob.com/
  13997. * @author alteredq / http://alteredqualia.com/
  13998. *
  13999. * parameters = {
  14000. * color: <hex>,
  14001. * opacity: <float>,
  14002. *
  14003. * linewidth: <float>,
  14004. * linecap: "round",
  14005. * linejoin: "round"
  14006. * }
  14007. */
  14008. function LineBasicMaterial( parameters ) {
  14009. Material.call( this );
  14010. this.type = 'LineBasicMaterial';
  14011. this.color = new Color( 0xffffff );
  14012. this.linewidth = 1;
  14013. this.linecap = 'round';
  14014. this.linejoin = 'round';
  14015. this.lights = false;
  14016. this.setValues( parameters );
  14017. }
  14018. LineBasicMaterial.prototype = Object.create( Material.prototype );
  14019. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  14020. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  14021. LineBasicMaterial.prototype.copy = function ( source ) {
  14022. Material.prototype.copy.call( this, source );
  14023. this.color.copy( source.color );
  14024. this.linewidth = source.linewidth;
  14025. this.linecap = source.linecap;
  14026. this.linejoin = source.linejoin;
  14027. return this;
  14028. };
  14029. /**
  14030. * @author mrdoob / http://mrdoob.com/
  14031. */
  14032. function Line( geometry, material, mode ) {
  14033. if ( mode === 1 ) {
  14034. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  14035. return new LineSegments( geometry, material );
  14036. }
  14037. Object3D.call( this );
  14038. this.type = 'Line';
  14039. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14040. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  14041. }
  14042. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14043. constructor: Line,
  14044. isLine: true,
  14045. raycast: ( function () {
  14046. var inverseMatrix = new Matrix4();
  14047. var ray = new Ray();
  14048. var sphere = new Sphere();
  14049. return function raycast( raycaster, intersects ) {
  14050. var precision = raycaster.linePrecision;
  14051. var precisionSq = precision * precision;
  14052. var geometry = this.geometry;
  14053. var matrixWorld = this.matrixWorld;
  14054. // Checking boundingSphere distance to ray
  14055. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14056. sphere.copy( geometry.boundingSphere );
  14057. sphere.applyMatrix4( matrixWorld );
  14058. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14059. //
  14060. inverseMatrix.getInverse( matrixWorld );
  14061. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14062. var vStart = new Vector3();
  14063. var vEnd = new Vector3();
  14064. var interSegment = new Vector3();
  14065. var interRay = new Vector3();
  14066. var step = (this && this.isLineSegments) ? 2 : 1;
  14067. if ( geometry.isBufferGeometry ) {
  14068. var index = geometry.index;
  14069. var attributes = geometry.attributes;
  14070. var positions = attributes.position.array;
  14071. if ( index !== null ) {
  14072. var indices = index.array;
  14073. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  14074. var a = indices[ i ];
  14075. var b = indices[ i + 1 ];
  14076. vStart.fromArray( positions, a * 3 );
  14077. vEnd.fromArray( positions, b * 3 );
  14078. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14079. if ( distSq > precisionSq ) continue;
  14080. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14081. var distance = raycaster.ray.origin.distanceTo( interRay );
  14082. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14083. intersects.push( {
  14084. distance: distance,
  14085. // What do we want? intersection point on the ray or on the segment??
  14086. // point: raycaster.ray.at( distance ),
  14087. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14088. index: i,
  14089. face: null,
  14090. faceIndex: null,
  14091. object: this
  14092. } );
  14093. }
  14094. } else {
  14095. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  14096. vStart.fromArray( positions, 3 * i );
  14097. vEnd.fromArray( positions, 3 * i + 3 );
  14098. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  14099. if ( distSq > precisionSq ) continue;
  14100. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14101. var distance = raycaster.ray.origin.distanceTo( interRay );
  14102. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14103. intersects.push( {
  14104. distance: distance,
  14105. // What do we want? intersection point on the ray or on the segment??
  14106. // point: raycaster.ray.at( distance ),
  14107. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14108. index: i,
  14109. face: null,
  14110. faceIndex: null,
  14111. object: this
  14112. } );
  14113. }
  14114. }
  14115. } else if ( geometry.isGeometry ) {
  14116. var vertices = geometry.vertices;
  14117. var nbVertices = vertices.length;
  14118. for ( var i = 0; i < nbVertices - 1; i += step ) {
  14119. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  14120. if ( distSq > precisionSq ) continue;
  14121. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  14122. var distance = raycaster.ray.origin.distanceTo( interRay );
  14123. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  14124. intersects.push( {
  14125. distance: distance,
  14126. // What do we want? intersection point on the ray or on the segment??
  14127. // point: raycaster.ray.at( distance ),
  14128. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  14129. index: i,
  14130. face: null,
  14131. faceIndex: null,
  14132. object: this
  14133. } );
  14134. }
  14135. }
  14136. };
  14137. }() ),
  14138. clone: function () {
  14139. return new this.constructor( this.geometry, this.material ).copy( this );
  14140. }
  14141. } );
  14142. /**
  14143. * @author mrdoob / http://mrdoob.com/
  14144. */
  14145. function LineSegments( geometry, material ) {
  14146. Line.call( this, geometry, material );
  14147. this.type = 'LineSegments';
  14148. }
  14149. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  14150. constructor: LineSegments,
  14151. isLineSegments: true
  14152. } );
  14153. /**
  14154. * @author mgreter / http://github.com/mgreter
  14155. */
  14156. function LineLoop( geometry, material ) {
  14157. Line.call( this, geometry, material );
  14158. this.type = 'LineLoop';
  14159. }
  14160. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  14161. constructor: LineLoop,
  14162. isLineLoop: true,
  14163. } );
  14164. /**
  14165. * @author mrdoob / http://mrdoob.com/
  14166. * @author alteredq / http://alteredqualia.com/
  14167. *
  14168. * parameters = {
  14169. * color: <hex>,
  14170. * opacity: <float>,
  14171. * map: new THREE.Texture( <Image> ),
  14172. *
  14173. * size: <float>,
  14174. * sizeAttenuation: <bool>
  14175. * }
  14176. */
  14177. function PointsMaterial( parameters ) {
  14178. Material.call( this );
  14179. this.type = 'PointsMaterial';
  14180. this.color = new Color( 0xffffff );
  14181. this.map = null;
  14182. this.size = 1;
  14183. this.sizeAttenuation = true;
  14184. this.lights = false;
  14185. this.setValues( parameters );
  14186. }
  14187. PointsMaterial.prototype = Object.create( Material.prototype );
  14188. PointsMaterial.prototype.constructor = PointsMaterial;
  14189. PointsMaterial.prototype.isPointsMaterial = true;
  14190. PointsMaterial.prototype.copy = function ( source ) {
  14191. Material.prototype.copy.call( this, source );
  14192. this.color.copy( source.color );
  14193. this.map = source.map;
  14194. this.size = source.size;
  14195. this.sizeAttenuation = source.sizeAttenuation;
  14196. return this;
  14197. };
  14198. /**
  14199. * @author alteredq / http://alteredqualia.com/
  14200. */
  14201. function Points( geometry, material ) {
  14202. Object3D.call( this );
  14203. this.type = 'Points';
  14204. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14205. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14206. }
  14207. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14208. constructor: Points,
  14209. isPoints: true,
  14210. raycast: ( function () {
  14211. var inverseMatrix = new Matrix4();
  14212. var ray = new Ray();
  14213. var sphere = new Sphere();
  14214. return function raycast( raycaster, intersects ) {
  14215. var object = this;
  14216. var geometry = this.geometry;
  14217. var matrixWorld = this.matrixWorld;
  14218. var threshold = raycaster.params.Points.threshold;
  14219. // Checking boundingSphere distance to ray
  14220. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14221. sphere.copy( geometry.boundingSphere );
  14222. sphere.applyMatrix4( matrixWorld );
  14223. sphere.radius += threshold;
  14224. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14225. //
  14226. inverseMatrix.getInverse( matrixWorld );
  14227. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14228. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14229. var localThresholdSq = localThreshold * localThreshold;
  14230. var position = new Vector3();
  14231. function testPoint( point, index ) {
  14232. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14233. if ( rayPointDistanceSq < localThresholdSq ) {
  14234. var intersectPoint = ray.closestPointToPoint( point );
  14235. intersectPoint.applyMatrix4( matrixWorld );
  14236. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14237. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14238. intersects.push( {
  14239. distance: distance,
  14240. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14241. point: intersectPoint.clone(),
  14242. index: index,
  14243. face: null,
  14244. object: object
  14245. } );
  14246. }
  14247. }
  14248. if ( geometry.isBufferGeometry ) {
  14249. var index = geometry.index;
  14250. var attributes = geometry.attributes;
  14251. var positions = attributes.position.array;
  14252. if ( index !== null ) {
  14253. var indices = index.array;
  14254. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14255. var a = indices[ i ];
  14256. position.fromArray( positions, a * 3 );
  14257. testPoint( position, a );
  14258. }
  14259. } else {
  14260. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14261. position.fromArray( positions, i * 3 );
  14262. testPoint( position, i );
  14263. }
  14264. }
  14265. } else {
  14266. var vertices = geometry.vertices;
  14267. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14268. testPoint( vertices[ i ], i );
  14269. }
  14270. }
  14271. };
  14272. }() ),
  14273. clone: function () {
  14274. return new this.constructor( this.geometry, this.material ).copy( this );
  14275. }
  14276. } );
  14277. /**
  14278. * @author mrdoob / http://mrdoob.com/
  14279. */
  14280. function Group() {
  14281. Object3D.call( this );
  14282. this.type = 'Group';
  14283. }
  14284. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14285. constructor: Group
  14286. } );
  14287. /**
  14288. * @author mrdoob / http://mrdoob.com/
  14289. */
  14290. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14291. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14292. this.generateMipmaps = false;
  14293. var scope = this;
  14294. function update() {
  14295. requestAnimationFrame( update );
  14296. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14297. scope.needsUpdate = true;
  14298. }
  14299. }
  14300. update();
  14301. }
  14302. VideoTexture.prototype = Object.create( Texture.prototype );
  14303. VideoTexture.prototype.constructor = VideoTexture;
  14304. /**
  14305. * @author alteredq / http://alteredqualia.com/
  14306. */
  14307. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14308. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14309. this.image = { width: width, height: height };
  14310. this.mipmaps = mipmaps;
  14311. // no flipping for cube textures
  14312. // (also flipping doesn't work for compressed textures )
  14313. this.flipY = false;
  14314. // can't generate mipmaps for compressed textures
  14315. // mips must be embedded in DDS files
  14316. this.generateMipmaps = false;
  14317. }
  14318. CompressedTexture.prototype = Object.create( Texture.prototype );
  14319. CompressedTexture.prototype.constructor = CompressedTexture;
  14320. CompressedTexture.prototype.isCompressedTexture = true;
  14321. /**
  14322. * @author mrdoob / http://mrdoob.com/
  14323. */
  14324. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14325. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14326. this.needsUpdate = true;
  14327. }
  14328. CanvasTexture.prototype = Object.create( Texture.prototype );
  14329. CanvasTexture.prototype.constructor = CanvasTexture;
  14330. /**
  14331. * @author Matt DesLauriers / @mattdesl
  14332. * @author atix / arthursilber.de
  14333. */
  14334. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14335. format = format !== undefined ? format : DepthFormat;
  14336. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14337. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14338. }
  14339. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14340. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14341. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14342. this.image = { width: width, height: height };
  14343. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14344. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14345. this.flipY = false;
  14346. this.generateMipmaps = false;
  14347. }
  14348. DepthTexture.prototype = Object.create( Texture.prototype );
  14349. DepthTexture.prototype.constructor = DepthTexture;
  14350. DepthTexture.prototype.isDepthTexture = true;
  14351. /**
  14352. * @author mrdoob / http://mrdoob.com/
  14353. * @author Mugen87 / https://github.com/Mugen87
  14354. */
  14355. function WireframeGeometry( geometry ) {
  14356. BufferGeometry.call( this );
  14357. this.type = 'WireframeGeometry';
  14358. // buffer
  14359. var vertices = [];
  14360. // helper variables
  14361. var i, j, l, o, ol;
  14362. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  14363. var key, keys = [ 'a', 'b', 'c' ];
  14364. var vertex;
  14365. // different logic for Geometry and BufferGeometry
  14366. if ( geometry && geometry.isGeometry ) {
  14367. // create a data structure that contains all edges without duplicates
  14368. var faces = geometry.faces;
  14369. for ( i = 0, l = faces.length; i < l; i ++ ) {
  14370. var face = faces[ i ];
  14371. for ( j = 0; j < 3; j ++ ) {
  14372. edge1 = face[ keys[ j ] ];
  14373. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  14374. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14375. edge[ 1 ] = Math.max( edge1, edge2 );
  14376. key = edge[ 0 ] + ',' + edge[ 1 ];
  14377. if ( edges[ key ] === undefined ) {
  14378. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14379. }
  14380. }
  14381. }
  14382. // generate vertices
  14383. for ( key in edges ) {
  14384. e = edges[ key ];
  14385. vertex = geometry.vertices[ e.index1 ];
  14386. vertices.push( vertex.x, vertex.y, vertex.z );
  14387. vertex = geometry.vertices[ e.index2 ];
  14388. vertices.push( vertex.x, vertex.y, vertex.z );
  14389. }
  14390. } else if ( geometry && geometry.isBufferGeometry ) {
  14391. var position, indices, groups;
  14392. var group, start, count;
  14393. var index1, index2;
  14394. vertex = new Vector3();
  14395. if ( geometry.index !== null ) {
  14396. // indexed BufferGeometry
  14397. position = geometry.attributes.position;
  14398. indices = geometry.index;
  14399. groups = geometry.groups;
  14400. if ( groups.length === 0 ) {
  14401. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  14402. }
  14403. // create a data structure that contains all eges without duplicates
  14404. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  14405. group = groups[ o ];
  14406. start = group.start;
  14407. count = group.count;
  14408. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  14409. for ( j = 0; j < 3; j ++ ) {
  14410. edge1 = indices.getX( i + j );
  14411. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  14412. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  14413. edge[ 1 ] = Math.max( edge1, edge2 );
  14414. key = edge[ 0 ] + ',' + edge[ 1 ];
  14415. if ( edges[ key ] === undefined ) {
  14416. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  14417. }
  14418. }
  14419. }
  14420. }
  14421. // generate vertices
  14422. for ( key in edges ) {
  14423. e = edges[ key ];
  14424. vertex.fromBufferAttribute( position, e.index1 );
  14425. vertices.push( vertex.x, vertex.y, vertex.z );
  14426. vertex.fromBufferAttribute( position, e.index2 );
  14427. vertices.push( vertex.x, vertex.y, vertex.z );
  14428. }
  14429. } else {
  14430. // non-indexed BufferGeometry
  14431. position = geometry.attributes.position;
  14432. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14433. for ( j = 0; j < 3; j ++ ) {
  14434. // three edges per triangle, an edge is represented as (index1, index2)
  14435. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14436. index1 = 3 * i + j;
  14437. vertex.fromBufferAttribute( position, index1 );
  14438. vertices.push( vertex.x, vertex.y, vertex.z );
  14439. index2 = 3 * i + ( ( j + 1 ) % 3 );
  14440. vertex.fromBufferAttribute( position, index2 );
  14441. vertices.push( vertex.x, vertex.y, vertex.z );
  14442. }
  14443. }
  14444. }
  14445. }
  14446. // build geometry
  14447. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14448. }
  14449. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14450. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14451. /**
  14452. * @author zz85 / https://github.com/zz85
  14453. * @author Mugen87 / https://github.com/Mugen87
  14454. *
  14455. * Parametric Surfaces Geometry
  14456. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14457. */
  14458. // ParametricGeometry
  14459. function ParametricGeometry( func, slices, stacks ) {
  14460. Geometry.call( this );
  14461. this.type = 'ParametricGeometry';
  14462. this.parameters = {
  14463. func: func,
  14464. slices: slices,
  14465. stacks: stacks
  14466. };
  14467. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14468. this.mergeVertices();
  14469. }
  14470. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14471. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14472. // ParametricBufferGeometry
  14473. function ParametricBufferGeometry( func, slices, stacks ) {
  14474. BufferGeometry.call( this );
  14475. this.type = 'ParametricBufferGeometry';
  14476. this.parameters = {
  14477. func: func,
  14478. slices: slices,
  14479. stacks: stacks
  14480. };
  14481. // buffers
  14482. var indices = [];
  14483. var vertices = [];
  14484. var normals = [];
  14485. var uvs = [];
  14486. var EPS = 0.00001;
  14487. var normal = new Vector3();
  14488. var p0 = new Vector3(), p1 = new Vector3();
  14489. var pu = new Vector3(), pv = new Vector3();
  14490. var i, j;
  14491. // generate vertices, normals and uvs
  14492. var sliceCount = slices + 1;
  14493. for ( i = 0; i <= stacks; i ++ ) {
  14494. var v = i / stacks;
  14495. for ( j = 0; j <= slices; j ++ ) {
  14496. var u = j / slices;
  14497. // vertex
  14498. p0 = func( u, v, p0 );
  14499. vertices.push( p0.x, p0.y, p0.z );
  14500. // normal
  14501. // approximate tangent vectors via finite differences
  14502. if ( u - EPS >= 0 ) {
  14503. p1 = func( u - EPS, v, p1 );
  14504. pu.subVectors( p0, p1 );
  14505. } else {
  14506. p1 = func( u + EPS, v, p1 );
  14507. pu.subVectors( p1, p0 );
  14508. }
  14509. if ( v - EPS >= 0 ) {
  14510. p1 = func( u, v - EPS, p1 );
  14511. pv.subVectors( p0, p1 );
  14512. } else {
  14513. p1 = func( u, v + EPS, p1 );
  14514. pv.subVectors( p1, p0 );
  14515. }
  14516. // cross product of tangent vectors returns surface normal
  14517. normal.crossVectors( pu, pv ).normalize();
  14518. normals.push( normal.x, normal.y, normal.z );
  14519. // uv
  14520. uvs.push( u, v );
  14521. }
  14522. }
  14523. // generate indices
  14524. for ( i = 0; i < stacks; i ++ ) {
  14525. for ( j = 0; j < slices; j ++ ) {
  14526. var a = i * sliceCount + j;
  14527. var b = i * sliceCount + j + 1;
  14528. var c = ( i + 1 ) * sliceCount + j + 1;
  14529. var d = ( i + 1 ) * sliceCount + j;
  14530. // faces one and two
  14531. indices.push( a, b, d );
  14532. indices.push( b, c, d );
  14533. }
  14534. }
  14535. // build geometry
  14536. this.setIndex( indices );
  14537. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14538. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14539. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14540. }
  14541. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14542. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14543. /**
  14544. * @author clockworkgeek / https://github.com/clockworkgeek
  14545. * @author timothypratley / https://github.com/timothypratley
  14546. * @author WestLangley / http://github.com/WestLangley
  14547. * @author Mugen87 / https://github.com/Mugen87
  14548. */
  14549. // PolyhedronGeometry
  14550. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14551. Geometry.call( this );
  14552. this.type = 'PolyhedronGeometry';
  14553. this.parameters = {
  14554. vertices: vertices,
  14555. indices: indices,
  14556. radius: radius,
  14557. detail: detail
  14558. };
  14559. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14560. this.mergeVertices();
  14561. }
  14562. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14563. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14564. // PolyhedronBufferGeometry
  14565. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14566. BufferGeometry.call( this );
  14567. this.type = 'PolyhedronBufferGeometry';
  14568. this.parameters = {
  14569. vertices: vertices,
  14570. indices: indices,
  14571. radius: radius,
  14572. detail: detail
  14573. };
  14574. radius = radius || 1;
  14575. detail = detail || 0;
  14576. // default buffer data
  14577. var vertexBuffer = [];
  14578. var uvBuffer = [];
  14579. // the subdivision creates the vertex buffer data
  14580. subdivide( detail );
  14581. // all vertices should lie on a conceptual sphere with a given radius
  14582. appplyRadius( radius );
  14583. // finally, create the uv data
  14584. generateUVs();
  14585. // build non-indexed geometry
  14586. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14587. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14588. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14589. this.normalizeNormals();
  14590. // helper functions
  14591. function subdivide( detail ) {
  14592. var a = new Vector3();
  14593. var b = new Vector3();
  14594. var c = new Vector3();
  14595. // iterate over all faces and apply a subdivison with the given detail value
  14596. for ( var i = 0; i < indices.length; i += 3 ) {
  14597. // get the vertices of the face
  14598. getVertexByIndex( indices[ i + 0 ], a );
  14599. getVertexByIndex( indices[ i + 1 ], b );
  14600. getVertexByIndex( indices[ i + 2 ], c );
  14601. // perform subdivision
  14602. subdivideFace( a, b, c, detail );
  14603. }
  14604. }
  14605. function subdivideFace( a, b, c, detail ) {
  14606. var cols = Math.pow( 2, detail );
  14607. // we use this multidimensional array as a data structure for creating the subdivision
  14608. var v = [];
  14609. var i, j;
  14610. // construct all of the vertices for this subdivision
  14611. for ( i = 0; i <= cols; i ++ ) {
  14612. v[ i ] = [];
  14613. var aj = a.clone().lerp( c, i / cols );
  14614. var bj = b.clone().lerp( c, i / cols );
  14615. var rows = cols - i;
  14616. for ( j = 0; j <= rows; j ++ ) {
  14617. if ( j === 0 && i === cols ) {
  14618. v[ i ][ j ] = aj;
  14619. } else {
  14620. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14621. }
  14622. }
  14623. }
  14624. // construct all of the faces
  14625. for ( i = 0; i < cols; i ++ ) {
  14626. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14627. var k = Math.floor( j / 2 );
  14628. if ( j % 2 === 0 ) {
  14629. pushVertex( v[ i ][ k + 1 ] );
  14630. pushVertex( v[ i + 1 ][ k ] );
  14631. pushVertex( v[ i ][ k ] );
  14632. } else {
  14633. pushVertex( v[ i ][ k + 1 ] );
  14634. pushVertex( v[ i + 1 ][ k + 1 ] );
  14635. pushVertex( v[ i + 1 ][ k ] );
  14636. }
  14637. }
  14638. }
  14639. }
  14640. function appplyRadius( radius ) {
  14641. var vertex = new Vector3();
  14642. // iterate over the entire buffer and apply the radius to each vertex
  14643. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14644. vertex.x = vertexBuffer[ i + 0 ];
  14645. vertex.y = vertexBuffer[ i + 1 ];
  14646. vertex.z = vertexBuffer[ i + 2 ];
  14647. vertex.normalize().multiplyScalar( radius );
  14648. vertexBuffer[ i + 0 ] = vertex.x;
  14649. vertexBuffer[ i + 1 ] = vertex.y;
  14650. vertexBuffer[ i + 2 ] = vertex.z;
  14651. }
  14652. }
  14653. function generateUVs() {
  14654. var vertex = new Vector3();
  14655. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14656. vertex.x = vertexBuffer[ i + 0 ];
  14657. vertex.y = vertexBuffer[ i + 1 ];
  14658. vertex.z = vertexBuffer[ i + 2 ];
  14659. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14660. var v = inclination( vertex ) / Math.PI + 0.5;
  14661. uvBuffer.push( u, 1 - v );
  14662. }
  14663. correctUVs();
  14664. correctSeam();
  14665. }
  14666. function correctSeam() {
  14667. // handle case when face straddles the seam, see #3269
  14668. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14669. // uv data of a single face
  14670. var x0 = uvBuffer[ i + 0 ];
  14671. var x1 = uvBuffer[ i + 2 ];
  14672. var x2 = uvBuffer[ i + 4 ];
  14673. var max = Math.max( x0, x1, x2 );
  14674. var min = Math.min( x0, x1, x2 );
  14675. // 0.9 is somewhat arbitrary
  14676. if ( max > 0.9 && min < 0.1 ) {
  14677. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14678. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14679. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14680. }
  14681. }
  14682. }
  14683. function pushVertex( vertex ) {
  14684. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14685. }
  14686. function getVertexByIndex( index, vertex ) {
  14687. var stride = index * 3;
  14688. vertex.x = vertices[ stride + 0 ];
  14689. vertex.y = vertices[ stride + 1 ];
  14690. vertex.z = vertices[ stride + 2 ];
  14691. }
  14692. function correctUVs() {
  14693. var a = new Vector3();
  14694. var b = new Vector3();
  14695. var c = new Vector3();
  14696. var centroid = new Vector3();
  14697. var uvA = new Vector2();
  14698. var uvB = new Vector2();
  14699. var uvC = new Vector2();
  14700. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14701. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14702. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14703. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14704. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14705. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14706. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14707. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14708. var azi = azimuth( centroid );
  14709. correctUV( uvA, j + 0, a, azi );
  14710. correctUV( uvB, j + 2, b, azi );
  14711. correctUV( uvC, j + 4, c, azi );
  14712. }
  14713. }
  14714. function correctUV( uv, stride, vector, azimuth ) {
  14715. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14716. uvBuffer[ stride ] = uv.x - 1;
  14717. }
  14718. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14719. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14720. }
  14721. }
  14722. // Angle around the Y axis, counter-clockwise when looking from above.
  14723. function azimuth( vector ) {
  14724. return Math.atan2( vector.z, - vector.x );
  14725. }
  14726. // Angle above the XZ plane.
  14727. function inclination( vector ) {
  14728. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14729. }
  14730. }
  14731. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14732. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14733. /**
  14734. * @author timothypratley / https://github.com/timothypratley
  14735. * @author Mugen87 / https://github.com/Mugen87
  14736. */
  14737. // TetrahedronGeometry
  14738. function TetrahedronGeometry( radius, detail ) {
  14739. Geometry.call( this );
  14740. this.type = 'TetrahedronGeometry';
  14741. this.parameters = {
  14742. radius: radius,
  14743. detail: detail
  14744. };
  14745. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14746. this.mergeVertices();
  14747. }
  14748. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14749. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14750. // TetrahedronBufferGeometry
  14751. function TetrahedronBufferGeometry( radius, detail ) {
  14752. var vertices = [
  14753. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14754. ];
  14755. var indices = [
  14756. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14757. ];
  14758. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14759. this.type = 'TetrahedronBufferGeometry';
  14760. this.parameters = {
  14761. radius: radius,
  14762. detail: detail
  14763. };
  14764. }
  14765. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14766. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14767. /**
  14768. * @author timothypratley / https://github.com/timothypratley
  14769. * @author Mugen87 / https://github.com/Mugen87
  14770. */
  14771. // OctahedronGeometry
  14772. function OctahedronGeometry( radius, detail ) {
  14773. Geometry.call( this );
  14774. this.type = 'OctahedronGeometry';
  14775. this.parameters = {
  14776. radius: radius,
  14777. detail: detail
  14778. };
  14779. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14780. this.mergeVertices();
  14781. }
  14782. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14783. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14784. // OctahedronBufferGeometry
  14785. function OctahedronBufferGeometry( radius, detail ) {
  14786. var vertices = [
  14787. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14788. ];
  14789. var indices = [
  14790. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14791. ];
  14792. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14793. this.type = 'OctahedronBufferGeometry';
  14794. this.parameters = {
  14795. radius: radius,
  14796. detail: detail
  14797. };
  14798. }
  14799. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14800. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14801. /**
  14802. * @author timothypratley / https://github.com/timothypratley
  14803. * @author Mugen87 / https://github.com/Mugen87
  14804. */
  14805. // IcosahedronGeometry
  14806. function IcosahedronGeometry( radius, detail ) {
  14807. Geometry.call( this );
  14808. this.type = 'IcosahedronGeometry';
  14809. this.parameters = {
  14810. radius: radius,
  14811. detail: detail
  14812. };
  14813. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14814. this.mergeVertices();
  14815. }
  14816. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14817. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14818. // IcosahedronBufferGeometry
  14819. function IcosahedronBufferGeometry( radius, detail ) {
  14820. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14821. var vertices = [
  14822. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14823. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14824. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14825. ];
  14826. var indices = [
  14827. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14828. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14829. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14830. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14831. ];
  14832. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14833. this.type = 'IcosahedronBufferGeometry';
  14834. this.parameters = {
  14835. radius: radius,
  14836. detail: detail
  14837. };
  14838. }
  14839. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14840. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14841. /**
  14842. * @author Abe Pazos / https://hamoid.com
  14843. * @author Mugen87 / https://github.com/Mugen87
  14844. */
  14845. // DodecahedronGeometry
  14846. function DodecahedronGeometry( radius, detail ) {
  14847. Geometry.call( this );
  14848. this.type = 'DodecahedronGeometry';
  14849. this.parameters = {
  14850. radius: radius,
  14851. detail: detail
  14852. };
  14853. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14854. this.mergeVertices();
  14855. }
  14856. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14857. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14858. // DodecahedronBufferGeometry
  14859. function DodecahedronBufferGeometry( radius, detail ) {
  14860. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14861. var r = 1 / t;
  14862. var vertices = [
  14863. // (±1, ±1, ±1)
  14864. - 1, - 1, - 1, - 1, - 1, 1,
  14865. - 1, 1, - 1, - 1, 1, 1,
  14866. 1, - 1, - 1, 1, - 1, 1,
  14867. 1, 1, - 1, 1, 1, 1,
  14868. // (0, ±1/φ, ±φ)
  14869. 0, - r, - t, 0, - r, t,
  14870. 0, r, - t, 0, r, t,
  14871. // (±1/φ, ±φ, 0)
  14872. - r, - t, 0, - r, t, 0,
  14873. r, - t, 0, r, t, 0,
  14874. // (±φ, 0, ±1/φ)
  14875. - t, 0, - r, t, 0, - r,
  14876. - t, 0, r, t, 0, r
  14877. ];
  14878. var indices = [
  14879. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14880. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14881. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14882. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14883. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14884. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14885. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14886. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14887. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14888. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14889. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14890. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14891. ];
  14892. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14893. this.type = 'DodecahedronBufferGeometry';
  14894. this.parameters = {
  14895. radius: radius,
  14896. detail: detail
  14897. };
  14898. }
  14899. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14900. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14901. /**
  14902. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14903. * @author WestLangley / https://github.com/WestLangley
  14904. * @author zz85 / https://github.com/zz85
  14905. * @author miningold / https://github.com/miningold
  14906. * @author jonobr1 / https://github.com/jonobr1
  14907. * @author Mugen87 / https://github.com/Mugen87
  14908. *
  14909. */
  14910. // TubeGeometry
  14911. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14912. Geometry.call( this );
  14913. this.type = 'TubeGeometry';
  14914. this.parameters = {
  14915. path: path,
  14916. tubularSegments: tubularSegments,
  14917. radius: radius,
  14918. radialSegments: radialSegments,
  14919. closed: closed
  14920. };
  14921. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14922. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14923. // expose internals
  14924. this.tangents = bufferGeometry.tangents;
  14925. this.normals = bufferGeometry.normals;
  14926. this.binormals = bufferGeometry.binormals;
  14927. // create geometry
  14928. this.fromBufferGeometry( bufferGeometry );
  14929. this.mergeVertices();
  14930. }
  14931. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14932. TubeGeometry.prototype.constructor = TubeGeometry;
  14933. // TubeBufferGeometry
  14934. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14935. BufferGeometry.call( this );
  14936. this.type = 'TubeBufferGeometry';
  14937. this.parameters = {
  14938. path: path,
  14939. tubularSegments: tubularSegments,
  14940. radius: radius,
  14941. radialSegments: radialSegments,
  14942. closed: closed
  14943. };
  14944. tubularSegments = tubularSegments || 64;
  14945. radius = radius || 1;
  14946. radialSegments = radialSegments || 8;
  14947. closed = closed || false;
  14948. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14949. // expose internals
  14950. this.tangents = frames.tangents;
  14951. this.normals = frames.normals;
  14952. this.binormals = frames.binormals;
  14953. // helper variables
  14954. var vertex = new Vector3();
  14955. var normal = new Vector3();
  14956. var uv = new Vector2();
  14957. var i, j;
  14958. // buffer
  14959. var vertices = [];
  14960. var normals = [];
  14961. var uvs = [];
  14962. var indices = [];
  14963. // create buffer data
  14964. generateBufferData();
  14965. // build geometry
  14966. this.setIndex( indices );
  14967. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14968. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14969. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14970. // functions
  14971. function generateBufferData() {
  14972. for ( i = 0; i < tubularSegments; i ++ ) {
  14973. generateSegment( i );
  14974. }
  14975. // if the geometry is not closed, generate the last row of vertices and normals
  14976. // at the regular position on the given path
  14977. //
  14978. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  14979. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  14980. // uvs are generated in a separate function.
  14981. // this makes it easy compute correct values for closed geometries
  14982. generateUVs();
  14983. // finally create faces
  14984. generateIndices();
  14985. }
  14986. function generateSegment( i ) {
  14987. // we use getPointAt to sample evenly distributed points from the given path
  14988. var P = path.getPointAt( i / tubularSegments );
  14989. // retrieve corresponding normal and binormal
  14990. var N = frames.normals[ i ];
  14991. var B = frames.binormals[ i ];
  14992. // generate normals and vertices for the current segment
  14993. for ( j = 0; j <= radialSegments; j ++ ) {
  14994. var v = j / radialSegments * Math.PI * 2;
  14995. var sin = Math.sin( v );
  14996. var cos = - Math.cos( v );
  14997. // normal
  14998. normal.x = ( cos * N.x + sin * B.x );
  14999. normal.y = ( cos * N.y + sin * B.y );
  15000. normal.z = ( cos * N.z + sin * B.z );
  15001. normal.normalize();
  15002. normals.push( normal.x, normal.y, normal.z );
  15003. // vertex
  15004. vertex.x = P.x + radius * normal.x;
  15005. vertex.y = P.y + radius * normal.y;
  15006. vertex.z = P.z + radius * normal.z;
  15007. vertices.push( vertex.x, vertex.y, vertex.z );
  15008. }
  15009. }
  15010. function generateIndices() {
  15011. for ( j = 1; j <= tubularSegments; j ++ ) {
  15012. for ( i = 1; i <= radialSegments; i ++ ) {
  15013. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15014. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15015. var c = ( radialSegments + 1 ) * j + i;
  15016. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15017. // faces
  15018. indices.push( a, b, d );
  15019. indices.push( b, c, d );
  15020. }
  15021. }
  15022. }
  15023. function generateUVs() {
  15024. for ( i = 0; i <= tubularSegments; i ++ ) {
  15025. for ( j = 0; j <= radialSegments; j ++ ) {
  15026. uv.x = i / tubularSegments;
  15027. uv.y = j / radialSegments;
  15028. uvs.push( uv.x, uv.y );
  15029. }
  15030. }
  15031. }
  15032. }
  15033. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15034. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  15035. /**
  15036. * @author oosmoxiecode
  15037. * @author Mugen87 / https://github.com/Mugen87
  15038. *
  15039. * based on http://www.blackpawn.com/texts/pqtorus/
  15040. */
  15041. // TorusKnotGeometry
  15042. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  15043. Geometry.call( this );
  15044. this.type = 'TorusKnotGeometry';
  15045. this.parameters = {
  15046. radius: radius,
  15047. tube: tube,
  15048. tubularSegments: tubularSegments,
  15049. radialSegments: radialSegments,
  15050. p: p,
  15051. q: q
  15052. };
  15053. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  15054. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  15055. this.mergeVertices();
  15056. }
  15057. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  15058. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  15059. // TorusKnotBufferGeometry
  15060. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  15061. BufferGeometry.call( this );
  15062. this.type = 'TorusKnotBufferGeometry';
  15063. this.parameters = {
  15064. radius: radius,
  15065. tube: tube,
  15066. tubularSegments: tubularSegments,
  15067. radialSegments: radialSegments,
  15068. p: p,
  15069. q: q
  15070. };
  15071. radius = radius || 100;
  15072. tube = tube || 40;
  15073. tubularSegments = Math.floor( tubularSegments ) || 64;
  15074. radialSegments = Math.floor( radialSegments ) || 8;
  15075. p = p || 2;
  15076. q = q || 3;
  15077. // buffers
  15078. var indices = [];
  15079. var vertices = [];
  15080. var normals = [];
  15081. var uvs = [];
  15082. // helper variables
  15083. var i, j;
  15084. var vertex = new Vector3();
  15085. var normal = new Vector3();
  15086. var P1 = new Vector3();
  15087. var P2 = new Vector3();
  15088. var B = new Vector3();
  15089. var T = new Vector3();
  15090. var N = new Vector3();
  15091. // generate vertices, normals and uvs
  15092. for ( i = 0; i <= tubularSegments; ++ i ) {
  15093. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  15094. var u = i / tubularSegments * p * Math.PI * 2;
  15095. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15096. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15097. calculatePositionOnCurve( u, p, q, radius, P1 );
  15098. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15099. // calculate orthonormal basis
  15100. T.subVectors( P2, P1 );
  15101. N.addVectors( P2, P1 );
  15102. B.crossVectors( T, N );
  15103. N.crossVectors( B, T );
  15104. // normalize B, N. T can be ignored, we don't use it
  15105. B.normalize();
  15106. N.normalize();
  15107. for ( j = 0; j <= radialSegments; ++ j ) {
  15108. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15109. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15110. var v = j / radialSegments * Math.PI * 2;
  15111. var cx = - tube * Math.cos( v );
  15112. var cy = tube * Math.sin( v );
  15113. // now calculate the final vertex position.
  15114. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  15115. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15116. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15117. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15118. vertices.push( vertex.x, vertex.y, vertex.z );
  15119. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15120. normal.subVectors( vertex, P1 ).normalize();
  15121. normals.push( normal.x, normal.y, normal.z );
  15122. // uv
  15123. uvs.push( i / tubularSegments );
  15124. uvs.push( j / radialSegments );
  15125. }
  15126. }
  15127. // generate indices
  15128. for ( j = 1; j <= tubularSegments; j ++ ) {
  15129. for ( i = 1; i <= radialSegments; i ++ ) {
  15130. // indices
  15131. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15132. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  15133. var c = ( radialSegments + 1 ) * j + i;
  15134. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15135. // faces
  15136. indices.push( a, b, d );
  15137. indices.push( b, c, d );
  15138. }
  15139. }
  15140. // build geometry
  15141. this.setIndex( indices );
  15142. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15143. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15144. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15145. // this function calculates the current position on the torus curve
  15146. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15147. var cu = Math.cos( u );
  15148. var su = Math.sin( u );
  15149. var quOverP = q / p * u;
  15150. var cs = Math.cos( quOverP );
  15151. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15152. position.y = radius * ( 2 + cs ) * su * 0.5;
  15153. position.z = radius * Math.sin( quOverP ) * 0.5;
  15154. }
  15155. }
  15156. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15157. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  15158. /**
  15159. * @author oosmoxiecode
  15160. * @author mrdoob / http://mrdoob.com/
  15161. * @author Mugen87 / https://github.com/Mugen87
  15162. *
  15163. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15164. */
  15165. // TorusGeometry
  15166. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15167. Geometry.call( this );
  15168. this.type = 'TorusGeometry';
  15169. this.parameters = {
  15170. radius: radius,
  15171. tube: tube,
  15172. radialSegments: radialSegments,
  15173. tubularSegments: tubularSegments,
  15174. arc: arc
  15175. };
  15176. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15177. this.mergeVertices();
  15178. }
  15179. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15180. TorusGeometry.prototype.constructor = TorusGeometry;
  15181. // TorusBufferGeometry
  15182. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15183. BufferGeometry.call( this );
  15184. this.type = 'TorusBufferGeometry';
  15185. this.parameters = {
  15186. radius: radius,
  15187. tube: tube,
  15188. radialSegments: radialSegments,
  15189. tubularSegments: tubularSegments,
  15190. arc: arc
  15191. };
  15192. radius = radius || 100;
  15193. tube = tube || 40;
  15194. radialSegments = Math.floor( radialSegments ) || 8;
  15195. tubularSegments = Math.floor( tubularSegments ) || 6;
  15196. arc = arc || Math.PI * 2;
  15197. // buffers
  15198. var indices = [];
  15199. var vertices = [];
  15200. var normals = [];
  15201. var uvs = [];
  15202. // helper variables
  15203. var center = new Vector3();
  15204. var vertex = new Vector3();
  15205. var normal = new Vector3();
  15206. var j, i;
  15207. // generate vertices, normals and uvs
  15208. for ( j = 0; j <= radialSegments; j ++ ) {
  15209. for ( i = 0; i <= tubularSegments; i ++ ) {
  15210. var u = i / tubularSegments * arc;
  15211. var v = j / radialSegments * Math.PI * 2;
  15212. // vertex
  15213. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15214. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15215. vertex.z = tube * Math.sin( v );
  15216. vertices.push( vertex.x, vertex.y, vertex.z );
  15217. // normal
  15218. center.x = radius * Math.cos( u );
  15219. center.y = radius * Math.sin( u );
  15220. normal.subVectors( vertex, center ).normalize();
  15221. normals.push( normal.x, normal.y, normal.z );
  15222. // uv
  15223. uvs.push( i / tubularSegments );
  15224. uvs.push( j / radialSegments );
  15225. }
  15226. }
  15227. // generate indices
  15228. for ( j = 1; j <= radialSegments; j ++ ) {
  15229. for ( i = 1; i <= tubularSegments; i ++ ) {
  15230. // indices
  15231. var a = ( tubularSegments + 1 ) * j + i - 1;
  15232. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15233. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15234. var d = ( tubularSegments + 1 ) * j + i;
  15235. // faces
  15236. indices.push( a, b, d );
  15237. indices.push( b, c, d );
  15238. }
  15239. }
  15240. // build geometry
  15241. this.setIndex( indices );
  15242. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15243. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15244. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15245. }
  15246. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15247. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15248. /**
  15249. * @author zz85 / http://www.lab4games.net/zz85/blog
  15250. */
  15251. var ShapeUtils = {
  15252. // calculate area of the contour polygon
  15253. area: function ( contour ) {
  15254. var n = contour.length;
  15255. var a = 0.0;
  15256. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15257. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15258. }
  15259. return a * 0.5;
  15260. },
  15261. triangulate: ( function () {
  15262. /**
  15263. * This code is a quick port of code written in C++ which was submitted to
  15264. * flipcode.com by John W. Ratcliff // July 22, 2000
  15265. * See original code and more information here:
  15266. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15267. *
  15268. * ported to actionscript by Zevan Rosser
  15269. * www.actionsnippet.com
  15270. *
  15271. * ported to javascript by Joshua Koo
  15272. * http://www.lab4games.net/zz85/blog
  15273. *
  15274. */
  15275. function snip( contour, u, v, w, n, verts ) {
  15276. var p;
  15277. var ax, ay, bx, by;
  15278. var cx, cy, px, py;
  15279. ax = contour[ verts[ u ] ].x;
  15280. ay = contour[ verts[ u ] ].y;
  15281. bx = contour[ verts[ v ] ].x;
  15282. by = contour[ verts[ v ] ].y;
  15283. cx = contour[ verts[ w ] ].x;
  15284. cy = contour[ verts[ w ] ].y;
  15285. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15286. var aX, aY, bX, bY, cX, cY;
  15287. var apx, apy, bpx, bpy, cpx, cpy;
  15288. var cCROSSap, bCROSScp, aCROSSbp;
  15289. aX = cx - bx; aY = cy - by;
  15290. bX = ax - cx; bY = ay - cy;
  15291. cX = bx - ax; cY = by - ay;
  15292. for ( p = 0; p < n; p ++ ) {
  15293. px = contour[ verts[ p ] ].x;
  15294. py = contour[ verts[ p ] ].y;
  15295. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15296. ( ( px === bx ) && ( py === by ) ) ||
  15297. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15298. apx = px - ax; apy = py - ay;
  15299. bpx = px - bx; bpy = py - by;
  15300. cpx = px - cx; cpy = py - cy;
  15301. // see if p is inside triangle abc
  15302. aCROSSbp = aX * bpy - aY * bpx;
  15303. cCROSSap = cX * apy - cY * apx;
  15304. bCROSScp = bX * cpy - bY * cpx;
  15305. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15306. }
  15307. return true;
  15308. }
  15309. // takes in an contour array and returns
  15310. return function triangulate( contour, indices ) {
  15311. var n = contour.length;
  15312. if ( n < 3 ) return null;
  15313. var result = [],
  15314. verts = [],
  15315. vertIndices = [];
  15316. /* we want a counter-clockwise polygon in verts */
  15317. var u, v, w;
  15318. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15319. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15320. } else {
  15321. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15322. }
  15323. var nv = n;
  15324. /* remove nv - 2 vertices, creating 1 triangle every time */
  15325. var count = 2 * nv; /* error detection */
  15326. for ( v = nv - 1; nv > 2; ) {
  15327. /* if we loop, it is probably a non-simple polygon */
  15328. if ( ( count -- ) <= 0 ) {
  15329. //** Triangulate: ERROR - probable bad polygon!
  15330. //throw ( "Warning, unable to triangulate polygon!" );
  15331. //return null;
  15332. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15333. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15334. if ( indices ) return vertIndices;
  15335. return result;
  15336. }
  15337. /* three consecutive vertices in current polygon, <u,v,w> */
  15338. u = v; if ( nv <= u ) u = 0; /* previous */
  15339. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15340. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15341. if ( snip( contour, u, v, w, nv, verts ) ) {
  15342. var a, b, c, s, t;
  15343. /* true names of the vertices */
  15344. a = verts[ u ];
  15345. b = verts[ v ];
  15346. c = verts[ w ];
  15347. /* output Triangle */
  15348. result.push( [ contour[ a ],
  15349. contour[ b ],
  15350. contour[ c ] ] );
  15351. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15352. /* remove v from the remaining polygon */
  15353. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15354. verts[ s ] = verts[ t ];
  15355. }
  15356. nv --;
  15357. /* reset error detection counter */
  15358. count = 2 * nv;
  15359. }
  15360. }
  15361. if ( indices ) return vertIndices;
  15362. return result;
  15363. }
  15364. } )(),
  15365. triangulateShape: function ( contour, holes ) {
  15366. function removeDupEndPts(points) {
  15367. var l = points.length;
  15368. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15369. points.pop();
  15370. }
  15371. }
  15372. removeDupEndPts( contour );
  15373. holes.forEach( removeDupEndPts );
  15374. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15375. // inOtherPt needs to be collinear to the inSegment
  15376. if ( inSegPt1.x !== inSegPt2.x ) {
  15377. if ( inSegPt1.x < inSegPt2.x ) {
  15378. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15379. } else {
  15380. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15381. }
  15382. } else {
  15383. if ( inSegPt1.y < inSegPt2.y ) {
  15384. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15385. } else {
  15386. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15387. }
  15388. }
  15389. }
  15390. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15391. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15392. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15393. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15394. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15395. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15396. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15397. if ( Math.abs( limit ) > Number.EPSILON ) {
  15398. // not parallel
  15399. var perpSeg2;
  15400. if ( limit > 0 ) {
  15401. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15402. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15403. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15404. } else {
  15405. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15406. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15407. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15408. }
  15409. // i.e. to reduce rounding errors
  15410. // intersection at endpoint of segment#1?
  15411. if ( perpSeg2 === 0 ) {
  15412. if ( ( inExcludeAdjacentSegs ) &&
  15413. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15414. return [ inSeg1Pt1 ];
  15415. }
  15416. if ( perpSeg2 === limit ) {
  15417. if ( ( inExcludeAdjacentSegs ) &&
  15418. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15419. return [ inSeg1Pt2 ];
  15420. }
  15421. // intersection at endpoint of segment#2?
  15422. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15423. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15424. // return real intersection point
  15425. var factorSeg1 = perpSeg2 / limit;
  15426. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15427. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15428. } else {
  15429. // parallel or collinear
  15430. if ( ( perpSeg1 !== 0 ) ||
  15431. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15432. // they are collinear or degenerate
  15433. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15434. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15435. // both segments are points
  15436. if ( seg1Pt && seg2Pt ) {
  15437. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15438. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15439. return [ inSeg1Pt1 ]; // they are the same point
  15440. }
  15441. // segment#1 is a single point
  15442. if ( seg1Pt ) {
  15443. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15444. return [ inSeg1Pt1 ];
  15445. }
  15446. // segment#2 is a single point
  15447. if ( seg2Pt ) {
  15448. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15449. return [ inSeg2Pt1 ];
  15450. }
  15451. // they are collinear segments, which might overlap
  15452. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15453. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15454. if ( seg1dx !== 0 ) {
  15455. // the segments are NOT on a vertical line
  15456. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15457. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15458. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15459. } else {
  15460. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15461. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15462. }
  15463. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15464. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15465. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15466. } else {
  15467. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15468. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15469. }
  15470. } else {
  15471. // the segments are on a vertical line
  15472. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15473. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15474. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15475. } else {
  15476. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15477. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15478. }
  15479. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15480. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15481. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15482. } else {
  15483. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15484. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15485. }
  15486. }
  15487. if ( seg1minVal <= seg2minVal ) {
  15488. if ( seg1maxVal < seg2minVal ) return [];
  15489. if ( seg1maxVal === seg2minVal ) {
  15490. if ( inExcludeAdjacentSegs ) return [];
  15491. return [ seg2min ];
  15492. }
  15493. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15494. return [ seg2min, seg2max ];
  15495. } else {
  15496. if ( seg1minVal > seg2maxVal ) return [];
  15497. if ( seg1minVal === seg2maxVal ) {
  15498. if ( inExcludeAdjacentSegs ) return [];
  15499. return [ seg1min ];
  15500. }
  15501. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15502. return [ seg1min, seg2max ];
  15503. }
  15504. }
  15505. }
  15506. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15507. // The order of legs is important
  15508. // translation of all points, so that Vertex is at (0,0)
  15509. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15510. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15511. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15512. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15513. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15514. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15515. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15516. // angle != 180 deg.
  15517. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15518. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15519. if ( from2toAngle > 0 ) {
  15520. // main angle < 180 deg.
  15521. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15522. } else {
  15523. // main angle > 180 deg.
  15524. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15525. }
  15526. } else {
  15527. // angle == 180 deg.
  15528. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15529. return ( from2otherAngle > 0 );
  15530. }
  15531. }
  15532. function removeHoles( contour, holes ) {
  15533. var shape = contour.concat(); // work on this shape
  15534. var hole;
  15535. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15536. // Check if hole point lies within angle around shape point
  15537. var lastShapeIdx = shape.length - 1;
  15538. var prevShapeIdx = inShapeIdx - 1;
  15539. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15540. var nextShapeIdx = inShapeIdx + 1;
  15541. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15542. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15543. if ( ! insideAngle ) {
  15544. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15545. return false;
  15546. }
  15547. // Check if shape point lies within angle around hole point
  15548. var lastHoleIdx = hole.length - 1;
  15549. var prevHoleIdx = inHoleIdx - 1;
  15550. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15551. var nextHoleIdx = inHoleIdx + 1;
  15552. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15553. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15554. if ( ! insideAngle ) {
  15555. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15556. return false;
  15557. }
  15558. return true;
  15559. }
  15560. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15561. // checks for intersections with shape edges
  15562. var sIdx, nextIdx, intersection;
  15563. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15564. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15565. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15566. if ( intersection.length > 0 ) return true;
  15567. }
  15568. return false;
  15569. }
  15570. var indepHoles = [];
  15571. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15572. // checks for intersections with hole edges
  15573. var ihIdx, chkHole,
  15574. hIdx, nextIdx, intersection;
  15575. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15576. chkHole = holes[ indepHoles[ ihIdx ]];
  15577. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15578. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15579. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15580. if ( intersection.length > 0 ) return true;
  15581. }
  15582. }
  15583. return false;
  15584. }
  15585. var holeIndex, shapeIndex,
  15586. shapePt, holePt,
  15587. holeIdx, cutKey, failedCuts = [],
  15588. tmpShape1, tmpShape2,
  15589. tmpHole1, tmpHole2;
  15590. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15591. indepHoles.push( h );
  15592. }
  15593. var minShapeIndex = 0;
  15594. var counter = indepHoles.length * 2;
  15595. while ( indepHoles.length > 0 ) {
  15596. counter --;
  15597. if ( counter < 0 ) {
  15598. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15599. break;
  15600. }
  15601. // search for shape-vertex and hole-vertex,
  15602. // which can be connected without intersections
  15603. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15604. shapePt = shape[ shapeIndex ];
  15605. holeIndex = - 1;
  15606. // search for hole which can be reached without intersections
  15607. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15608. holeIdx = indepHoles[ h ];
  15609. // prevent multiple checks
  15610. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15611. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15612. hole = holes[ holeIdx ];
  15613. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15614. holePt = hole[ h2 ];
  15615. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15616. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15617. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15618. holeIndex = h2;
  15619. indepHoles.splice( h, 1 );
  15620. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15621. tmpShape2 = shape.slice( shapeIndex );
  15622. tmpHole1 = hole.slice( holeIndex );
  15623. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15624. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15625. minShapeIndex = shapeIndex;
  15626. // Debug only, to show the selected cuts
  15627. // glob_CutLines.push( [ shapePt, holePt ] );
  15628. break;
  15629. }
  15630. if ( holeIndex >= 0 ) break; // hole-vertex found
  15631. failedCuts[ cutKey ] = true; // remember failure
  15632. }
  15633. if ( holeIndex >= 0 ) break; // hole-vertex found
  15634. }
  15635. }
  15636. return shape; /* shape with no holes */
  15637. }
  15638. var i, il, f, face,
  15639. key, index,
  15640. allPointsMap = {};
  15641. // 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.
  15642. var allpoints = contour.concat();
  15643. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15644. Array.prototype.push.apply( allpoints, holes[ h ] );
  15645. }
  15646. //console.log( "allpoints",allpoints, allpoints.length );
  15647. // prepare all points map
  15648. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15649. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15650. if ( allPointsMap[ key ] !== undefined ) {
  15651. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15652. }
  15653. allPointsMap[ key ] = i;
  15654. }
  15655. // remove holes by cutting paths to holes and adding them to the shape
  15656. var shapeWithoutHoles = removeHoles( contour, holes );
  15657. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15658. //console.log( "triangles",triangles, triangles.length );
  15659. // check all face vertices against all points map
  15660. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15661. face = triangles[ i ];
  15662. for ( f = 0; f < 3; f ++ ) {
  15663. key = face[ f ].x + ":" + face[ f ].y;
  15664. index = allPointsMap[ key ];
  15665. if ( index !== undefined ) {
  15666. face[ f ] = index;
  15667. }
  15668. }
  15669. }
  15670. return triangles.concat();
  15671. },
  15672. isClockWise: function ( pts ) {
  15673. return ShapeUtils.area( pts ) < 0;
  15674. }
  15675. };
  15676. /**
  15677. * @author zz85 / http://www.lab4games.net/zz85/blog
  15678. *
  15679. * Creates extruded geometry from a path shape.
  15680. *
  15681. * parameters = {
  15682. *
  15683. * curveSegments: <int>, // number of points on the curves
  15684. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15685. * amount: <int>, // Depth to extrude the shape
  15686. *
  15687. * bevelEnabled: <bool>, // turn on bevel
  15688. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15689. * bevelSize: <float>, // how far from shape outline is bevel
  15690. * bevelSegments: <int>, // number of bevel layers
  15691. *
  15692. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15693. * frames: <Object> // containing arrays of tangents, normals, binormals
  15694. *
  15695. * UVGenerator: <Object> // object that provides UV generator functions
  15696. *
  15697. * }
  15698. */
  15699. // ExtrudeGeometry
  15700. function ExtrudeGeometry( shapes, options ) {
  15701. Geometry.call( this );
  15702. this.type = 'ExtrudeGeometry';
  15703. this.parameters = {
  15704. shapes: shapes,
  15705. options: options
  15706. };
  15707. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  15708. this.mergeVertices();
  15709. }
  15710. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15711. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15712. // ExtrudeBufferGeometry
  15713. function ExtrudeBufferGeometry( shapes, options ) {
  15714. if ( typeof ( shapes ) === "undefined" ) {
  15715. shapes = [];
  15716. return;
  15717. }
  15718. BufferGeometry.call( this );
  15719. this.type = 'ExtrudeBufferGeometry';
  15720. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15721. this.addShapeList( shapes, options );
  15722. this.computeVertexNormals();
  15723. // can't really use automatic vertex normals
  15724. // as then front and back sides get smoothed too
  15725. // should do separate smoothing just for sides
  15726. //this.computeVertexNormals();
  15727. //console.log( "took", ( Date.now() - startTime ) );
  15728. }
  15729. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15730. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  15731. ExtrudeBufferGeometry.prototype.getArrays = function () {
  15732. var positionAttribute = this.getAttribute( "position" );
  15733. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  15734. var uvAttribute = this.getAttribute( "uv" );
  15735. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  15736. var IndexAttribute = this.index;
  15737. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  15738. return {
  15739. position: verticesArray,
  15740. uv: uvArray,
  15741. index: indicesArray
  15742. };
  15743. };
  15744. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  15745. var sl = shapes.length;
  15746. options.arrays = this.getArrays();
  15747. for ( var s = 0; s < sl; s ++ ) {
  15748. var shape = shapes[ s ];
  15749. this.addShape( shape, options );
  15750. }
  15751. this.setIndex( options.arrays.index );
  15752. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  15753. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  15754. };
  15755. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  15756. var arrays = options.arrays ? options.arrays : this.getArrays();
  15757. var verticesArray = arrays.position;
  15758. var indicesArray = arrays.index;
  15759. var uvArray = arrays.uv;
  15760. var placeholder = [];
  15761. var amount = options.amount !== undefined ? options.amount : 100;
  15762. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15763. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15764. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15765. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15766. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15767. var steps = options.steps !== undefined ? options.steps : 1;
  15768. var extrudePath = options.extrudePath;
  15769. var extrudePts, extrudeByPath = false;
  15770. // Use default WorldUVGenerator if no UV generators are specified.
  15771. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15772. var splineTube, binormal, normal, position2;
  15773. if ( extrudePath ) {
  15774. extrudePts = extrudePath.getSpacedPoints( steps );
  15775. extrudeByPath = true;
  15776. bevelEnabled = false; // bevels not supported for path extrusion
  15777. // SETUP TNB variables
  15778. // TODO1 - have a .isClosed in spline?
  15779. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15780. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15781. binormal = new Vector3();
  15782. normal = new Vector3();
  15783. position2 = new Vector3();
  15784. }
  15785. // Safeguards if bevels are not enabled
  15786. if ( ! bevelEnabled ) {
  15787. bevelSegments = 0;
  15788. bevelThickness = 0;
  15789. bevelSize = 0;
  15790. }
  15791. // Variables initialization
  15792. var ahole, h, hl; // looping of holes
  15793. var scope = this;
  15794. var shapePoints = shape.extractPoints( curveSegments );
  15795. var vertices = shapePoints.shape;
  15796. var holes = shapePoints.holes;
  15797. var reverse = ! ShapeUtils.isClockWise( vertices );
  15798. if ( reverse ) {
  15799. vertices = vertices.reverse();
  15800. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15801. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15802. ahole = holes[ h ];
  15803. if ( ShapeUtils.isClockWise( ahole ) ) {
  15804. holes[ h ] = ahole.reverse();
  15805. }
  15806. }
  15807. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15808. }
  15809. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15810. /* Vertices */
  15811. var contour = vertices; // vertices has all points but contour has only points of circumference
  15812. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15813. ahole = holes[ h ];
  15814. vertices = vertices.concat( ahole );
  15815. }
  15816. function scalePt2( pt, vec, size ) {
  15817. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15818. return vec.clone().multiplyScalar( size ).add( pt );
  15819. }
  15820. var b, bs, t, z,
  15821. vert, vlen = vertices.length,
  15822. face, flen = faces.length;
  15823. // Find directions for point movement
  15824. function getBevelVec( inPt, inPrev, inNext ) {
  15825. // computes for inPt the corresponding point inPt' on a new contour
  15826. // shifted by 1 unit (length of normalized vector) to the left
  15827. // if we walk along contour clockwise, this new contour is outside the old one
  15828. //
  15829. // inPt' is the intersection of the two lines parallel to the two
  15830. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15831. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15832. // good reading for geometry algorithms (here: line-line intersection)
  15833. // http://geomalgorithms.com/a05-_intersect-1.html
  15834. var v_prev_x = inPt.x - inPrev.x,
  15835. v_prev_y = inPt.y - inPrev.y;
  15836. var v_next_x = inNext.x - inPt.x,
  15837. v_next_y = inNext.y - inPt.y;
  15838. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15839. // check for collinear edges
  15840. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15841. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15842. // not collinear
  15843. // length of vectors for normalizing
  15844. var v_prev_len = Math.sqrt( v_prev_lensq );
  15845. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15846. // shift adjacent points by unit vectors to the left
  15847. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15848. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15849. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15850. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15851. // scaling factor for v_prev to intersection point
  15852. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15853. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15854. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15855. // vector from inPt to intersection point
  15856. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15857. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15858. // Don't normalize!, otherwise sharp corners become ugly
  15859. // but prevent crazy spikes
  15860. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15861. if ( v_trans_lensq <= 2 ) {
  15862. return new Vector2( v_trans_x, v_trans_y );
  15863. } else {
  15864. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15865. }
  15866. } else {
  15867. // handle special case of collinear edges
  15868. var direction_eq = false; // assumes: opposite
  15869. if ( v_prev_x > Number.EPSILON ) {
  15870. if ( v_next_x > Number.EPSILON ) {
  15871. direction_eq = true;
  15872. }
  15873. } else {
  15874. if ( v_prev_x < - Number.EPSILON ) {
  15875. if ( v_next_x < - Number.EPSILON ) {
  15876. direction_eq = true;
  15877. }
  15878. } else {
  15879. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15880. direction_eq = true;
  15881. }
  15882. }
  15883. }
  15884. if ( direction_eq ) {
  15885. // console.log("Warning: lines are a straight sequence");
  15886. v_trans_x = - v_prev_y;
  15887. v_trans_y = v_prev_x;
  15888. shrink_by = Math.sqrt( v_prev_lensq );
  15889. } else {
  15890. // console.log("Warning: lines are a straight spike");
  15891. v_trans_x = v_prev_x;
  15892. v_trans_y = v_prev_y;
  15893. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15894. }
  15895. }
  15896. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15897. }
  15898. var contourMovements = [];
  15899. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15900. if ( j === il ) j = 0;
  15901. if ( k === il ) k = 0;
  15902. // (j)---(i)---(k)
  15903. // console.log('i,j,k', i, j , k)
  15904. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15905. }
  15906. var holesMovements = [],
  15907. oneHoleMovements, verticesMovements = contourMovements.concat();
  15908. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15909. ahole = holes[ h ];
  15910. oneHoleMovements = [];
  15911. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15912. if ( j === il ) j = 0;
  15913. if ( k === il ) k = 0;
  15914. // (j)---(i)---(k)
  15915. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15916. }
  15917. holesMovements.push( oneHoleMovements );
  15918. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15919. }
  15920. // Loop bevelSegments, 1 for the front, 1 for the back
  15921. for ( b = 0; b < bevelSegments; b ++ ) {
  15922. //for ( b = bevelSegments; b > 0; b -- ) {
  15923. t = b / bevelSegments;
  15924. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15925. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15926. // contract shape
  15927. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15928. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15929. v( vert.x, vert.y, - z );
  15930. }
  15931. // expand holes
  15932. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15933. ahole = holes[ h ];
  15934. oneHoleMovements = holesMovements[ h ];
  15935. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15936. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15937. v( vert.x, vert.y, - z );
  15938. }
  15939. }
  15940. }
  15941. bs = bevelSize;
  15942. // Back facing vertices
  15943. for ( i = 0; i < vlen; i ++ ) {
  15944. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15945. if ( ! extrudeByPath ) {
  15946. v( vert.x, vert.y, 0 );
  15947. } else {
  15948. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15949. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15950. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15951. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15952. v( position2.x, position2.y, position2.z );
  15953. }
  15954. }
  15955. // Add stepped vertices...
  15956. // Including front facing vertices
  15957. var s;
  15958. for ( s = 1; s <= steps; s ++ ) {
  15959. for ( i = 0; i < vlen; i ++ ) {
  15960. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15961. if ( ! extrudeByPath ) {
  15962. v( vert.x, vert.y, amount / steps * s );
  15963. } else {
  15964. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15965. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15966. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15967. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15968. v( position2.x, position2.y, position2.z );
  15969. }
  15970. }
  15971. }
  15972. // Add bevel segments planes
  15973. //for ( b = 1; b <= bevelSegments; b ++ ) {
  15974. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  15975. t = b / bevelSegments;
  15976. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15977. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15978. // contract shape
  15979. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15980. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15981. v( vert.x, vert.y, amount + z );
  15982. }
  15983. // expand holes
  15984. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15985. ahole = holes[ h ];
  15986. oneHoleMovements = holesMovements[ h ];
  15987. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15988. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15989. if ( ! extrudeByPath ) {
  15990. v( vert.x, vert.y, amount + z );
  15991. } else {
  15992. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  15993. }
  15994. }
  15995. }
  15996. }
  15997. /* Faces */
  15998. // Top and bottom faces
  15999. buildLidFaces();
  16000. // Sides faces
  16001. buildSideFaces();
  16002. ///// Internal functions
  16003. function buildLidFaces() {
  16004. var start = verticesArray.length/3;
  16005. if ( bevelEnabled ) {
  16006. var layer = 0; // steps + 1
  16007. var offset = vlen * layer;
  16008. // Bottom faces
  16009. for ( i = 0; i < flen; i ++ ) {
  16010. face = faces[ i ];
  16011. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  16012. }
  16013. layer = steps + bevelSegments * 2;
  16014. offset = vlen * layer;
  16015. // Top faces
  16016. for ( i = 0; i < flen; i ++ ) {
  16017. face = faces[ i ];
  16018. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  16019. }
  16020. } else {
  16021. // Bottom faces
  16022. for ( i = 0; i < flen; i ++ ) {
  16023. face = faces[ i ];
  16024. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  16025. }
  16026. // Top faces
  16027. for ( i = 0; i < flen; i ++ ) {
  16028. face = faces[ i ];
  16029. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  16030. }
  16031. }
  16032. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  16033. }
  16034. // Create faces for the z-sides of the shape
  16035. function buildSideFaces() {
  16036. var start = verticesArray.length/3;
  16037. var layeroffset = 0;
  16038. sidewalls( contour, layeroffset );
  16039. layeroffset += contour.length;
  16040. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  16041. ahole = holes[ h ];
  16042. sidewalls( ahole, layeroffset );
  16043. //, true
  16044. layeroffset += ahole.length;
  16045. }
  16046. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  16047. }
  16048. function sidewalls( contour, layeroffset ) {
  16049. var j, k;
  16050. i = contour.length;
  16051. while ( -- i >= 0 ) {
  16052. j = i;
  16053. k = i - 1;
  16054. if ( k < 0 ) k = contour.length - 1;
  16055. //console.log('b', i,j, i-1, k,vertices.length);
  16056. var s = 0,
  16057. sl = steps + bevelSegments * 2;
  16058. for ( s = 0; s < sl; s ++ ) {
  16059. var slen1 = vlen * s;
  16060. var slen2 = vlen * ( s + 1 );
  16061. var a = layeroffset + j + slen1,
  16062. b = layeroffset + k + slen1,
  16063. c = layeroffset + k + slen2,
  16064. d = layeroffset + j + slen2;
  16065. f4( a, b, c, d, contour, s, sl, j, k );
  16066. }
  16067. }
  16068. }
  16069. function v( x, y, z ) {
  16070. placeholder.push( x );
  16071. placeholder.push( y );
  16072. placeholder.push( z );
  16073. }
  16074. function f3( a, b, c ) {
  16075. addVertex( a );
  16076. addVertex( b );
  16077. addVertex( c );
  16078. var nextIndex = verticesArray.length / 3;
  16079. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16080. addUV( uvs[ 0 ] );
  16081. addUV( uvs[ 1 ] );
  16082. addUV( uvs[ 2 ] );
  16083. }
  16084. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  16085. addVertex( a );
  16086. addVertex( b );
  16087. addVertex( d );
  16088. addVertex( b );
  16089. addVertex( c );
  16090. addVertex( d );
  16091. var nextIndex = verticesArray.length / 3;
  16092. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  16093. addUV( uvs[ 0 ] );
  16094. addUV( uvs[ 1 ] );
  16095. addUV( uvs[ 3 ] );
  16096. addUV( uvs[ 1 ] );
  16097. addUV( uvs[ 2 ] );
  16098. addUV( uvs[ 3 ] );
  16099. }
  16100. function addVertex( index ) {
  16101. indicesArray.push( verticesArray.length / 3 );
  16102. verticesArray.push( placeholder[ index * 3 + 0 ] );
  16103. verticesArray.push( placeholder[ index * 3 + 1 ] );
  16104. verticesArray.push( placeholder[ index * 3 + 2 ] );
  16105. }
  16106. function addUV( vector2 ) {
  16107. uvArray.push( vector2.x );
  16108. uvArray.push( vector2.y );
  16109. }
  16110. if ( ! options.arrays ) {
  16111. this.setIndex( indicesArray );
  16112. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  16113. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  16114. }
  16115. };
  16116. ExtrudeGeometry.WorldUVGenerator = {
  16117. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  16118. var a_x = vertices[ indexA * 3 ];
  16119. var a_y = vertices[ indexA * 3 + 1 ];
  16120. var b_x = vertices[ indexB * 3 ];
  16121. var b_y = vertices[ indexB * 3 + 1 ];
  16122. var c_x = vertices[ indexC * 3 ];
  16123. var c_y = vertices[ indexC * 3 + 1 ];
  16124. return [
  16125. new Vector2( a_x, a_y ),
  16126. new Vector2( b_x, b_y ),
  16127. new Vector2( c_x, c_y )
  16128. ];
  16129. },
  16130. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  16131. var a_x = vertices[ indexA * 3 ];
  16132. var a_y = vertices[ indexA * 3 + 1 ];
  16133. var a_z = vertices[ indexA * 3 + 2 ];
  16134. var b_x = vertices[ indexB * 3 ];
  16135. var b_y = vertices[ indexB * 3 + 1 ];
  16136. var b_z = vertices[ indexB * 3 + 2 ];
  16137. var c_x = vertices[ indexC * 3 ];
  16138. var c_y = vertices[ indexC * 3 + 1 ];
  16139. var c_z = vertices[ indexC * 3 + 2 ];
  16140. var d_x = vertices[ indexD * 3 ];
  16141. var d_y = vertices[ indexD * 3 + 1 ];
  16142. var d_z = vertices[ indexD * 3 + 2 ];
  16143. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  16144. return [
  16145. new Vector2( a_x, 1 - a_z ),
  16146. new Vector2( b_x, 1 - b_z ),
  16147. new Vector2( c_x, 1 - c_z ),
  16148. new Vector2( d_x, 1 - d_z )
  16149. ];
  16150. } else {
  16151. return [
  16152. new Vector2( a_y, 1 - a_z ),
  16153. new Vector2( b_y, 1 - b_z ),
  16154. new Vector2( c_y, 1 - c_z ),
  16155. new Vector2( d_y, 1 - d_z )
  16156. ];
  16157. }
  16158. }
  16159. };
  16160. /**
  16161. * @author zz85 / http://www.lab4games.net/zz85/blog
  16162. * @author alteredq / http://alteredqualia.com/
  16163. *
  16164. * Text = 3D Text
  16165. *
  16166. * parameters = {
  16167. * font: <THREE.Font>, // font
  16168. *
  16169. * size: <float>, // size of the text
  16170. * height: <float>, // thickness to extrude text
  16171. * curveSegments: <int>, // number of points on the curves
  16172. *
  16173. * bevelEnabled: <bool>, // turn on bevel
  16174. * bevelThickness: <float>, // how deep into text bevel goes
  16175. * bevelSize: <float> // how far from text outline is bevel
  16176. * }
  16177. */
  16178. // TextGeometry
  16179. function TextGeometry( text, parameters ) {
  16180. Geometry.call( this );
  16181. this.type = 'TextGeometry';
  16182. this.parameters = {
  16183. text: text,
  16184. parameters: parameters
  16185. };
  16186. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  16187. this.mergeVertices();
  16188. }
  16189. TextGeometry.prototype = Object.create( Geometry.prototype );
  16190. TextGeometry.prototype.constructor = TextGeometry;
  16191. // TextBufferGeometry
  16192. function TextBufferGeometry( text, parameters ) {
  16193. parameters = parameters || {};
  16194. var font = parameters.font;
  16195. if ( ( font && font.isFont ) === false ) {
  16196. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  16197. return new Geometry();
  16198. }
  16199. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  16200. // translate parameters to ExtrudeGeometry API
  16201. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  16202. // defaults
  16203. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  16204. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  16205. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  16206. ExtrudeBufferGeometry.call( this, shapes, parameters );
  16207. this.type = 'TextBufferGeometry';
  16208. }
  16209. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  16210. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  16211. /**
  16212. * @author mrdoob / http://mrdoob.com/
  16213. * @author benaadams / https://twitter.com/ben_a_adams
  16214. * @author Mugen87 / https://github.com/Mugen87
  16215. */
  16216. // SphereGeometry
  16217. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16218. Geometry.call( this );
  16219. this.type = 'SphereGeometry';
  16220. this.parameters = {
  16221. radius: radius,
  16222. widthSegments: widthSegments,
  16223. heightSegments: heightSegments,
  16224. phiStart: phiStart,
  16225. phiLength: phiLength,
  16226. thetaStart: thetaStart,
  16227. thetaLength: thetaLength
  16228. };
  16229. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16230. this.mergeVertices();
  16231. }
  16232. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16233. SphereGeometry.prototype.constructor = SphereGeometry;
  16234. // SphereBufferGeometry
  16235. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16236. BufferGeometry.call( this );
  16237. this.type = 'SphereBufferGeometry';
  16238. this.parameters = {
  16239. radius: radius,
  16240. widthSegments: widthSegments,
  16241. heightSegments: heightSegments,
  16242. phiStart: phiStart,
  16243. phiLength: phiLength,
  16244. thetaStart: thetaStart,
  16245. thetaLength: thetaLength
  16246. };
  16247. radius = radius || 50;
  16248. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  16249. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  16250. phiStart = phiStart !== undefined ? phiStart : 0;
  16251. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  16252. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16253. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  16254. var thetaEnd = thetaStart + thetaLength;
  16255. var ix, iy;
  16256. var index = 0;
  16257. var grid = [];
  16258. var vertex = new Vector3();
  16259. var normal = new Vector3();
  16260. // buffers
  16261. var indices = [];
  16262. var vertices = [];
  16263. var normals = [];
  16264. var uvs = [];
  16265. // generate vertices, normals and uvs
  16266. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  16267. var verticesRow = [];
  16268. var v = iy / heightSegments;
  16269. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  16270. var u = ix / widthSegments;
  16271. // vertex
  16272. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16273. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  16274. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  16275. vertices.push( vertex.x, vertex.y, vertex.z );
  16276. // normal
  16277. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  16278. normals.push( normal.x, normal.y, normal.z );
  16279. // uv
  16280. uvs.push( u, 1 - v );
  16281. verticesRow.push( index ++ );
  16282. }
  16283. grid.push( verticesRow );
  16284. }
  16285. // indices
  16286. for ( iy = 0; iy < heightSegments; iy ++ ) {
  16287. for ( ix = 0; ix < widthSegments; ix ++ ) {
  16288. var a = grid[ iy ][ ix + 1 ];
  16289. var b = grid[ iy ][ ix ];
  16290. var c = grid[ iy + 1 ][ ix ];
  16291. var d = grid[ iy + 1 ][ ix + 1 ];
  16292. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  16293. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  16294. }
  16295. }
  16296. // build geometry
  16297. this.setIndex( indices );
  16298. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16299. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16300. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16301. }
  16302. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16303. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16304. /**
  16305. * @author Kaleb Murphy
  16306. * @author Mugen87 / https://github.com/Mugen87
  16307. */
  16308. // RingGeometry
  16309. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16310. Geometry.call( this );
  16311. this.type = 'RingGeometry';
  16312. this.parameters = {
  16313. innerRadius: innerRadius,
  16314. outerRadius: outerRadius,
  16315. thetaSegments: thetaSegments,
  16316. phiSegments: phiSegments,
  16317. thetaStart: thetaStart,
  16318. thetaLength: thetaLength
  16319. };
  16320. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16321. this.mergeVertices();
  16322. }
  16323. RingGeometry.prototype = Object.create( Geometry.prototype );
  16324. RingGeometry.prototype.constructor = RingGeometry;
  16325. // RingBufferGeometry
  16326. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16327. BufferGeometry.call( this );
  16328. this.type = 'RingBufferGeometry';
  16329. this.parameters = {
  16330. innerRadius: innerRadius,
  16331. outerRadius: outerRadius,
  16332. thetaSegments: thetaSegments,
  16333. phiSegments: phiSegments,
  16334. thetaStart: thetaStart,
  16335. thetaLength: thetaLength
  16336. };
  16337. innerRadius = innerRadius || 20;
  16338. outerRadius = outerRadius || 50;
  16339. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16340. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16341. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16342. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16343. // buffers
  16344. var indices = [];
  16345. var vertices = [];
  16346. var normals = [];
  16347. var uvs = [];
  16348. // some helper variables
  16349. var segment;
  16350. var radius = innerRadius;
  16351. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16352. var vertex = new Vector3();
  16353. var uv = new Vector2();
  16354. var j, i;
  16355. // generate vertices, normals and uvs
  16356. for ( j = 0; j <= phiSegments; j ++ ) {
  16357. for ( i = 0; i <= thetaSegments; i ++ ) {
  16358. // values are generate from the inside of the ring to the outside
  16359. segment = thetaStart + i / thetaSegments * thetaLength;
  16360. // vertex
  16361. vertex.x = radius * Math.cos( segment );
  16362. vertex.y = radius * Math.sin( segment );
  16363. vertices.push( vertex.x, vertex.y, vertex.z );
  16364. // normal
  16365. normals.push( 0, 0, 1 );
  16366. // uv
  16367. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16368. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16369. uvs.push( uv.x, uv.y );
  16370. }
  16371. // increase the radius for next row of vertices
  16372. radius += radiusStep;
  16373. }
  16374. // indices
  16375. for ( j = 0; j < phiSegments; j ++ ) {
  16376. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16377. for ( i = 0; i < thetaSegments; i ++ ) {
  16378. segment = i + thetaSegmentLevel;
  16379. var a = segment;
  16380. var b = segment + thetaSegments + 1;
  16381. var c = segment + thetaSegments + 2;
  16382. var d = segment + 1;
  16383. // faces
  16384. indices.push( a, b, d );
  16385. indices.push( b, c, d );
  16386. }
  16387. }
  16388. // build geometry
  16389. this.setIndex( indices );
  16390. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16391. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16392. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16393. }
  16394. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16395. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16396. /**
  16397. * @author astrodud / http://astrodud.isgreat.org/
  16398. * @author zz85 / https://github.com/zz85
  16399. * @author bhouston / http://clara.io
  16400. * @author Mugen87 / https://github.com/Mugen87
  16401. */
  16402. // LatheGeometry
  16403. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16404. Geometry.call( this );
  16405. this.type = 'LatheGeometry';
  16406. this.parameters = {
  16407. points: points,
  16408. segments: segments,
  16409. phiStart: phiStart,
  16410. phiLength: phiLength
  16411. };
  16412. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16413. this.mergeVertices();
  16414. }
  16415. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16416. LatheGeometry.prototype.constructor = LatheGeometry;
  16417. // LatheBufferGeometry
  16418. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16419. BufferGeometry.call( this );
  16420. this.type = 'LatheBufferGeometry';
  16421. this.parameters = {
  16422. points: points,
  16423. segments: segments,
  16424. phiStart: phiStart,
  16425. phiLength: phiLength
  16426. };
  16427. segments = Math.floor( segments ) || 12;
  16428. phiStart = phiStart || 0;
  16429. phiLength = phiLength || Math.PI * 2;
  16430. // clamp phiLength so it's in range of [ 0, 2PI ]
  16431. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16432. // buffers
  16433. var indices = [];
  16434. var vertices = [];
  16435. var uvs = [];
  16436. // helper variables
  16437. var base;
  16438. var inverseSegments = 1.0 / segments;
  16439. var vertex = new Vector3();
  16440. var uv = new Vector2();
  16441. var i, j;
  16442. // generate vertices and uvs
  16443. for ( i = 0; i <= segments; i ++ ) {
  16444. var phi = phiStart + i * inverseSegments * phiLength;
  16445. var sin = Math.sin( phi );
  16446. var cos = Math.cos( phi );
  16447. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16448. // vertex
  16449. vertex.x = points[ j ].x * sin;
  16450. vertex.y = points[ j ].y;
  16451. vertex.z = points[ j ].x * cos;
  16452. vertices.push( vertex.x, vertex.y, vertex.z );
  16453. // uv
  16454. uv.x = i / segments;
  16455. uv.y = j / ( points.length - 1 );
  16456. uvs.push( uv.x, uv.y );
  16457. }
  16458. }
  16459. // indices
  16460. for ( i = 0; i < segments; i ++ ) {
  16461. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16462. base = j + i * points.length;
  16463. var a = base;
  16464. var b = base + points.length;
  16465. var c = base + points.length + 1;
  16466. var d = base + 1;
  16467. // faces
  16468. indices.push( a, b, d );
  16469. indices.push( b, c, d );
  16470. }
  16471. }
  16472. // build geometry
  16473. this.setIndex( indices );
  16474. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16475. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16476. // generate normals
  16477. this.computeVertexNormals();
  16478. // if the geometry is closed, we need to average the normals along the seam.
  16479. // because the corresponding vertices are identical (but still have different UVs).
  16480. if ( phiLength === Math.PI * 2 ) {
  16481. var normals = this.attributes.normal.array;
  16482. var n1 = new Vector3();
  16483. var n2 = new Vector3();
  16484. var n = new Vector3();
  16485. // this is the buffer offset for the last line of vertices
  16486. base = segments * points.length * 3;
  16487. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16488. // select the normal of the vertex in the first line
  16489. n1.x = normals[ j + 0 ];
  16490. n1.y = normals[ j + 1 ];
  16491. n1.z = normals[ j + 2 ];
  16492. // select the normal of the vertex in the last line
  16493. n2.x = normals[ base + j + 0 ];
  16494. n2.y = normals[ base + j + 1 ];
  16495. n2.z = normals[ base + j + 2 ];
  16496. // average normals
  16497. n.addVectors( n1, n2 ).normalize();
  16498. // assign the new values to both normals
  16499. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16500. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16501. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16502. }
  16503. }
  16504. }
  16505. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16506. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16507. /**
  16508. * @author jonobr1 / http://jonobr1.com
  16509. * @author Mugen87 / https://github.com/Mugen87
  16510. */
  16511. // ShapeGeometry
  16512. function ShapeGeometry( shapes, curveSegments ) {
  16513. Geometry.call( this );
  16514. this.type = 'ShapeGeometry';
  16515. if ( typeof curveSegments === 'object' ) {
  16516. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16517. curveSegments = curveSegments.curveSegments;
  16518. }
  16519. this.parameters = {
  16520. shapes: shapes,
  16521. curveSegments: curveSegments
  16522. };
  16523. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16524. this.mergeVertices();
  16525. }
  16526. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16527. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16528. // ShapeBufferGeometry
  16529. function ShapeBufferGeometry( shapes, curveSegments ) {
  16530. BufferGeometry.call( this );
  16531. this.type = 'ShapeBufferGeometry';
  16532. this.parameters = {
  16533. shapes: shapes,
  16534. curveSegments: curveSegments
  16535. };
  16536. curveSegments = curveSegments || 12;
  16537. // buffers
  16538. var indices = [];
  16539. var vertices = [];
  16540. var normals = [];
  16541. var uvs = [];
  16542. // helper variables
  16543. var groupStart = 0;
  16544. var groupCount = 0;
  16545. // allow single and array values for "shapes" parameter
  16546. if ( Array.isArray( shapes ) === false ) {
  16547. addShape( shapes );
  16548. } else {
  16549. for ( var i = 0; i < shapes.length; i ++ ) {
  16550. addShape( shapes[ i ] );
  16551. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16552. groupStart += groupCount;
  16553. groupCount = 0;
  16554. }
  16555. }
  16556. // build geometry
  16557. this.setIndex( indices );
  16558. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16559. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16560. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16561. // helper functions
  16562. function addShape( shape ) {
  16563. var i, l, shapeHole;
  16564. var indexOffset = vertices.length / 3;
  16565. var points = shape.extractPoints( curveSegments );
  16566. var shapeVertices = points.shape;
  16567. var shapeHoles = points.holes;
  16568. // check direction of vertices
  16569. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16570. shapeVertices = shapeVertices.reverse();
  16571. // also check if holes are in the opposite direction
  16572. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16573. shapeHole = shapeHoles[ i ];
  16574. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16575. shapeHoles[ i ] = shapeHole.reverse();
  16576. }
  16577. }
  16578. }
  16579. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16580. // join vertices of inner and outer paths to a single array
  16581. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16582. shapeHole = shapeHoles[ i ];
  16583. shapeVertices = shapeVertices.concat( shapeHole );
  16584. }
  16585. // vertices, normals, uvs
  16586. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16587. var vertex = shapeVertices[ i ];
  16588. vertices.push( vertex.x, vertex.y, 0 );
  16589. normals.push( 0, 0, 1 );
  16590. uvs.push( vertex.x, vertex.y ); // world uvs
  16591. }
  16592. // incides
  16593. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16594. var face = faces[ i ];
  16595. var a = face[ 0 ] + indexOffset;
  16596. var b = face[ 1 ] + indexOffset;
  16597. var c = face[ 2 ] + indexOffset;
  16598. indices.push( a, b, c );
  16599. groupCount += 3;
  16600. }
  16601. }
  16602. }
  16603. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16604. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16605. /**
  16606. * @author WestLangley / http://github.com/WestLangley
  16607. * @author Mugen87 / https://github.com/Mugen87
  16608. */
  16609. function EdgesGeometry( geometry, thresholdAngle ) {
  16610. BufferGeometry.call( this );
  16611. this.type = 'EdgesGeometry';
  16612. this.parameters = {
  16613. thresholdAngle: thresholdAngle
  16614. };
  16615. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16616. // buffer
  16617. var vertices = [];
  16618. // helper variables
  16619. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16620. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  16621. var key, keys = [ 'a', 'b', 'c' ];
  16622. // prepare source geometry
  16623. var geometry2;
  16624. if ( geometry.isBufferGeometry ) {
  16625. geometry2 = new Geometry();
  16626. geometry2.fromBufferGeometry( geometry );
  16627. } else {
  16628. geometry2 = geometry.clone();
  16629. }
  16630. geometry2.mergeVertices();
  16631. geometry2.computeFaceNormals();
  16632. var sourceVertices = geometry2.vertices;
  16633. var faces = geometry2.faces;
  16634. // now create a data structure where each entry represents an edge with its adjoining faces
  16635. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16636. var face = faces[ i ];
  16637. for ( var j = 0; j < 3; j ++ ) {
  16638. edge1 = face[ keys[ j ] ];
  16639. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  16640. edge[ 0 ] = Math.min( edge1, edge2 );
  16641. edge[ 1 ] = Math.max( edge1, edge2 );
  16642. key = edge[ 0 ] + ',' + edge[ 1 ];
  16643. if ( edges[ key ] === undefined ) {
  16644. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  16645. } else {
  16646. edges[ key ].face2 = i;
  16647. }
  16648. }
  16649. }
  16650. // generate vertices
  16651. for ( key in edges ) {
  16652. var e = edges[ key ];
  16653. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16654. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  16655. var vertex = sourceVertices[ e.index1 ];
  16656. vertices.push( vertex.x, vertex.y, vertex.z );
  16657. vertex = sourceVertices[ e.index2 ];
  16658. vertices.push( vertex.x, vertex.y, vertex.z );
  16659. }
  16660. }
  16661. // build geometry
  16662. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16663. }
  16664. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16665. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16666. /**
  16667. * @author mrdoob / http://mrdoob.com/
  16668. * @author Mugen87 / https://github.com/Mugen87
  16669. */
  16670. // CylinderGeometry
  16671. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16672. Geometry.call( this );
  16673. this.type = 'CylinderGeometry';
  16674. this.parameters = {
  16675. radiusTop: radiusTop,
  16676. radiusBottom: radiusBottom,
  16677. height: height,
  16678. radialSegments: radialSegments,
  16679. heightSegments: heightSegments,
  16680. openEnded: openEnded,
  16681. thetaStart: thetaStart,
  16682. thetaLength: thetaLength
  16683. };
  16684. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16685. this.mergeVertices();
  16686. }
  16687. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16688. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16689. // CylinderBufferGeometry
  16690. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16691. BufferGeometry.call( this );
  16692. this.type = 'CylinderBufferGeometry';
  16693. this.parameters = {
  16694. radiusTop: radiusTop,
  16695. radiusBottom: radiusBottom,
  16696. height: height,
  16697. radialSegments: radialSegments,
  16698. heightSegments: heightSegments,
  16699. openEnded: openEnded,
  16700. thetaStart: thetaStart,
  16701. thetaLength: thetaLength
  16702. };
  16703. var scope = this;
  16704. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16705. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16706. height = height !== undefined ? height : 100;
  16707. radialSegments = Math.floor( radialSegments ) || 8;
  16708. heightSegments = Math.floor( heightSegments ) || 1;
  16709. openEnded = openEnded !== undefined ? openEnded : false;
  16710. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16711. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16712. // buffers
  16713. var indices = [];
  16714. var vertices = [];
  16715. var normals = [];
  16716. var uvs = [];
  16717. // helper variables
  16718. var index = 0;
  16719. var indexArray = [];
  16720. var halfHeight = height / 2;
  16721. var groupStart = 0;
  16722. // generate geometry
  16723. generateTorso();
  16724. if ( openEnded === false ) {
  16725. if ( radiusTop > 0 ) generateCap( true );
  16726. if ( radiusBottom > 0 ) generateCap( false );
  16727. }
  16728. // build geometry
  16729. this.setIndex( indices );
  16730. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16731. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16732. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16733. function generateTorso() {
  16734. var x, y;
  16735. var normal = new Vector3();
  16736. var vertex = new Vector3();
  16737. var groupCount = 0;
  16738. // this will be used to calculate the normal
  16739. var slope = ( radiusBottom - radiusTop ) / height;
  16740. // generate vertices, normals and uvs
  16741. for ( y = 0; y <= heightSegments; y ++ ) {
  16742. var indexRow = [];
  16743. var v = y / heightSegments;
  16744. // calculate the radius of the current row
  16745. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16746. for ( x = 0; x <= radialSegments; x ++ ) {
  16747. var u = x / radialSegments;
  16748. var theta = u * thetaLength + thetaStart;
  16749. var sinTheta = Math.sin( theta );
  16750. var cosTheta = Math.cos( theta );
  16751. // vertex
  16752. vertex.x = radius * sinTheta;
  16753. vertex.y = - v * height + halfHeight;
  16754. vertex.z = radius * cosTheta;
  16755. vertices.push( vertex.x, vertex.y, vertex.z );
  16756. // normal
  16757. normal.set( sinTheta, slope, cosTheta ).normalize();
  16758. normals.push( normal.x, normal.y, normal.z );
  16759. // uv
  16760. uvs.push( u, 1 - v );
  16761. // save index of vertex in respective row
  16762. indexRow.push( index ++ );
  16763. }
  16764. // now save vertices of the row in our index array
  16765. indexArray.push( indexRow );
  16766. }
  16767. // generate indices
  16768. for ( x = 0; x < radialSegments; x ++ ) {
  16769. for ( y = 0; y < heightSegments; y ++ ) {
  16770. // we use the index array to access the correct indices
  16771. var a = indexArray[ y ][ x ];
  16772. var b = indexArray[ y + 1 ][ x ];
  16773. var c = indexArray[ y + 1 ][ x + 1 ];
  16774. var d = indexArray[ y ][ x + 1 ];
  16775. // faces
  16776. indices.push( a, b, d );
  16777. indices.push( b, c, d );
  16778. // update group counter
  16779. groupCount += 6;
  16780. }
  16781. }
  16782. // add a group to the geometry. this will ensure multi material support
  16783. scope.addGroup( groupStart, groupCount, 0 );
  16784. // calculate new start value for groups
  16785. groupStart += groupCount;
  16786. }
  16787. function generateCap( top ) {
  16788. var x, centerIndexStart, centerIndexEnd;
  16789. var uv = new Vector2();
  16790. var vertex = new Vector3();
  16791. var groupCount = 0;
  16792. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16793. var sign = ( top === true ) ? 1 : - 1;
  16794. // save the index of the first center vertex
  16795. centerIndexStart = index;
  16796. // first we generate the center vertex data of the cap.
  16797. // because the geometry needs one set of uvs per face,
  16798. // we must generate a center vertex per face/segment
  16799. for ( x = 1; x <= radialSegments; x ++ ) {
  16800. // vertex
  16801. vertices.push( 0, halfHeight * sign, 0 );
  16802. // normal
  16803. normals.push( 0, sign, 0 );
  16804. // uv
  16805. uvs.push( 0.5, 0.5 );
  16806. // increase index
  16807. index ++;
  16808. }
  16809. // save the index of the last center vertex
  16810. centerIndexEnd = index;
  16811. // now we generate the surrounding vertices, normals and uvs
  16812. for ( x = 0; x <= radialSegments; x ++ ) {
  16813. var u = x / radialSegments;
  16814. var theta = u * thetaLength + thetaStart;
  16815. var cosTheta = Math.cos( theta );
  16816. var sinTheta = Math.sin( theta );
  16817. // vertex
  16818. vertex.x = radius * sinTheta;
  16819. vertex.y = halfHeight * sign;
  16820. vertex.z = radius * cosTheta;
  16821. vertices.push( vertex.x, vertex.y, vertex.z );
  16822. // normal
  16823. normals.push( 0, sign, 0 );
  16824. // uv
  16825. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16826. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16827. uvs.push( uv.x, uv.y );
  16828. // increase index
  16829. index ++;
  16830. }
  16831. // generate indices
  16832. for ( x = 0; x < radialSegments; x ++ ) {
  16833. var c = centerIndexStart + x;
  16834. var i = centerIndexEnd + x;
  16835. if ( top === true ) {
  16836. // face top
  16837. indices.push( i, i + 1, c );
  16838. } else {
  16839. // face bottom
  16840. indices.push( i + 1, i, c );
  16841. }
  16842. groupCount += 3;
  16843. }
  16844. // add a group to the geometry. this will ensure multi material support
  16845. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16846. // calculate new start value for groups
  16847. groupStart += groupCount;
  16848. }
  16849. }
  16850. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16851. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16852. /**
  16853. * @author abelnation / http://github.com/abelnation
  16854. */
  16855. // ConeGeometry
  16856. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16857. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16858. this.type = 'ConeGeometry';
  16859. this.parameters = {
  16860. radius: radius,
  16861. height: height,
  16862. radialSegments: radialSegments,
  16863. heightSegments: heightSegments,
  16864. openEnded: openEnded,
  16865. thetaStart: thetaStart,
  16866. thetaLength: thetaLength
  16867. };
  16868. }
  16869. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16870. ConeGeometry.prototype.constructor = ConeGeometry;
  16871. // ConeBufferGeometry
  16872. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16873. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16874. this.type = 'ConeBufferGeometry';
  16875. this.parameters = {
  16876. radius: radius,
  16877. height: height,
  16878. radialSegments: radialSegments,
  16879. heightSegments: heightSegments,
  16880. openEnded: openEnded,
  16881. thetaStart: thetaStart,
  16882. thetaLength: thetaLength
  16883. };
  16884. }
  16885. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16886. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16887. /**
  16888. * @author benaadams / https://twitter.com/ben_a_adams
  16889. * @author Mugen87 / https://github.com/Mugen87
  16890. * @author hughes
  16891. */
  16892. // CircleGeometry
  16893. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16894. Geometry.call( this );
  16895. this.type = 'CircleGeometry';
  16896. this.parameters = {
  16897. radius: radius,
  16898. segments: segments,
  16899. thetaStart: thetaStart,
  16900. thetaLength: thetaLength
  16901. };
  16902. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16903. this.mergeVertices();
  16904. }
  16905. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16906. CircleGeometry.prototype.constructor = CircleGeometry;
  16907. // CircleBufferGeometry
  16908. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16909. BufferGeometry.call( this );
  16910. this.type = 'CircleBufferGeometry';
  16911. this.parameters = {
  16912. radius: radius,
  16913. segments: segments,
  16914. thetaStart: thetaStart,
  16915. thetaLength: thetaLength
  16916. };
  16917. radius = radius || 50;
  16918. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16919. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16920. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16921. // buffers
  16922. var indices = [];
  16923. var vertices = [];
  16924. var normals = [];
  16925. var uvs = [];
  16926. // helper variables
  16927. var i, s;
  16928. var vertex = new Vector3();
  16929. var uv = new Vector2();
  16930. // center point
  16931. vertices.push( 0, 0, 0 );
  16932. normals.push( 0, 0, 1 );
  16933. uvs.push( 0.5, 0.5 );
  16934. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  16935. var segment = thetaStart + s / segments * thetaLength;
  16936. // vertex
  16937. vertex.x = radius * Math.cos( segment );
  16938. vertex.y = radius * Math.sin( segment );
  16939. vertices.push( vertex.x, vertex.y, vertex.z );
  16940. // normal
  16941. normals.push( 0, 0, 1 );
  16942. // uvs
  16943. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  16944. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  16945. uvs.push( uv.x, uv.y );
  16946. }
  16947. // indices
  16948. for ( i = 1; i <= segments; i ++ ) {
  16949. indices.push( i, i + 1, 0 );
  16950. }
  16951. // build geometry
  16952. this.setIndex( indices );
  16953. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16954. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16955. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16956. }
  16957. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16958. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16959. var Geometries = Object.freeze({
  16960. WireframeGeometry: WireframeGeometry,
  16961. ParametricGeometry: ParametricGeometry,
  16962. ParametricBufferGeometry: ParametricBufferGeometry,
  16963. TetrahedronGeometry: TetrahedronGeometry,
  16964. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16965. OctahedronGeometry: OctahedronGeometry,
  16966. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16967. IcosahedronGeometry: IcosahedronGeometry,
  16968. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16969. DodecahedronGeometry: DodecahedronGeometry,
  16970. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  16971. PolyhedronGeometry: PolyhedronGeometry,
  16972. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  16973. TubeGeometry: TubeGeometry,
  16974. TubeBufferGeometry: TubeBufferGeometry,
  16975. TorusKnotGeometry: TorusKnotGeometry,
  16976. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  16977. TorusGeometry: TorusGeometry,
  16978. TorusBufferGeometry: TorusBufferGeometry,
  16979. TextGeometry: TextGeometry,
  16980. TextBufferGeometry: TextBufferGeometry,
  16981. SphereGeometry: SphereGeometry,
  16982. SphereBufferGeometry: SphereBufferGeometry,
  16983. RingGeometry: RingGeometry,
  16984. RingBufferGeometry: RingBufferGeometry,
  16985. PlaneGeometry: PlaneGeometry,
  16986. PlaneBufferGeometry: PlaneBufferGeometry,
  16987. LatheGeometry: LatheGeometry,
  16988. LatheBufferGeometry: LatheBufferGeometry,
  16989. ShapeGeometry: ShapeGeometry,
  16990. ShapeBufferGeometry: ShapeBufferGeometry,
  16991. ExtrudeGeometry: ExtrudeGeometry,
  16992. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  16993. EdgesGeometry: EdgesGeometry,
  16994. ConeGeometry: ConeGeometry,
  16995. ConeBufferGeometry: ConeBufferGeometry,
  16996. CylinderGeometry: CylinderGeometry,
  16997. CylinderBufferGeometry: CylinderBufferGeometry,
  16998. CircleGeometry: CircleGeometry,
  16999. CircleBufferGeometry: CircleBufferGeometry,
  17000. BoxGeometry: BoxGeometry,
  17001. BoxBufferGeometry: BoxBufferGeometry
  17002. });
  17003. /**
  17004. * @author mrdoob / http://mrdoob.com/
  17005. *
  17006. * parameters = {
  17007. * opacity: <float>
  17008. * }
  17009. */
  17010. function ShadowMaterial( parameters ) {
  17011. ShaderMaterial.call( this, {
  17012. uniforms: UniformsUtils.merge( [
  17013. UniformsLib.lights,
  17014. {
  17015. opacity: { value: 1.0 }
  17016. }
  17017. ] ),
  17018. vertexShader: ShaderChunk[ 'shadow_vert' ],
  17019. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  17020. } );
  17021. this.lights = true;
  17022. this.transparent = true;
  17023. Object.defineProperties( this, {
  17024. opacity: {
  17025. enumerable: true,
  17026. get: function () {
  17027. return this.uniforms.opacity.value;
  17028. },
  17029. set: function ( value ) {
  17030. this.uniforms.opacity.value = value;
  17031. }
  17032. }
  17033. } );
  17034. this.setValues( parameters );
  17035. }
  17036. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17037. ShadowMaterial.prototype.constructor = ShadowMaterial;
  17038. ShadowMaterial.prototype.isShadowMaterial = true;
  17039. /**
  17040. * @author mrdoob / http://mrdoob.com/
  17041. */
  17042. function RawShaderMaterial( parameters ) {
  17043. ShaderMaterial.call( this, parameters );
  17044. this.type = 'RawShaderMaterial';
  17045. }
  17046. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  17047. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  17048. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  17049. /**
  17050. * @author WestLangley / http://github.com/WestLangley
  17051. *
  17052. * parameters = {
  17053. * color: <hex>,
  17054. * roughness: <float>,
  17055. * metalness: <float>,
  17056. * opacity: <float>,
  17057. *
  17058. * map: new THREE.Texture( <Image> ),
  17059. *
  17060. * lightMap: new THREE.Texture( <Image> ),
  17061. * lightMapIntensity: <float>
  17062. *
  17063. * aoMap: new THREE.Texture( <Image> ),
  17064. * aoMapIntensity: <float>
  17065. *
  17066. * emissive: <hex>,
  17067. * emissiveIntensity: <float>
  17068. * emissiveMap: new THREE.Texture( <Image> ),
  17069. *
  17070. * bumpMap: new THREE.Texture( <Image> ),
  17071. * bumpScale: <float>,
  17072. *
  17073. * normalMap: new THREE.Texture( <Image> ),
  17074. * normalScale: <Vector2>,
  17075. *
  17076. * displacementMap: new THREE.Texture( <Image> ),
  17077. * displacementScale: <float>,
  17078. * displacementBias: <float>,
  17079. *
  17080. * roughnessMap: new THREE.Texture( <Image> ),
  17081. *
  17082. * metalnessMap: new THREE.Texture( <Image> ),
  17083. *
  17084. * alphaMap: new THREE.Texture( <Image> ),
  17085. *
  17086. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  17087. * envMapIntensity: <float>
  17088. *
  17089. * refractionRatio: <float>,
  17090. *
  17091. * wireframe: <boolean>,
  17092. * wireframeLinewidth: <float>,
  17093. *
  17094. * skinning: <bool>,
  17095. * morphTargets: <bool>,
  17096. * morphNormals: <bool>
  17097. * }
  17098. */
  17099. function MeshStandardMaterial( parameters ) {
  17100. Material.call( this );
  17101. this.defines = { 'STANDARD': '' };
  17102. this.type = 'MeshStandardMaterial';
  17103. this.color = new Color( 0xffffff ); // diffuse
  17104. this.roughness = 0.5;
  17105. this.metalness = 0.5;
  17106. this.map = null;
  17107. this.lightMap = null;
  17108. this.lightMapIntensity = 1.0;
  17109. this.aoMap = null;
  17110. this.aoMapIntensity = 1.0;
  17111. this.emissive = new Color( 0x000000 );
  17112. this.emissiveIntensity = 1.0;
  17113. this.emissiveMap = null;
  17114. this.bumpMap = null;
  17115. this.bumpScale = 1;
  17116. this.normalMap = null;
  17117. this.normalScale = new Vector2( 1, 1 );
  17118. this.displacementMap = null;
  17119. this.displacementScale = 1;
  17120. this.displacementBias = 0;
  17121. this.roughnessMap = null;
  17122. this.metalnessMap = null;
  17123. this.alphaMap = null;
  17124. this.envMap = null;
  17125. this.envMapIntensity = 1.0;
  17126. this.refractionRatio = 0.98;
  17127. this.wireframe = false;
  17128. this.wireframeLinewidth = 1;
  17129. this.wireframeLinecap = 'round';
  17130. this.wireframeLinejoin = 'round';
  17131. this.skinning = false;
  17132. this.morphTargets = false;
  17133. this.morphNormals = false;
  17134. this.setValues( parameters );
  17135. }
  17136. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  17137. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  17138. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  17139. MeshStandardMaterial.prototype.copy = function ( source ) {
  17140. Material.prototype.copy.call( this, source );
  17141. this.defines = { 'STANDARD': '' };
  17142. this.color.copy( source.color );
  17143. this.roughness = source.roughness;
  17144. this.metalness = source.metalness;
  17145. this.map = source.map;
  17146. this.lightMap = source.lightMap;
  17147. this.lightMapIntensity = source.lightMapIntensity;
  17148. this.aoMap = source.aoMap;
  17149. this.aoMapIntensity = source.aoMapIntensity;
  17150. this.emissive.copy( source.emissive );
  17151. this.emissiveMap = source.emissiveMap;
  17152. this.emissiveIntensity = source.emissiveIntensity;
  17153. this.bumpMap = source.bumpMap;
  17154. this.bumpScale = source.bumpScale;
  17155. this.normalMap = source.normalMap;
  17156. this.normalScale.copy( source.normalScale );
  17157. this.displacementMap = source.displacementMap;
  17158. this.displacementScale = source.displacementScale;
  17159. this.displacementBias = source.displacementBias;
  17160. this.roughnessMap = source.roughnessMap;
  17161. this.metalnessMap = source.metalnessMap;
  17162. this.alphaMap = source.alphaMap;
  17163. this.envMap = source.envMap;
  17164. this.envMapIntensity = source.envMapIntensity;
  17165. this.refractionRatio = source.refractionRatio;
  17166. this.wireframe = source.wireframe;
  17167. this.wireframeLinewidth = source.wireframeLinewidth;
  17168. this.wireframeLinecap = source.wireframeLinecap;
  17169. this.wireframeLinejoin = source.wireframeLinejoin;
  17170. this.skinning = source.skinning;
  17171. this.morphTargets = source.morphTargets;
  17172. this.morphNormals = source.morphNormals;
  17173. return this;
  17174. };
  17175. /**
  17176. * @author WestLangley / http://github.com/WestLangley
  17177. *
  17178. * parameters = {
  17179. * reflectivity: <float>
  17180. * }
  17181. */
  17182. function MeshPhysicalMaterial( parameters ) {
  17183. MeshStandardMaterial.call( this );
  17184. this.defines = { 'PHYSICAL': '' };
  17185. this.type = 'MeshPhysicalMaterial';
  17186. this.reflectivity = 0.5; // maps to F0 = 0.04
  17187. this.clearCoat = 0.0;
  17188. this.clearCoatRoughness = 0.0;
  17189. this.setValues( parameters );
  17190. }
  17191. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17192. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17193. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17194. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17195. MeshStandardMaterial.prototype.copy.call( this, source );
  17196. this.defines = { 'PHYSICAL': '' };
  17197. this.reflectivity = source.reflectivity;
  17198. this.clearCoat = source.clearCoat;
  17199. this.clearCoatRoughness = source.clearCoatRoughness;
  17200. return this;
  17201. };
  17202. /**
  17203. * @author mrdoob / http://mrdoob.com/
  17204. * @author alteredq / http://alteredqualia.com/
  17205. *
  17206. * parameters = {
  17207. * color: <hex>,
  17208. * specular: <hex>,
  17209. * shininess: <float>,
  17210. * opacity: <float>,
  17211. *
  17212. * map: new THREE.Texture( <Image> ),
  17213. *
  17214. * lightMap: new THREE.Texture( <Image> ),
  17215. * lightMapIntensity: <float>
  17216. *
  17217. * aoMap: new THREE.Texture( <Image> ),
  17218. * aoMapIntensity: <float>
  17219. *
  17220. * emissive: <hex>,
  17221. * emissiveIntensity: <float>
  17222. * emissiveMap: new THREE.Texture( <Image> ),
  17223. *
  17224. * bumpMap: new THREE.Texture( <Image> ),
  17225. * bumpScale: <float>,
  17226. *
  17227. * normalMap: new THREE.Texture( <Image> ),
  17228. * normalScale: <Vector2>,
  17229. *
  17230. * displacementMap: new THREE.Texture( <Image> ),
  17231. * displacementScale: <float>,
  17232. * displacementBias: <float>,
  17233. *
  17234. * specularMap: new THREE.Texture( <Image> ),
  17235. *
  17236. * alphaMap: new THREE.Texture( <Image> ),
  17237. *
  17238. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17239. * combine: THREE.Multiply,
  17240. * reflectivity: <float>,
  17241. * refractionRatio: <float>,
  17242. *
  17243. * wireframe: <boolean>,
  17244. * wireframeLinewidth: <float>,
  17245. *
  17246. * skinning: <bool>,
  17247. * morphTargets: <bool>,
  17248. * morphNormals: <bool>
  17249. * }
  17250. */
  17251. function MeshPhongMaterial( parameters ) {
  17252. Material.call( this );
  17253. this.type = 'MeshPhongMaterial';
  17254. this.color = new Color( 0xffffff ); // diffuse
  17255. this.specular = new Color( 0x111111 );
  17256. this.shininess = 30;
  17257. this.map = null;
  17258. this.lightMap = null;
  17259. this.lightMapIntensity = 1.0;
  17260. this.aoMap = null;
  17261. this.aoMapIntensity = 1.0;
  17262. this.emissive = new Color( 0x000000 );
  17263. this.emissiveIntensity = 1.0;
  17264. this.emissiveMap = null;
  17265. this.bumpMap = null;
  17266. this.bumpScale = 1;
  17267. this.normalMap = null;
  17268. this.normalScale = new Vector2( 1, 1 );
  17269. this.displacementMap = null;
  17270. this.displacementScale = 1;
  17271. this.displacementBias = 0;
  17272. this.specularMap = null;
  17273. this.alphaMap = null;
  17274. this.envMap = null;
  17275. this.combine = MultiplyOperation;
  17276. this.reflectivity = 1;
  17277. this.refractionRatio = 0.98;
  17278. this.wireframe = false;
  17279. this.wireframeLinewidth = 1;
  17280. this.wireframeLinecap = 'round';
  17281. this.wireframeLinejoin = 'round';
  17282. this.skinning = false;
  17283. this.morphTargets = false;
  17284. this.morphNormals = false;
  17285. this.setValues( parameters );
  17286. }
  17287. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17288. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17289. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17290. MeshPhongMaterial.prototype.copy = function ( source ) {
  17291. Material.prototype.copy.call( this, source );
  17292. this.color.copy( source.color );
  17293. this.specular.copy( source.specular );
  17294. this.shininess = source.shininess;
  17295. this.map = source.map;
  17296. this.lightMap = source.lightMap;
  17297. this.lightMapIntensity = source.lightMapIntensity;
  17298. this.aoMap = source.aoMap;
  17299. this.aoMapIntensity = source.aoMapIntensity;
  17300. this.emissive.copy( source.emissive );
  17301. this.emissiveMap = source.emissiveMap;
  17302. this.emissiveIntensity = source.emissiveIntensity;
  17303. this.bumpMap = source.bumpMap;
  17304. this.bumpScale = source.bumpScale;
  17305. this.normalMap = source.normalMap;
  17306. this.normalScale.copy( source.normalScale );
  17307. this.displacementMap = source.displacementMap;
  17308. this.displacementScale = source.displacementScale;
  17309. this.displacementBias = source.displacementBias;
  17310. this.specularMap = source.specularMap;
  17311. this.alphaMap = source.alphaMap;
  17312. this.envMap = source.envMap;
  17313. this.combine = source.combine;
  17314. this.reflectivity = source.reflectivity;
  17315. this.refractionRatio = source.refractionRatio;
  17316. this.wireframe = source.wireframe;
  17317. this.wireframeLinewidth = source.wireframeLinewidth;
  17318. this.wireframeLinecap = source.wireframeLinecap;
  17319. this.wireframeLinejoin = source.wireframeLinejoin;
  17320. this.skinning = source.skinning;
  17321. this.morphTargets = source.morphTargets;
  17322. this.morphNormals = source.morphNormals;
  17323. return this;
  17324. };
  17325. /**
  17326. * @author takahirox / http://github.com/takahirox
  17327. *
  17328. * parameters = {
  17329. * gradientMap: new THREE.Texture( <Image> )
  17330. * }
  17331. */
  17332. function MeshToonMaterial( parameters ) {
  17333. MeshPhongMaterial.call( this );
  17334. this.defines = { 'TOON': '' };
  17335. this.type = 'MeshToonMaterial';
  17336. this.gradientMap = null;
  17337. this.setValues( parameters );
  17338. }
  17339. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17340. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17341. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17342. MeshToonMaterial.prototype.copy = function ( source ) {
  17343. MeshPhongMaterial.prototype.copy.call( this, source );
  17344. this.gradientMap = source.gradientMap;
  17345. return this;
  17346. };
  17347. /**
  17348. * @author mrdoob / http://mrdoob.com/
  17349. * @author WestLangley / http://github.com/WestLangley
  17350. *
  17351. * parameters = {
  17352. * opacity: <float>,
  17353. *
  17354. * bumpMap: new THREE.Texture( <Image> ),
  17355. * bumpScale: <float>,
  17356. *
  17357. * normalMap: new THREE.Texture( <Image> ),
  17358. * normalScale: <Vector2>,
  17359. *
  17360. * displacementMap: new THREE.Texture( <Image> ),
  17361. * displacementScale: <float>,
  17362. * displacementBias: <float>,
  17363. *
  17364. * wireframe: <boolean>,
  17365. * wireframeLinewidth: <float>
  17366. *
  17367. * skinning: <bool>,
  17368. * morphTargets: <bool>,
  17369. * morphNormals: <bool>
  17370. * }
  17371. */
  17372. function MeshNormalMaterial( parameters ) {
  17373. Material.call( this, parameters );
  17374. this.type = 'MeshNormalMaterial';
  17375. this.bumpMap = null;
  17376. this.bumpScale = 1;
  17377. this.normalMap = null;
  17378. this.normalScale = new Vector2( 1, 1 );
  17379. this.displacementMap = null;
  17380. this.displacementScale = 1;
  17381. this.displacementBias = 0;
  17382. this.wireframe = false;
  17383. this.wireframeLinewidth = 1;
  17384. this.fog = false;
  17385. this.lights = false;
  17386. this.skinning = false;
  17387. this.morphTargets = false;
  17388. this.morphNormals = false;
  17389. this.setValues( parameters );
  17390. }
  17391. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17392. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17393. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17394. MeshNormalMaterial.prototype.copy = function ( source ) {
  17395. Material.prototype.copy.call( this, source );
  17396. this.bumpMap = source.bumpMap;
  17397. this.bumpScale = source.bumpScale;
  17398. this.normalMap = source.normalMap;
  17399. this.normalScale.copy( source.normalScale );
  17400. this.displacementMap = source.displacementMap;
  17401. this.displacementScale = source.displacementScale;
  17402. this.displacementBias = source.displacementBias;
  17403. this.wireframe = source.wireframe;
  17404. this.wireframeLinewidth = source.wireframeLinewidth;
  17405. this.skinning = source.skinning;
  17406. this.morphTargets = source.morphTargets;
  17407. this.morphNormals = source.morphNormals;
  17408. return this;
  17409. };
  17410. /**
  17411. * @author mrdoob / http://mrdoob.com/
  17412. * @author alteredq / http://alteredqualia.com/
  17413. *
  17414. * parameters = {
  17415. * color: <hex>,
  17416. * opacity: <float>,
  17417. *
  17418. * map: new THREE.Texture( <Image> ),
  17419. *
  17420. * lightMap: new THREE.Texture( <Image> ),
  17421. * lightMapIntensity: <float>
  17422. *
  17423. * aoMap: new THREE.Texture( <Image> ),
  17424. * aoMapIntensity: <float>
  17425. *
  17426. * emissive: <hex>,
  17427. * emissiveIntensity: <float>
  17428. * emissiveMap: new THREE.Texture( <Image> ),
  17429. *
  17430. * specularMap: new THREE.Texture( <Image> ),
  17431. *
  17432. * alphaMap: new THREE.Texture( <Image> ),
  17433. *
  17434. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17435. * combine: THREE.Multiply,
  17436. * reflectivity: <float>,
  17437. * refractionRatio: <float>,
  17438. *
  17439. * wireframe: <boolean>,
  17440. * wireframeLinewidth: <float>,
  17441. *
  17442. * skinning: <bool>,
  17443. * morphTargets: <bool>,
  17444. * morphNormals: <bool>
  17445. * }
  17446. */
  17447. function MeshLambertMaterial( parameters ) {
  17448. Material.call( this );
  17449. this.type = 'MeshLambertMaterial';
  17450. this.color = new Color( 0xffffff ); // diffuse
  17451. this.map = null;
  17452. this.lightMap = null;
  17453. this.lightMapIntensity = 1.0;
  17454. this.aoMap = null;
  17455. this.aoMapIntensity = 1.0;
  17456. this.emissive = new Color( 0x000000 );
  17457. this.emissiveIntensity = 1.0;
  17458. this.emissiveMap = null;
  17459. this.specularMap = null;
  17460. this.alphaMap = null;
  17461. this.envMap = null;
  17462. this.combine = MultiplyOperation;
  17463. this.reflectivity = 1;
  17464. this.refractionRatio = 0.98;
  17465. this.wireframe = false;
  17466. this.wireframeLinewidth = 1;
  17467. this.wireframeLinecap = 'round';
  17468. this.wireframeLinejoin = 'round';
  17469. this.skinning = false;
  17470. this.morphTargets = false;
  17471. this.morphNormals = false;
  17472. this.setValues( parameters );
  17473. }
  17474. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17475. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17476. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17477. MeshLambertMaterial.prototype.copy = function ( source ) {
  17478. Material.prototype.copy.call( this, source );
  17479. this.color.copy( source.color );
  17480. this.map = source.map;
  17481. this.lightMap = source.lightMap;
  17482. this.lightMapIntensity = source.lightMapIntensity;
  17483. this.aoMap = source.aoMap;
  17484. this.aoMapIntensity = source.aoMapIntensity;
  17485. this.emissive.copy( source.emissive );
  17486. this.emissiveMap = source.emissiveMap;
  17487. this.emissiveIntensity = source.emissiveIntensity;
  17488. this.specularMap = source.specularMap;
  17489. this.alphaMap = source.alphaMap;
  17490. this.envMap = source.envMap;
  17491. this.combine = source.combine;
  17492. this.reflectivity = source.reflectivity;
  17493. this.refractionRatio = source.refractionRatio;
  17494. this.wireframe = source.wireframe;
  17495. this.wireframeLinewidth = source.wireframeLinewidth;
  17496. this.wireframeLinecap = source.wireframeLinecap;
  17497. this.wireframeLinejoin = source.wireframeLinejoin;
  17498. this.skinning = source.skinning;
  17499. this.morphTargets = source.morphTargets;
  17500. this.morphNormals = source.morphNormals;
  17501. return this;
  17502. };
  17503. /**
  17504. * @author alteredq / http://alteredqualia.com/
  17505. *
  17506. * parameters = {
  17507. * color: <hex>,
  17508. * opacity: <float>,
  17509. *
  17510. * linewidth: <float>,
  17511. *
  17512. * scale: <float>,
  17513. * dashSize: <float>,
  17514. * gapSize: <float>
  17515. * }
  17516. */
  17517. function LineDashedMaterial( parameters ) {
  17518. Material.call( this );
  17519. this.type = 'LineDashedMaterial';
  17520. this.color = new Color( 0xffffff );
  17521. this.linewidth = 1;
  17522. this.scale = 1;
  17523. this.dashSize = 3;
  17524. this.gapSize = 1;
  17525. this.lights = false;
  17526. this.setValues( parameters );
  17527. }
  17528. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17529. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17530. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17531. LineDashedMaterial.prototype.copy = function ( source ) {
  17532. Material.prototype.copy.call( this, source );
  17533. this.color.copy( source.color );
  17534. this.linewidth = source.linewidth;
  17535. this.scale = source.scale;
  17536. this.dashSize = source.dashSize;
  17537. this.gapSize = source.gapSize;
  17538. return this;
  17539. };
  17540. var Materials = Object.freeze({
  17541. ShadowMaterial: ShadowMaterial,
  17542. SpriteMaterial: SpriteMaterial,
  17543. RawShaderMaterial: RawShaderMaterial,
  17544. ShaderMaterial: ShaderMaterial,
  17545. PointsMaterial: PointsMaterial,
  17546. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17547. MeshStandardMaterial: MeshStandardMaterial,
  17548. MeshPhongMaterial: MeshPhongMaterial,
  17549. MeshToonMaterial: MeshToonMaterial,
  17550. MeshNormalMaterial: MeshNormalMaterial,
  17551. MeshLambertMaterial: MeshLambertMaterial,
  17552. MeshDepthMaterial: MeshDepthMaterial,
  17553. MeshBasicMaterial: MeshBasicMaterial,
  17554. LineDashedMaterial: LineDashedMaterial,
  17555. LineBasicMaterial: LineBasicMaterial,
  17556. Material: Material
  17557. });
  17558. /**
  17559. * @author mrdoob / http://mrdoob.com/
  17560. */
  17561. var Cache = {
  17562. enabled: false,
  17563. files: {},
  17564. add: function ( key, file ) {
  17565. if ( this.enabled === false ) return;
  17566. // console.log( 'THREE.Cache', 'Adding key:', key );
  17567. this.files[ key ] = file;
  17568. },
  17569. get: function ( key ) {
  17570. if ( this.enabled === false ) return;
  17571. // console.log( 'THREE.Cache', 'Checking key:', key );
  17572. return this.files[ key ];
  17573. },
  17574. remove: function ( key ) {
  17575. delete this.files[ key ];
  17576. },
  17577. clear: function () {
  17578. this.files = {};
  17579. }
  17580. };
  17581. /**
  17582. * @author mrdoob / http://mrdoob.com/
  17583. */
  17584. function LoadingManager( onLoad, onProgress, onError ) {
  17585. var scope = this;
  17586. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17587. this.onStart = undefined;
  17588. this.onLoad = onLoad;
  17589. this.onProgress = onProgress;
  17590. this.onError = onError;
  17591. this.itemStart = function ( url ) {
  17592. itemsTotal ++;
  17593. if ( isLoading === false ) {
  17594. if ( scope.onStart !== undefined ) {
  17595. scope.onStart( url, itemsLoaded, itemsTotal );
  17596. }
  17597. }
  17598. isLoading = true;
  17599. };
  17600. this.itemEnd = function ( url ) {
  17601. itemsLoaded ++;
  17602. if ( scope.onProgress !== undefined ) {
  17603. scope.onProgress( url, itemsLoaded, itemsTotal );
  17604. }
  17605. if ( itemsLoaded === itemsTotal ) {
  17606. isLoading = false;
  17607. if ( scope.onLoad !== undefined ) {
  17608. scope.onLoad();
  17609. }
  17610. }
  17611. };
  17612. this.itemError = function ( url ) {
  17613. if ( scope.onError !== undefined ) {
  17614. scope.onError( url );
  17615. }
  17616. };
  17617. }
  17618. var DefaultLoadingManager = new LoadingManager();
  17619. /**
  17620. * @author mrdoob / http://mrdoob.com/
  17621. */
  17622. function FileLoader( manager ) {
  17623. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17624. }
  17625. Object.assign( FileLoader.prototype, {
  17626. load: function ( url, onLoad, onProgress, onError ) {
  17627. if ( url === undefined ) url = '';
  17628. if ( this.path !== undefined ) url = this.path + url;
  17629. var scope = this;
  17630. var cached = Cache.get( url );
  17631. if ( cached !== undefined ) {
  17632. scope.manager.itemStart( url );
  17633. setTimeout( function () {
  17634. if ( onLoad ) onLoad( cached );
  17635. scope.manager.itemEnd( url );
  17636. }, 0 );
  17637. return cached;
  17638. }
  17639. // Check for data: URI
  17640. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17641. var dataUriRegexResult = url.match( dataUriRegex );
  17642. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17643. if ( dataUriRegexResult ) {
  17644. var mimeType = dataUriRegexResult[ 1 ];
  17645. var isBase64 = !! dataUriRegexResult[ 2 ];
  17646. var data = dataUriRegexResult[ 3 ];
  17647. data = window.decodeURIComponent( data );
  17648. if ( isBase64 ) data = window.atob( data );
  17649. try {
  17650. var response;
  17651. var responseType = ( this.responseType || '' ).toLowerCase();
  17652. switch ( responseType ) {
  17653. case 'arraybuffer':
  17654. case 'blob':
  17655. response = new ArrayBuffer( data.length );
  17656. var view = new Uint8Array( response );
  17657. for ( var i = 0; i < data.length; i ++ ) {
  17658. view[ i ] = data.charCodeAt( i );
  17659. }
  17660. if ( responseType === 'blob' ) {
  17661. response = new Blob( [ response ], { type: mimeType } );
  17662. }
  17663. break;
  17664. case 'document':
  17665. var parser = new DOMParser();
  17666. response = parser.parseFromString( data, mimeType );
  17667. break;
  17668. case 'json':
  17669. response = JSON.parse( data );
  17670. break;
  17671. default: // 'text' or other
  17672. response = data;
  17673. break;
  17674. }
  17675. // Wait for next browser tick
  17676. window.setTimeout( function () {
  17677. if ( onLoad ) onLoad( response );
  17678. scope.manager.itemEnd( url );
  17679. }, 0 );
  17680. } catch ( error ) {
  17681. // Wait for next browser tick
  17682. window.setTimeout( function () {
  17683. if ( onError ) onError( error );
  17684. scope.manager.itemEnd( url );
  17685. scope.manager.itemError( url );
  17686. }, 0 );
  17687. }
  17688. } else {
  17689. var request = new XMLHttpRequest();
  17690. request.open( 'GET', url, true );
  17691. request.addEventListener( 'load', function ( event ) {
  17692. var response = event.target.response;
  17693. Cache.add( url, response );
  17694. if ( this.status === 200 ) {
  17695. if ( onLoad ) onLoad( response );
  17696. scope.manager.itemEnd( url );
  17697. } else if ( this.status === 0 ) {
  17698. // Some browsers return HTTP Status 0 when using non-http protocol
  17699. // e.g. 'file://' or 'data://'. Handle as success.
  17700. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17701. if ( onLoad ) onLoad( response );
  17702. scope.manager.itemEnd( url );
  17703. } else {
  17704. if ( onError ) onError( event );
  17705. scope.manager.itemEnd( url );
  17706. scope.manager.itemError( url );
  17707. }
  17708. }, false );
  17709. if ( onProgress !== undefined ) {
  17710. request.addEventListener( 'progress', function ( event ) {
  17711. onProgress( event );
  17712. }, false );
  17713. }
  17714. request.addEventListener( 'error', function ( event ) {
  17715. if ( onError ) onError( event );
  17716. scope.manager.itemEnd( url );
  17717. scope.manager.itemError( url );
  17718. }, false );
  17719. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17720. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17721. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17722. for ( var header in this.requestHeader ) {
  17723. request.setRequestHeader( header, this.requestHeader[ header ] );
  17724. }
  17725. request.send( null );
  17726. }
  17727. scope.manager.itemStart( url );
  17728. return request;
  17729. },
  17730. setPath: function ( value ) {
  17731. this.path = value;
  17732. return this;
  17733. },
  17734. setResponseType: function ( value ) {
  17735. this.responseType = value;
  17736. return this;
  17737. },
  17738. setWithCredentials: function ( value ) {
  17739. this.withCredentials = value;
  17740. return this;
  17741. },
  17742. setMimeType: function ( value ) {
  17743. this.mimeType = value;
  17744. return this;
  17745. },
  17746. setRequestHeader: function ( value ) {
  17747. this.requestHeader = value;
  17748. return this;
  17749. }
  17750. } );
  17751. /**
  17752. * @author mrdoob / http://mrdoob.com/
  17753. *
  17754. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17755. */
  17756. function CompressedTextureLoader( manager ) {
  17757. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17758. // override in sub classes
  17759. this._parser = null;
  17760. }
  17761. Object.assign( CompressedTextureLoader.prototype, {
  17762. load: function ( url, onLoad, onProgress, onError ) {
  17763. var scope = this;
  17764. var images = [];
  17765. var texture = new CompressedTexture();
  17766. texture.image = images;
  17767. var loader = new FileLoader( this.manager );
  17768. loader.setPath( this.path );
  17769. loader.setResponseType( 'arraybuffer' );
  17770. function loadTexture( i ) {
  17771. loader.load( url[ i ], function ( buffer ) {
  17772. var texDatas = scope._parser( buffer, true );
  17773. images[ i ] = {
  17774. width: texDatas.width,
  17775. height: texDatas.height,
  17776. format: texDatas.format,
  17777. mipmaps: texDatas.mipmaps
  17778. };
  17779. loaded += 1;
  17780. if ( loaded === 6 ) {
  17781. if ( texDatas.mipmapCount === 1 )
  17782. texture.minFilter = LinearFilter;
  17783. texture.format = texDatas.format;
  17784. texture.needsUpdate = true;
  17785. if ( onLoad ) onLoad( texture );
  17786. }
  17787. }, onProgress, onError );
  17788. }
  17789. if ( Array.isArray( url ) ) {
  17790. var loaded = 0;
  17791. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17792. loadTexture( i );
  17793. }
  17794. } else {
  17795. // compressed cubemap texture stored in a single DDS file
  17796. loader.load( url, function ( buffer ) {
  17797. var texDatas = scope._parser( buffer, true );
  17798. if ( texDatas.isCubemap ) {
  17799. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17800. for ( var f = 0; f < faces; f ++ ) {
  17801. images[ f ] = { mipmaps : [] };
  17802. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17803. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17804. images[ f ].format = texDatas.format;
  17805. images[ f ].width = texDatas.width;
  17806. images[ f ].height = texDatas.height;
  17807. }
  17808. }
  17809. } else {
  17810. texture.image.width = texDatas.width;
  17811. texture.image.height = texDatas.height;
  17812. texture.mipmaps = texDatas.mipmaps;
  17813. }
  17814. if ( texDatas.mipmapCount === 1 ) {
  17815. texture.minFilter = LinearFilter;
  17816. }
  17817. texture.format = texDatas.format;
  17818. texture.needsUpdate = true;
  17819. if ( onLoad ) onLoad( texture );
  17820. }, onProgress, onError );
  17821. }
  17822. return texture;
  17823. },
  17824. setPath: function ( value ) {
  17825. this.path = value;
  17826. return this;
  17827. }
  17828. } );
  17829. /**
  17830. * @author Nikos M. / https://github.com/foo123/
  17831. *
  17832. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17833. */
  17834. function DataTextureLoader( manager ) {
  17835. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17836. // override in sub classes
  17837. this._parser = null;
  17838. }
  17839. Object.assign( DataTextureLoader.prototype, {
  17840. load: function ( url, onLoad, onProgress, onError ) {
  17841. var scope = this;
  17842. var texture = new DataTexture();
  17843. var loader = new FileLoader( this.manager );
  17844. loader.setResponseType( 'arraybuffer' );
  17845. loader.load( url, function ( buffer ) {
  17846. var texData = scope._parser( buffer );
  17847. if ( ! texData ) return;
  17848. if ( undefined !== texData.image ) {
  17849. texture.image = texData.image;
  17850. } else if ( undefined !== texData.data ) {
  17851. texture.image.width = texData.width;
  17852. texture.image.height = texData.height;
  17853. texture.image.data = texData.data;
  17854. }
  17855. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17856. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17857. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17858. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17859. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17860. if ( undefined !== texData.format ) {
  17861. texture.format = texData.format;
  17862. }
  17863. if ( undefined !== texData.type ) {
  17864. texture.type = texData.type;
  17865. }
  17866. if ( undefined !== texData.mipmaps ) {
  17867. texture.mipmaps = texData.mipmaps;
  17868. }
  17869. if ( 1 === texData.mipmapCount ) {
  17870. texture.minFilter = LinearFilter;
  17871. }
  17872. texture.needsUpdate = true;
  17873. if ( onLoad ) onLoad( texture, texData );
  17874. }, onProgress, onError );
  17875. return texture;
  17876. }
  17877. } );
  17878. /**
  17879. * @author mrdoob / http://mrdoob.com/
  17880. */
  17881. function ImageLoader( manager ) {
  17882. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17883. }
  17884. Object.assign( ImageLoader.prototype, {
  17885. load: function ( url, onLoad, onProgress, onError ) {
  17886. if ( url === undefined ) url = '';
  17887. if ( this.path !== undefined ) url = this.path + url;
  17888. var scope = this;
  17889. var cached = Cache.get( url );
  17890. if ( cached !== undefined ) {
  17891. scope.manager.itemStart( url );
  17892. setTimeout( function () {
  17893. if ( onLoad ) onLoad( cached );
  17894. scope.manager.itemEnd( url );
  17895. }, 0 );
  17896. return cached;
  17897. }
  17898. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17899. image.addEventListener( 'load', function () {
  17900. Cache.add( url, this );
  17901. if ( onLoad ) onLoad( this );
  17902. scope.manager.itemEnd( url );
  17903. }, false );
  17904. /*
  17905. image.addEventListener( 'progress', function ( event ) {
  17906. if ( onProgress ) onProgress( event );
  17907. }, false );
  17908. */
  17909. image.addEventListener( 'error', function ( event ) {
  17910. if ( onError ) onError( event );
  17911. scope.manager.itemEnd( url );
  17912. scope.manager.itemError( url );
  17913. }, false );
  17914. if ( url.substr( 0, 5 ) !== 'data:' ) {
  17915. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  17916. }
  17917. scope.manager.itemStart( url );
  17918. image.src = url;
  17919. return image;
  17920. },
  17921. setCrossOrigin: function ( value ) {
  17922. this.crossOrigin = value;
  17923. return this;
  17924. },
  17925. setPath: function ( value ) {
  17926. this.path = value;
  17927. return this;
  17928. }
  17929. } );
  17930. /**
  17931. * @author mrdoob / http://mrdoob.com/
  17932. */
  17933. function CubeTextureLoader( manager ) {
  17934. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17935. }
  17936. Object.assign( CubeTextureLoader.prototype, {
  17937. load: function ( urls, onLoad, onProgress, onError ) {
  17938. var texture = new CubeTexture();
  17939. var loader = new ImageLoader( this.manager );
  17940. loader.setCrossOrigin( this.crossOrigin );
  17941. loader.setPath( this.path );
  17942. var loaded = 0;
  17943. function loadTexture( i ) {
  17944. loader.load( urls[ i ], function ( image ) {
  17945. texture.images[ i ] = image;
  17946. loaded ++;
  17947. if ( loaded === 6 ) {
  17948. texture.needsUpdate = true;
  17949. if ( onLoad ) onLoad( texture );
  17950. }
  17951. }, undefined, onError );
  17952. }
  17953. for ( var i = 0; i < urls.length; ++ i ) {
  17954. loadTexture( i );
  17955. }
  17956. return texture;
  17957. },
  17958. setCrossOrigin: function ( value ) {
  17959. this.crossOrigin = value;
  17960. return this;
  17961. },
  17962. setPath: function ( value ) {
  17963. this.path = value;
  17964. return this;
  17965. }
  17966. } );
  17967. /**
  17968. * @author mrdoob / http://mrdoob.com/
  17969. */
  17970. function TextureLoader( manager ) {
  17971. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17972. }
  17973. Object.assign( TextureLoader.prototype, {
  17974. load: function ( url, onLoad, onProgress, onError ) {
  17975. var loader = new ImageLoader( this.manager );
  17976. loader.setCrossOrigin( this.crossOrigin );
  17977. loader.setPath( this.path );
  17978. var texture = new Texture();
  17979. texture.image = loader.load( url, function () {
  17980. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  17981. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  17982. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  17983. texture.needsUpdate = true;
  17984. if ( onLoad !== undefined ) {
  17985. onLoad( texture );
  17986. }
  17987. }, onProgress, onError );
  17988. return texture;
  17989. },
  17990. setCrossOrigin: function ( value ) {
  17991. this.crossOrigin = value;
  17992. return this;
  17993. },
  17994. setPath: function ( value ) {
  17995. this.path = value;
  17996. return this;
  17997. }
  17998. } );
  17999. /**
  18000. * @author mrdoob / http://mrdoob.com/
  18001. * @author alteredq / http://alteredqualia.com/
  18002. */
  18003. function Light( color, intensity ) {
  18004. Object3D.call( this );
  18005. this.type = 'Light';
  18006. this.color = new Color( color );
  18007. this.intensity = intensity !== undefined ? intensity : 1;
  18008. this.receiveShadow = undefined;
  18009. }
  18010. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18011. constructor: Light,
  18012. isLight: true,
  18013. copy: function ( source ) {
  18014. Object3D.prototype.copy.call( this, source );
  18015. this.color.copy( source.color );
  18016. this.intensity = source.intensity;
  18017. return this;
  18018. },
  18019. toJSON: function ( meta ) {
  18020. var data = Object3D.prototype.toJSON.call( this, meta );
  18021. data.object.color = this.color.getHex();
  18022. data.object.intensity = this.intensity;
  18023. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18024. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18025. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18026. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18027. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18028. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18029. return data;
  18030. }
  18031. } );
  18032. /**
  18033. * @author alteredq / http://alteredqualia.com/
  18034. */
  18035. function HemisphereLight( skyColor, groundColor, intensity ) {
  18036. Light.call( this, skyColor, intensity );
  18037. this.type = 'HemisphereLight';
  18038. this.castShadow = undefined;
  18039. this.position.copy( Object3D.DefaultUp );
  18040. this.updateMatrix();
  18041. this.groundColor = new Color( groundColor );
  18042. }
  18043. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18044. constructor: HemisphereLight,
  18045. isHemisphereLight: true,
  18046. copy: function ( source ) {
  18047. Light.prototype.copy.call( this, source );
  18048. this.groundColor.copy( source.groundColor );
  18049. return this;
  18050. }
  18051. } );
  18052. /**
  18053. * @author mrdoob / http://mrdoob.com/
  18054. */
  18055. function LightShadow( camera ) {
  18056. this.camera = camera;
  18057. this.bias = 0;
  18058. this.radius = 1;
  18059. this.mapSize = new Vector2( 512, 512 );
  18060. this.map = null;
  18061. this.matrix = new Matrix4();
  18062. }
  18063. Object.assign( LightShadow.prototype, {
  18064. copy: function ( source ) {
  18065. this.camera = source.camera.clone();
  18066. this.bias = source.bias;
  18067. this.radius = source.radius;
  18068. this.mapSize.copy( source.mapSize );
  18069. return this;
  18070. },
  18071. clone: function () {
  18072. return new this.constructor().copy( this );
  18073. },
  18074. toJSON: function () {
  18075. var object = {};
  18076. if ( this.bias !== 0 ) object.bias = this.bias;
  18077. if ( this.radius !== 1 ) object.radius = this.radius;
  18078. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18079. object.camera = this.camera.toJSON( false ).object;
  18080. delete object.camera.matrix;
  18081. return object;
  18082. }
  18083. } );
  18084. /**
  18085. * @author mrdoob / http://mrdoob.com/
  18086. */
  18087. function SpotLightShadow() {
  18088. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18089. }
  18090. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18091. constructor: SpotLightShadow,
  18092. isSpotLightShadow: true,
  18093. update: function ( light ) {
  18094. var camera = this.camera;
  18095. var fov = _Math.RAD2DEG * 2 * light.angle;
  18096. var aspect = this.mapSize.width / this.mapSize.height;
  18097. var far = light.distance || camera.far;
  18098. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18099. camera.fov = fov;
  18100. camera.aspect = aspect;
  18101. camera.far = far;
  18102. camera.updateProjectionMatrix();
  18103. }
  18104. }
  18105. } );
  18106. /**
  18107. * @author alteredq / http://alteredqualia.com/
  18108. */
  18109. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  18110. Light.call( this, color, intensity );
  18111. this.type = 'SpotLight';
  18112. this.position.copy( Object3D.DefaultUp );
  18113. this.updateMatrix();
  18114. this.target = new Object3D();
  18115. Object.defineProperty( this, 'power', {
  18116. get: function () {
  18117. // intensity = power per solid angle.
  18118. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18119. return this.intensity * Math.PI;
  18120. },
  18121. set: function ( power ) {
  18122. // intensity = power per solid angle.
  18123. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18124. this.intensity = power / Math.PI;
  18125. }
  18126. } );
  18127. this.distance = ( distance !== undefined ) ? distance : 0;
  18128. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  18129. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  18130. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18131. this.shadow = new SpotLightShadow();
  18132. }
  18133. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18134. constructor: SpotLight,
  18135. isSpotLight: true,
  18136. copy: function ( source ) {
  18137. Light.prototype.copy.call( this, source );
  18138. this.distance = source.distance;
  18139. this.angle = source.angle;
  18140. this.penumbra = source.penumbra;
  18141. this.decay = source.decay;
  18142. this.target = source.target.clone();
  18143. this.shadow = source.shadow.clone();
  18144. return this;
  18145. }
  18146. } );
  18147. /**
  18148. * @author mrdoob / http://mrdoob.com/
  18149. */
  18150. function PointLight( color, intensity, distance, decay ) {
  18151. Light.call( this, color, intensity );
  18152. this.type = 'PointLight';
  18153. Object.defineProperty( this, 'power', {
  18154. get: function () {
  18155. // intensity = power per solid angle.
  18156. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18157. return this.intensity * 4 * Math.PI;
  18158. },
  18159. set: function ( power ) {
  18160. // intensity = power per solid angle.
  18161. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18162. this.intensity = power / ( 4 * Math.PI );
  18163. }
  18164. } );
  18165. this.distance = ( distance !== undefined ) ? distance : 0;
  18166. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18167. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18168. }
  18169. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18170. constructor: PointLight,
  18171. isPointLight: true,
  18172. copy: function ( source ) {
  18173. Light.prototype.copy.call( this, source );
  18174. this.distance = source.distance;
  18175. this.decay = source.decay;
  18176. this.shadow = source.shadow.clone();
  18177. return this;
  18178. }
  18179. } );
  18180. /**
  18181. * @author mrdoob / http://mrdoob.com/
  18182. */
  18183. function DirectionalLightShadow( ) {
  18184. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18185. }
  18186. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18187. constructor: DirectionalLightShadow
  18188. } );
  18189. /**
  18190. * @author mrdoob / http://mrdoob.com/
  18191. * @author alteredq / http://alteredqualia.com/
  18192. */
  18193. function DirectionalLight( color, intensity ) {
  18194. Light.call( this, color, intensity );
  18195. this.type = 'DirectionalLight';
  18196. this.position.copy( Object3D.DefaultUp );
  18197. this.updateMatrix();
  18198. this.target = new Object3D();
  18199. this.shadow = new DirectionalLightShadow();
  18200. }
  18201. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18202. constructor: DirectionalLight,
  18203. isDirectionalLight: true,
  18204. copy: function ( source ) {
  18205. Light.prototype.copy.call( this, source );
  18206. this.target = source.target.clone();
  18207. this.shadow = source.shadow.clone();
  18208. return this;
  18209. }
  18210. } );
  18211. /**
  18212. * @author mrdoob / http://mrdoob.com/
  18213. */
  18214. function AmbientLight( color, intensity ) {
  18215. Light.call( this, color, intensity );
  18216. this.type = 'AmbientLight';
  18217. this.castShadow = undefined;
  18218. }
  18219. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18220. constructor: AmbientLight,
  18221. isAmbientLight: true
  18222. } );
  18223. /**
  18224. * @author abelnation / http://github.com/abelnation
  18225. */
  18226. function RectAreaLight( color, intensity, width, height ) {
  18227. Light.call( this, color, intensity );
  18228. this.type = 'RectAreaLight';
  18229. this.position.set( 0, 1, 0 );
  18230. this.updateMatrix();
  18231. this.width = ( width !== undefined ) ? width : 10;
  18232. this.height = ( height !== undefined ) ? height : 10;
  18233. // TODO (abelnation): distance/decay
  18234. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  18235. // TODO (abelnation): shadows
  18236. }
  18237. // TODO (abelnation): RectAreaLight update when light shape is changed
  18238. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18239. constructor: RectAreaLight,
  18240. isRectAreaLight: true,
  18241. copy: function ( source ) {
  18242. Light.prototype.copy.call( this, source );
  18243. this.width = source.width;
  18244. this.height = source.height;
  18245. return this;
  18246. },
  18247. toJSON: function ( meta ) {
  18248. var data = Light.prototype.toJSON.call( this, meta );
  18249. data.object.width = this.width;
  18250. data.object.height = this.height;
  18251. return data;
  18252. }
  18253. } );
  18254. /**
  18255. * @author tschw
  18256. * @author Ben Houston / http://clara.io/
  18257. * @author David Sarno / http://lighthaus.us/
  18258. */
  18259. var AnimationUtils = {
  18260. // same as Array.prototype.slice, but also works on typed arrays
  18261. arraySlice: function ( array, from, to ) {
  18262. if ( AnimationUtils.isTypedArray( array ) ) {
  18263. // in ios9 array.subarray(from, undefined) will return empty array
  18264. // but array.subarray(from) or array.subarray(from, len) is correct
  18265. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  18266. }
  18267. return array.slice( from, to );
  18268. },
  18269. // converts an array to a specific type
  18270. convertArray: function ( array, type, forceClone ) {
  18271. if ( ! array || // let 'undefined' and 'null' pass
  18272. ! forceClone && array.constructor === type ) return array;
  18273. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18274. return new type( array ); // create typed array
  18275. }
  18276. return Array.prototype.slice.call( array ); // create Array
  18277. },
  18278. isTypedArray: function ( object ) {
  18279. return ArrayBuffer.isView( object ) &&
  18280. ! ( object instanceof DataView );
  18281. },
  18282. // returns an array by which times and values can be sorted
  18283. getKeyframeOrder: function ( times ) {
  18284. function compareTime( i, j ) {
  18285. return times[ i ] - times[ j ];
  18286. }
  18287. var n = times.length;
  18288. var result = new Array( n );
  18289. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18290. result.sort( compareTime );
  18291. return result;
  18292. },
  18293. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18294. sortedArray: function ( values, stride, order ) {
  18295. var nValues = values.length;
  18296. var result = new values.constructor( nValues );
  18297. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18298. var srcOffset = order[ i ] * stride;
  18299. for ( var j = 0; j !== stride; ++ j ) {
  18300. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18301. }
  18302. }
  18303. return result;
  18304. },
  18305. // function for parsing AOS keyframe formats
  18306. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  18307. var i = 1, key = jsonKeys[ 0 ];
  18308. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18309. key = jsonKeys[ i ++ ];
  18310. }
  18311. if ( key === undefined ) return; // no data
  18312. var value = key[ valuePropertyName ];
  18313. if ( value === undefined ) return; // no data
  18314. if ( Array.isArray( value ) ) {
  18315. do {
  18316. value = key[ valuePropertyName ];
  18317. if ( value !== undefined ) {
  18318. times.push( key.time );
  18319. values.push.apply( values, value ); // push all elements
  18320. }
  18321. key = jsonKeys[ i ++ ];
  18322. } while ( key !== undefined );
  18323. } else if ( value.toArray !== undefined ) {
  18324. // ...assume THREE.Math-ish
  18325. do {
  18326. value = key[ valuePropertyName ];
  18327. if ( value !== undefined ) {
  18328. times.push( key.time );
  18329. value.toArray( values, values.length );
  18330. }
  18331. key = jsonKeys[ i ++ ];
  18332. } while ( key !== undefined );
  18333. } else {
  18334. // otherwise push as-is
  18335. do {
  18336. value = key[ valuePropertyName ];
  18337. if ( value !== undefined ) {
  18338. times.push( key.time );
  18339. values.push( value );
  18340. }
  18341. key = jsonKeys[ i ++ ];
  18342. } while ( key !== undefined );
  18343. }
  18344. }
  18345. };
  18346. /**
  18347. * Abstract base class of interpolants over parametric samples.
  18348. *
  18349. * The parameter domain is one dimensional, typically the time or a path
  18350. * along a curve defined by the data.
  18351. *
  18352. * The sample values can have any dimensionality and derived classes may
  18353. * apply special interpretations to the data.
  18354. *
  18355. * This class provides the interval seek in a Template Method, deferring
  18356. * the actual interpolation to derived classes.
  18357. *
  18358. * Time complexity is O(1) for linear access crossing at most two points
  18359. * and O(log N) for random access, where N is the number of positions.
  18360. *
  18361. * References:
  18362. *
  18363. * http://www.oodesign.com/template-method-pattern.html
  18364. *
  18365. * @author tschw
  18366. */
  18367. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18368. this.parameterPositions = parameterPositions;
  18369. this._cachedIndex = 0;
  18370. this.resultBuffer = resultBuffer !== undefined ?
  18371. resultBuffer : new sampleValues.constructor( sampleSize );
  18372. this.sampleValues = sampleValues;
  18373. this.valueSize = sampleSize;
  18374. }
  18375. Object.assign( Interpolant.prototype, {
  18376. evaluate: function( t ) {
  18377. var pp = this.parameterPositions,
  18378. i1 = this._cachedIndex,
  18379. t1 = pp[ i1 ],
  18380. t0 = pp[ i1 - 1 ];
  18381. validate_interval: {
  18382. seek: {
  18383. var right;
  18384. linear_scan: {
  18385. //- See http://jsperf.com/comparison-to-undefined/3
  18386. //- slower code:
  18387. //-
  18388. //- if ( t >= t1 || t1 === undefined ) {
  18389. forward_scan: if ( ! ( t < t1 ) ) {
  18390. for ( var giveUpAt = i1 + 2; ;) {
  18391. if ( t1 === undefined ) {
  18392. if ( t < t0 ) break forward_scan;
  18393. // after end
  18394. i1 = pp.length;
  18395. this._cachedIndex = i1;
  18396. return this.afterEnd_( i1 - 1, t, t0 );
  18397. }
  18398. if ( i1 === giveUpAt ) break; // this loop
  18399. t0 = t1;
  18400. t1 = pp[ ++ i1 ];
  18401. if ( t < t1 ) {
  18402. // we have arrived at the sought interval
  18403. break seek;
  18404. }
  18405. }
  18406. // prepare binary search on the right side of the index
  18407. right = pp.length;
  18408. break linear_scan;
  18409. }
  18410. //- slower code:
  18411. //- if ( t < t0 || t0 === undefined ) {
  18412. if ( ! ( t >= t0 ) ) {
  18413. // looping?
  18414. var t1global = pp[ 1 ];
  18415. if ( t < t1global ) {
  18416. i1 = 2; // + 1, using the scan for the details
  18417. t0 = t1global;
  18418. }
  18419. // linear reverse scan
  18420. for ( var giveUpAt = i1 - 2; ;) {
  18421. if ( t0 === undefined ) {
  18422. // before start
  18423. this._cachedIndex = 0;
  18424. return this.beforeStart_( 0, t, t1 );
  18425. }
  18426. if ( i1 === giveUpAt ) break; // this loop
  18427. t1 = t0;
  18428. t0 = pp[ -- i1 - 1 ];
  18429. if ( t >= t0 ) {
  18430. // we have arrived at the sought interval
  18431. break seek;
  18432. }
  18433. }
  18434. // prepare binary search on the left side of the index
  18435. right = i1;
  18436. i1 = 0;
  18437. break linear_scan;
  18438. }
  18439. // the interval is valid
  18440. break validate_interval;
  18441. } // linear scan
  18442. // binary search
  18443. while ( i1 < right ) {
  18444. var mid = ( i1 + right ) >>> 1;
  18445. if ( t < pp[ mid ] ) {
  18446. right = mid;
  18447. } else {
  18448. i1 = mid + 1;
  18449. }
  18450. }
  18451. t1 = pp[ i1 ];
  18452. t0 = pp[ i1 - 1 ];
  18453. // check boundary cases, again
  18454. if ( t0 === undefined ) {
  18455. this._cachedIndex = 0;
  18456. return this.beforeStart_( 0, t, t1 );
  18457. }
  18458. if ( t1 === undefined ) {
  18459. i1 = pp.length;
  18460. this._cachedIndex = i1;
  18461. return this.afterEnd_( i1 - 1, t0, t );
  18462. }
  18463. } // seek
  18464. this._cachedIndex = i1;
  18465. this.intervalChanged_( i1, t0, t1 );
  18466. } // validate_interval
  18467. return this.interpolate_( i1, t0, t, t1 );
  18468. },
  18469. settings: null, // optional, subclass-specific settings structure
  18470. // Note: The indirection allows central control of many interpolants.
  18471. // --- Protected interface
  18472. DefaultSettings_: {},
  18473. getSettings_: function() {
  18474. return this.settings || this.DefaultSettings_;
  18475. },
  18476. copySampleValue_: function( index ) {
  18477. // copies a sample value to the result buffer
  18478. var result = this.resultBuffer,
  18479. values = this.sampleValues,
  18480. stride = this.valueSize,
  18481. offset = index * stride;
  18482. for ( var i = 0; i !== stride; ++ i ) {
  18483. result[ i ] = values[ offset + i ];
  18484. }
  18485. return result;
  18486. },
  18487. // Template methods for derived classes:
  18488. interpolate_: function( i1, t0, t, t1 ) {
  18489. throw new Error( "call to abstract method" );
  18490. // implementations shall return this.resultBuffer
  18491. },
  18492. intervalChanged_: function( i1, t0, t1 ) {
  18493. // empty
  18494. }
  18495. } );
  18496. //!\ DECLARE ALIAS AFTER assign prototype !
  18497. Object.assign( Interpolant.prototype, {
  18498. //( 0, t, t0 ), returns this.resultBuffer
  18499. beforeStart_: Interpolant.prototype.copySampleValue_,
  18500. //( N-1, tN-1, t ), returns this.resultBuffer
  18501. afterEnd_: Interpolant.prototype.copySampleValue_,
  18502. } );
  18503. /**
  18504. * Fast and simple cubic spline interpolant.
  18505. *
  18506. * It was derived from a Hermitian construction setting the first derivative
  18507. * at each sample position to the linear slope between neighboring positions
  18508. * over their parameter interval.
  18509. *
  18510. * @author tschw
  18511. */
  18512. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18513. Interpolant.call(
  18514. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18515. this._weightPrev = -0;
  18516. this._offsetPrev = -0;
  18517. this._weightNext = -0;
  18518. this._offsetNext = -0;
  18519. }
  18520. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18521. constructor: CubicInterpolant,
  18522. DefaultSettings_: {
  18523. endingStart: ZeroCurvatureEnding,
  18524. endingEnd: ZeroCurvatureEnding
  18525. },
  18526. intervalChanged_: function( i1, t0, t1 ) {
  18527. var pp = this.parameterPositions,
  18528. iPrev = i1 - 2,
  18529. iNext = i1 + 1,
  18530. tPrev = pp[ iPrev ],
  18531. tNext = pp[ iNext ];
  18532. if ( tPrev === undefined ) {
  18533. switch ( this.getSettings_().endingStart ) {
  18534. case ZeroSlopeEnding:
  18535. // f'(t0) = 0
  18536. iPrev = i1;
  18537. tPrev = 2 * t0 - t1;
  18538. break;
  18539. case WrapAroundEnding:
  18540. // use the other end of the curve
  18541. iPrev = pp.length - 2;
  18542. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18543. break;
  18544. default: // ZeroCurvatureEnding
  18545. // f''(t0) = 0 a.k.a. Natural Spline
  18546. iPrev = i1;
  18547. tPrev = t1;
  18548. }
  18549. }
  18550. if ( tNext === undefined ) {
  18551. switch ( this.getSettings_().endingEnd ) {
  18552. case ZeroSlopeEnding:
  18553. // f'(tN) = 0
  18554. iNext = i1;
  18555. tNext = 2 * t1 - t0;
  18556. break;
  18557. case WrapAroundEnding:
  18558. // use the other end of the curve
  18559. iNext = 1;
  18560. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18561. break;
  18562. default: // ZeroCurvatureEnding
  18563. // f''(tN) = 0, a.k.a. Natural Spline
  18564. iNext = i1 - 1;
  18565. tNext = t0;
  18566. }
  18567. }
  18568. var halfDt = ( t1 - t0 ) * 0.5,
  18569. stride = this.valueSize;
  18570. this._weightPrev = halfDt / ( t0 - tPrev );
  18571. this._weightNext = halfDt / ( tNext - t1 );
  18572. this._offsetPrev = iPrev * stride;
  18573. this._offsetNext = iNext * stride;
  18574. },
  18575. interpolate_: function( i1, t0, t, t1 ) {
  18576. var result = this.resultBuffer,
  18577. values = this.sampleValues,
  18578. stride = this.valueSize,
  18579. o1 = i1 * stride, o0 = o1 - stride,
  18580. oP = this._offsetPrev, oN = this._offsetNext,
  18581. wP = this._weightPrev, wN = this._weightNext,
  18582. p = ( t - t0 ) / ( t1 - t0 ),
  18583. pp = p * p,
  18584. ppp = pp * p;
  18585. // evaluate polynomials
  18586. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18587. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18588. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18589. var sN = wN * ppp - wN * pp;
  18590. // combine data linearly
  18591. for ( var i = 0; i !== stride; ++ i ) {
  18592. result[ i ] =
  18593. sP * values[ oP + i ] +
  18594. s0 * values[ o0 + i ] +
  18595. s1 * values[ o1 + i ] +
  18596. sN * values[ oN + i ];
  18597. }
  18598. return result;
  18599. }
  18600. } );
  18601. /**
  18602. * @author tschw
  18603. */
  18604. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18605. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18606. }
  18607. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18608. constructor: LinearInterpolant,
  18609. interpolate_: function( i1, t0, t, t1 ) {
  18610. var result = this.resultBuffer,
  18611. values = this.sampleValues,
  18612. stride = this.valueSize,
  18613. offset1 = i1 * stride,
  18614. offset0 = offset1 - stride,
  18615. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18616. weight0 = 1 - weight1;
  18617. for ( var i = 0; i !== stride; ++ i ) {
  18618. result[ i ] =
  18619. values[ offset0 + i ] * weight0 +
  18620. values[ offset1 + i ] * weight1;
  18621. }
  18622. return result;
  18623. }
  18624. } );
  18625. /**
  18626. *
  18627. * Interpolant that evaluates to the sample value at the position preceeding
  18628. * the parameter.
  18629. *
  18630. * @author tschw
  18631. */
  18632. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18633. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18634. }
  18635. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18636. constructor: DiscreteInterpolant,
  18637. interpolate_: function( i1, t0, t, t1 ) {
  18638. return this.copySampleValue_( i1 - 1 );
  18639. }
  18640. } );
  18641. var KeyframeTrackPrototype;
  18642. KeyframeTrackPrototype = {
  18643. TimeBufferType: Float32Array,
  18644. ValueBufferType: Float32Array,
  18645. DefaultInterpolation: InterpolateLinear,
  18646. InterpolantFactoryMethodDiscrete: function ( result ) {
  18647. return new DiscreteInterpolant(
  18648. this.times, this.values, this.getValueSize(), result );
  18649. },
  18650. InterpolantFactoryMethodLinear: function ( result ) {
  18651. return new LinearInterpolant(
  18652. this.times, this.values, this.getValueSize(), result );
  18653. },
  18654. InterpolantFactoryMethodSmooth: function ( result ) {
  18655. return new CubicInterpolant(
  18656. this.times, this.values, this.getValueSize(), result );
  18657. },
  18658. setInterpolation: function ( interpolation ) {
  18659. var factoryMethod;
  18660. switch ( interpolation ) {
  18661. case InterpolateDiscrete:
  18662. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18663. break;
  18664. case InterpolateLinear:
  18665. factoryMethod = this.InterpolantFactoryMethodLinear;
  18666. break;
  18667. case InterpolateSmooth:
  18668. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18669. break;
  18670. }
  18671. if ( factoryMethod === undefined ) {
  18672. var message = "unsupported interpolation for " +
  18673. this.ValueTypeName + " keyframe track named " + this.name;
  18674. if ( this.createInterpolant === undefined ) {
  18675. // fall back to default, unless the default itself is messed up
  18676. if ( interpolation !== this.DefaultInterpolation ) {
  18677. this.setInterpolation( this.DefaultInterpolation );
  18678. } else {
  18679. throw new Error( message ); // fatal, in this case
  18680. }
  18681. }
  18682. console.warn( message );
  18683. return;
  18684. }
  18685. this.createInterpolant = factoryMethod;
  18686. },
  18687. getInterpolation: function () {
  18688. switch ( this.createInterpolant ) {
  18689. case this.InterpolantFactoryMethodDiscrete:
  18690. return InterpolateDiscrete;
  18691. case this.InterpolantFactoryMethodLinear:
  18692. return InterpolateLinear;
  18693. case this.InterpolantFactoryMethodSmooth:
  18694. return InterpolateSmooth;
  18695. }
  18696. },
  18697. getValueSize: function () {
  18698. return this.values.length / this.times.length;
  18699. },
  18700. // move all keyframes either forwards or backwards in time
  18701. shift: function ( timeOffset ) {
  18702. if ( timeOffset !== 0.0 ) {
  18703. var times = this.times;
  18704. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18705. times[ i ] += timeOffset;
  18706. }
  18707. }
  18708. return this;
  18709. },
  18710. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18711. scale: function ( timeScale ) {
  18712. if ( timeScale !== 1.0 ) {
  18713. var times = this.times;
  18714. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18715. times[ i ] *= timeScale;
  18716. }
  18717. }
  18718. return this;
  18719. },
  18720. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18721. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18722. trim: function ( startTime, endTime ) {
  18723. var times = this.times,
  18724. nKeys = times.length,
  18725. from = 0,
  18726. to = nKeys - 1;
  18727. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18728. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18729. ++ to; // inclusive -> exclusive bound
  18730. if ( from !== 0 || to !== nKeys ) {
  18731. // empty tracks are forbidden, so keep at least one keyframe
  18732. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18733. var stride = this.getValueSize();
  18734. this.times = AnimationUtils.arraySlice( times, from, to );
  18735. this.values = AnimationUtils.
  18736. arraySlice( this.values, from * stride, to * stride );
  18737. }
  18738. return this;
  18739. },
  18740. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18741. validate: function () {
  18742. var valid = true;
  18743. var valueSize = this.getValueSize();
  18744. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18745. console.error( "invalid value size in track", this );
  18746. valid = false;
  18747. }
  18748. var times = this.times,
  18749. values = this.values,
  18750. nKeys = times.length;
  18751. if ( nKeys === 0 ) {
  18752. console.error( "track is empty", this );
  18753. valid = false;
  18754. }
  18755. var prevTime = null;
  18756. for ( var i = 0; i !== nKeys; i ++ ) {
  18757. var currTime = times[ i ];
  18758. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18759. console.error( "time is not a valid number", this, i, currTime );
  18760. valid = false;
  18761. break;
  18762. }
  18763. if ( prevTime !== null && prevTime > currTime ) {
  18764. console.error( "out of order keys", this, i, currTime, prevTime );
  18765. valid = false;
  18766. break;
  18767. }
  18768. prevTime = currTime;
  18769. }
  18770. if ( values !== undefined ) {
  18771. if ( AnimationUtils.isTypedArray( values ) ) {
  18772. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18773. var value = values[ i ];
  18774. if ( isNaN( value ) ) {
  18775. console.error( "value is not a valid number", this, i, value );
  18776. valid = false;
  18777. break;
  18778. }
  18779. }
  18780. }
  18781. }
  18782. return valid;
  18783. },
  18784. // removes equivalent sequential keys as common in morph target sequences
  18785. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18786. optimize: function () {
  18787. var times = this.times,
  18788. values = this.values,
  18789. stride = this.getValueSize(),
  18790. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18791. writeIndex = 1,
  18792. lastIndex = times.length - 1;
  18793. for ( var i = 1; i < lastIndex; ++ i ) {
  18794. var keep = false;
  18795. var time = times[ i ];
  18796. var timeNext = times[ i + 1 ];
  18797. // remove adjacent keyframes scheduled at the same time
  18798. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18799. if ( ! smoothInterpolation ) {
  18800. // remove unnecessary keyframes same as their neighbors
  18801. var offset = i * stride,
  18802. offsetP = offset - stride,
  18803. offsetN = offset + stride;
  18804. for ( var j = 0; j !== stride; ++ j ) {
  18805. var value = values[ offset + j ];
  18806. if ( value !== values[ offsetP + j ] ||
  18807. value !== values[ offsetN + j ] ) {
  18808. keep = true;
  18809. break;
  18810. }
  18811. }
  18812. } else keep = true;
  18813. }
  18814. // in-place compaction
  18815. if ( keep ) {
  18816. if ( i !== writeIndex ) {
  18817. times[ writeIndex ] = times[ i ];
  18818. var readOffset = i * stride,
  18819. writeOffset = writeIndex * stride;
  18820. for ( var j = 0; j !== stride; ++ j )
  18821. values[ writeOffset + j ] = values[ readOffset + j ];
  18822. }
  18823. ++ writeIndex;
  18824. }
  18825. }
  18826. // flush last keyframe (compaction looks ahead)
  18827. if ( lastIndex > 0 ) {
  18828. times[ writeIndex ] = times[ lastIndex ];
  18829. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18830. values[ writeOffset + j ] = values[ readOffset + j ];
  18831. ++ writeIndex;
  18832. }
  18833. if ( writeIndex !== times.length ) {
  18834. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18835. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18836. }
  18837. return this;
  18838. }
  18839. };
  18840. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18841. if ( name === undefined ) throw new Error( "track name is undefined" );
  18842. if ( times === undefined || times.length === 0 ) {
  18843. throw new Error( "no keyframes in track named " + name );
  18844. }
  18845. this.name = name;
  18846. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18847. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18848. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18849. this.validate();
  18850. this.optimize();
  18851. }
  18852. /**
  18853. *
  18854. * A Track of vectored keyframe values.
  18855. *
  18856. *
  18857. * @author Ben Houston / http://clara.io/
  18858. * @author David Sarno / http://lighthaus.us/
  18859. * @author tschw
  18860. */
  18861. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18862. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18863. }
  18864. VectorKeyframeTrack.prototype =
  18865. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18866. constructor: VectorKeyframeTrack,
  18867. ValueTypeName: 'vector'
  18868. // ValueBufferType is inherited
  18869. // DefaultInterpolation is inherited
  18870. } );
  18871. /**
  18872. * Spherical linear unit quaternion interpolant.
  18873. *
  18874. * @author tschw
  18875. */
  18876. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18877. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18878. }
  18879. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  18880. constructor: QuaternionLinearInterpolant,
  18881. interpolate_: function( i1, t0, t, t1 ) {
  18882. var result = this.resultBuffer,
  18883. values = this.sampleValues,
  18884. stride = this.valueSize,
  18885. offset = i1 * stride,
  18886. alpha = ( t - t0 ) / ( t1 - t0 );
  18887. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18888. Quaternion.slerpFlat( result, 0,
  18889. values, offset - stride, values, offset, alpha );
  18890. }
  18891. return result;
  18892. }
  18893. } );
  18894. /**
  18895. *
  18896. * A Track of quaternion keyframe values.
  18897. *
  18898. * @author Ben Houston / http://clara.io/
  18899. * @author David Sarno / http://lighthaus.us/
  18900. * @author tschw
  18901. */
  18902. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18903. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18904. }
  18905. QuaternionKeyframeTrack.prototype =
  18906. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18907. constructor: QuaternionKeyframeTrack,
  18908. ValueTypeName: 'quaternion',
  18909. // ValueBufferType is inherited
  18910. DefaultInterpolation: InterpolateLinear,
  18911. InterpolantFactoryMethodLinear: function( result ) {
  18912. return new QuaternionLinearInterpolant(
  18913. this.times, this.values, this.getValueSize(), result );
  18914. },
  18915. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18916. } );
  18917. /**
  18918. *
  18919. * A Track of numeric keyframe values.
  18920. *
  18921. * @author Ben Houston / http://clara.io/
  18922. * @author David Sarno / http://lighthaus.us/
  18923. * @author tschw
  18924. */
  18925. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18926. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18927. }
  18928. NumberKeyframeTrack.prototype =
  18929. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18930. constructor: NumberKeyframeTrack,
  18931. ValueTypeName: 'number'
  18932. // ValueBufferType is inherited
  18933. // DefaultInterpolation is inherited
  18934. } );
  18935. /**
  18936. *
  18937. * A Track that interpolates Strings
  18938. *
  18939. *
  18940. * @author Ben Houston / http://clara.io/
  18941. * @author David Sarno / http://lighthaus.us/
  18942. * @author tschw
  18943. */
  18944. function StringKeyframeTrack( name, times, values, interpolation ) {
  18945. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18946. }
  18947. StringKeyframeTrack.prototype =
  18948. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18949. constructor: StringKeyframeTrack,
  18950. ValueTypeName: 'string',
  18951. ValueBufferType: Array,
  18952. DefaultInterpolation: InterpolateDiscrete,
  18953. InterpolantFactoryMethodLinear: undefined,
  18954. InterpolantFactoryMethodSmooth: undefined
  18955. } );
  18956. /**
  18957. *
  18958. * A Track of Boolean keyframe values.
  18959. *
  18960. *
  18961. * @author Ben Houston / http://clara.io/
  18962. * @author David Sarno / http://lighthaus.us/
  18963. * @author tschw
  18964. */
  18965. function BooleanKeyframeTrack( name, times, values ) {
  18966. KeyframeTrackConstructor.call( this, name, times, values );
  18967. }
  18968. BooleanKeyframeTrack.prototype =
  18969. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18970. constructor: BooleanKeyframeTrack,
  18971. ValueTypeName: 'bool',
  18972. ValueBufferType: Array,
  18973. DefaultInterpolation: InterpolateDiscrete,
  18974. InterpolantFactoryMethodLinear: undefined,
  18975. InterpolantFactoryMethodSmooth: undefined
  18976. // Note: Actually this track could have a optimized / compressed
  18977. // representation of a single value and a custom interpolant that
  18978. // computes "firstValue ^ isOdd( index )".
  18979. } );
  18980. /**
  18981. *
  18982. * A Track of keyframe values that represent color.
  18983. *
  18984. *
  18985. * @author Ben Houston / http://clara.io/
  18986. * @author David Sarno / http://lighthaus.us/
  18987. * @author tschw
  18988. */
  18989. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18990. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18991. }
  18992. ColorKeyframeTrack.prototype =
  18993. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18994. constructor: ColorKeyframeTrack,
  18995. ValueTypeName: 'color'
  18996. // ValueBufferType is inherited
  18997. // DefaultInterpolation is inherited
  18998. // Note: Very basic implementation and nothing special yet.
  18999. // However, this is the place for color space parameterization.
  19000. } );
  19001. /**
  19002. *
  19003. * A timed sequence of keyframes for a specific property.
  19004. *
  19005. *
  19006. * @author Ben Houston / http://clara.io/
  19007. * @author David Sarno / http://lighthaus.us/
  19008. * @author tschw
  19009. */
  19010. function KeyframeTrack( name, times, values, interpolation ) {
  19011. KeyframeTrackConstructor.apply( this, arguments );
  19012. }
  19013. KeyframeTrack.prototype = KeyframeTrackPrototype;
  19014. KeyframeTrackPrototype.constructor = KeyframeTrack;
  19015. // Static methods:
  19016. Object.assign( KeyframeTrack, {
  19017. // Serialization (in static context, because of constructor invocation
  19018. // and automatic invocation of .toJSON):
  19019. parse: function( json ) {
  19020. if( json.type === undefined ) {
  19021. throw new Error( "track type undefined, can not parse" );
  19022. }
  19023. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  19024. if ( json.times === undefined ) {
  19025. var times = [], values = [];
  19026. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  19027. json.times = times;
  19028. json.values = values;
  19029. }
  19030. // derived classes can define a static parse method
  19031. if ( trackType.parse !== undefined ) {
  19032. return trackType.parse( json );
  19033. } else {
  19034. // by default, we asssume a constructor compatible with the base
  19035. return new trackType(
  19036. json.name, json.times, json.values, json.interpolation );
  19037. }
  19038. },
  19039. toJSON: function( track ) {
  19040. var trackType = track.constructor;
  19041. var json;
  19042. // derived classes can define a static toJSON method
  19043. if ( trackType.toJSON !== undefined ) {
  19044. json = trackType.toJSON( track );
  19045. } else {
  19046. // by default, we assume the data can be serialized as-is
  19047. json = {
  19048. 'name': track.name,
  19049. 'times': AnimationUtils.convertArray( track.times, Array ),
  19050. 'values': AnimationUtils.convertArray( track.values, Array )
  19051. };
  19052. var interpolation = track.getInterpolation();
  19053. if ( interpolation !== track.DefaultInterpolation ) {
  19054. json.interpolation = interpolation;
  19055. }
  19056. }
  19057. json.type = track.ValueTypeName; // mandatory
  19058. return json;
  19059. },
  19060. _getTrackTypeForValueTypeName: function( typeName ) {
  19061. switch( typeName.toLowerCase() ) {
  19062. case "scalar":
  19063. case "double":
  19064. case "float":
  19065. case "number":
  19066. case "integer":
  19067. return NumberKeyframeTrack;
  19068. case "vector":
  19069. case "vector2":
  19070. case "vector3":
  19071. case "vector4":
  19072. return VectorKeyframeTrack;
  19073. case "color":
  19074. return ColorKeyframeTrack;
  19075. case "quaternion":
  19076. return QuaternionKeyframeTrack;
  19077. case "bool":
  19078. case "boolean":
  19079. return BooleanKeyframeTrack;
  19080. case "string":
  19081. return StringKeyframeTrack;
  19082. }
  19083. throw new Error( "Unsupported typeName: " + typeName );
  19084. }
  19085. } );
  19086. /**
  19087. *
  19088. * Reusable set of Tracks that represent an animation.
  19089. *
  19090. * @author Ben Houston / http://clara.io/
  19091. * @author David Sarno / http://lighthaus.us/
  19092. */
  19093. function AnimationClip( name, duration, tracks ) {
  19094. this.name = name;
  19095. this.tracks = tracks;
  19096. this.duration = ( duration !== undefined ) ? duration : - 1;
  19097. this.uuid = _Math.generateUUID();
  19098. // this means it should figure out its duration by scanning the tracks
  19099. if ( this.duration < 0 ) {
  19100. this.resetDuration();
  19101. }
  19102. this.optimize();
  19103. }
  19104. Object.assign( AnimationClip, {
  19105. parse: function ( json ) {
  19106. var tracks = [],
  19107. jsonTracks = json.tracks,
  19108. frameTime = 1.0 / ( json.fps || 1.0 );
  19109. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19110. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  19111. }
  19112. return new AnimationClip( json.name, json.duration, tracks );
  19113. },
  19114. toJSON: function ( clip ) {
  19115. var tracks = [],
  19116. clipTracks = clip.tracks;
  19117. var json = {
  19118. 'name': clip.name,
  19119. 'duration': clip.duration,
  19120. 'tracks': tracks
  19121. };
  19122. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  19123. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  19124. }
  19125. return json;
  19126. },
  19127. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  19128. var numMorphTargets = morphTargetSequence.length;
  19129. var tracks = [];
  19130. for ( var i = 0; i < numMorphTargets; i ++ ) {
  19131. var times = [];
  19132. var values = [];
  19133. times.push(
  19134. ( i + numMorphTargets - 1 ) % numMorphTargets,
  19135. i,
  19136. ( i + 1 ) % numMorphTargets );
  19137. values.push( 0, 1, 0 );
  19138. var order = AnimationUtils.getKeyframeOrder( times );
  19139. times = AnimationUtils.sortedArray( times, 1, order );
  19140. values = AnimationUtils.sortedArray( values, 1, order );
  19141. // if there is a key at the first frame, duplicate it as the
  19142. // last frame as well for perfect loop.
  19143. if ( ! noLoop && times[ 0 ] === 0 ) {
  19144. times.push( numMorphTargets );
  19145. values.push( values[ 0 ] );
  19146. }
  19147. tracks.push(
  19148. new NumberKeyframeTrack(
  19149. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19150. times, values
  19151. ).scale( 1.0 / fps ) );
  19152. }
  19153. return new AnimationClip( name, - 1, tracks );
  19154. },
  19155. findByName: function ( objectOrClipArray, name ) {
  19156. var clipArray = objectOrClipArray;
  19157. if ( ! Array.isArray( objectOrClipArray ) ) {
  19158. var o = objectOrClipArray;
  19159. clipArray = o.geometry && o.geometry.animations || o.animations;
  19160. }
  19161. for ( var i = 0; i < clipArray.length; i ++ ) {
  19162. if ( clipArray[ i ].name === name ) {
  19163. return clipArray[ i ];
  19164. }
  19165. }
  19166. return null;
  19167. },
  19168. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  19169. var animationToMorphTargets = {};
  19170. // tested with https://regex101.com/ on trick sequences
  19171. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19172. var pattern = /^([\w-]*?)([\d]+)$/;
  19173. // sort morph target names into animation groups based
  19174. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19175. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19176. var morphTarget = morphTargets[ i ];
  19177. var parts = morphTarget.name.match( pattern );
  19178. if ( parts && parts.length > 1 ) {
  19179. var name = parts[ 1 ];
  19180. var animationMorphTargets = animationToMorphTargets[ name ];
  19181. if ( ! animationMorphTargets ) {
  19182. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19183. }
  19184. animationMorphTargets.push( morphTarget );
  19185. }
  19186. }
  19187. var clips = [];
  19188. for ( var name in animationToMorphTargets ) {
  19189. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19190. }
  19191. return clips;
  19192. },
  19193. // parse the animation.hierarchy format
  19194. parseAnimation: function ( animation, bones ) {
  19195. if ( ! animation ) {
  19196. console.error( " no animation in JSONLoader data" );
  19197. return null;
  19198. }
  19199. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  19200. // only return track if there are actually keys.
  19201. if ( animationKeys.length !== 0 ) {
  19202. var times = [];
  19203. var values = [];
  19204. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  19205. // empty keys are filtered out, so check again
  19206. if ( times.length !== 0 ) {
  19207. destTracks.push( new trackType( trackName, times, values ) );
  19208. }
  19209. }
  19210. };
  19211. var tracks = [];
  19212. var clipName = animation.name || 'default';
  19213. // automatic length determination in AnimationClip.
  19214. var duration = animation.length || - 1;
  19215. var fps = animation.fps || 30;
  19216. var hierarchyTracks = animation.hierarchy || [];
  19217. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19218. var animationKeys = hierarchyTracks[ h ].keys;
  19219. // skip empty tracks
  19220. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19221. // process morph targets in a way exactly compatible
  19222. // with AnimationHandler.init( animation )
  19223. if ( animationKeys[ 0 ].morphTargets ) {
  19224. // figure out all morph targets used in this track
  19225. var morphTargetNames = {};
  19226. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19227. if ( animationKeys[ k ].morphTargets ) {
  19228. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  19229. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  19230. }
  19231. }
  19232. }
  19233. // create a track for each morph target with all zero
  19234. // morphTargetInfluences except for the keys in which
  19235. // the morphTarget is named.
  19236. for ( var morphTargetName in morphTargetNames ) {
  19237. var times = [];
  19238. var values = [];
  19239. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  19240. var animationKey = animationKeys[ k ];
  19241. times.push( animationKey.time );
  19242. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19243. }
  19244. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19245. }
  19246. duration = morphTargetNames.length * ( fps || 1.0 );
  19247. } else {
  19248. // ...assume skeletal animation
  19249. var boneName = '.bones[' + bones[ h ].name + ']';
  19250. addNonemptyTrack(
  19251. VectorKeyframeTrack, boneName + '.position',
  19252. animationKeys, 'pos', tracks );
  19253. addNonemptyTrack(
  19254. QuaternionKeyframeTrack, boneName + '.quaternion',
  19255. animationKeys, 'rot', tracks );
  19256. addNonemptyTrack(
  19257. VectorKeyframeTrack, boneName + '.scale',
  19258. animationKeys, 'scl', tracks );
  19259. }
  19260. }
  19261. if ( tracks.length === 0 ) {
  19262. return null;
  19263. }
  19264. var clip = new AnimationClip( clipName, duration, tracks );
  19265. return clip;
  19266. }
  19267. } );
  19268. Object.assign( AnimationClip.prototype, {
  19269. resetDuration: function () {
  19270. var tracks = this.tracks, duration = 0;
  19271. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  19272. var track = this.tracks[ i ];
  19273. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  19274. }
  19275. this.duration = duration;
  19276. },
  19277. trim: function () {
  19278. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19279. this.tracks[ i ].trim( 0, this.duration );
  19280. }
  19281. return this;
  19282. },
  19283. optimize: function () {
  19284. for ( var i = 0; i < this.tracks.length; i ++ ) {
  19285. this.tracks[ i ].optimize();
  19286. }
  19287. return this;
  19288. }
  19289. } );
  19290. /**
  19291. * @author mrdoob / http://mrdoob.com/
  19292. */
  19293. function MaterialLoader( manager ) {
  19294. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19295. this.textures = {};
  19296. }
  19297. Object.assign( MaterialLoader.prototype, {
  19298. load: function ( url, onLoad, onProgress, onError ) {
  19299. var scope = this;
  19300. var loader = new FileLoader( scope.manager );
  19301. loader.setResponseType( 'json' );
  19302. loader.load( url, function ( json ) {
  19303. onLoad( scope.parse( json ) );
  19304. }, onProgress, onError );
  19305. },
  19306. setTextures: function ( value ) {
  19307. this.textures = value;
  19308. },
  19309. parse: function ( json ) {
  19310. var textures = this.textures;
  19311. function getTexture( name ) {
  19312. if ( textures[ name ] === undefined ) {
  19313. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19314. }
  19315. return textures[ name ];
  19316. }
  19317. var material = new Materials[ json.type ]();
  19318. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19319. if ( json.name !== undefined ) material.name = json.name;
  19320. if ( json.color !== undefined ) material.color.setHex( json.color );
  19321. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19322. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19323. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19324. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19325. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19326. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19327. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19328. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19329. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19330. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19331. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19332. if ( json.fog !== undefined ) material.fog = json.fog;
  19333. if ( json.shading !== undefined ) material.shading = json.shading;
  19334. if ( json.blending !== undefined ) material.blending = json.blending;
  19335. if ( json.side !== undefined ) material.side = json.side;
  19336. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19337. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19338. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19339. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19340. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19341. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19342. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19343. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19344. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19345. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19346. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19347. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19348. // for PointsMaterial
  19349. if ( json.size !== undefined ) material.size = json.size;
  19350. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19351. // maps
  19352. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19353. if ( json.alphaMap !== undefined ) {
  19354. material.alphaMap = getTexture( json.alphaMap );
  19355. material.transparent = true;
  19356. }
  19357. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19358. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19359. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19360. if ( json.normalScale !== undefined ) {
  19361. var normalScale = json.normalScale;
  19362. if ( Array.isArray( normalScale ) === false ) {
  19363. // Blender exporter used to export a scalar. See #7459
  19364. normalScale = [ normalScale, normalScale ];
  19365. }
  19366. material.normalScale = new Vector2().fromArray( normalScale );
  19367. }
  19368. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19369. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19370. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19371. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19372. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19373. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19374. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19375. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19376. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19377. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19378. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19379. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19380. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19381. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19382. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19383. // MultiMaterial
  19384. if ( json.materials !== undefined ) {
  19385. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  19386. material.materials.push( this.parse( json.materials[ i ] ) );
  19387. }
  19388. }
  19389. return material;
  19390. }
  19391. } );
  19392. /**
  19393. * @author mrdoob / http://mrdoob.com/
  19394. */
  19395. function BufferGeometryLoader( manager ) {
  19396. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19397. }
  19398. Object.assign( BufferGeometryLoader.prototype, {
  19399. load: function ( url, onLoad, onProgress, onError ) {
  19400. var scope = this;
  19401. var loader = new FileLoader( scope.manager );
  19402. loader.setResponseType( 'json' );
  19403. loader.load( url, function ( json ) {
  19404. onLoad( scope.parse( json ) );
  19405. }, onProgress, onError );
  19406. },
  19407. parse: function ( json ) {
  19408. var geometry = new BufferGeometry();
  19409. var index = json.data.index;
  19410. if ( index !== undefined ) {
  19411. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19412. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19413. }
  19414. var attributes = json.data.attributes;
  19415. for ( var key in attributes ) {
  19416. var attribute = attributes[ key ];
  19417. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19418. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19419. }
  19420. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19421. if ( groups !== undefined ) {
  19422. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19423. var group = groups[ i ];
  19424. geometry.addGroup( group.start, group.count, group.materialIndex );
  19425. }
  19426. }
  19427. var boundingSphere = json.data.boundingSphere;
  19428. if ( boundingSphere !== undefined ) {
  19429. var center = new Vector3();
  19430. if ( boundingSphere.center !== undefined ) {
  19431. center.fromArray( boundingSphere.center );
  19432. }
  19433. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19434. }
  19435. return geometry;
  19436. }
  19437. } );
  19438. var TYPED_ARRAYS = {
  19439. Int8Array: Int8Array,
  19440. Uint8Array: Uint8Array,
  19441. Uint8ClampedArray: Uint8ClampedArray,
  19442. Int16Array: Int16Array,
  19443. Uint16Array: Uint16Array,
  19444. Int32Array: Int32Array,
  19445. Uint32Array: Uint32Array,
  19446. Float32Array: Float32Array,
  19447. Float64Array: Float64Array
  19448. };
  19449. /**
  19450. * @author alteredq / http://alteredqualia.com/
  19451. */
  19452. function Loader() {
  19453. this.onLoadStart = function () {};
  19454. this.onLoadProgress = function () {};
  19455. this.onLoadComplete = function () {};
  19456. }
  19457. Loader.Handlers = {
  19458. handlers: [],
  19459. add: function ( regex, loader ) {
  19460. this.handlers.push( regex, loader );
  19461. },
  19462. get: function ( file ) {
  19463. var handlers = this.handlers;
  19464. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19465. var regex = handlers[ i ];
  19466. var loader = handlers[ i + 1 ];
  19467. if ( regex.test( file ) ) {
  19468. return loader;
  19469. }
  19470. }
  19471. return null;
  19472. }
  19473. };
  19474. Object.assign( Loader.prototype, {
  19475. crossOrigin: undefined,
  19476. extractUrlBase: function ( url ) {
  19477. var parts = url.split( '/' );
  19478. if ( parts.length === 1 ) return './';
  19479. parts.pop();
  19480. return parts.join( '/' ) + '/';
  19481. },
  19482. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19483. var array = [];
  19484. for ( var i = 0; i < materials.length; ++ i ) {
  19485. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19486. }
  19487. return array;
  19488. },
  19489. createMaterial: ( function () {
  19490. var BlendingMode = {
  19491. NoBlending: NoBlending,
  19492. NormalBlending: NormalBlending,
  19493. AdditiveBlending: AdditiveBlending,
  19494. SubtractiveBlending: SubtractiveBlending,
  19495. MultiplyBlending: MultiplyBlending,
  19496. CustomBlending: CustomBlending
  19497. };
  19498. var color = new Color();
  19499. var textureLoader = new TextureLoader();
  19500. var materialLoader = new MaterialLoader();
  19501. return function createMaterial( m, texturePath, crossOrigin ) {
  19502. // convert from old material format
  19503. var textures = {};
  19504. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19505. var fullPath = texturePath + path;
  19506. var loader = Loader.Handlers.get( fullPath );
  19507. var texture;
  19508. if ( loader !== null ) {
  19509. texture = loader.load( fullPath );
  19510. } else {
  19511. textureLoader.setCrossOrigin( crossOrigin );
  19512. texture = textureLoader.load( fullPath );
  19513. }
  19514. if ( repeat !== undefined ) {
  19515. texture.repeat.fromArray( repeat );
  19516. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19517. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19518. }
  19519. if ( offset !== undefined ) {
  19520. texture.offset.fromArray( offset );
  19521. }
  19522. if ( wrap !== undefined ) {
  19523. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19524. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19525. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19526. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19527. }
  19528. if ( anisotropy !== undefined ) {
  19529. texture.anisotropy = anisotropy;
  19530. }
  19531. var uuid = _Math.generateUUID();
  19532. textures[ uuid ] = texture;
  19533. return uuid;
  19534. }
  19535. //
  19536. var json = {
  19537. uuid: _Math.generateUUID(),
  19538. type: 'MeshLambertMaterial'
  19539. };
  19540. for ( var name in m ) {
  19541. var value = m[ name ];
  19542. switch ( name ) {
  19543. case 'DbgColor':
  19544. case 'DbgIndex':
  19545. case 'opticalDensity':
  19546. case 'illumination':
  19547. break;
  19548. case 'DbgName':
  19549. json.name = value;
  19550. break;
  19551. case 'blending':
  19552. json.blending = BlendingMode[ value ];
  19553. break;
  19554. case 'colorAmbient':
  19555. case 'mapAmbient':
  19556. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19557. break;
  19558. case 'colorDiffuse':
  19559. json.color = color.fromArray( value ).getHex();
  19560. break;
  19561. case 'colorSpecular':
  19562. json.specular = color.fromArray( value ).getHex();
  19563. break;
  19564. case 'colorEmissive':
  19565. json.emissive = color.fromArray( value ).getHex();
  19566. break;
  19567. case 'specularCoef':
  19568. json.shininess = value;
  19569. break;
  19570. case 'shading':
  19571. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19572. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19573. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19574. break;
  19575. case 'mapDiffuse':
  19576. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19577. break;
  19578. case 'mapDiffuseRepeat':
  19579. case 'mapDiffuseOffset':
  19580. case 'mapDiffuseWrap':
  19581. case 'mapDiffuseAnisotropy':
  19582. break;
  19583. case 'mapEmissive':
  19584. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19585. break;
  19586. case 'mapEmissiveRepeat':
  19587. case 'mapEmissiveOffset':
  19588. case 'mapEmissiveWrap':
  19589. case 'mapEmissiveAnisotropy':
  19590. break;
  19591. case 'mapLight':
  19592. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19593. break;
  19594. case 'mapLightRepeat':
  19595. case 'mapLightOffset':
  19596. case 'mapLightWrap':
  19597. case 'mapLightAnisotropy':
  19598. break;
  19599. case 'mapAO':
  19600. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19601. break;
  19602. case 'mapAORepeat':
  19603. case 'mapAOOffset':
  19604. case 'mapAOWrap':
  19605. case 'mapAOAnisotropy':
  19606. break;
  19607. case 'mapBump':
  19608. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19609. break;
  19610. case 'mapBumpScale':
  19611. json.bumpScale = value;
  19612. break;
  19613. case 'mapBumpRepeat':
  19614. case 'mapBumpOffset':
  19615. case 'mapBumpWrap':
  19616. case 'mapBumpAnisotropy':
  19617. break;
  19618. case 'mapNormal':
  19619. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19620. break;
  19621. case 'mapNormalFactor':
  19622. json.normalScale = [ value, value ];
  19623. break;
  19624. case 'mapNormalRepeat':
  19625. case 'mapNormalOffset':
  19626. case 'mapNormalWrap':
  19627. case 'mapNormalAnisotropy':
  19628. break;
  19629. case 'mapSpecular':
  19630. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19631. break;
  19632. case 'mapSpecularRepeat':
  19633. case 'mapSpecularOffset':
  19634. case 'mapSpecularWrap':
  19635. case 'mapSpecularAnisotropy':
  19636. break;
  19637. case 'mapMetalness':
  19638. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19639. break;
  19640. case 'mapMetalnessRepeat':
  19641. case 'mapMetalnessOffset':
  19642. case 'mapMetalnessWrap':
  19643. case 'mapMetalnessAnisotropy':
  19644. break;
  19645. case 'mapRoughness':
  19646. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19647. break;
  19648. case 'mapRoughnessRepeat':
  19649. case 'mapRoughnessOffset':
  19650. case 'mapRoughnessWrap':
  19651. case 'mapRoughnessAnisotropy':
  19652. break;
  19653. case 'mapAlpha':
  19654. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19655. break;
  19656. case 'mapAlphaRepeat':
  19657. case 'mapAlphaOffset':
  19658. case 'mapAlphaWrap':
  19659. case 'mapAlphaAnisotropy':
  19660. break;
  19661. case 'flipSided':
  19662. json.side = BackSide;
  19663. break;
  19664. case 'doubleSided':
  19665. json.side = DoubleSide;
  19666. break;
  19667. case 'transparency':
  19668. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19669. json.opacity = value;
  19670. break;
  19671. case 'depthTest':
  19672. case 'depthWrite':
  19673. case 'colorWrite':
  19674. case 'opacity':
  19675. case 'reflectivity':
  19676. case 'transparent':
  19677. case 'visible':
  19678. case 'wireframe':
  19679. json[ name ] = value;
  19680. break;
  19681. case 'vertexColors':
  19682. if ( value === true ) json.vertexColors = VertexColors;
  19683. if ( value === 'face' ) json.vertexColors = FaceColors;
  19684. break;
  19685. default:
  19686. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19687. break;
  19688. }
  19689. }
  19690. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19691. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19692. if ( json.opacity < 1 ) json.transparent = true;
  19693. materialLoader.setTextures( textures );
  19694. return materialLoader.parse( json );
  19695. };
  19696. } )()
  19697. } );
  19698. /**
  19699. * @author mrdoob / http://mrdoob.com/
  19700. * @author alteredq / http://alteredqualia.com/
  19701. */
  19702. function JSONLoader( manager ) {
  19703. if ( typeof manager === 'boolean' ) {
  19704. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19705. manager = undefined;
  19706. }
  19707. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19708. this.withCredentials = false;
  19709. }
  19710. Object.assign( JSONLoader.prototype, {
  19711. load: function ( url, onLoad, onProgress, onError ) {
  19712. var scope = this;
  19713. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19714. var loader = new FileLoader( this.manager );
  19715. loader.setResponseType( 'json' );
  19716. loader.setWithCredentials( this.withCredentials );
  19717. loader.load( url, function ( json ) {
  19718. var metadata = json.metadata;
  19719. if ( metadata !== undefined ) {
  19720. var type = metadata.type;
  19721. if ( type !== undefined ) {
  19722. if ( type.toLowerCase() === 'object' ) {
  19723. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19724. return;
  19725. }
  19726. if ( type.toLowerCase() === 'scene' ) {
  19727. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19728. return;
  19729. }
  19730. }
  19731. }
  19732. var object = scope.parse( json, texturePath );
  19733. onLoad( object.geometry, object.materials );
  19734. }, onProgress, onError );
  19735. },
  19736. setTexturePath: function ( value ) {
  19737. this.texturePath = value;
  19738. },
  19739. parse: ( function () {
  19740. function parseModel( json, geometry ) {
  19741. function isBitSet( value, position ) {
  19742. return value & ( 1 << position );
  19743. }
  19744. var i, j, fi,
  19745. offset, zLength,
  19746. colorIndex, normalIndex, uvIndex, materialIndex,
  19747. type,
  19748. isQuad,
  19749. hasMaterial,
  19750. hasFaceVertexUv,
  19751. hasFaceNormal, hasFaceVertexNormal,
  19752. hasFaceColor, hasFaceVertexColor,
  19753. vertex, face, faceA, faceB, hex, normal,
  19754. uvLayer, uv, u, v,
  19755. faces = json.faces,
  19756. vertices = json.vertices,
  19757. normals = json.normals,
  19758. colors = json.colors,
  19759. scale = json.scale,
  19760. nUvLayers = 0;
  19761. if ( json.uvs !== undefined ) {
  19762. // disregard empty arrays
  19763. for ( i = 0; i < json.uvs.length; i ++ ) {
  19764. if ( json.uvs[ i ].length ) nUvLayers ++;
  19765. }
  19766. for ( i = 0; i < nUvLayers; i ++ ) {
  19767. geometry.faceVertexUvs[ i ] = [];
  19768. }
  19769. }
  19770. offset = 0;
  19771. zLength = vertices.length;
  19772. while ( offset < zLength ) {
  19773. vertex = new Vector3();
  19774. vertex.x = vertices[ offset ++ ] * scale;
  19775. vertex.y = vertices[ offset ++ ] * scale;
  19776. vertex.z = vertices[ offset ++ ] * scale;
  19777. geometry.vertices.push( vertex );
  19778. }
  19779. offset = 0;
  19780. zLength = faces.length;
  19781. while ( offset < zLength ) {
  19782. type = faces[ offset ++ ];
  19783. isQuad = isBitSet( type, 0 );
  19784. hasMaterial = isBitSet( type, 1 );
  19785. hasFaceVertexUv = isBitSet( type, 3 );
  19786. hasFaceNormal = isBitSet( type, 4 );
  19787. hasFaceVertexNormal = isBitSet( type, 5 );
  19788. hasFaceColor = isBitSet( type, 6 );
  19789. hasFaceVertexColor = isBitSet( type, 7 );
  19790. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19791. if ( isQuad ) {
  19792. faceA = new Face3();
  19793. faceA.a = faces[ offset ];
  19794. faceA.b = faces[ offset + 1 ];
  19795. faceA.c = faces[ offset + 3 ];
  19796. faceB = new Face3();
  19797. faceB.a = faces[ offset + 1 ];
  19798. faceB.b = faces[ offset + 2 ];
  19799. faceB.c = faces[ offset + 3 ];
  19800. offset += 4;
  19801. if ( hasMaterial ) {
  19802. materialIndex = faces[ offset ++ ];
  19803. faceA.materialIndex = materialIndex;
  19804. faceB.materialIndex = materialIndex;
  19805. }
  19806. // to get face <=> uv index correspondence
  19807. fi = geometry.faces.length;
  19808. if ( hasFaceVertexUv ) {
  19809. for ( i = 0; i < nUvLayers; i ++ ) {
  19810. uvLayer = json.uvs[ i ];
  19811. geometry.faceVertexUvs[ i ][ fi ] = [];
  19812. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19813. for ( j = 0; j < 4; j ++ ) {
  19814. uvIndex = faces[ offset ++ ];
  19815. u = uvLayer[ uvIndex * 2 ];
  19816. v = uvLayer[ uvIndex * 2 + 1 ];
  19817. uv = new Vector2( u, v );
  19818. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19819. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19820. }
  19821. }
  19822. }
  19823. if ( hasFaceNormal ) {
  19824. normalIndex = faces[ offset ++ ] * 3;
  19825. faceA.normal.set(
  19826. normals[ normalIndex ++ ],
  19827. normals[ normalIndex ++ ],
  19828. normals[ normalIndex ]
  19829. );
  19830. faceB.normal.copy( faceA.normal );
  19831. }
  19832. if ( hasFaceVertexNormal ) {
  19833. for ( i = 0; i < 4; i ++ ) {
  19834. normalIndex = faces[ offset ++ ] * 3;
  19835. normal = new Vector3(
  19836. normals[ normalIndex ++ ],
  19837. normals[ normalIndex ++ ],
  19838. normals[ normalIndex ]
  19839. );
  19840. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19841. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19842. }
  19843. }
  19844. if ( hasFaceColor ) {
  19845. colorIndex = faces[ offset ++ ];
  19846. hex = colors[ colorIndex ];
  19847. faceA.color.setHex( hex );
  19848. faceB.color.setHex( hex );
  19849. }
  19850. if ( hasFaceVertexColor ) {
  19851. for ( i = 0; i < 4; i ++ ) {
  19852. colorIndex = faces[ offset ++ ];
  19853. hex = colors[ colorIndex ];
  19854. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19855. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19856. }
  19857. }
  19858. geometry.faces.push( faceA );
  19859. geometry.faces.push( faceB );
  19860. } else {
  19861. face = new Face3();
  19862. face.a = faces[ offset ++ ];
  19863. face.b = faces[ offset ++ ];
  19864. face.c = faces[ offset ++ ];
  19865. if ( hasMaterial ) {
  19866. materialIndex = faces[ offset ++ ];
  19867. face.materialIndex = materialIndex;
  19868. }
  19869. // to get face <=> uv index correspondence
  19870. fi = geometry.faces.length;
  19871. if ( hasFaceVertexUv ) {
  19872. for ( i = 0; i < nUvLayers; i ++ ) {
  19873. uvLayer = json.uvs[ i ];
  19874. geometry.faceVertexUvs[ i ][ fi ] = [];
  19875. for ( j = 0; j < 3; j ++ ) {
  19876. uvIndex = faces[ offset ++ ];
  19877. u = uvLayer[ uvIndex * 2 ];
  19878. v = uvLayer[ uvIndex * 2 + 1 ];
  19879. uv = new Vector2( u, v );
  19880. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19881. }
  19882. }
  19883. }
  19884. if ( hasFaceNormal ) {
  19885. normalIndex = faces[ offset ++ ] * 3;
  19886. face.normal.set(
  19887. normals[ normalIndex ++ ],
  19888. normals[ normalIndex ++ ],
  19889. normals[ normalIndex ]
  19890. );
  19891. }
  19892. if ( hasFaceVertexNormal ) {
  19893. for ( i = 0; i < 3; i ++ ) {
  19894. normalIndex = faces[ offset ++ ] * 3;
  19895. normal = new Vector3(
  19896. normals[ normalIndex ++ ],
  19897. normals[ normalIndex ++ ],
  19898. normals[ normalIndex ]
  19899. );
  19900. face.vertexNormals.push( normal );
  19901. }
  19902. }
  19903. if ( hasFaceColor ) {
  19904. colorIndex = faces[ offset ++ ];
  19905. face.color.setHex( colors[ colorIndex ] );
  19906. }
  19907. if ( hasFaceVertexColor ) {
  19908. for ( i = 0; i < 3; i ++ ) {
  19909. colorIndex = faces[ offset ++ ];
  19910. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19911. }
  19912. }
  19913. geometry.faces.push( face );
  19914. }
  19915. }
  19916. }
  19917. function parseSkin( json, geometry ) {
  19918. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19919. if ( json.skinWeights ) {
  19920. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19921. var x = json.skinWeights[ i ];
  19922. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19923. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19924. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19925. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19926. }
  19927. }
  19928. if ( json.skinIndices ) {
  19929. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19930. var a = json.skinIndices[ i ];
  19931. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19932. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19933. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19934. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19935. }
  19936. }
  19937. geometry.bones = json.bones;
  19938. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19939. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19940. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19941. }
  19942. }
  19943. function parseMorphing( json, geometry ) {
  19944. var scale = json.scale;
  19945. if ( json.morphTargets !== undefined ) {
  19946. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19947. geometry.morphTargets[ i ] = {};
  19948. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19949. geometry.morphTargets[ i ].vertices = [];
  19950. var dstVertices = geometry.morphTargets[ i ].vertices;
  19951. var srcVertices = json.morphTargets[ i ].vertices;
  19952. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19953. var vertex = new Vector3();
  19954. vertex.x = srcVertices[ v ] * scale;
  19955. vertex.y = srcVertices[ v + 1 ] * scale;
  19956. vertex.z = srcVertices[ v + 2 ] * scale;
  19957. dstVertices.push( vertex );
  19958. }
  19959. }
  19960. }
  19961. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19962. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19963. var faces = geometry.faces;
  19964. var morphColors = json.morphColors[ 0 ].colors;
  19965. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19966. faces[ i ].color.fromArray( morphColors, i * 3 );
  19967. }
  19968. }
  19969. }
  19970. function parseAnimations( json, geometry ) {
  19971. var outputAnimations = [];
  19972. // parse old style Bone/Hierarchy animations
  19973. var animations = [];
  19974. if ( json.animation !== undefined ) {
  19975. animations.push( json.animation );
  19976. }
  19977. if ( json.animations !== undefined ) {
  19978. if ( json.animations.length ) {
  19979. animations = animations.concat( json.animations );
  19980. } else {
  19981. animations.push( json.animations );
  19982. }
  19983. }
  19984. for ( var i = 0; i < animations.length; i ++ ) {
  19985. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  19986. if ( clip ) outputAnimations.push( clip );
  19987. }
  19988. // parse implicit morph animations
  19989. if ( geometry.morphTargets ) {
  19990. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  19991. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  19992. outputAnimations = outputAnimations.concat( morphAnimationClips );
  19993. }
  19994. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  19995. }
  19996. return function ( json, texturePath ) {
  19997. if ( json.data !== undefined ) {
  19998. // Geometry 4.0 spec
  19999. json = json.data;
  20000. }
  20001. if ( json.scale !== undefined ) {
  20002. json.scale = 1.0 / json.scale;
  20003. } else {
  20004. json.scale = 1.0;
  20005. }
  20006. var geometry = new Geometry();
  20007. parseModel( json, geometry );
  20008. parseSkin( json, geometry );
  20009. parseMorphing( json, geometry );
  20010. parseAnimations( json, geometry );
  20011. geometry.computeFaceNormals();
  20012. geometry.computeBoundingSphere();
  20013. if ( json.materials === undefined || json.materials.length === 0 ) {
  20014. return { geometry: geometry };
  20015. } else {
  20016. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  20017. return { geometry: geometry, materials: materials };
  20018. }
  20019. };
  20020. } )()
  20021. } );
  20022. /**
  20023. * @author mrdoob / http://mrdoob.com/
  20024. */
  20025. function ObjectLoader( manager ) {
  20026. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20027. this.texturePath = '';
  20028. }
  20029. Object.assign( ObjectLoader.prototype, {
  20030. load: function ( url, onLoad, onProgress, onError ) {
  20031. if ( this.texturePath === '' ) {
  20032. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  20033. }
  20034. var scope = this;
  20035. var loader = new FileLoader( scope.manager );
  20036. loader.load( url, function ( text ) {
  20037. var json = null;
  20038. try {
  20039. json = JSON.parse( text );
  20040. } catch ( error ) {
  20041. if ( onError !== undefined ) onError( error );
  20042. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  20043. return;
  20044. }
  20045. var metadata = json.metadata;
  20046. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  20047. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  20048. return;
  20049. }
  20050. scope.parse( json, onLoad );
  20051. }, onProgress, onError );
  20052. },
  20053. setTexturePath: function ( value ) {
  20054. this.texturePath = value;
  20055. },
  20056. setCrossOrigin: function ( value ) {
  20057. this.crossOrigin = value;
  20058. },
  20059. parse: function ( json, onLoad ) {
  20060. var geometries = this.parseGeometries( json.geometries );
  20061. var images = this.parseImages( json.images, function () {
  20062. if ( onLoad !== undefined ) onLoad( object );
  20063. } );
  20064. var textures = this.parseTextures( json.textures, images );
  20065. var materials = this.parseMaterials( json.materials, textures );
  20066. var object = this.parseObject( json.object, geometries, materials );
  20067. if ( json.animations ) {
  20068. object.animations = this.parseAnimations( json.animations );
  20069. }
  20070. if ( json.images === undefined || json.images.length === 0 ) {
  20071. if ( onLoad !== undefined ) onLoad( object );
  20072. }
  20073. return object;
  20074. },
  20075. parseGeometries: function ( json ) {
  20076. var geometries = {};
  20077. if ( json !== undefined ) {
  20078. var geometryLoader = new JSONLoader();
  20079. var bufferGeometryLoader = new BufferGeometryLoader();
  20080. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20081. var geometry;
  20082. var data = json[ i ];
  20083. switch ( data.type ) {
  20084. case 'PlaneGeometry':
  20085. case 'PlaneBufferGeometry':
  20086. geometry = new Geometries[ data.type ](
  20087. data.width,
  20088. data.height,
  20089. data.widthSegments,
  20090. data.heightSegments
  20091. );
  20092. break;
  20093. case 'BoxGeometry':
  20094. case 'BoxBufferGeometry':
  20095. case 'CubeGeometry': // backwards compatible
  20096. geometry = new Geometries[ data.type ](
  20097. data.width,
  20098. data.height,
  20099. data.depth,
  20100. data.widthSegments,
  20101. data.heightSegments,
  20102. data.depthSegments
  20103. );
  20104. break;
  20105. case 'CircleGeometry':
  20106. case 'CircleBufferGeometry':
  20107. geometry = new Geometries[ data.type ](
  20108. data.radius,
  20109. data.segments,
  20110. data.thetaStart,
  20111. data.thetaLength
  20112. );
  20113. break;
  20114. case 'CylinderGeometry':
  20115. case 'CylinderBufferGeometry':
  20116. geometry = new Geometries[ data.type ](
  20117. data.radiusTop,
  20118. data.radiusBottom,
  20119. data.height,
  20120. data.radialSegments,
  20121. data.heightSegments,
  20122. data.openEnded,
  20123. data.thetaStart,
  20124. data.thetaLength
  20125. );
  20126. break;
  20127. case 'ConeGeometry':
  20128. case 'ConeBufferGeometry':
  20129. geometry = new Geometries[ data.type ](
  20130. data.radius,
  20131. data.height,
  20132. data.radialSegments,
  20133. data.heightSegments,
  20134. data.openEnded,
  20135. data.thetaStart,
  20136. data.thetaLength
  20137. );
  20138. break;
  20139. case 'SphereGeometry':
  20140. case 'SphereBufferGeometry':
  20141. geometry = new Geometries[ data.type ](
  20142. data.radius,
  20143. data.widthSegments,
  20144. data.heightSegments,
  20145. data.phiStart,
  20146. data.phiLength,
  20147. data.thetaStart,
  20148. data.thetaLength
  20149. );
  20150. break;
  20151. case 'DodecahedronGeometry':
  20152. case 'IcosahedronGeometry':
  20153. case 'OctahedronGeometry':
  20154. case 'TetrahedronGeometry':
  20155. geometry = new Geometries[ data.type ](
  20156. data.radius,
  20157. data.detail
  20158. );
  20159. break;
  20160. case 'RingGeometry':
  20161. case 'RingBufferGeometry':
  20162. geometry = new Geometries[ data.type ](
  20163. data.innerRadius,
  20164. data.outerRadius,
  20165. data.thetaSegments,
  20166. data.phiSegments,
  20167. data.thetaStart,
  20168. data.thetaLength
  20169. );
  20170. break;
  20171. case 'TorusGeometry':
  20172. case 'TorusBufferGeometry':
  20173. geometry = new Geometries[ data.type ](
  20174. data.radius,
  20175. data.tube,
  20176. data.radialSegments,
  20177. data.tubularSegments,
  20178. data.arc
  20179. );
  20180. break;
  20181. case 'TorusKnotGeometry':
  20182. case 'TorusKnotBufferGeometry':
  20183. geometry = new Geometries[ data.type ](
  20184. data.radius,
  20185. data.tube,
  20186. data.tubularSegments,
  20187. data.radialSegments,
  20188. data.p,
  20189. data.q
  20190. );
  20191. break;
  20192. case 'LatheGeometry':
  20193. case 'LatheBufferGeometry':
  20194. geometry = new Geometries[ data.type ](
  20195. data.points,
  20196. data.segments,
  20197. data.phiStart,
  20198. data.phiLength
  20199. );
  20200. break;
  20201. case 'BufferGeometry':
  20202. geometry = bufferGeometryLoader.parse( data );
  20203. break;
  20204. case 'Geometry':
  20205. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  20206. break;
  20207. default:
  20208. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20209. continue;
  20210. }
  20211. geometry.uuid = data.uuid;
  20212. if ( data.name !== undefined ) geometry.name = data.name;
  20213. geometries[ data.uuid ] = geometry;
  20214. }
  20215. }
  20216. return geometries;
  20217. },
  20218. parseMaterials: function ( json, textures ) {
  20219. var materials = {};
  20220. if ( json !== undefined ) {
  20221. var loader = new MaterialLoader();
  20222. loader.setTextures( textures );
  20223. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20224. var material = loader.parse( json[ i ] );
  20225. materials[ material.uuid ] = material;
  20226. }
  20227. }
  20228. return materials;
  20229. },
  20230. parseAnimations: function ( json ) {
  20231. var animations = [];
  20232. for ( var i = 0; i < json.length; i ++ ) {
  20233. var clip = AnimationClip.parse( json[ i ] );
  20234. animations.push( clip );
  20235. }
  20236. return animations;
  20237. },
  20238. parseImages: function ( json, onLoad ) {
  20239. var scope = this;
  20240. var images = {};
  20241. function loadImage( url ) {
  20242. scope.manager.itemStart( url );
  20243. return loader.load( url, function () {
  20244. scope.manager.itemEnd( url );
  20245. }, undefined, function () {
  20246. scope.manager.itemEnd( url );
  20247. scope.manager.itemError( url );
  20248. } );
  20249. }
  20250. if ( json !== undefined && json.length > 0 ) {
  20251. var manager = new LoadingManager( onLoad );
  20252. var loader = new ImageLoader( manager );
  20253. loader.setCrossOrigin( this.crossOrigin );
  20254. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20255. var image = json[ i ];
  20256. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20257. images[ image.uuid ] = loadImage( path );
  20258. }
  20259. }
  20260. return images;
  20261. },
  20262. parseTextures: function ( json, images ) {
  20263. function parseConstant( value, type ) {
  20264. if ( typeof( value ) === 'number' ) return value;
  20265. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20266. return type[ value ];
  20267. }
  20268. var textures = {};
  20269. if ( json !== undefined ) {
  20270. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20271. var data = json[ i ];
  20272. if ( data.image === undefined ) {
  20273. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20274. }
  20275. if ( images[ data.image ] === undefined ) {
  20276. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20277. }
  20278. var texture = new Texture( images[ data.image ] );
  20279. texture.needsUpdate = true;
  20280. texture.uuid = data.uuid;
  20281. if ( data.name !== undefined ) texture.name = data.name;
  20282. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  20283. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20284. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20285. if ( data.wrap !== undefined ) {
  20286. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  20287. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  20288. }
  20289. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  20290. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  20291. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20292. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20293. textures[ data.uuid ] = texture;
  20294. }
  20295. }
  20296. return textures;
  20297. },
  20298. parseObject: function () {
  20299. var matrix = new Matrix4();
  20300. return function parseObject( data, geometries, materials ) {
  20301. var object;
  20302. function getGeometry( name ) {
  20303. if ( geometries[ name ] === undefined ) {
  20304. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20305. }
  20306. return geometries[ name ];
  20307. }
  20308. function getMaterial( name ) {
  20309. if ( name === undefined ) return undefined;
  20310. if ( Array.isArray( name ) ) {
  20311. var array = [];
  20312. for ( var i = 0, l = name.length; i < l; i ++ ) {
  20313. var uuid = name[ i ];
  20314. if ( materials[ uuid ] === undefined ) {
  20315. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  20316. }
  20317. array.push( materials[ uuid ] );
  20318. }
  20319. return array;
  20320. }
  20321. if ( materials[ name ] === undefined ) {
  20322. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20323. }
  20324. return materials[ name ];
  20325. }
  20326. switch ( data.type ) {
  20327. case 'Scene':
  20328. object = new Scene();
  20329. if ( data.background !== undefined ) {
  20330. if ( Number.isInteger( data.background ) ) {
  20331. object.background = new Color( data.background );
  20332. }
  20333. }
  20334. if ( data.fog !== undefined ) {
  20335. if ( data.fog.type === 'Fog' ) {
  20336. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20337. } else if ( data.fog.type === 'FogExp2' ) {
  20338. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20339. }
  20340. }
  20341. break;
  20342. case 'PerspectiveCamera':
  20343. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20344. if ( data.focus !== undefined ) object.focus = data.focus;
  20345. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20346. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20347. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20348. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20349. break;
  20350. case 'OrthographicCamera':
  20351. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20352. break;
  20353. case 'AmbientLight':
  20354. object = new AmbientLight( data.color, data.intensity );
  20355. break;
  20356. case 'DirectionalLight':
  20357. object = new DirectionalLight( data.color, data.intensity );
  20358. break;
  20359. case 'PointLight':
  20360. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20361. break;
  20362. case 'RectAreaLight':
  20363. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  20364. break;
  20365. case 'SpotLight':
  20366. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20367. break;
  20368. case 'HemisphereLight':
  20369. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20370. break;
  20371. case 'SkinnedMesh':
  20372. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  20373. case 'Mesh':
  20374. var geometry = getGeometry( data.geometry );
  20375. var material = getMaterial( data.material );
  20376. if ( geometry.bones && geometry.bones.length > 0 ) {
  20377. object = new SkinnedMesh( geometry, material );
  20378. } else {
  20379. object = new Mesh( geometry, material );
  20380. }
  20381. break;
  20382. case 'LOD':
  20383. object = new LOD();
  20384. break;
  20385. case 'Line':
  20386. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20387. break;
  20388. case 'LineLoop':
  20389. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  20390. break;
  20391. case 'LineSegments':
  20392. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20393. break;
  20394. case 'PointCloud':
  20395. case 'Points':
  20396. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20397. break;
  20398. case 'Sprite':
  20399. object = new Sprite( getMaterial( data.material ) );
  20400. break;
  20401. case 'Group':
  20402. object = new Group();
  20403. break;
  20404. default:
  20405. object = new Object3D();
  20406. }
  20407. object.uuid = data.uuid;
  20408. if ( data.name !== undefined ) object.name = data.name;
  20409. if ( data.matrix !== undefined ) {
  20410. matrix.fromArray( data.matrix );
  20411. matrix.decompose( object.position, object.quaternion, object.scale );
  20412. } else {
  20413. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20414. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20415. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20416. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20417. }
  20418. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20419. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20420. if ( data.shadow ) {
  20421. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20422. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20423. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20424. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20425. }
  20426. if ( data.visible !== undefined ) object.visible = data.visible;
  20427. if ( data.userData !== undefined ) object.userData = data.userData;
  20428. if ( data.children !== undefined ) {
  20429. for ( var child in data.children ) {
  20430. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20431. }
  20432. }
  20433. if ( data.type === 'LOD' ) {
  20434. var levels = data.levels;
  20435. for ( var l = 0; l < levels.length; l ++ ) {
  20436. var level = levels[ l ];
  20437. var child = object.getObjectByProperty( 'uuid', level.object );
  20438. if ( child !== undefined ) {
  20439. object.addLevel( child, level.distance );
  20440. }
  20441. }
  20442. }
  20443. return object;
  20444. };
  20445. }()
  20446. } );
  20447. var TEXTURE_MAPPING = {
  20448. UVMapping: UVMapping,
  20449. CubeReflectionMapping: CubeReflectionMapping,
  20450. CubeRefractionMapping: CubeRefractionMapping,
  20451. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20452. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20453. SphericalReflectionMapping: SphericalReflectionMapping,
  20454. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20455. CubeUVRefractionMapping: CubeUVRefractionMapping
  20456. };
  20457. var TEXTURE_WRAPPING = {
  20458. RepeatWrapping: RepeatWrapping,
  20459. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20460. MirroredRepeatWrapping: MirroredRepeatWrapping
  20461. };
  20462. var TEXTURE_FILTER = {
  20463. NearestFilter: NearestFilter,
  20464. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20465. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20466. LinearFilter: LinearFilter,
  20467. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20468. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20469. };
  20470. /**
  20471. * @author zz85 / http://www.lab4games.net/zz85/blog
  20472. *
  20473. * Bezier Curves formulas obtained from
  20474. * http://en.wikipedia.org/wiki/Bézier_curve
  20475. */
  20476. function CatmullRom( t, p0, p1, p2, p3 ) {
  20477. var v0 = ( p2 - p0 ) * 0.5;
  20478. var v1 = ( p3 - p1 ) * 0.5;
  20479. var t2 = t * t;
  20480. var t3 = t * t2;
  20481. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20482. }
  20483. //
  20484. function QuadraticBezierP0( t, p ) {
  20485. var k = 1 - t;
  20486. return k * k * p;
  20487. }
  20488. function QuadraticBezierP1( t, p ) {
  20489. return 2 * ( 1 - t ) * t * p;
  20490. }
  20491. function QuadraticBezierP2( t, p ) {
  20492. return t * t * p;
  20493. }
  20494. function QuadraticBezier( t, p0, p1, p2 ) {
  20495. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20496. QuadraticBezierP2( t, p2 );
  20497. }
  20498. //
  20499. function CubicBezierP0( t, p ) {
  20500. var k = 1 - t;
  20501. return k * k * k * p;
  20502. }
  20503. function CubicBezierP1( t, p ) {
  20504. var k = 1 - t;
  20505. return 3 * k * k * t * p;
  20506. }
  20507. function CubicBezierP2( t, p ) {
  20508. return 3 * ( 1 - t ) * t * t * p;
  20509. }
  20510. function CubicBezierP3( t, p ) {
  20511. return t * t * t * p;
  20512. }
  20513. function CubicBezier( t, p0, p1, p2, p3 ) {
  20514. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20515. CubicBezierP3( t, p3 );
  20516. }
  20517. /**
  20518. * @author zz85 / http://www.lab4games.net/zz85/blog
  20519. * Extensible curve object
  20520. *
  20521. * Some common of curve methods:
  20522. * .getPoint(t), getTangent(t)
  20523. * .getPointAt(u), getTangentAt(u)
  20524. * .getPoints(), .getSpacedPoints()
  20525. * .getLength()
  20526. * .updateArcLengths()
  20527. *
  20528. * This following curves inherit from THREE.Curve:
  20529. *
  20530. * -- 2D curves --
  20531. * THREE.ArcCurve
  20532. * THREE.CubicBezierCurve
  20533. * THREE.EllipseCurve
  20534. * THREE.LineCurve
  20535. * THREE.QuadraticBezierCurve
  20536. * THREE.SplineCurve
  20537. *
  20538. * -- 3D curves --
  20539. * THREE.CatmullRomCurve3
  20540. * THREE.CubicBezierCurve3
  20541. * THREE.LineCurve3
  20542. * THREE.QuadraticBezierCurve3
  20543. *
  20544. * A series of curves can be represented as a THREE.CurvePath.
  20545. *
  20546. **/
  20547. /**************************************************************
  20548. * Abstract Curve base class
  20549. **************************************************************/
  20550. function Curve() {
  20551. this.arcLengthDivisions = 200;
  20552. }
  20553. Object.assign( Curve.prototype, {
  20554. // Virtual base class method to overwrite and implement in subclasses
  20555. // - t [0 .. 1]
  20556. getPoint: function () {
  20557. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20558. return null;
  20559. },
  20560. // Get point at relative position in curve according to arc length
  20561. // - u [0 .. 1]
  20562. getPointAt: function ( u ) {
  20563. var t = this.getUtoTmapping( u );
  20564. return this.getPoint( t );
  20565. },
  20566. // Get sequence of points using getPoint( t )
  20567. getPoints: function ( divisions ) {
  20568. if ( divisions === undefined ) divisions = 5;
  20569. var points = [];
  20570. for ( var d = 0; d <= divisions; d ++ ) {
  20571. points.push( this.getPoint( d / divisions ) );
  20572. }
  20573. return points;
  20574. },
  20575. // Get sequence of points using getPointAt( u )
  20576. getSpacedPoints: function ( divisions ) {
  20577. if ( divisions === undefined ) divisions = 5;
  20578. var points = [];
  20579. for ( var d = 0; d <= divisions; d ++ ) {
  20580. points.push( this.getPointAt( d / divisions ) );
  20581. }
  20582. return points;
  20583. },
  20584. // Get total curve arc length
  20585. getLength: function () {
  20586. var lengths = this.getLengths();
  20587. return lengths[ lengths.length - 1 ];
  20588. },
  20589. // Get list of cumulative segment lengths
  20590. getLengths: function ( divisions ) {
  20591. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20592. if ( this.cacheArcLengths &&
  20593. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20594. ! this.needsUpdate ) {
  20595. return this.cacheArcLengths;
  20596. }
  20597. this.needsUpdate = false;
  20598. var cache = [];
  20599. var current, last = this.getPoint( 0 );
  20600. var p, sum = 0;
  20601. cache.push( 0 );
  20602. for ( p = 1; p <= divisions; p ++ ) {
  20603. current = this.getPoint( p / divisions );
  20604. sum += current.distanceTo( last );
  20605. cache.push( sum );
  20606. last = current;
  20607. }
  20608. this.cacheArcLengths = cache;
  20609. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20610. },
  20611. updateArcLengths: function () {
  20612. this.needsUpdate = true;
  20613. this.getLengths();
  20614. },
  20615. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20616. getUtoTmapping: function ( u, distance ) {
  20617. var arcLengths = this.getLengths();
  20618. var i = 0, il = arcLengths.length;
  20619. var targetArcLength; // The targeted u distance value to get
  20620. if ( distance ) {
  20621. targetArcLength = distance;
  20622. } else {
  20623. targetArcLength = u * arcLengths[ il - 1 ];
  20624. }
  20625. // binary search for the index with largest value smaller than target u distance
  20626. var low = 0, high = il - 1, comparison;
  20627. while ( low <= high ) {
  20628. 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
  20629. comparison = arcLengths[ i ] - targetArcLength;
  20630. if ( comparison < 0 ) {
  20631. low = i + 1;
  20632. } else if ( comparison > 0 ) {
  20633. high = i - 1;
  20634. } else {
  20635. high = i;
  20636. break;
  20637. // DONE
  20638. }
  20639. }
  20640. i = high;
  20641. if ( arcLengths[ i ] === targetArcLength ) {
  20642. return i / ( il - 1 );
  20643. }
  20644. // we could get finer grain at lengths, or use simple interpolation between two points
  20645. var lengthBefore = arcLengths[ i ];
  20646. var lengthAfter = arcLengths[ i + 1 ];
  20647. var segmentLength = lengthAfter - lengthBefore;
  20648. // determine where we are between the 'before' and 'after' points
  20649. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20650. // add that fractional amount to t
  20651. var t = ( i + segmentFraction ) / ( il - 1 );
  20652. return t;
  20653. },
  20654. // Returns a unit vector tangent at t
  20655. // In case any sub curve does not implement its tangent derivation,
  20656. // 2 points a small delta apart will be used to find its gradient
  20657. // which seems to give a reasonable approximation
  20658. getTangent: function ( t ) {
  20659. var delta = 0.0001;
  20660. var t1 = t - delta;
  20661. var t2 = t + delta;
  20662. // Capping in case of danger
  20663. if ( t1 < 0 ) t1 = 0;
  20664. if ( t2 > 1 ) t2 = 1;
  20665. var pt1 = this.getPoint( t1 );
  20666. var pt2 = this.getPoint( t2 );
  20667. var vec = pt2.clone().sub( pt1 );
  20668. return vec.normalize();
  20669. },
  20670. getTangentAt: function ( u ) {
  20671. var t = this.getUtoTmapping( u );
  20672. return this.getTangent( t );
  20673. },
  20674. computeFrenetFrames: function ( segments, closed ) {
  20675. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20676. var normal = new Vector3();
  20677. var tangents = [];
  20678. var normals = [];
  20679. var binormals = [];
  20680. var vec = new Vector3();
  20681. var mat = new Matrix4();
  20682. var i, u, theta;
  20683. // compute the tangent vectors for each segment on the curve
  20684. for ( i = 0; i <= segments; i ++ ) {
  20685. u = i / segments;
  20686. tangents[ i ] = this.getTangentAt( u );
  20687. tangents[ i ].normalize();
  20688. }
  20689. // select an initial normal vector perpendicular to the first tangent vector,
  20690. // and in the direction of the minimum tangent xyz component
  20691. normals[ 0 ] = new Vector3();
  20692. binormals[ 0 ] = new Vector3();
  20693. var min = Number.MAX_VALUE;
  20694. var tx = Math.abs( tangents[ 0 ].x );
  20695. var ty = Math.abs( tangents[ 0 ].y );
  20696. var tz = Math.abs( tangents[ 0 ].z );
  20697. if ( tx <= min ) {
  20698. min = tx;
  20699. normal.set( 1, 0, 0 );
  20700. }
  20701. if ( ty <= min ) {
  20702. min = ty;
  20703. normal.set( 0, 1, 0 );
  20704. }
  20705. if ( tz <= min ) {
  20706. normal.set( 0, 0, 1 );
  20707. }
  20708. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20709. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20710. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20711. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20712. for ( i = 1; i <= segments; i ++ ) {
  20713. normals[ i ] = normals[ i - 1 ].clone();
  20714. binormals[ i ] = binormals[ i - 1 ].clone();
  20715. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20716. if ( vec.length() > Number.EPSILON ) {
  20717. vec.normalize();
  20718. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20719. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20720. }
  20721. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20722. }
  20723. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20724. if ( closed === true ) {
  20725. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20726. theta /= segments;
  20727. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20728. theta = - theta;
  20729. }
  20730. for ( i = 1; i <= segments; i ++ ) {
  20731. // twist a little...
  20732. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20733. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20734. }
  20735. }
  20736. return {
  20737. tangents: tangents,
  20738. normals: normals,
  20739. binormals: binormals
  20740. };
  20741. }
  20742. } );
  20743. function LineCurve( v1, v2 ) {
  20744. Curve.call( this );
  20745. this.v1 = v1;
  20746. this.v2 = v2;
  20747. }
  20748. LineCurve.prototype = Object.create( Curve.prototype );
  20749. LineCurve.prototype.constructor = LineCurve;
  20750. LineCurve.prototype.isLineCurve = true;
  20751. LineCurve.prototype.getPoint = function ( t ) {
  20752. if ( t === 1 ) {
  20753. return this.v2.clone();
  20754. }
  20755. var point = this.v2.clone().sub( this.v1 );
  20756. point.multiplyScalar( t ).add( this.v1 );
  20757. return point;
  20758. };
  20759. // Line curve is linear, so we can overwrite default getPointAt
  20760. LineCurve.prototype.getPointAt = function ( u ) {
  20761. return this.getPoint( u );
  20762. };
  20763. LineCurve.prototype.getTangent = function ( t ) {
  20764. var tangent = this.v2.clone().sub( this.v1 );
  20765. return tangent.normalize();
  20766. };
  20767. /**
  20768. * @author zz85 / http://www.lab4games.net/zz85/blog
  20769. *
  20770. **/
  20771. /**************************************************************
  20772. * Curved Path - a curve path is simply a array of connected
  20773. * curves, but retains the api of a curve
  20774. **************************************************************/
  20775. function CurvePath() {
  20776. Curve.call( this );
  20777. this.curves = [];
  20778. this.autoClose = false; // Automatically closes the path
  20779. }
  20780. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20781. constructor: CurvePath,
  20782. add: function ( curve ) {
  20783. this.curves.push( curve );
  20784. },
  20785. closePath: function () {
  20786. // Add a line curve if start and end of lines are not connected
  20787. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20788. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20789. if ( ! startPoint.equals( endPoint ) ) {
  20790. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20791. }
  20792. },
  20793. // To get accurate point with reference to
  20794. // entire path distance at time t,
  20795. // following has to be done:
  20796. // 1. Length of each sub path have to be known
  20797. // 2. Locate and identify type of curve
  20798. // 3. Get t for the curve
  20799. // 4. Return curve.getPointAt(t')
  20800. getPoint: function ( t ) {
  20801. var d = t * this.getLength();
  20802. var curveLengths = this.getCurveLengths();
  20803. var i = 0;
  20804. // To think about boundaries points.
  20805. while ( i < curveLengths.length ) {
  20806. if ( curveLengths[ i ] >= d ) {
  20807. var diff = curveLengths[ i ] - d;
  20808. var curve = this.curves[ i ];
  20809. var segmentLength = curve.getLength();
  20810. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20811. return curve.getPointAt( u );
  20812. }
  20813. i ++;
  20814. }
  20815. return null;
  20816. // loop where sum != 0, sum > d , sum+1 <d
  20817. },
  20818. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20819. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20820. // getPoint() depends on getLength
  20821. getLength: function () {
  20822. var lens = this.getCurveLengths();
  20823. return lens[ lens.length - 1 ];
  20824. },
  20825. // cacheLengths must be recalculated.
  20826. updateArcLengths: function () {
  20827. this.needsUpdate = true;
  20828. this.cacheLengths = null;
  20829. this.getCurveLengths();
  20830. },
  20831. // Compute lengths and cache them
  20832. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20833. getCurveLengths: function () {
  20834. // We use cache values if curves and cache array are same length
  20835. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20836. return this.cacheLengths;
  20837. }
  20838. // Get length of sub-curve
  20839. // Push sums into cached array
  20840. var lengths = [], sums = 0;
  20841. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20842. sums += this.curves[ i ].getLength();
  20843. lengths.push( sums );
  20844. }
  20845. this.cacheLengths = lengths;
  20846. return lengths;
  20847. },
  20848. getSpacedPoints: function ( divisions ) {
  20849. if ( divisions === undefined ) divisions = 40;
  20850. var points = [];
  20851. for ( var i = 0; i <= divisions; i ++ ) {
  20852. points.push( this.getPoint( i / divisions ) );
  20853. }
  20854. if ( this.autoClose ) {
  20855. points.push( points[ 0 ] );
  20856. }
  20857. return points;
  20858. },
  20859. getPoints: function ( divisions ) {
  20860. divisions = divisions || 12;
  20861. var points = [], last;
  20862. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20863. var curve = curves[ i ];
  20864. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20865. : (curve && curve.isLineCurve) ? 1
  20866. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20867. : divisions;
  20868. var pts = curve.getPoints( resolution );
  20869. for ( var j = 0; j < pts.length; j++ ) {
  20870. var point = pts[ j ];
  20871. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20872. points.push( point );
  20873. last = point;
  20874. }
  20875. }
  20876. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20877. points.push( points[ 0 ] );
  20878. }
  20879. return points;
  20880. },
  20881. /**************************************************************
  20882. * Create Geometries Helpers
  20883. **************************************************************/
  20884. /// Generate geometry from path points (for Line or Points objects)
  20885. createPointsGeometry: function ( divisions ) {
  20886. var pts = this.getPoints( divisions );
  20887. return this.createGeometry( pts );
  20888. },
  20889. // Generate geometry from equidistant sampling along the path
  20890. createSpacedPointsGeometry: function ( divisions ) {
  20891. var pts = this.getSpacedPoints( divisions );
  20892. return this.createGeometry( pts );
  20893. },
  20894. createGeometry: function ( points ) {
  20895. var geometry = new Geometry();
  20896. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20897. var point = points[ i ];
  20898. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20899. }
  20900. return geometry;
  20901. }
  20902. } );
  20903. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20904. Curve.call( this );
  20905. this.aX = aX;
  20906. this.aY = aY;
  20907. this.xRadius = xRadius;
  20908. this.yRadius = yRadius;
  20909. this.aStartAngle = aStartAngle;
  20910. this.aEndAngle = aEndAngle;
  20911. this.aClockwise = aClockwise;
  20912. this.aRotation = aRotation || 0;
  20913. }
  20914. EllipseCurve.prototype = Object.create( Curve.prototype );
  20915. EllipseCurve.prototype.constructor = EllipseCurve;
  20916. EllipseCurve.prototype.isEllipseCurve = true;
  20917. EllipseCurve.prototype.getPoint = function ( t ) {
  20918. var twoPi = Math.PI * 2;
  20919. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20920. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20921. // ensures that deltaAngle is 0 .. 2 PI
  20922. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20923. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20924. if ( deltaAngle < Number.EPSILON ) {
  20925. if ( samePoints ) {
  20926. deltaAngle = 0;
  20927. } else {
  20928. deltaAngle = twoPi;
  20929. }
  20930. }
  20931. if ( this.aClockwise === true && ! samePoints ) {
  20932. if ( deltaAngle === twoPi ) {
  20933. deltaAngle = - twoPi;
  20934. } else {
  20935. deltaAngle = deltaAngle - twoPi;
  20936. }
  20937. }
  20938. var angle = this.aStartAngle + t * deltaAngle;
  20939. var x = this.aX + this.xRadius * Math.cos( angle );
  20940. var y = this.aY + this.yRadius * Math.sin( angle );
  20941. if ( this.aRotation !== 0 ) {
  20942. var cos = Math.cos( this.aRotation );
  20943. var sin = Math.sin( this.aRotation );
  20944. var tx = x - this.aX;
  20945. var ty = y - this.aY;
  20946. // Rotate the point about the center of the ellipse.
  20947. x = tx * cos - ty * sin + this.aX;
  20948. y = tx * sin + ty * cos + this.aY;
  20949. }
  20950. return new Vector2( x, y );
  20951. };
  20952. function SplineCurve( points /* array of Vector2 */ ) {
  20953. Curve.call( this );
  20954. this.points = ( points === undefined ) ? [] : points;
  20955. }
  20956. SplineCurve.prototype = Object.create( Curve.prototype );
  20957. SplineCurve.prototype.constructor = SplineCurve;
  20958. SplineCurve.prototype.isSplineCurve = true;
  20959. SplineCurve.prototype.getPoint = function ( t ) {
  20960. var points = this.points;
  20961. var point = ( points.length - 1 ) * t;
  20962. var intPoint = Math.floor( point );
  20963. var weight = point - intPoint;
  20964. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20965. var point1 = points[ intPoint ];
  20966. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20967. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20968. return new Vector2(
  20969. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  20970. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  20971. );
  20972. };
  20973. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20974. Curve.call( this );
  20975. this.v0 = v0;
  20976. this.v1 = v1;
  20977. this.v2 = v2;
  20978. this.v3 = v3;
  20979. }
  20980. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20981. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20982. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20983. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20984. return new Vector2(
  20985. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20986. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  20987. );
  20988. };
  20989. function QuadraticBezierCurve( v0, v1, v2 ) {
  20990. Curve.call( this );
  20991. this.v0 = v0;
  20992. this.v1 = v1;
  20993. this.v2 = v2;
  20994. }
  20995. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20996. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20997. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20998. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20999. return new Vector2(
  21000. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21001. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21002. );
  21003. };
  21004. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  21005. fromPoints: function ( vectors ) {
  21006. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  21007. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  21008. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  21009. }
  21010. },
  21011. moveTo: function ( x, y ) {
  21012. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21013. },
  21014. lineTo: function ( x, y ) {
  21015. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21016. this.curves.push( curve );
  21017. this.currentPoint.set( x, y );
  21018. },
  21019. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21020. var curve = new QuadraticBezierCurve(
  21021. this.currentPoint.clone(),
  21022. new Vector2( aCPx, aCPy ),
  21023. new Vector2( aX, aY )
  21024. );
  21025. this.curves.push( curve );
  21026. this.currentPoint.set( aX, aY );
  21027. },
  21028. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21029. var curve = new CubicBezierCurve(
  21030. this.currentPoint.clone(),
  21031. new Vector2( aCP1x, aCP1y ),
  21032. new Vector2( aCP2x, aCP2y ),
  21033. new Vector2( aX, aY )
  21034. );
  21035. this.curves.push( curve );
  21036. this.currentPoint.set( aX, aY );
  21037. },
  21038. splineThru: function ( pts /*Array of Vector*/ ) {
  21039. var npts = [ this.currentPoint.clone() ].concat( pts );
  21040. var curve = new SplineCurve( npts );
  21041. this.curves.push( curve );
  21042. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21043. },
  21044. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21045. var x0 = this.currentPoint.x;
  21046. var y0 = this.currentPoint.y;
  21047. this.absarc( aX + x0, aY + y0, aRadius,
  21048. aStartAngle, aEndAngle, aClockwise );
  21049. },
  21050. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21051. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21052. },
  21053. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21054. var x0 = this.currentPoint.x;
  21055. var y0 = this.currentPoint.y;
  21056. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21057. },
  21058. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21059. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21060. if ( this.curves.length > 0 ) {
  21061. // if a previous curve is present, attempt to join
  21062. var firstPoint = curve.getPoint( 0 );
  21063. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21064. this.lineTo( firstPoint.x, firstPoint.y );
  21065. }
  21066. }
  21067. this.curves.push( curve );
  21068. var lastPoint = curve.getPoint( 1 );
  21069. this.currentPoint.copy( lastPoint );
  21070. }
  21071. } );
  21072. /**
  21073. * @author zz85 / http://www.lab4games.net/zz85/blog
  21074. * Creates free form 2d path using series of points, lines or curves.
  21075. **/
  21076. function Path( points ) {
  21077. CurvePath.call( this );
  21078. this.currentPoint = new Vector2();
  21079. if ( points ) {
  21080. this.fromPoints( points );
  21081. }
  21082. }
  21083. Path.prototype = PathPrototype;
  21084. PathPrototype.constructor = Path;
  21085. /**
  21086. * @author zz85 / http://www.lab4games.net/zz85/blog
  21087. * Defines a 2d shape plane using paths.
  21088. **/
  21089. // STEP 1 Create a path.
  21090. // STEP 2 Turn path into shape.
  21091. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21092. // STEP 3a - Extract points from each shape, turn to vertices
  21093. // STEP 3b - Triangulate each shape, add faces.
  21094. function Shape() {
  21095. Path.apply( this, arguments );
  21096. this.holes = [];
  21097. }
  21098. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  21099. constructor: Shape,
  21100. getPointsHoles: function ( divisions ) {
  21101. var holesPts = [];
  21102. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21103. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21104. }
  21105. return holesPts;
  21106. },
  21107. // Get points of shape and holes (keypoints based on segments parameter)
  21108. extractAllPoints: function ( divisions ) {
  21109. return {
  21110. shape: this.getPoints( divisions ),
  21111. holes: this.getPointsHoles( divisions )
  21112. };
  21113. },
  21114. extractPoints: function ( divisions ) {
  21115. return this.extractAllPoints( divisions );
  21116. }
  21117. } );
  21118. /**
  21119. * @author zz85 / http://www.lab4games.net/zz85/blog
  21120. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  21121. **/
  21122. function ShapePath() {
  21123. this.subPaths = [];
  21124. this.currentPath = null;
  21125. }
  21126. Object.assign( ShapePath.prototype, {
  21127. moveTo: function ( x, y ) {
  21128. this.currentPath = new Path();
  21129. this.subPaths.push( this.currentPath );
  21130. this.currentPath.moveTo( x, y );
  21131. },
  21132. lineTo: function ( x, y ) {
  21133. this.currentPath.lineTo( x, y );
  21134. },
  21135. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  21136. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21137. },
  21138. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21139. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21140. },
  21141. splineThru: function ( pts ) {
  21142. this.currentPath.splineThru( pts );
  21143. },
  21144. toShapes: function ( isCCW, noHoles ) {
  21145. function toShapesNoHoles( inSubpaths ) {
  21146. var shapes = [];
  21147. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21148. var tmpPath = inSubpaths[ i ];
  21149. var tmpShape = new Shape();
  21150. tmpShape.curves = tmpPath.curves;
  21151. shapes.push( tmpShape );
  21152. }
  21153. return shapes;
  21154. }
  21155. function isPointInsidePolygon( inPt, inPolygon ) {
  21156. var polyLen = inPolygon.length;
  21157. // inPt on polygon contour => immediate success or
  21158. // toggling of inside/outside at every single! intersection point of an edge
  21159. // with the horizontal line through inPt, left of inPt
  21160. // not counting lowerY endpoints of edges and whole edges on that line
  21161. var inside = false;
  21162. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21163. var edgeLowPt = inPolygon[ p ];
  21164. var edgeHighPt = inPolygon[ q ];
  21165. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21166. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21167. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21168. // not parallel
  21169. if ( edgeDy < 0 ) {
  21170. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21171. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21172. }
  21173. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21174. if ( inPt.y === edgeLowPt.y ) {
  21175. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21176. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21177. } else {
  21178. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21179. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21180. if ( perpEdge < 0 ) continue;
  21181. inside = ! inside; // true intersection left of inPt
  21182. }
  21183. } else {
  21184. // parallel or collinear
  21185. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21186. // edge lies on the same horizontal line as inPt
  21187. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21188. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21189. // continue;
  21190. }
  21191. }
  21192. return inside;
  21193. }
  21194. var isClockWise = ShapeUtils.isClockWise;
  21195. var subPaths = this.subPaths;
  21196. if ( subPaths.length === 0 ) return [];
  21197. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21198. var solid, tmpPath, tmpShape, shapes = [];
  21199. if ( subPaths.length === 1 ) {
  21200. tmpPath = subPaths[ 0 ];
  21201. tmpShape = new Shape();
  21202. tmpShape.curves = tmpPath.curves;
  21203. shapes.push( tmpShape );
  21204. return shapes;
  21205. }
  21206. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21207. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21208. // console.log("Holes first", holesFirst);
  21209. var betterShapeHoles = [];
  21210. var newShapes = [];
  21211. var newShapeHoles = [];
  21212. var mainIdx = 0;
  21213. var tmpPoints;
  21214. newShapes[ mainIdx ] = undefined;
  21215. newShapeHoles[ mainIdx ] = [];
  21216. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21217. tmpPath = subPaths[ i ];
  21218. tmpPoints = tmpPath.getPoints();
  21219. solid = isClockWise( tmpPoints );
  21220. solid = isCCW ? ! solid : solid;
  21221. if ( solid ) {
  21222. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21223. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21224. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21225. if ( holesFirst ) mainIdx ++;
  21226. newShapeHoles[ mainIdx ] = [];
  21227. //console.log('cw', i);
  21228. } else {
  21229. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21230. //console.log('ccw', i);
  21231. }
  21232. }
  21233. // only Holes? -> probably all Shapes with wrong orientation
  21234. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21235. if ( newShapes.length > 1 ) {
  21236. var ambiguous = false;
  21237. var toChange = [];
  21238. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21239. betterShapeHoles[ sIdx ] = [];
  21240. }
  21241. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21242. var sho = newShapeHoles[ sIdx ];
  21243. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21244. var ho = sho[ hIdx ];
  21245. var hole_unassigned = true;
  21246. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21247. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21248. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21249. if ( hole_unassigned ) {
  21250. hole_unassigned = false;
  21251. betterShapeHoles[ s2Idx ].push( ho );
  21252. } else {
  21253. ambiguous = true;
  21254. }
  21255. }
  21256. }
  21257. if ( hole_unassigned ) {
  21258. betterShapeHoles[ sIdx ].push( ho );
  21259. }
  21260. }
  21261. }
  21262. // console.log("ambiguous: ", ambiguous);
  21263. if ( toChange.length > 0 ) {
  21264. // console.log("to change: ", toChange);
  21265. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21266. }
  21267. }
  21268. var tmpHoles;
  21269. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21270. tmpShape = newShapes[ i ].s;
  21271. shapes.push( tmpShape );
  21272. tmpHoles = newShapeHoles[ i ];
  21273. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21274. tmpShape.holes.push( tmpHoles[ j ].h );
  21275. }
  21276. }
  21277. //console.log("shape", shapes);
  21278. return shapes;
  21279. }
  21280. } );
  21281. /**
  21282. * @author zz85 / http://www.lab4games.net/zz85/blog
  21283. * @author mrdoob / http://mrdoob.com/
  21284. */
  21285. function Font( data ) {
  21286. this.data = data;
  21287. }
  21288. Object.assign( Font.prototype, {
  21289. isFont: true,
  21290. generateShapes: function ( text, size, divisions ) {
  21291. function createPaths( text ) {
  21292. var chars = String( text ).split( '' );
  21293. var scale = size / data.resolution;
  21294. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  21295. var offsetX = 0, offsetY = 0;
  21296. var paths = [];
  21297. for ( var i = 0; i < chars.length; i ++ ) {
  21298. var char = chars[ i ];
  21299. if ( char === '\n' ) {
  21300. offsetX = 0;
  21301. offsetY -= line_height;
  21302. } else {
  21303. var ret = createPath( char, scale, offsetX, offsetY );
  21304. offsetX += ret.offsetX;
  21305. paths.push( ret.path );
  21306. }
  21307. }
  21308. return paths;
  21309. }
  21310. function createPath( c, scale, offsetX, offsetY ) {
  21311. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21312. if ( ! glyph ) return;
  21313. var path = new ShapePath();
  21314. var pts = [];
  21315. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21316. if ( glyph.o ) {
  21317. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21318. for ( var i = 0, l = outline.length; i < l; ) {
  21319. var action = outline[ i ++ ];
  21320. switch ( action ) {
  21321. case 'm': // moveTo
  21322. x = outline[ i ++ ] * scale + offsetX;
  21323. y = outline[ i ++ ] * scale + offsetY;
  21324. path.moveTo( x, y );
  21325. break;
  21326. case 'l': // lineTo
  21327. x = outline[ i ++ ] * scale + offsetX;
  21328. y = outline[ i ++ ] * scale + offsetY;
  21329. path.lineTo( x, y );
  21330. break;
  21331. case 'q': // quadraticCurveTo
  21332. cpx = outline[ i ++ ] * scale + offsetX;
  21333. cpy = outline[ i ++ ] * scale + offsetY;
  21334. cpx1 = outline[ i ++ ] * scale + offsetX;
  21335. cpy1 = outline[ i ++ ] * scale + offsetY;
  21336. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21337. laste = pts[ pts.length - 1 ];
  21338. if ( laste ) {
  21339. cpx0 = laste.x;
  21340. cpy0 = laste.y;
  21341. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21342. var t = i2 / divisions;
  21343. QuadraticBezier( t, cpx0, cpx1, cpx );
  21344. QuadraticBezier( t, cpy0, cpy1, cpy );
  21345. }
  21346. }
  21347. break;
  21348. case 'b': // bezierCurveTo
  21349. cpx = outline[ i ++ ] * scale + offsetX;
  21350. cpy = outline[ i ++ ] * scale + offsetY;
  21351. cpx1 = outline[ i ++ ] * scale + offsetX;
  21352. cpy1 = outline[ i ++ ] * scale + offsetY;
  21353. cpx2 = outline[ i ++ ] * scale + offsetX;
  21354. cpy2 = outline[ i ++ ] * scale + offsetY;
  21355. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21356. laste = pts[ pts.length - 1 ];
  21357. if ( laste ) {
  21358. cpx0 = laste.x;
  21359. cpy0 = laste.y;
  21360. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21361. var t = i2 / divisions;
  21362. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21363. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21364. }
  21365. }
  21366. break;
  21367. }
  21368. }
  21369. }
  21370. return { offsetX: glyph.ha * scale, path: path };
  21371. }
  21372. //
  21373. if ( size === undefined ) size = 100;
  21374. if ( divisions === undefined ) divisions = 4;
  21375. var data = this.data;
  21376. var paths = createPaths( text );
  21377. var shapes = [];
  21378. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21379. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21380. }
  21381. return shapes;
  21382. }
  21383. } );
  21384. /**
  21385. * @author mrdoob / http://mrdoob.com/
  21386. */
  21387. function FontLoader( manager ) {
  21388. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21389. }
  21390. Object.assign( FontLoader.prototype, {
  21391. load: function ( url, onLoad, onProgress, onError ) {
  21392. var scope = this;
  21393. var loader = new FileLoader( this.manager );
  21394. loader.load( url, function ( text ) {
  21395. var json;
  21396. try {
  21397. json = JSON.parse( text );
  21398. } catch ( e ) {
  21399. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21400. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21401. }
  21402. var font = scope.parse( json );
  21403. if ( onLoad ) onLoad( font );
  21404. }, onProgress, onError );
  21405. },
  21406. parse: function ( json ) {
  21407. return new Font( json );
  21408. }
  21409. } );
  21410. var context;
  21411. var AudioContext = {
  21412. getContext: function () {
  21413. if ( context === undefined ) {
  21414. context = new ( window.AudioContext || window.webkitAudioContext )();
  21415. }
  21416. return context;
  21417. },
  21418. setContext: function ( value ) {
  21419. context = value;
  21420. }
  21421. };
  21422. /**
  21423. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21424. */
  21425. function AudioLoader( manager ) {
  21426. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21427. }
  21428. Object.assign( AudioLoader.prototype, {
  21429. load: function ( url, onLoad, onProgress, onError ) {
  21430. var loader = new FileLoader( this.manager );
  21431. loader.setResponseType( 'arraybuffer' );
  21432. loader.load( url, function ( buffer ) {
  21433. var context = AudioContext.getContext();
  21434. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21435. onLoad( audioBuffer );
  21436. } );
  21437. }, onProgress, onError );
  21438. }
  21439. } );
  21440. /**
  21441. * @author mrdoob / http://mrdoob.com/
  21442. */
  21443. function StereoCamera() {
  21444. this.type = 'StereoCamera';
  21445. this.aspect = 1;
  21446. this.eyeSep = 0.064;
  21447. this.cameraL = new PerspectiveCamera();
  21448. this.cameraL.layers.enable( 1 );
  21449. this.cameraL.matrixAutoUpdate = false;
  21450. this.cameraR = new PerspectiveCamera();
  21451. this.cameraR.layers.enable( 2 );
  21452. this.cameraR.matrixAutoUpdate = false;
  21453. }
  21454. Object.assign( StereoCamera.prototype, {
  21455. update: ( function () {
  21456. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  21457. var eyeRight = new Matrix4();
  21458. var eyeLeft = new Matrix4();
  21459. return function update( camera ) {
  21460. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21461. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21462. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  21463. if ( needsUpdate ) {
  21464. instance = this;
  21465. focus = camera.focus;
  21466. fov = camera.fov;
  21467. aspect = camera.aspect * this.aspect;
  21468. near = camera.near;
  21469. far = camera.far;
  21470. zoom = camera.zoom;
  21471. // Off-axis stereoscopic effect based on
  21472. // http://paulbourke.net/stereographics/stereorender/
  21473. var projectionMatrix = camera.projectionMatrix.clone();
  21474. eyeSep = this.eyeSep / 2;
  21475. var eyeSepOnProjection = eyeSep * near / focus;
  21476. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21477. var xmin, xmax;
  21478. // translate xOffset
  21479. eyeLeft.elements[ 12 ] = - eyeSep;
  21480. eyeRight.elements[ 12 ] = eyeSep;
  21481. // for left eye
  21482. xmin = - ymax * aspect + eyeSepOnProjection;
  21483. xmax = ymax * aspect + eyeSepOnProjection;
  21484. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21485. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21486. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21487. // for right eye
  21488. xmin = - ymax * aspect - eyeSepOnProjection;
  21489. xmax = ymax * aspect - eyeSepOnProjection;
  21490. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21491. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21492. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21493. }
  21494. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21495. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21496. };
  21497. } )()
  21498. } );
  21499. /**
  21500. * Camera for rendering cube maps
  21501. * - renders scene into axis-aligned cube
  21502. *
  21503. * @author alteredq / http://alteredqualia.com/
  21504. */
  21505. function CubeCamera( near, far, cubeResolution ) {
  21506. Object3D.call( this );
  21507. this.type = 'CubeCamera';
  21508. var fov = 90, aspect = 1;
  21509. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21510. cameraPX.up.set( 0, - 1, 0 );
  21511. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21512. this.add( cameraPX );
  21513. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21514. cameraNX.up.set( 0, - 1, 0 );
  21515. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21516. this.add( cameraNX );
  21517. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21518. cameraPY.up.set( 0, 0, 1 );
  21519. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21520. this.add( cameraPY );
  21521. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21522. cameraNY.up.set( 0, 0, - 1 );
  21523. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21524. this.add( cameraNY );
  21525. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21526. cameraPZ.up.set( 0, - 1, 0 );
  21527. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21528. this.add( cameraPZ );
  21529. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21530. cameraNZ.up.set( 0, - 1, 0 );
  21531. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21532. this.add( cameraNZ );
  21533. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21534. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21535. this.renderTarget.texture.name = "CubeCamera";
  21536. this.updateCubeMap = function ( renderer, scene ) {
  21537. if ( this.parent === null ) this.updateMatrixWorld();
  21538. var renderTarget = this.renderTarget;
  21539. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21540. renderTarget.texture.generateMipmaps = false;
  21541. renderTarget.activeCubeFace = 0;
  21542. renderer.render( scene, cameraPX, renderTarget );
  21543. renderTarget.activeCubeFace = 1;
  21544. renderer.render( scene, cameraNX, renderTarget );
  21545. renderTarget.activeCubeFace = 2;
  21546. renderer.render( scene, cameraPY, renderTarget );
  21547. renderTarget.activeCubeFace = 3;
  21548. renderer.render( scene, cameraNY, renderTarget );
  21549. renderTarget.activeCubeFace = 4;
  21550. renderer.render( scene, cameraPZ, renderTarget );
  21551. renderTarget.texture.generateMipmaps = generateMipmaps;
  21552. renderTarget.activeCubeFace = 5;
  21553. renderer.render( scene, cameraNZ, renderTarget );
  21554. renderer.setRenderTarget( null );
  21555. };
  21556. }
  21557. CubeCamera.prototype = Object.create( Object3D.prototype );
  21558. CubeCamera.prototype.constructor = CubeCamera;
  21559. /**
  21560. * @author mrdoob / http://mrdoob.com/
  21561. */
  21562. function ArrayCamera( array ) {
  21563. PerspectiveCamera.call( this );
  21564. this.enabled = false;
  21565. this.cameras = array || [];
  21566. }
  21567. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  21568. constructor: ArrayCamera,
  21569. isArrayCamera: true
  21570. } );
  21571. /**
  21572. * @author mrdoob / http://mrdoob.com/
  21573. */
  21574. function AudioListener() {
  21575. Object3D.call( this );
  21576. this.type = 'AudioListener';
  21577. this.context = AudioContext.getContext();
  21578. this.gain = this.context.createGain();
  21579. this.gain.connect( this.context.destination );
  21580. this.filter = null;
  21581. }
  21582. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21583. constructor: AudioListener,
  21584. getInput: function () {
  21585. return this.gain;
  21586. },
  21587. removeFilter: function ( ) {
  21588. if ( this.filter !== null ) {
  21589. this.gain.disconnect( this.filter );
  21590. this.filter.disconnect( this.context.destination );
  21591. this.gain.connect( this.context.destination );
  21592. this.filter = null;
  21593. }
  21594. },
  21595. getFilter: function () {
  21596. return this.filter;
  21597. },
  21598. setFilter: function ( value ) {
  21599. if ( this.filter !== null ) {
  21600. this.gain.disconnect( this.filter );
  21601. this.filter.disconnect( this.context.destination );
  21602. } else {
  21603. this.gain.disconnect( this.context.destination );
  21604. }
  21605. this.filter = value;
  21606. this.gain.connect( this.filter );
  21607. this.filter.connect( this.context.destination );
  21608. },
  21609. getMasterVolume: function () {
  21610. return this.gain.gain.value;
  21611. },
  21612. setMasterVolume: function ( value ) {
  21613. this.gain.gain.value = value;
  21614. },
  21615. updateMatrixWorld: ( function () {
  21616. var position = new Vector3();
  21617. var quaternion = new Quaternion();
  21618. var scale = new Vector3();
  21619. var orientation = new Vector3();
  21620. return function updateMatrixWorld( force ) {
  21621. Object3D.prototype.updateMatrixWorld.call( this, force );
  21622. var listener = this.context.listener;
  21623. var up = this.up;
  21624. this.matrixWorld.decompose( position, quaternion, scale );
  21625. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21626. if ( listener.positionX ) {
  21627. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21628. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21629. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21630. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21631. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21632. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21633. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21634. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21635. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21636. } else {
  21637. listener.setPosition( position.x, position.y, position.z );
  21638. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21639. }
  21640. };
  21641. } )()
  21642. } );
  21643. /**
  21644. * @author mrdoob / http://mrdoob.com/
  21645. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21646. */
  21647. function Audio( listener ) {
  21648. Object3D.call( this );
  21649. this.type = 'Audio';
  21650. this.context = listener.context;
  21651. this.gain = this.context.createGain();
  21652. this.gain.connect( listener.getInput() );
  21653. this.autoplay = false;
  21654. this.buffer = null;
  21655. this.loop = false;
  21656. this.startTime = 0;
  21657. this.playbackRate = 1;
  21658. this.isPlaying = false;
  21659. this.hasPlaybackControl = true;
  21660. this.sourceType = 'empty';
  21661. this.filters = [];
  21662. }
  21663. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21664. constructor: Audio,
  21665. getOutput: function () {
  21666. return this.gain;
  21667. },
  21668. setNodeSource: function ( audioNode ) {
  21669. this.hasPlaybackControl = false;
  21670. this.sourceType = 'audioNode';
  21671. this.source = audioNode;
  21672. this.connect();
  21673. return this;
  21674. },
  21675. setBuffer: function ( audioBuffer ) {
  21676. this.buffer = audioBuffer;
  21677. this.sourceType = 'buffer';
  21678. if ( this.autoplay ) this.play();
  21679. return this;
  21680. },
  21681. play: function () {
  21682. if ( this.isPlaying === true ) {
  21683. console.warn( 'THREE.Audio: Audio is already playing.' );
  21684. return;
  21685. }
  21686. if ( this.hasPlaybackControl === false ) {
  21687. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21688. return;
  21689. }
  21690. var source = this.context.createBufferSource();
  21691. source.buffer = this.buffer;
  21692. source.loop = this.loop;
  21693. source.onended = this.onEnded.bind( this );
  21694. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21695. source.start( 0, this.startTime );
  21696. this.isPlaying = true;
  21697. this.source = source;
  21698. return this.connect();
  21699. },
  21700. pause: function () {
  21701. if ( this.hasPlaybackControl === false ) {
  21702. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21703. return;
  21704. }
  21705. this.source.stop();
  21706. this.startTime = this.context.currentTime;
  21707. this.isPlaying = false;
  21708. return this;
  21709. },
  21710. stop: function () {
  21711. if ( this.hasPlaybackControl === false ) {
  21712. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21713. return;
  21714. }
  21715. this.source.stop();
  21716. this.startTime = 0;
  21717. this.isPlaying = false;
  21718. return this;
  21719. },
  21720. connect: function () {
  21721. if ( this.filters.length > 0 ) {
  21722. this.source.connect( this.filters[ 0 ] );
  21723. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21724. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21725. }
  21726. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21727. } else {
  21728. this.source.connect( this.getOutput() );
  21729. }
  21730. return this;
  21731. },
  21732. disconnect: function () {
  21733. if ( this.filters.length > 0 ) {
  21734. this.source.disconnect( this.filters[ 0 ] );
  21735. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21736. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21737. }
  21738. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21739. } else {
  21740. this.source.disconnect( this.getOutput() );
  21741. }
  21742. return this;
  21743. },
  21744. getFilters: function () {
  21745. return this.filters;
  21746. },
  21747. setFilters: function ( value ) {
  21748. if ( ! value ) value = [];
  21749. if ( this.isPlaying === true ) {
  21750. this.disconnect();
  21751. this.filters = value;
  21752. this.connect();
  21753. } else {
  21754. this.filters = value;
  21755. }
  21756. return this;
  21757. },
  21758. getFilter: function () {
  21759. return this.getFilters()[ 0 ];
  21760. },
  21761. setFilter: function ( filter ) {
  21762. return this.setFilters( filter ? [ filter ] : [] );
  21763. },
  21764. setPlaybackRate: function ( value ) {
  21765. if ( this.hasPlaybackControl === false ) {
  21766. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21767. return;
  21768. }
  21769. this.playbackRate = value;
  21770. if ( this.isPlaying === true ) {
  21771. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21772. }
  21773. return this;
  21774. },
  21775. getPlaybackRate: function () {
  21776. return this.playbackRate;
  21777. },
  21778. onEnded: function () {
  21779. this.isPlaying = false;
  21780. },
  21781. getLoop: function () {
  21782. if ( this.hasPlaybackControl === false ) {
  21783. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21784. return false;
  21785. }
  21786. return this.loop;
  21787. },
  21788. setLoop: function ( value ) {
  21789. if ( this.hasPlaybackControl === false ) {
  21790. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21791. return;
  21792. }
  21793. this.loop = value;
  21794. if ( this.isPlaying === true ) {
  21795. this.source.loop = this.loop;
  21796. }
  21797. return this;
  21798. },
  21799. getVolume: function () {
  21800. return this.gain.gain.value;
  21801. },
  21802. setVolume: function ( value ) {
  21803. this.gain.gain.value = value;
  21804. return this;
  21805. }
  21806. } );
  21807. /**
  21808. * @author mrdoob / http://mrdoob.com/
  21809. */
  21810. function PositionalAudio( listener ) {
  21811. Audio.call( this, listener );
  21812. this.panner = this.context.createPanner();
  21813. this.panner.connect( this.gain );
  21814. }
  21815. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21816. constructor: PositionalAudio,
  21817. getOutput: function () {
  21818. return this.panner;
  21819. },
  21820. getRefDistance: function () {
  21821. return this.panner.refDistance;
  21822. },
  21823. setRefDistance: function ( value ) {
  21824. this.panner.refDistance = value;
  21825. },
  21826. getRolloffFactor: function () {
  21827. return this.panner.rolloffFactor;
  21828. },
  21829. setRolloffFactor: function ( value ) {
  21830. this.panner.rolloffFactor = value;
  21831. },
  21832. getDistanceModel: function () {
  21833. return this.panner.distanceModel;
  21834. },
  21835. setDistanceModel: function ( value ) {
  21836. this.panner.distanceModel = value;
  21837. },
  21838. getMaxDistance: function () {
  21839. return this.panner.maxDistance;
  21840. },
  21841. setMaxDistance: function ( value ) {
  21842. this.panner.maxDistance = value;
  21843. },
  21844. updateMatrixWorld: ( function () {
  21845. var position = new Vector3();
  21846. return function updateMatrixWorld( force ) {
  21847. Object3D.prototype.updateMatrixWorld.call( this, force );
  21848. position.setFromMatrixPosition( this.matrixWorld );
  21849. this.panner.setPosition( position.x, position.y, position.z );
  21850. };
  21851. } )()
  21852. } );
  21853. /**
  21854. * @author mrdoob / http://mrdoob.com/
  21855. */
  21856. function AudioAnalyser( audio, fftSize ) {
  21857. this.analyser = audio.context.createAnalyser();
  21858. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21859. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21860. audio.getOutput().connect( this.analyser );
  21861. }
  21862. Object.assign( AudioAnalyser.prototype, {
  21863. getFrequencyData: function () {
  21864. this.analyser.getByteFrequencyData( this.data );
  21865. return this.data;
  21866. },
  21867. getAverageFrequency: function () {
  21868. var value = 0, data = this.getFrequencyData();
  21869. for ( var i = 0; i < data.length; i ++ ) {
  21870. value += data[ i ];
  21871. }
  21872. return value / data.length;
  21873. }
  21874. } );
  21875. /**
  21876. *
  21877. * Buffered scene graph property that allows weighted accumulation.
  21878. *
  21879. *
  21880. * @author Ben Houston / http://clara.io/
  21881. * @author David Sarno / http://lighthaus.us/
  21882. * @author tschw
  21883. */
  21884. function PropertyMixer( binding, typeName, valueSize ) {
  21885. this.binding = binding;
  21886. this.valueSize = valueSize;
  21887. var bufferType = Float64Array,
  21888. mixFunction;
  21889. switch ( typeName ) {
  21890. case 'quaternion':
  21891. mixFunction = this._slerp;
  21892. break;
  21893. case 'string':
  21894. case 'bool':
  21895. bufferType = Array;
  21896. mixFunction = this._select;
  21897. break;
  21898. default:
  21899. mixFunction = this._lerp;
  21900. }
  21901. this.buffer = new bufferType( valueSize * 4 );
  21902. // layout: [ incoming | accu0 | accu1 | orig ]
  21903. //
  21904. // interpolators can use .buffer as their .result
  21905. // the data then goes to 'incoming'
  21906. //
  21907. // 'accu0' and 'accu1' are used frame-interleaved for
  21908. // the cumulative result and are compared to detect
  21909. // changes
  21910. //
  21911. // 'orig' stores the original state of the property
  21912. this._mixBufferRegion = mixFunction;
  21913. this.cumulativeWeight = 0;
  21914. this.useCount = 0;
  21915. this.referenceCount = 0;
  21916. }
  21917. Object.assign( PropertyMixer.prototype, {
  21918. // accumulate data in the 'incoming' region into 'accu<i>'
  21919. accumulate: function ( accuIndex, weight ) {
  21920. // note: happily accumulating nothing when weight = 0, the caller knows
  21921. // the weight and shouldn't have made the call in the first place
  21922. var buffer = this.buffer,
  21923. stride = this.valueSize,
  21924. offset = accuIndex * stride + stride,
  21925. currentWeight = this.cumulativeWeight;
  21926. if ( currentWeight === 0 ) {
  21927. // accuN := incoming * weight
  21928. for ( var i = 0; i !== stride; ++ i ) {
  21929. buffer[ offset + i ] = buffer[ i ];
  21930. }
  21931. currentWeight = weight;
  21932. } else {
  21933. // accuN := accuN + incoming * weight
  21934. currentWeight += weight;
  21935. var mix = weight / currentWeight;
  21936. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21937. }
  21938. this.cumulativeWeight = currentWeight;
  21939. },
  21940. // apply the state of 'accu<i>' to the binding when accus differ
  21941. apply: function ( accuIndex ) {
  21942. var stride = this.valueSize,
  21943. buffer = this.buffer,
  21944. offset = accuIndex * stride + stride,
  21945. weight = this.cumulativeWeight,
  21946. binding = this.binding;
  21947. this.cumulativeWeight = 0;
  21948. if ( weight < 1 ) {
  21949. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21950. var originalValueOffset = stride * 3;
  21951. this._mixBufferRegion(
  21952. buffer, offset, originalValueOffset, 1 - weight, stride );
  21953. }
  21954. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21955. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21956. // value has changed -> update scene graph
  21957. binding.setValue( buffer, offset );
  21958. break;
  21959. }
  21960. }
  21961. },
  21962. // remember the state of the bound property and copy it to both accus
  21963. saveOriginalState: function () {
  21964. var binding = this.binding;
  21965. var buffer = this.buffer,
  21966. stride = this.valueSize,
  21967. originalValueOffset = stride * 3;
  21968. binding.getValue( buffer, originalValueOffset );
  21969. // accu[0..1] := orig -- initially detect changes against the original
  21970. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21971. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21972. }
  21973. this.cumulativeWeight = 0;
  21974. },
  21975. // apply the state previously taken via 'saveOriginalState' to the binding
  21976. restoreOriginalState: function () {
  21977. var originalValueOffset = this.valueSize * 3;
  21978. this.binding.setValue( this.buffer, originalValueOffset );
  21979. },
  21980. // mix functions
  21981. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  21982. if ( t >= 0.5 ) {
  21983. for ( var i = 0; i !== stride; ++ i ) {
  21984. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21985. }
  21986. }
  21987. },
  21988. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  21989. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  21990. },
  21991. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  21992. var s = 1 - t;
  21993. for ( var i = 0; i !== stride; ++ i ) {
  21994. var j = dstOffset + i;
  21995. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21996. }
  21997. }
  21998. } );
  21999. /**
  22000. *
  22001. * A reference to a real property in the scene graph.
  22002. *
  22003. *
  22004. * @author Ben Houston / http://clara.io/
  22005. * @author David Sarno / http://lighthaus.us/
  22006. * @author tschw
  22007. */
  22008. function Composite( targetGroup, path, optionalParsedPath ) {
  22009. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22010. this._targetGroup = targetGroup;
  22011. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22012. }
  22013. Object.assign( Composite.prototype, {
  22014. getValue: function ( array, offset ) {
  22015. this.bind(); // bind all binding
  22016. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22017. binding = this._bindings[ firstValidIndex ];
  22018. // and only call .getValue on the first
  22019. if ( binding !== undefined ) binding.getValue( array, offset );
  22020. },
  22021. setValue: function ( array, offset ) {
  22022. var bindings = this._bindings;
  22023. for ( var i = this._targetGroup.nCachedObjects_,
  22024. n = bindings.length; i !== n; ++ i ) {
  22025. bindings[ i ].setValue( array, offset );
  22026. }
  22027. },
  22028. bind: function () {
  22029. var bindings = this._bindings;
  22030. for ( var i = this._targetGroup.nCachedObjects_,
  22031. n = bindings.length; i !== n; ++ i ) {
  22032. bindings[ i ].bind();
  22033. }
  22034. },
  22035. unbind: function () {
  22036. var bindings = this._bindings;
  22037. for ( var i = this._targetGroup.nCachedObjects_,
  22038. n = bindings.length; i !== n; ++ i ) {
  22039. bindings[ i ].unbind();
  22040. }
  22041. }
  22042. } );
  22043. function PropertyBinding( rootNode, path, parsedPath ) {
  22044. this.path = path;
  22045. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22046. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22047. this.rootNode = rootNode;
  22048. }
  22049. Object.assign( PropertyBinding, {
  22050. Composite: Composite,
  22051. create: function ( root, path, parsedPath ) {
  22052. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22053. return new PropertyBinding( root, path, parsedPath );
  22054. } else {
  22055. return new PropertyBinding.Composite( root, path, parsedPath );
  22056. }
  22057. },
  22058. parseTrackName: function () {
  22059. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22060. // be matched to parse the rest of the track name.
  22061. var directoryRe = /((?:[\w-]+[\/:])*)/;
  22062. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22063. var nodeRe = /([\w-\.]+)?/;
  22064. // Object on target node, and accessor. Name may contain only word
  22065. // characters. Accessor may contain any character except closing bracket.
  22066. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  22067. // Property and accessor. May contain only word characters. Accessor may
  22068. // contain any non-bracket characters.
  22069. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  22070. var trackRe = new RegExp(''
  22071. + '^'
  22072. + directoryRe.source
  22073. + nodeRe.source
  22074. + objectRe.source
  22075. + propertyRe.source
  22076. + '$'
  22077. );
  22078. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22079. return function ( trackName ) {
  22080. var matches = trackRe.exec( trackName );
  22081. if ( ! matches ) {
  22082. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22083. }
  22084. var results = {
  22085. // directoryName: matches[ 1 ], // (tschw) currently unused
  22086. nodeName: matches[ 2 ],
  22087. objectName: matches[ 3 ],
  22088. objectIndex: matches[ 4 ],
  22089. propertyName: matches[ 5 ], // required
  22090. propertyIndex: matches[ 6 ]
  22091. };
  22092. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22093. if ( lastDot !== undefined && lastDot !== -1 ) {
  22094. var objectName = results.nodeName.substring( lastDot + 1 );
  22095. // Object names must be checked against a whitelist. Otherwise, there
  22096. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22097. // 'bar' could be the objectName, or part of a nodeName (which can
  22098. // include '.' characters).
  22099. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  22100. results.nodeName = results.nodeName.substring( 0, lastDot );
  22101. results.objectName = objectName;
  22102. }
  22103. }
  22104. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22105. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22106. }
  22107. return results;
  22108. };
  22109. }(),
  22110. findNode: function ( root, nodeName ) {
  22111. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22112. return root;
  22113. }
  22114. // search into skeleton bones.
  22115. if ( root.skeleton ) {
  22116. var searchSkeleton = function ( skeleton ) {
  22117. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  22118. var bone = skeleton.bones[ i ];
  22119. if ( bone.name === nodeName ) {
  22120. return bone;
  22121. }
  22122. }
  22123. return null;
  22124. };
  22125. var bone = searchSkeleton( root.skeleton );
  22126. if ( bone ) {
  22127. return bone;
  22128. }
  22129. }
  22130. // search into node subtree.
  22131. if ( root.children ) {
  22132. var searchNodeSubtree = function ( children ) {
  22133. for ( var i = 0; i < children.length; i ++ ) {
  22134. var childNode = children[ i ];
  22135. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22136. return childNode;
  22137. }
  22138. var result = searchNodeSubtree( childNode.children );
  22139. if ( result ) return result;
  22140. }
  22141. return null;
  22142. };
  22143. var subTreeNode = searchNodeSubtree( root.children );
  22144. if ( subTreeNode ) {
  22145. return subTreeNode;
  22146. }
  22147. }
  22148. return null;
  22149. }
  22150. } );
  22151. Object.assign( PropertyBinding.prototype, { // prototype, continued
  22152. // these are used to "bind" a nonexistent property
  22153. _getValue_unavailable: function () {},
  22154. _setValue_unavailable: function () {},
  22155. BindingType: {
  22156. Direct: 0,
  22157. EntireArray: 1,
  22158. ArrayElement: 2,
  22159. HasFromToArray: 3
  22160. },
  22161. Versioning: {
  22162. None: 0,
  22163. NeedsUpdate: 1,
  22164. MatrixWorldNeedsUpdate: 2
  22165. },
  22166. GetterByBindingType: [
  22167. function getValue_direct( buffer, offset ) {
  22168. buffer[ offset ] = this.node[ this.propertyName ];
  22169. },
  22170. function getValue_array( buffer, offset ) {
  22171. var source = this.resolvedProperty;
  22172. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  22173. buffer[ offset ++ ] = source[ i ];
  22174. }
  22175. },
  22176. function getValue_arrayElement( buffer, offset ) {
  22177. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22178. },
  22179. function getValue_toArray( buffer, offset ) {
  22180. this.resolvedProperty.toArray( buffer, offset );
  22181. }
  22182. ],
  22183. SetterByBindingTypeAndVersioning: [
  22184. [
  22185. // Direct
  22186. function setValue_direct( buffer, offset ) {
  22187. this.node[ this.propertyName ] = buffer[ offset ];
  22188. },
  22189. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22190. this.node[ this.propertyName ] = buffer[ offset ];
  22191. this.targetObject.needsUpdate = true;
  22192. },
  22193. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22194. this.node[ this.propertyName ] = buffer[ offset ];
  22195. this.targetObject.matrixWorldNeedsUpdate = true;
  22196. }
  22197. ], [
  22198. // EntireArray
  22199. function setValue_array( buffer, offset ) {
  22200. var dest = this.resolvedProperty;
  22201. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22202. dest[ i ] = buffer[ offset ++ ];
  22203. }
  22204. },
  22205. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22206. var dest = this.resolvedProperty;
  22207. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22208. dest[ i ] = buffer[ offset ++ ];
  22209. }
  22210. this.targetObject.needsUpdate = true;
  22211. },
  22212. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22213. var dest = this.resolvedProperty;
  22214. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22215. dest[ i ] = buffer[ offset ++ ];
  22216. }
  22217. this.targetObject.matrixWorldNeedsUpdate = true;
  22218. }
  22219. ], [
  22220. // ArrayElement
  22221. function setValue_arrayElement( buffer, offset ) {
  22222. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22223. },
  22224. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22225. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22226. this.targetObject.needsUpdate = true;
  22227. },
  22228. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22229. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22230. this.targetObject.matrixWorldNeedsUpdate = true;
  22231. }
  22232. ], [
  22233. // HasToFromArray
  22234. function setValue_fromArray( buffer, offset ) {
  22235. this.resolvedProperty.fromArray( buffer, offset );
  22236. },
  22237. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22238. this.resolvedProperty.fromArray( buffer, offset );
  22239. this.targetObject.needsUpdate = true;
  22240. },
  22241. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22242. this.resolvedProperty.fromArray( buffer, offset );
  22243. this.targetObject.matrixWorldNeedsUpdate = true;
  22244. }
  22245. ]
  22246. ],
  22247. getValue: function getValue_unbound( targetArray, offset ) {
  22248. this.bind();
  22249. this.getValue( targetArray, offset );
  22250. // Note: This class uses a State pattern on a per-method basis:
  22251. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22252. // prototype version of these methods with one that represents
  22253. // the bound state. When the property is not found, the methods
  22254. // become no-ops.
  22255. },
  22256. setValue: function getValue_unbound( sourceArray, offset ) {
  22257. this.bind();
  22258. this.setValue( sourceArray, offset );
  22259. },
  22260. // create getter / setter pair for a property in the scene graph
  22261. bind: function () {
  22262. var targetObject = this.node,
  22263. parsedPath = this.parsedPath,
  22264. objectName = parsedPath.objectName,
  22265. propertyName = parsedPath.propertyName,
  22266. propertyIndex = parsedPath.propertyIndex;
  22267. if ( ! targetObject ) {
  22268. targetObject = PropertyBinding.findNode(
  22269. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22270. this.node = targetObject;
  22271. }
  22272. // set fail state so we can just 'return' on error
  22273. this.getValue = this._getValue_unavailable;
  22274. this.setValue = this._setValue_unavailable;
  22275. // ensure there is a value node
  22276. if ( ! targetObject ) {
  22277. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  22278. return;
  22279. }
  22280. if ( objectName ) {
  22281. var objectIndex = parsedPath.objectIndex;
  22282. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22283. switch ( objectName ) {
  22284. case 'materials':
  22285. if ( ! targetObject.material ) {
  22286. console.error( ' can not bind to material as node does not have a material', this );
  22287. return;
  22288. }
  22289. if ( ! targetObject.material.materials ) {
  22290. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  22291. return;
  22292. }
  22293. targetObject = targetObject.material.materials;
  22294. break;
  22295. case 'bones':
  22296. if ( ! targetObject.skeleton ) {
  22297. console.error( ' can not bind to bones as node does not have a skeleton', this );
  22298. return;
  22299. }
  22300. // potential future optimization: skip this if propertyIndex is already an integer
  22301. // and convert the integer string to a true integer.
  22302. targetObject = targetObject.skeleton.bones;
  22303. // support resolving morphTarget names into indices.
  22304. for ( var i = 0; i < targetObject.length; i ++ ) {
  22305. if ( targetObject[ i ].name === objectIndex ) {
  22306. objectIndex = i;
  22307. break;
  22308. }
  22309. }
  22310. break;
  22311. default:
  22312. if ( targetObject[ objectName ] === undefined ) {
  22313. console.error( ' can not bind to objectName of node, undefined', this );
  22314. return;
  22315. }
  22316. targetObject = targetObject[ objectName ];
  22317. }
  22318. if ( objectIndex !== undefined ) {
  22319. if ( targetObject[ objectIndex ] === undefined ) {
  22320. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  22321. return;
  22322. }
  22323. targetObject = targetObject[ objectIndex ];
  22324. }
  22325. }
  22326. // resolve property
  22327. var nodeProperty = targetObject[ propertyName ];
  22328. if ( nodeProperty === undefined ) {
  22329. var nodeName = parsedPath.nodeName;
  22330. console.error( " trying to update property for track: " + nodeName +
  22331. '.' + propertyName + " but it wasn't found.", targetObject );
  22332. return;
  22333. }
  22334. // determine versioning scheme
  22335. var versioning = this.Versioning.None;
  22336. if ( targetObject.needsUpdate !== undefined ) { // material
  22337. versioning = this.Versioning.NeedsUpdate;
  22338. this.targetObject = targetObject;
  22339. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22340. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22341. this.targetObject = targetObject;
  22342. }
  22343. // determine how the property gets bound
  22344. var bindingType = this.BindingType.Direct;
  22345. if ( propertyIndex !== undefined ) {
  22346. // access a sub element of the property array (only primitives are supported right now)
  22347. if ( propertyName === "morphTargetInfluences" ) {
  22348. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22349. // support resolving morphTarget names into indices.
  22350. if ( ! targetObject.geometry ) {
  22351. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  22352. return;
  22353. }
  22354. if ( ! targetObject.geometry.morphTargets ) {
  22355. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  22356. return;
  22357. }
  22358. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  22359. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  22360. propertyIndex = i;
  22361. break;
  22362. }
  22363. }
  22364. }
  22365. bindingType = this.BindingType.ArrayElement;
  22366. this.resolvedProperty = nodeProperty;
  22367. this.propertyIndex = propertyIndex;
  22368. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22369. // must use copy for Object3D.Euler/Quaternion
  22370. bindingType = this.BindingType.HasFromToArray;
  22371. this.resolvedProperty = nodeProperty;
  22372. } else if ( Array.isArray( nodeProperty ) ) {
  22373. bindingType = this.BindingType.EntireArray;
  22374. this.resolvedProperty = nodeProperty;
  22375. } else {
  22376. this.propertyName = propertyName;
  22377. }
  22378. // select getter / setter
  22379. this.getValue = this.GetterByBindingType[ bindingType ];
  22380. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22381. },
  22382. unbind: function () {
  22383. this.node = null;
  22384. // back to the prototype version of getValue / setValue
  22385. // note: avoiding to mutate the shape of 'this' via 'delete'
  22386. this.getValue = this._getValue_unbound;
  22387. this.setValue = this._setValue_unbound;
  22388. }
  22389. } );
  22390. //!\ DECLARE ALIAS AFTER assign prototype !
  22391. Object.assign( PropertyBinding.prototype, {
  22392. // initial state of these methods that calls 'bind'
  22393. _getValue_unbound: PropertyBinding.prototype.getValue,
  22394. _setValue_unbound: PropertyBinding.prototype.setValue,
  22395. } );
  22396. /**
  22397. *
  22398. * A group of objects that receives a shared animation state.
  22399. *
  22400. * Usage:
  22401. *
  22402. * - Add objects you would otherwise pass as 'root' to the
  22403. * constructor or the .clipAction method of AnimationMixer.
  22404. *
  22405. * - Instead pass this object as 'root'.
  22406. *
  22407. * - You can also add and remove objects later when the mixer
  22408. * is running.
  22409. *
  22410. * Note:
  22411. *
  22412. * Objects of this class appear as one object to the mixer,
  22413. * so cache control of the individual objects must be done
  22414. * on the group.
  22415. *
  22416. * Limitation:
  22417. *
  22418. * - The animated properties must be compatible among the
  22419. * all objects in the group.
  22420. *
  22421. * - A single property can either be controlled through a
  22422. * target group or directly, but not both.
  22423. *
  22424. * @author tschw
  22425. */
  22426. function AnimationObjectGroup( var_args ) {
  22427. this.uuid = _Math.generateUUID();
  22428. // cached objects followed by the active ones
  22429. this._objects = Array.prototype.slice.call( arguments );
  22430. this.nCachedObjects_ = 0; // threshold
  22431. // note: read by PropertyBinding.Composite
  22432. var indices = {};
  22433. this._indicesByUUID = indices; // for bookkeeping
  22434. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22435. indices[ arguments[ i ].uuid ] = i;
  22436. }
  22437. this._paths = []; // inside: string
  22438. this._parsedPaths = []; // inside: { we don't care, here }
  22439. this._bindings = []; // inside: Array< PropertyBinding >
  22440. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22441. var scope = this;
  22442. this.stats = {
  22443. objects: {
  22444. get total() { return scope._objects.length; },
  22445. get inUse() { return this.total - scope.nCachedObjects_; }
  22446. },
  22447. get bindingsPerObject() { return scope._bindings.length; }
  22448. };
  22449. }
  22450. Object.assign( AnimationObjectGroup.prototype, {
  22451. isAnimationObjectGroup: true,
  22452. add: function( var_args ) {
  22453. var objects = this._objects,
  22454. nObjects = objects.length,
  22455. nCachedObjects = this.nCachedObjects_,
  22456. indicesByUUID = this._indicesByUUID,
  22457. paths = this._paths,
  22458. parsedPaths = this._parsedPaths,
  22459. bindings = this._bindings,
  22460. nBindings = bindings.length;
  22461. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22462. var object = arguments[ i ],
  22463. uuid = object.uuid,
  22464. index = indicesByUUID[ uuid ],
  22465. knownObject = undefined;
  22466. if ( index === undefined ) {
  22467. // unknown object -> add it to the ACTIVE region
  22468. index = nObjects ++;
  22469. indicesByUUID[ uuid ] = index;
  22470. objects.push( object );
  22471. // accounting is done, now do the same for all bindings
  22472. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22473. bindings[ j ].push(
  22474. new PropertyBinding(
  22475. object, paths[ j ], parsedPaths[ j ] ) );
  22476. }
  22477. } else if ( index < nCachedObjects ) {
  22478. knownObject = objects[ index ];
  22479. // move existing object to the ACTIVE region
  22480. var firstActiveIndex = -- nCachedObjects,
  22481. lastCachedObject = objects[ firstActiveIndex ];
  22482. indicesByUUID[ lastCachedObject.uuid ] = index;
  22483. objects[ index ] = lastCachedObject;
  22484. indicesByUUID[ uuid ] = firstActiveIndex;
  22485. objects[ firstActiveIndex ] = object;
  22486. // accounting is done, now do the same for all bindings
  22487. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22488. var bindingsForPath = bindings[ j ],
  22489. lastCached = bindingsForPath[ firstActiveIndex ],
  22490. binding = bindingsForPath[ index ];
  22491. bindingsForPath[ index ] = lastCached;
  22492. if ( binding === undefined ) {
  22493. // since we do not bother to create new bindings
  22494. // for objects that are cached, the binding may
  22495. // or may not exist
  22496. binding = new PropertyBinding(
  22497. object, paths[ j ], parsedPaths[ j ] );
  22498. }
  22499. bindingsForPath[ firstActiveIndex ] = binding;
  22500. }
  22501. } else if ( objects[ index ] !== knownObject ) {
  22502. console.error( "Different objects with the same UUID " +
  22503. "detected. Clean the caches or recreate your " +
  22504. "infrastructure when reloading scenes..." );
  22505. } // else the object is already where we want it to be
  22506. } // for arguments
  22507. this.nCachedObjects_ = nCachedObjects;
  22508. },
  22509. remove: function( var_args ) {
  22510. var objects = this._objects,
  22511. nCachedObjects = this.nCachedObjects_,
  22512. indicesByUUID = this._indicesByUUID,
  22513. bindings = this._bindings,
  22514. nBindings = bindings.length;
  22515. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22516. var object = arguments[ i ],
  22517. uuid = object.uuid,
  22518. index = indicesByUUID[ uuid ];
  22519. if ( index !== undefined && index >= nCachedObjects ) {
  22520. // move existing object into the CACHED region
  22521. var lastCachedIndex = nCachedObjects ++,
  22522. firstActiveObject = objects[ lastCachedIndex ];
  22523. indicesByUUID[ firstActiveObject.uuid ] = index;
  22524. objects[ index ] = firstActiveObject;
  22525. indicesByUUID[ uuid ] = lastCachedIndex;
  22526. objects[ lastCachedIndex ] = object;
  22527. // accounting is done, now do the same for all bindings
  22528. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22529. var bindingsForPath = bindings[ j ],
  22530. firstActive = bindingsForPath[ lastCachedIndex ],
  22531. binding = bindingsForPath[ index ];
  22532. bindingsForPath[ index ] = firstActive;
  22533. bindingsForPath[ lastCachedIndex ] = binding;
  22534. }
  22535. }
  22536. } // for arguments
  22537. this.nCachedObjects_ = nCachedObjects;
  22538. },
  22539. // remove & forget
  22540. uncache: function( var_args ) {
  22541. var objects = this._objects,
  22542. nObjects = objects.length,
  22543. nCachedObjects = this.nCachedObjects_,
  22544. indicesByUUID = this._indicesByUUID,
  22545. bindings = this._bindings,
  22546. nBindings = bindings.length;
  22547. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22548. var object = arguments[ i ],
  22549. uuid = object.uuid,
  22550. index = indicesByUUID[ uuid ];
  22551. if ( index !== undefined ) {
  22552. delete indicesByUUID[ uuid ];
  22553. if ( index < nCachedObjects ) {
  22554. // object is cached, shrink the CACHED region
  22555. var firstActiveIndex = -- nCachedObjects,
  22556. lastCachedObject = objects[ firstActiveIndex ],
  22557. lastIndex = -- nObjects,
  22558. lastObject = objects[ lastIndex ];
  22559. // last cached object takes this object's place
  22560. indicesByUUID[ lastCachedObject.uuid ] = index;
  22561. objects[ index ] = lastCachedObject;
  22562. // last object goes to the activated slot and pop
  22563. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22564. objects[ firstActiveIndex ] = lastObject;
  22565. objects.pop();
  22566. // accounting is done, now do the same for all bindings
  22567. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22568. var bindingsForPath = bindings[ j ],
  22569. lastCached = bindingsForPath[ firstActiveIndex ],
  22570. last = bindingsForPath[ lastIndex ];
  22571. bindingsForPath[ index ] = lastCached;
  22572. bindingsForPath[ firstActiveIndex ] = last;
  22573. bindingsForPath.pop();
  22574. }
  22575. } else {
  22576. // object is active, just swap with the last and pop
  22577. var lastIndex = -- nObjects,
  22578. lastObject = objects[ lastIndex ];
  22579. indicesByUUID[ lastObject.uuid ] = index;
  22580. objects[ index ] = lastObject;
  22581. objects.pop();
  22582. // accounting is done, now do the same for all bindings
  22583. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22584. var bindingsForPath = bindings[ j ];
  22585. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22586. bindingsForPath.pop();
  22587. }
  22588. } // cached or active
  22589. } // if object is known
  22590. } // for arguments
  22591. this.nCachedObjects_ = nCachedObjects;
  22592. },
  22593. // Internal interface used by befriended PropertyBinding.Composite:
  22594. subscribe_: function ( path, parsedPath ) {
  22595. // returns an array of bindings for the given path that is changed
  22596. // according to the contained objects in the group
  22597. var indicesByPath = this._bindingsIndicesByPath,
  22598. index = indicesByPath[ path ],
  22599. bindings = this._bindings;
  22600. if ( index !== undefined ) return bindings[ index ];
  22601. var paths = this._paths,
  22602. parsedPaths = this._parsedPaths,
  22603. objects = this._objects,
  22604. nObjects = objects.length,
  22605. nCachedObjects = this.nCachedObjects_,
  22606. bindingsForPath = new Array( nObjects );
  22607. index = bindings.length;
  22608. indicesByPath[ path ] = index;
  22609. paths.push( path );
  22610. parsedPaths.push( parsedPath );
  22611. bindings.push( bindingsForPath );
  22612. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  22613. var object = objects[ i ];
  22614. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  22615. }
  22616. return bindingsForPath;
  22617. },
  22618. unsubscribe_: function ( path ) {
  22619. // tells the group to forget about a property path and no longer
  22620. // update the array previously obtained with 'subscribe_'
  22621. var indicesByPath = this._bindingsIndicesByPath,
  22622. index = indicesByPath[ path ];
  22623. if ( index !== undefined ) {
  22624. var paths = this._paths,
  22625. parsedPaths = this._parsedPaths,
  22626. bindings = this._bindings,
  22627. lastBindingsIndex = bindings.length - 1,
  22628. lastBindings = bindings[ lastBindingsIndex ],
  22629. lastBindingsPath = path[ lastBindingsIndex ];
  22630. indicesByPath[ lastBindingsPath ] = index;
  22631. bindings[ index ] = lastBindings;
  22632. bindings.pop();
  22633. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22634. parsedPaths.pop();
  22635. paths[ index ] = paths[ lastBindingsIndex ];
  22636. paths.pop();
  22637. }
  22638. }
  22639. } );
  22640. /**
  22641. *
  22642. * Action provided by AnimationMixer for scheduling clip playback on specific
  22643. * objects.
  22644. *
  22645. * @author Ben Houston / http://clara.io/
  22646. * @author David Sarno / http://lighthaus.us/
  22647. * @author tschw
  22648. *
  22649. */
  22650. function AnimationAction( mixer, clip, localRoot ) {
  22651. this._mixer = mixer;
  22652. this._clip = clip;
  22653. this._localRoot = localRoot || null;
  22654. var tracks = clip.tracks,
  22655. nTracks = tracks.length,
  22656. interpolants = new Array( nTracks );
  22657. var interpolantSettings = {
  22658. endingStart: ZeroCurvatureEnding,
  22659. endingEnd: ZeroCurvatureEnding
  22660. };
  22661. for ( var i = 0; i !== nTracks; ++ i ) {
  22662. var interpolant = tracks[ i ].createInterpolant( null );
  22663. interpolants[ i ] = interpolant;
  22664. interpolant.settings = interpolantSettings;
  22665. }
  22666. this._interpolantSettings = interpolantSettings;
  22667. this._interpolants = interpolants; // bound by the mixer
  22668. // inside: PropertyMixer (managed by the mixer)
  22669. this._propertyBindings = new Array( nTracks );
  22670. this._cacheIndex = null; // for the memory manager
  22671. this._byClipCacheIndex = null; // for the memory manager
  22672. this._timeScaleInterpolant = null;
  22673. this._weightInterpolant = null;
  22674. this.loop = LoopRepeat;
  22675. this._loopCount = -1;
  22676. // global mixer time when the action is to be started
  22677. // it's set back to 'null' upon start of the action
  22678. this._startTime = null;
  22679. // scaled local time of the action
  22680. // gets clamped or wrapped to 0..clip.duration according to loop
  22681. this.time = 0;
  22682. this.timeScale = 1;
  22683. this._effectiveTimeScale = 1;
  22684. this.weight = 1;
  22685. this._effectiveWeight = 1;
  22686. this.repetitions = Infinity; // no. of repetitions when looping
  22687. this.paused = false; // true -> zero effective time scale
  22688. this.enabled = true; // false -> zero effective weight
  22689. this.clampWhenFinished = false; // keep feeding the last frame?
  22690. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22691. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22692. }
  22693. Object.assign( AnimationAction.prototype, {
  22694. // State & Scheduling
  22695. play: function() {
  22696. this._mixer._activateAction( this );
  22697. return this;
  22698. },
  22699. stop: function() {
  22700. this._mixer._deactivateAction( this );
  22701. return this.reset();
  22702. },
  22703. reset: function() {
  22704. this.paused = false;
  22705. this.enabled = true;
  22706. this.time = 0; // restart clip
  22707. this._loopCount = -1; // forget previous loops
  22708. this._startTime = null; // forget scheduling
  22709. return this.stopFading().stopWarping();
  22710. },
  22711. isRunning: function() {
  22712. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22713. this._startTime === null && this._mixer._isActiveAction( this );
  22714. },
  22715. // return true when play has been called
  22716. isScheduled: function() {
  22717. return this._mixer._isActiveAction( this );
  22718. },
  22719. startAt: function( time ) {
  22720. this._startTime = time;
  22721. return this;
  22722. },
  22723. setLoop: function( mode, repetitions ) {
  22724. this.loop = mode;
  22725. this.repetitions = repetitions;
  22726. return this;
  22727. },
  22728. // Weight
  22729. // set the weight stopping any scheduled fading
  22730. // although .enabled = false yields an effective weight of zero, this
  22731. // method does *not* change .enabled, because it would be confusing
  22732. setEffectiveWeight: function( weight ) {
  22733. this.weight = weight;
  22734. // note: same logic as when updated at runtime
  22735. this._effectiveWeight = this.enabled ? weight : 0;
  22736. return this.stopFading();
  22737. },
  22738. // return the weight considering fading and .enabled
  22739. getEffectiveWeight: function() {
  22740. return this._effectiveWeight;
  22741. },
  22742. fadeIn: function( duration ) {
  22743. return this._scheduleFading( duration, 0, 1 );
  22744. },
  22745. fadeOut: function( duration ) {
  22746. return this._scheduleFading( duration, 1, 0 );
  22747. },
  22748. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22749. fadeOutAction.fadeOut( duration );
  22750. this.fadeIn( duration );
  22751. if( warp ) {
  22752. var fadeInDuration = this._clip.duration,
  22753. fadeOutDuration = fadeOutAction._clip.duration,
  22754. startEndRatio = fadeOutDuration / fadeInDuration,
  22755. endStartRatio = fadeInDuration / fadeOutDuration;
  22756. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22757. this.warp( endStartRatio, 1.0, duration );
  22758. }
  22759. return this;
  22760. },
  22761. crossFadeTo: function( fadeInAction, duration, warp ) {
  22762. return fadeInAction.crossFadeFrom( this, duration, warp );
  22763. },
  22764. stopFading: function() {
  22765. var weightInterpolant = this._weightInterpolant;
  22766. if ( weightInterpolant !== null ) {
  22767. this._weightInterpolant = null;
  22768. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22769. }
  22770. return this;
  22771. },
  22772. // Time Scale Control
  22773. // set the time scale stopping any scheduled warping
  22774. // although .paused = true yields an effective time scale of zero, this
  22775. // method does *not* change .paused, because it would be confusing
  22776. setEffectiveTimeScale: function( timeScale ) {
  22777. this.timeScale = timeScale;
  22778. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22779. return this.stopWarping();
  22780. },
  22781. // return the time scale considering warping and .paused
  22782. getEffectiveTimeScale: function() {
  22783. return this._effectiveTimeScale;
  22784. },
  22785. setDuration: function( duration ) {
  22786. this.timeScale = this._clip.duration / duration;
  22787. return this.stopWarping();
  22788. },
  22789. syncWith: function( action ) {
  22790. this.time = action.time;
  22791. this.timeScale = action.timeScale;
  22792. return this.stopWarping();
  22793. },
  22794. halt: function( duration ) {
  22795. return this.warp( this._effectiveTimeScale, 0, duration );
  22796. },
  22797. warp: function( startTimeScale, endTimeScale, duration ) {
  22798. var mixer = this._mixer, now = mixer.time,
  22799. interpolant = this._timeScaleInterpolant,
  22800. timeScale = this.timeScale;
  22801. if ( interpolant === null ) {
  22802. interpolant = mixer._lendControlInterpolant();
  22803. this._timeScaleInterpolant = interpolant;
  22804. }
  22805. var times = interpolant.parameterPositions,
  22806. values = interpolant.sampleValues;
  22807. times[ 0 ] = now;
  22808. times[ 1 ] = now + duration;
  22809. values[ 0 ] = startTimeScale / timeScale;
  22810. values[ 1 ] = endTimeScale / timeScale;
  22811. return this;
  22812. },
  22813. stopWarping: function() {
  22814. var timeScaleInterpolant = this._timeScaleInterpolant;
  22815. if ( timeScaleInterpolant !== null ) {
  22816. this._timeScaleInterpolant = null;
  22817. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22818. }
  22819. return this;
  22820. },
  22821. // Object Accessors
  22822. getMixer: function() {
  22823. return this._mixer;
  22824. },
  22825. getClip: function() {
  22826. return this._clip;
  22827. },
  22828. getRoot: function() {
  22829. return this._localRoot || this._mixer._root;
  22830. },
  22831. // Interna
  22832. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22833. // called by the mixer
  22834. if ( ! this.enabled ) {
  22835. // call ._updateWeight() to update ._effectiveWeight
  22836. this._updateWeight( time );
  22837. return;
  22838. }
  22839. var startTime = this._startTime;
  22840. if ( startTime !== null ) {
  22841. // check for scheduled start of action
  22842. var timeRunning = ( time - startTime ) * timeDirection;
  22843. if ( timeRunning < 0 || timeDirection === 0 ) {
  22844. return; // yet to come / don't decide when delta = 0
  22845. }
  22846. // start
  22847. this._startTime = null; // unschedule
  22848. deltaTime = timeDirection * timeRunning;
  22849. }
  22850. // apply time scale and advance time
  22851. deltaTime *= this._updateTimeScale( time );
  22852. var clipTime = this._updateTime( deltaTime );
  22853. // note: _updateTime may disable the action resulting in
  22854. // an effective weight of 0
  22855. var weight = this._updateWeight( time );
  22856. if ( weight > 0 ) {
  22857. var interpolants = this._interpolants;
  22858. var propertyMixers = this._propertyBindings;
  22859. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22860. interpolants[ j ].evaluate( clipTime );
  22861. propertyMixers[ j ].accumulate( accuIndex, weight );
  22862. }
  22863. }
  22864. },
  22865. _updateWeight: function( time ) {
  22866. var weight = 0;
  22867. if ( this.enabled ) {
  22868. weight = this.weight;
  22869. var interpolant = this._weightInterpolant;
  22870. if ( interpolant !== null ) {
  22871. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22872. weight *= interpolantValue;
  22873. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22874. this.stopFading();
  22875. if ( interpolantValue === 0 ) {
  22876. // faded out, disable
  22877. this.enabled = false;
  22878. }
  22879. }
  22880. }
  22881. }
  22882. this._effectiveWeight = weight;
  22883. return weight;
  22884. },
  22885. _updateTimeScale: function( time ) {
  22886. var timeScale = 0;
  22887. if ( ! this.paused ) {
  22888. timeScale = this.timeScale;
  22889. var interpolant = this._timeScaleInterpolant;
  22890. if ( interpolant !== null ) {
  22891. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22892. timeScale *= interpolantValue;
  22893. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22894. this.stopWarping();
  22895. if ( timeScale === 0 ) {
  22896. // motion has halted, pause
  22897. this.paused = true;
  22898. } else {
  22899. // warp done - apply final time scale
  22900. this.timeScale = timeScale;
  22901. }
  22902. }
  22903. }
  22904. }
  22905. this._effectiveTimeScale = timeScale;
  22906. return timeScale;
  22907. },
  22908. _updateTime: function( deltaTime ) {
  22909. var time = this.time + deltaTime;
  22910. if ( deltaTime === 0 ) return time;
  22911. var duration = this._clip.duration,
  22912. loop = this.loop,
  22913. loopCount = this._loopCount;
  22914. if ( loop === LoopOnce ) {
  22915. if ( loopCount === -1 ) {
  22916. // just started
  22917. this._loopCount = 0;
  22918. this._setEndings( true, true, false );
  22919. }
  22920. handle_stop: {
  22921. if ( time >= duration ) {
  22922. time = duration;
  22923. } else if ( time < 0 ) {
  22924. time = 0;
  22925. } else break handle_stop;
  22926. if ( this.clampWhenFinished ) this.paused = true;
  22927. else this.enabled = false;
  22928. this._mixer.dispatchEvent( {
  22929. type: 'finished', action: this,
  22930. direction: deltaTime < 0 ? -1 : 1
  22931. } );
  22932. }
  22933. } else { // repetitive Repeat or PingPong
  22934. var pingPong = ( loop === LoopPingPong );
  22935. if ( loopCount === -1 ) {
  22936. // just started
  22937. if ( deltaTime >= 0 ) {
  22938. loopCount = 0;
  22939. this._setEndings(
  22940. true, this.repetitions === 0, pingPong );
  22941. } else {
  22942. // when looping in reverse direction, the initial
  22943. // transition through zero counts as a repetition,
  22944. // so leave loopCount at -1
  22945. this._setEndings(
  22946. this.repetitions === 0, true, pingPong );
  22947. }
  22948. }
  22949. if ( time >= duration || time < 0 ) {
  22950. // wrap around
  22951. var loopDelta = Math.floor( time / duration ); // signed
  22952. time -= duration * loopDelta;
  22953. loopCount += Math.abs( loopDelta );
  22954. var pending = this.repetitions - loopCount;
  22955. if ( pending < 0 ) {
  22956. // have to stop (switch state, clamp time, fire event)
  22957. if ( this.clampWhenFinished ) this.paused = true;
  22958. else this.enabled = false;
  22959. time = deltaTime > 0 ? duration : 0;
  22960. this._mixer.dispatchEvent( {
  22961. type: 'finished', action: this,
  22962. direction: deltaTime > 0 ? 1 : -1
  22963. } );
  22964. } else {
  22965. // keep running
  22966. if ( pending === 0 ) {
  22967. // entering the last round
  22968. var atStart = deltaTime < 0;
  22969. this._setEndings( atStart, ! atStart, pingPong );
  22970. } else {
  22971. this._setEndings( false, false, pingPong );
  22972. }
  22973. this._loopCount = loopCount;
  22974. this._mixer.dispatchEvent( {
  22975. type: 'loop', action: this, loopDelta: loopDelta
  22976. } );
  22977. }
  22978. }
  22979. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22980. // invert time for the "pong round"
  22981. this.time = time;
  22982. return duration - time;
  22983. }
  22984. }
  22985. this.time = time;
  22986. return time;
  22987. },
  22988. _setEndings: function( atStart, atEnd, pingPong ) {
  22989. var settings = this._interpolantSettings;
  22990. if ( pingPong ) {
  22991. settings.endingStart = ZeroSlopeEnding;
  22992. settings.endingEnd = ZeroSlopeEnding;
  22993. } else {
  22994. // assuming for LoopOnce atStart == atEnd == true
  22995. if ( atStart ) {
  22996. settings.endingStart = this.zeroSlopeAtStart ?
  22997. ZeroSlopeEnding : ZeroCurvatureEnding;
  22998. } else {
  22999. settings.endingStart = WrapAroundEnding;
  23000. }
  23001. if ( atEnd ) {
  23002. settings.endingEnd = this.zeroSlopeAtEnd ?
  23003. ZeroSlopeEnding : ZeroCurvatureEnding;
  23004. } else {
  23005. settings.endingEnd = WrapAroundEnding;
  23006. }
  23007. }
  23008. },
  23009. _scheduleFading: function( duration, weightNow, weightThen ) {
  23010. var mixer = this._mixer, now = mixer.time,
  23011. interpolant = this._weightInterpolant;
  23012. if ( interpolant === null ) {
  23013. interpolant = mixer._lendControlInterpolant();
  23014. this._weightInterpolant = interpolant;
  23015. }
  23016. var times = interpolant.parameterPositions,
  23017. values = interpolant.sampleValues;
  23018. times[ 0 ] = now; values[ 0 ] = weightNow;
  23019. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  23020. return this;
  23021. }
  23022. } );
  23023. /**
  23024. *
  23025. * Player for AnimationClips.
  23026. *
  23027. *
  23028. * @author Ben Houston / http://clara.io/
  23029. * @author David Sarno / http://lighthaus.us/
  23030. * @author tschw
  23031. */
  23032. function AnimationMixer( root ) {
  23033. this._root = root;
  23034. this._initMemoryManager();
  23035. this._accuIndex = 0;
  23036. this.time = 0;
  23037. this.timeScale = 1.0;
  23038. }
  23039. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  23040. _bindAction: function ( action, prototypeAction ) {
  23041. var root = action._localRoot || this._root,
  23042. tracks = action._clip.tracks,
  23043. nTracks = tracks.length,
  23044. bindings = action._propertyBindings,
  23045. interpolants = action._interpolants,
  23046. rootUuid = root.uuid,
  23047. bindingsByRoot = this._bindingsByRootAndName,
  23048. bindingsByName = bindingsByRoot[ rootUuid ];
  23049. if ( bindingsByName === undefined ) {
  23050. bindingsByName = {};
  23051. bindingsByRoot[ rootUuid ] = bindingsByName;
  23052. }
  23053. for ( var i = 0; i !== nTracks; ++ i ) {
  23054. var track = tracks[ i ],
  23055. trackName = track.name,
  23056. binding = bindingsByName[ trackName ];
  23057. if ( binding !== undefined ) {
  23058. bindings[ i ] = binding;
  23059. } else {
  23060. binding = bindings[ i ];
  23061. if ( binding !== undefined ) {
  23062. // existing binding, make sure the cache knows
  23063. if ( binding._cacheIndex === null ) {
  23064. ++ binding.referenceCount;
  23065. this._addInactiveBinding( binding, rootUuid, trackName );
  23066. }
  23067. continue;
  23068. }
  23069. var path = prototypeAction && prototypeAction.
  23070. _propertyBindings[ i ].binding.parsedPath;
  23071. binding = new PropertyMixer(
  23072. PropertyBinding.create( root, trackName, path ),
  23073. track.ValueTypeName, track.getValueSize() );
  23074. ++ binding.referenceCount;
  23075. this._addInactiveBinding( binding, rootUuid, trackName );
  23076. bindings[ i ] = binding;
  23077. }
  23078. interpolants[ i ].resultBuffer = binding.buffer;
  23079. }
  23080. },
  23081. _activateAction: function ( action ) {
  23082. if ( ! this._isActiveAction( action ) ) {
  23083. if ( action._cacheIndex === null ) {
  23084. // this action has been forgotten by the cache, but the user
  23085. // appears to be still using it -> rebind
  23086. var rootUuid = ( action._localRoot || this._root ).uuid,
  23087. clipUuid = action._clip.uuid,
  23088. actionsForClip = this._actionsByClip[ clipUuid ];
  23089. this._bindAction( action,
  23090. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23091. this._addInactiveAction( action, clipUuid, rootUuid );
  23092. }
  23093. var bindings = action._propertyBindings;
  23094. // increment reference counts / sort out state
  23095. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23096. var binding = bindings[ i ];
  23097. if ( binding.useCount ++ === 0 ) {
  23098. this._lendBinding( binding );
  23099. binding.saveOriginalState();
  23100. }
  23101. }
  23102. this._lendAction( action );
  23103. }
  23104. },
  23105. _deactivateAction: function ( action ) {
  23106. if ( this._isActiveAction( action ) ) {
  23107. var bindings = action._propertyBindings;
  23108. // decrement reference counts / sort out state
  23109. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23110. var binding = bindings[ i ];
  23111. if ( -- binding.useCount === 0 ) {
  23112. binding.restoreOriginalState();
  23113. this._takeBackBinding( binding );
  23114. }
  23115. }
  23116. this._takeBackAction( action );
  23117. }
  23118. },
  23119. // Memory manager
  23120. _initMemoryManager: function () {
  23121. this._actions = []; // 'nActiveActions' followed by inactive ones
  23122. this._nActiveActions = 0;
  23123. this._actionsByClip = {};
  23124. // inside:
  23125. // {
  23126. // knownActions: Array< AnimationAction > - used as prototypes
  23127. // actionByRoot: AnimationAction - lookup
  23128. // }
  23129. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23130. this._nActiveBindings = 0;
  23131. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23132. this._controlInterpolants = []; // same game as above
  23133. this._nActiveControlInterpolants = 0;
  23134. var scope = this;
  23135. this.stats = {
  23136. actions: {
  23137. get total() { return scope._actions.length; },
  23138. get inUse() { return scope._nActiveActions; }
  23139. },
  23140. bindings: {
  23141. get total() { return scope._bindings.length; },
  23142. get inUse() { return scope._nActiveBindings; }
  23143. },
  23144. controlInterpolants: {
  23145. get total() { return scope._controlInterpolants.length; },
  23146. get inUse() { return scope._nActiveControlInterpolants; }
  23147. }
  23148. };
  23149. },
  23150. // Memory management for AnimationAction objects
  23151. _isActiveAction: function ( action ) {
  23152. var index = action._cacheIndex;
  23153. return index !== null && index < this._nActiveActions;
  23154. },
  23155. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23156. var actions = this._actions,
  23157. actionsByClip = this._actionsByClip,
  23158. actionsForClip = actionsByClip[ clipUuid ];
  23159. if ( actionsForClip === undefined ) {
  23160. actionsForClip = {
  23161. knownActions: [ action ],
  23162. actionByRoot: {}
  23163. };
  23164. action._byClipCacheIndex = 0;
  23165. actionsByClip[ clipUuid ] = actionsForClip;
  23166. } else {
  23167. var knownActions = actionsForClip.knownActions;
  23168. action._byClipCacheIndex = knownActions.length;
  23169. knownActions.push( action );
  23170. }
  23171. action._cacheIndex = actions.length;
  23172. actions.push( action );
  23173. actionsForClip.actionByRoot[ rootUuid ] = action;
  23174. },
  23175. _removeInactiveAction: function ( action ) {
  23176. var actions = this._actions,
  23177. lastInactiveAction = actions[ actions.length - 1 ],
  23178. cacheIndex = action._cacheIndex;
  23179. lastInactiveAction._cacheIndex = cacheIndex;
  23180. actions[ cacheIndex ] = lastInactiveAction;
  23181. actions.pop();
  23182. action._cacheIndex = null;
  23183. var clipUuid = action._clip.uuid,
  23184. actionsByClip = this._actionsByClip,
  23185. actionsForClip = actionsByClip[ clipUuid ],
  23186. knownActionsForClip = actionsForClip.knownActions,
  23187. lastKnownAction =
  23188. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23189. byClipCacheIndex = action._byClipCacheIndex;
  23190. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23191. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23192. knownActionsForClip.pop();
  23193. action._byClipCacheIndex = null;
  23194. var actionByRoot = actionsForClip.actionByRoot,
  23195. rootUuid = ( action._localRoot || this._root ).uuid;
  23196. delete actionByRoot[ rootUuid ];
  23197. if ( knownActionsForClip.length === 0 ) {
  23198. delete actionsByClip[ clipUuid ];
  23199. }
  23200. this._removeInactiveBindingsForAction( action );
  23201. },
  23202. _removeInactiveBindingsForAction: function ( action ) {
  23203. var bindings = action._propertyBindings;
  23204. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23205. var binding = bindings[ i ];
  23206. if ( -- binding.referenceCount === 0 ) {
  23207. this._removeInactiveBinding( binding );
  23208. }
  23209. }
  23210. },
  23211. _lendAction: function ( action ) {
  23212. // [ active actions | inactive actions ]
  23213. // [ active actions >| inactive actions ]
  23214. // s a
  23215. // <-swap->
  23216. // a s
  23217. var actions = this._actions,
  23218. prevIndex = action._cacheIndex,
  23219. lastActiveIndex = this._nActiveActions ++,
  23220. firstInactiveAction = actions[ lastActiveIndex ];
  23221. action._cacheIndex = lastActiveIndex;
  23222. actions[ lastActiveIndex ] = action;
  23223. firstInactiveAction._cacheIndex = prevIndex;
  23224. actions[ prevIndex ] = firstInactiveAction;
  23225. },
  23226. _takeBackAction: function ( action ) {
  23227. // [ active actions | inactive actions ]
  23228. // [ active actions |< inactive actions ]
  23229. // a s
  23230. // <-swap->
  23231. // s a
  23232. var actions = this._actions,
  23233. prevIndex = action._cacheIndex,
  23234. firstInactiveIndex = -- this._nActiveActions,
  23235. lastActiveAction = actions[ firstInactiveIndex ];
  23236. action._cacheIndex = firstInactiveIndex;
  23237. actions[ firstInactiveIndex ] = action;
  23238. lastActiveAction._cacheIndex = prevIndex;
  23239. actions[ prevIndex ] = lastActiveAction;
  23240. },
  23241. // Memory management for PropertyMixer objects
  23242. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23243. var bindingsByRoot = this._bindingsByRootAndName,
  23244. bindingByName = bindingsByRoot[ rootUuid ],
  23245. bindings = this._bindings;
  23246. if ( bindingByName === undefined ) {
  23247. bindingByName = {};
  23248. bindingsByRoot[ rootUuid ] = bindingByName;
  23249. }
  23250. bindingByName[ trackName ] = binding;
  23251. binding._cacheIndex = bindings.length;
  23252. bindings.push( binding );
  23253. },
  23254. _removeInactiveBinding: function ( binding ) {
  23255. var bindings = this._bindings,
  23256. propBinding = binding.binding,
  23257. rootUuid = propBinding.rootNode.uuid,
  23258. trackName = propBinding.path,
  23259. bindingsByRoot = this._bindingsByRootAndName,
  23260. bindingByName = bindingsByRoot[ rootUuid ],
  23261. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23262. cacheIndex = binding._cacheIndex;
  23263. lastInactiveBinding._cacheIndex = cacheIndex;
  23264. bindings[ cacheIndex ] = lastInactiveBinding;
  23265. bindings.pop();
  23266. delete bindingByName[ trackName ];
  23267. remove_empty_map: {
  23268. for ( var _ in bindingByName ) break remove_empty_map;
  23269. delete bindingsByRoot[ rootUuid ];
  23270. }
  23271. },
  23272. _lendBinding: function ( binding ) {
  23273. var bindings = this._bindings,
  23274. prevIndex = binding._cacheIndex,
  23275. lastActiveIndex = this._nActiveBindings ++,
  23276. firstInactiveBinding = bindings[ lastActiveIndex ];
  23277. binding._cacheIndex = lastActiveIndex;
  23278. bindings[ lastActiveIndex ] = binding;
  23279. firstInactiveBinding._cacheIndex = prevIndex;
  23280. bindings[ prevIndex ] = firstInactiveBinding;
  23281. },
  23282. _takeBackBinding: function ( binding ) {
  23283. var bindings = this._bindings,
  23284. prevIndex = binding._cacheIndex,
  23285. firstInactiveIndex = -- this._nActiveBindings,
  23286. lastActiveBinding = bindings[ firstInactiveIndex ];
  23287. binding._cacheIndex = firstInactiveIndex;
  23288. bindings[ firstInactiveIndex ] = binding;
  23289. lastActiveBinding._cacheIndex = prevIndex;
  23290. bindings[ prevIndex ] = lastActiveBinding;
  23291. },
  23292. // Memory management of Interpolants for weight and time scale
  23293. _lendControlInterpolant: function () {
  23294. var interpolants = this._controlInterpolants,
  23295. lastActiveIndex = this._nActiveControlInterpolants ++,
  23296. interpolant = interpolants[ lastActiveIndex ];
  23297. if ( interpolant === undefined ) {
  23298. interpolant = new LinearInterpolant(
  23299. new Float32Array( 2 ), new Float32Array( 2 ),
  23300. 1, this._controlInterpolantsResultBuffer );
  23301. interpolant.__cacheIndex = lastActiveIndex;
  23302. interpolants[ lastActiveIndex ] = interpolant;
  23303. }
  23304. return interpolant;
  23305. },
  23306. _takeBackControlInterpolant: function ( interpolant ) {
  23307. var interpolants = this._controlInterpolants,
  23308. prevIndex = interpolant.__cacheIndex,
  23309. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23310. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23311. interpolant.__cacheIndex = firstInactiveIndex;
  23312. interpolants[ firstInactiveIndex ] = interpolant;
  23313. lastActiveInterpolant.__cacheIndex = prevIndex;
  23314. interpolants[ prevIndex ] = lastActiveInterpolant;
  23315. },
  23316. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  23317. // return an action for a clip optionally using a custom root target
  23318. // object (this method allocates a lot of dynamic memory in case a
  23319. // previously unknown clip/root combination is specified)
  23320. clipAction: function ( clip, optionalRoot ) {
  23321. var root = optionalRoot || this._root,
  23322. rootUuid = root.uuid,
  23323. clipObject = typeof clip === 'string' ?
  23324. AnimationClip.findByName( root, clip ) : clip,
  23325. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  23326. actionsForClip = this._actionsByClip[ clipUuid ],
  23327. prototypeAction = null;
  23328. if ( actionsForClip !== undefined ) {
  23329. var existingAction =
  23330. actionsForClip.actionByRoot[ rootUuid ];
  23331. if ( existingAction !== undefined ) {
  23332. return existingAction;
  23333. }
  23334. // we know the clip, so we don't have to parse all
  23335. // the bindings again but can just copy
  23336. prototypeAction = actionsForClip.knownActions[ 0 ];
  23337. // also, take the clip from the prototype action
  23338. if ( clipObject === null )
  23339. clipObject = prototypeAction._clip;
  23340. }
  23341. // clip must be known when specified via string
  23342. if ( clipObject === null ) return null;
  23343. // allocate all resources required to run it
  23344. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  23345. this._bindAction( newAction, prototypeAction );
  23346. // and make the action known to the memory manager
  23347. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23348. return newAction;
  23349. },
  23350. // get an existing action
  23351. existingAction: function ( clip, optionalRoot ) {
  23352. var root = optionalRoot || this._root,
  23353. rootUuid = root.uuid,
  23354. clipObject = typeof clip === 'string' ?
  23355. AnimationClip.findByName( root, clip ) : clip,
  23356. clipUuid = clipObject ? clipObject.uuid : clip,
  23357. actionsForClip = this._actionsByClip[ clipUuid ];
  23358. if ( actionsForClip !== undefined ) {
  23359. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23360. }
  23361. return null;
  23362. },
  23363. // deactivates all previously scheduled actions
  23364. stopAllAction: function () {
  23365. var actions = this._actions,
  23366. nActions = this._nActiveActions,
  23367. bindings = this._bindings,
  23368. nBindings = this._nActiveBindings;
  23369. this._nActiveActions = 0;
  23370. this._nActiveBindings = 0;
  23371. for ( var i = 0; i !== nActions; ++ i ) {
  23372. actions[ i ].reset();
  23373. }
  23374. for ( var i = 0; i !== nBindings; ++ i ) {
  23375. bindings[ i ].useCount = 0;
  23376. }
  23377. return this;
  23378. },
  23379. // advance the time and update apply the animation
  23380. update: function ( deltaTime ) {
  23381. deltaTime *= this.timeScale;
  23382. var actions = this._actions,
  23383. nActions = this._nActiveActions,
  23384. time = this.time += deltaTime,
  23385. timeDirection = Math.sign( deltaTime ),
  23386. accuIndex = this._accuIndex ^= 1;
  23387. // run active actions
  23388. for ( var i = 0; i !== nActions; ++ i ) {
  23389. var action = actions[ i ];
  23390. action._update( time, deltaTime, timeDirection, accuIndex );
  23391. }
  23392. // update scene graph
  23393. var bindings = this._bindings,
  23394. nBindings = this._nActiveBindings;
  23395. for ( var i = 0; i !== nBindings; ++ i ) {
  23396. bindings[ i ].apply( accuIndex );
  23397. }
  23398. return this;
  23399. },
  23400. // return this mixer's root target object
  23401. getRoot: function () {
  23402. return this._root;
  23403. },
  23404. // free all resources specific to a particular clip
  23405. uncacheClip: function ( clip ) {
  23406. var actions = this._actions,
  23407. clipUuid = clip.uuid,
  23408. actionsByClip = this._actionsByClip,
  23409. actionsForClip = actionsByClip[ clipUuid ];
  23410. if ( actionsForClip !== undefined ) {
  23411. // note: just calling _removeInactiveAction would mess up the
  23412. // iteration state and also require updating the state we can
  23413. // just throw away
  23414. var actionsToRemove = actionsForClip.knownActions;
  23415. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23416. var action = actionsToRemove[ i ];
  23417. this._deactivateAction( action );
  23418. var cacheIndex = action._cacheIndex,
  23419. lastInactiveAction = actions[ actions.length - 1 ];
  23420. action._cacheIndex = null;
  23421. action._byClipCacheIndex = null;
  23422. lastInactiveAction._cacheIndex = cacheIndex;
  23423. actions[ cacheIndex ] = lastInactiveAction;
  23424. actions.pop();
  23425. this._removeInactiveBindingsForAction( action );
  23426. }
  23427. delete actionsByClip[ clipUuid ];
  23428. }
  23429. },
  23430. // free all resources specific to a particular root target object
  23431. uncacheRoot: function ( root ) {
  23432. var rootUuid = root.uuid,
  23433. actionsByClip = this._actionsByClip;
  23434. for ( var clipUuid in actionsByClip ) {
  23435. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23436. action = actionByRoot[ rootUuid ];
  23437. if ( action !== undefined ) {
  23438. this._deactivateAction( action );
  23439. this._removeInactiveAction( action );
  23440. }
  23441. }
  23442. var bindingsByRoot = this._bindingsByRootAndName,
  23443. bindingByName = bindingsByRoot[ rootUuid ];
  23444. if ( bindingByName !== undefined ) {
  23445. for ( var trackName in bindingByName ) {
  23446. var binding = bindingByName[ trackName ];
  23447. binding.restoreOriginalState();
  23448. this._removeInactiveBinding( binding );
  23449. }
  23450. }
  23451. },
  23452. // remove a targeted clip from the cache
  23453. uncacheAction: function ( clip, optionalRoot ) {
  23454. var action = this.existingAction( clip, optionalRoot );
  23455. if ( action !== null ) {
  23456. this._deactivateAction( action );
  23457. this._removeInactiveAction( action );
  23458. }
  23459. }
  23460. } );
  23461. /**
  23462. * @author mrdoob / http://mrdoob.com/
  23463. */
  23464. function Uniform( value ) {
  23465. if ( typeof value === 'string' ) {
  23466. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23467. value = arguments[ 1 ];
  23468. }
  23469. this.value = value;
  23470. }
  23471. Uniform.prototype.clone = function () {
  23472. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23473. };
  23474. /**
  23475. * @author benaadams / https://twitter.com/ben_a_adams
  23476. */
  23477. function InstancedBufferGeometry() {
  23478. BufferGeometry.call( this );
  23479. this.type = 'InstancedBufferGeometry';
  23480. this.maxInstancedCount = undefined;
  23481. }
  23482. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  23483. constructor: InstancedBufferGeometry,
  23484. isInstancedBufferGeometry: true,
  23485. addGroup: function ( start, count, materialIndex ) {
  23486. this.groups.push( {
  23487. start: start,
  23488. count: count,
  23489. materialIndex: materialIndex
  23490. } );
  23491. },
  23492. copy: function ( source ) {
  23493. var index = source.index;
  23494. if ( index !== null ) {
  23495. this.setIndex( index.clone() );
  23496. }
  23497. var attributes = source.attributes;
  23498. for ( var name in attributes ) {
  23499. var attribute = attributes[ name ];
  23500. this.addAttribute( name, attribute.clone() );
  23501. }
  23502. var groups = source.groups;
  23503. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23504. var group = groups[ i ];
  23505. this.addGroup( group.start, group.count, group.materialIndex );
  23506. }
  23507. return this;
  23508. }
  23509. } );
  23510. /**
  23511. * @author benaadams / https://twitter.com/ben_a_adams
  23512. */
  23513. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23514. this.uuid = _Math.generateUUID();
  23515. this.data = interleavedBuffer;
  23516. this.itemSize = itemSize;
  23517. this.offset = offset;
  23518. this.normalized = normalized === true;
  23519. }
  23520. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  23521. count: {
  23522. get: function () {
  23523. return this.data.count;
  23524. }
  23525. },
  23526. array: {
  23527. get: function () {
  23528. return this.data.array;
  23529. }
  23530. }
  23531. } );
  23532. Object.assign( InterleavedBufferAttribute.prototype, {
  23533. isInterleavedBufferAttribute: true,
  23534. setX: function ( index, x ) {
  23535. this.data.array[ index * this.data.stride + this.offset ] = x;
  23536. return this;
  23537. },
  23538. setY: function ( index, y ) {
  23539. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23540. return this;
  23541. },
  23542. setZ: function ( index, z ) {
  23543. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23544. return this;
  23545. },
  23546. setW: function ( index, w ) {
  23547. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23548. return this;
  23549. },
  23550. getX: function ( index ) {
  23551. return this.data.array[ index * this.data.stride + this.offset ];
  23552. },
  23553. getY: function ( index ) {
  23554. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23555. },
  23556. getZ: function ( index ) {
  23557. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23558. },
  23559. getW: function ( index ) {
  23560. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23561. },
  23562. setXY: function ( index, x, y ) {
  23563. index = index * this.data.stride + this.offset;
  23564. this.data.array[ index + 0 ] = x;
  23565. this.data.array[ index + 1 ] = y;
  23566. return this;
  23567. },
  23568. setXYZ: function ( index, x, y, z ) {
  23569. index = index * this.data.stride + this.offset;
  23570. this.data.array[ index + 0 ] = x;
  23571. this.data.array[ index + 1 ] = y;
  23572. this.data.array[ index + 2 ] = z;
  23573. return this;
  23574. },
  23575. setXYZW: function ( index, x, y, z, w ) {
  23576. index = index * this.data.stride + this.offset;
  23577. this.data.array[ index + 0 ] = x;
  23578. this.data.array[ index + 1 ] = y;
  23579. this.data.array[ index + 2 ] = z;
  23580. this.data.array[ index + 3 ] = w;
  23581. return this;
  23582. }
  23583. } );
  23584. /**
  23585. * @author benaadams / https://twitter.com/ben_a_adams
  23586. */
  23587. function InterleavedBuffer( array, stride ) {
  23588. this.uuid = _Math.generateUUID();
  23589. this.array = array;
  23590. this.stride = stride;
  23591. this.count = array !== undefined ? array.length / stride : 0;
  23592. this.dynamic = false;
  23593. this.updateRange = { offset: 0, count: - 1 };
  23594. this.onUploadCallback = function () {};
  23595. this.version = 0;
  23596. }
  23597. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  23598. set: function ( value ) {
  23599. if ( value === true ) this.version ++;
  23600. }
  23601. } );
  23602. Object.assign( InterleavedBuffer.prototype, {
  23603. isInterleavedBuffer: true,
  23604. setArray: function ( array ) {
  23605. if ( Array.isArray( array ) ) {
  23606. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23607. }
  23608. this.count = array !== undefined ? array.length / this.stride : 0;
  23609. this.array = array;
  23610. },
  23611. setDynamic: function ( value ) {
  23612. this.dynamic = value;
  23613. return this;
  23614. },
  23615. copy: function ( source ) {
  23616. this.array = new source.array.constructor( source.array );
  23617. this.count = source.count;
  23618. this.stride = source.stride;
  23619. this.dynamic = source.dynamic;
  23620. return this;
  23621. },
  23622. copyAt: function ( index1, attribute, index2 ) {
  23623. index1 *= this.stride;
  23624. index2 *= attribute.stride;
  23625. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23626. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23627. }
  23628. return this;
  23629. },
  23630. set: function ( value, offset ) {
  23631. if ( offset === undefined ) offset = 0;
  23632. this.array.set( value, offset );
  23633. return this;
  23634. },
  23635. clone: function () {
  23636. return new this.constructor().copy( this );
  23637. },
  23638. onUpload: function ( callback ) {
  23639. this.onUploadCallback = callback;
  23640. return this;
  23641. }
  23642. } );
  23643. /**
  23644. * @author benaadams / https://twitter.com/ben_a_adams
  23645. */
  23646. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23647. InterleavedBuffer.call( this, array, stride );
  23648. this.meshPerAttribute = meshPerAttribute || 1;
  23649. }
  23650. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  23651. constructor: InstancedInterleavedBuffer,
  23652. isInstancedInterleavedBuffer: true,
  23653. copy: function ( source ) {
  23654. InterleavedBuffer.prototype.copy.call( this, source );
  23655. this.meshPerAttribute = source.meshPerAttribute;
  23656. return this;
  23657. }
  23658. } );
  23659. /**
  23660. * @author benaadams / https://twitter.com/ben_a_adams
  23661. */
  23662. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23663. BufferAttribute.call( this, array, itemSize );
  23664. this.meshPerAttribute = meshPerAttribute || 1;
  23665. }
  23666. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  23667. constructor: InstancedBufferAttribute,
  23668. isInstancedBufferAttribute: true,
  23669. copy: function ( source ) {
  23670. BufferAttribute.prototype.copy.call( this, source );
  23671. this.meshPerAttribute = source.meshPerAttribute;
  23672. return this;
  23673. }
  23674. } );
  23675. /**
  23676. * @author mrdoob / http://mrdoob.com/
  23677. * @author bhouston / http://clara.io/
  23678. * @author stephomi / http://stephaneginier.com/
  23679. */
  23680. function Raycaster( origin, direction, near, far ) {
  23681. this.ray = new Ray( origin, direction );
  23682. // direction is assumed to be normalized (for accurate distance calculations)
  23683. this.near = near || 0;
  23684. this.far = far || Infinity;
  23685. this.params = {
  23686. Mesh: {},
  23687. Line: {},
  23688. LOD: {},
  23689. Points: { threshold: 1 },
  23690. Sprite: {}
  23691. };
  23692. Object.defineProperties( this.params, {
  23693. PointCloud: {
  23694. get: function () {
  23695. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23696. return this.Points;
  23697. }
  23698. }
  23699. } );
  23700. }
  23701. function ascSort( a, b ) {
  23702. return a.distance - b.distance;
  23703. }
  23704. function intersectObject( object, raycaster, intersects, recursive ) {
  23705. if ( object.visible === false ) return;
  23706. object.raycast( raycaster, intersects );
  23707. if ( recursive === true ) {
  23708. var children = object.children;
  23709. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23710. intersectObject( children[ i ], raycaster, intersects, true );
  23711. }
  23712. }
  23713. }
  23714. Object.assign( Raycaster.prototype, {
  23715. linePrecision: 1,
  23716. set: function ( origin, direction ) {
  23717. // direction is assumed to be normalized (for accurate distance calculations)
  23718. this.ray.set( origin, direction );
  23719. },
  23720. setFromCamera: function ( coords, camera ) {
  23721. if ( ( camera && camera.isPerspectiveCamera ) ) {
  23722. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23723. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23724. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  23725. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23726. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23727. } else {
  23728. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23729. }
  23730. },
  23731. intersectObject: function ( object, recursive ) {
  23732. var intersects = [];
  23733. intersectObject( object, this, intersects, recursive );
  23734. intersects.sort( ascSort );
  23735. return intersects;
  23736. },
  23737. intersectObjects: function ( objects, recursive ) {
  23738. var intersects = [];
  23739. if ( Array.isArray( objects ) === false ) {
  23740. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23741. return intersects;
  23742. }
  23743. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23744. intersectObject( objects[ i ], this, intersects, recursive );
  23745. }
  23746. intersects.sort( ascSort );
  23747. return intersects;
  23748. }
  23749. } );
  23750. /**
  23751. * @author alteredq / http://alteredqualia.com/
  23752. */
  23753. function Clock( autoStart ) {
  23754. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23755. this.startTime = 0;
  23756. this.oldTime = 0;
  23757. this.elapsedTime = 0;
  23758. this.running = false;
  23759. }
  23760. Object.assign( Clock.prototype, {
  23761. start: function () {
  23762. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  23763. this.oldTime = this.startTime;
  23764. this.elapsedTime = 0;
  23765. this.running = true;
  23766. },
  23767. stop: function () {
  23768. this.getElapsedTime();
  23769. this.running = false;
  23770. },
  23771. getElapsedTime: function () {
  23772. this.getDelta();
  23773. return this.elapsedTime;
  23774. },
  23775. getDelta: function () {
  23776. var diff = 0;
  23777. if ( this.autoStart && ! this.running ) {
  23778. this.start();
  23779. return 0;
  23780. }
  23781. if ( this.running ) {
  23782. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  23783. diff = ( newTime - this.oldTime ) / 1000;
  23784. this.oldTime = newTime;
  23785. this.elapsedTime += diff;
  23786. }
  23787. return diff;
  23788. }
  23789. } );
  23790. /**
  23791. * @author bhouston / http://clara.io
  23792. * @author WestLangley / http://github.com/WestLangley
  23793. *
  23794. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23795. *
  23796. * The poles (phi) are at the positive and negative y axis.
  23797. * The equator starts at positive z.
  23798. */
  23799. function Spherical( radius, phi, theta ) {
  23800. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23801. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23802. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23803. return this;
  23804. }
  23805. Object.assign( Spherical.prototype, {
  23806. set: function ( radius, phi, theta ) {
  23807. this.radius = radius;
  23808. this.phi = phi;
  23809. this.theta = theta;
  23810. return this;
  23811. },
  23812. clone: function () {
  23813. return new this.constructor().copy( this );
  23814. },
  23815. copy: function ( other ) {
  23816. this.radius = other.radius;
  23817. this.phi = other.phi;
  23818. this.theta = other.theta;
  23819. return this;
  23820. },
  23821. // restrict phi to be betwee EPS and PI-EPS
  23822. makeSafe: function() {
  23823. var EPS = 0.000001;
  23824. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23825. return this;
  23826. },
  23827. setFromVector3: function( vec3 ) {
  23828. this.radius = vec3.length();
  23829. if ( this.radius === 0 ) {
  23830. this.theta = 0;
  23831. this.phi = 0;
  23832. } else {
  23833. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23834. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23835. }
  23836. return this;
  23837. }
  23838. } );
  23839. /**
  23840. * @author Mugen87 / https://github.com/Mugen87
  23841. *
  23842. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  23843. *
  23844. */
  23845. function Cylindrical( radius, theta, y ) {
  23846. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  23847. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  23848. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  23849. return this;
  23850. }
  23851. Object.assign( Cylindrical.prototype, {
  23852. set: function ( radius, theta, y ) {
  23853. this.radius = radius;
  23854. this.theta = theta;
  23855. this.y = y;
  23856. return this;
  23857. },
  23858. clone: function () {
  23859. return new this.constructor().copy( this );
  23860. },
  23861. copy: function ( other ) {
  23862. this.radius = other.radius;
  23863. this.theta = other.theta;
  23864. this.y = other.y;
  23865. return this;
  23866. },
  23867. setFromVector3: function( vec3 ) {
  23868. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  23869. this.theta = Math.atan2( vec3.x, vec3.z );
  23870. this.y = vec3.y;
  23871. return this;
  23872. }
  23873. } );
  23874. /**
  23875. * @author alteredq / http://alteredqualia.com/
  23876. */
  23877. function MorphBlendMesh( geometry, material ) {
  23878. Mesh.call( this, geometry, material );
  23879. this.animationsMap = {};
  23880. this.animationsList = [];
  23881. // prepare default animation
  23882. // (all frames played together in 1 second)
  23883. var numFrames = this.geometry.morphTargets.length;
  23884. var name = "__default";
  23885. var startFrame = 0;
  23886. var endFrame = numFrames - 1;
  23887. var fps = numFrames / 1;
  23888. this.createAnimation( name, startFrame, endFrame, fps );
  23889. this.setAnimationWeight( name, 1 );
  23890. }
  23891. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23892. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23893. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23894. var animation = {
  23895. start: start,
  23896. end: end,
  23897. length: end - start + 1,
  23898. fps: fps,
  23899. duration: ( end - start ) / fps,
  23900. lastFrame: 0,
  23901. currentFrame: 0,
  23902. active: false,
  23903. time: 0,
  23904. direction: 1,
  23905. weight: 1,
  23906. directionBackwards: false,
  23907. mirroredLoop: false
  23908. };
  23909. this.animationsMap[ name ] = animation;
  23910. this.animationsList.push( animation );
  23911. };
  23912. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23913. var pattern = /([a-z]+)_?(\d+)/i;
  23914. var firstAnimation, frameRanges = {};
  23915. var geometry = this.geometry;
  23916. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23917. var morph = geometry.morphTargets[ i ];
  23918. var chunks = morph.name.match( pattern );
  23919. if ( chunks && chunks.length > 1 ) {
  23920. var name = chunks[ 1 ];
  23921. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23922. var range = frameRanges[ name ];
  23923. if ( i < range.start ) range.start = i;
  23924. if ( i > range.end ) range.end = i;
  23925. if ( ! firstAnimation ) firstAnimation = name;
  23926. }
  23927. }
  23928. for ( var name in frameRanges ) {
  23929. var range = frameRanges[ name ];
  23930. this.createAnimation( name, range.start, range.end, fps );
  23931. }
  23932. this.firstAnimation = firstAnimation;
  23933. };
  23934. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23935. var animation = this.animationsMap[ name ];
  23936. if ( animation ) {
  23937. animation.direction = 1;
  23938. animation.directionBackwards = false;
  23939. }
  23940. };
  23941. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23942. var animation = this.animationsMap[ name ];
  23943. if ( animation ) {
  23944. animation.direction = - 1;
  23945. animation.directionBackwards = true;
  23946. }
  23947. };
  23948. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23949. var animation = this.animationsMap[ name ];
  23950. if ( animation ) {
  23951. animation.fps = fps;
  23952. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23953. }
  23954. };
  23955. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23956. var animation = this.animationsMap[ name ];
  23957. if ( animation ) {
  23958. animation.duration = duration;
  23959. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23960. }
  23961. };
  23962. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23963. var animation = this.animationsMap[ name ];
  23964. if ( animation ) {
  23965. animation.weight = weight;
  23966. }
  23967. };
  23968. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23969. var animation = this.animationsMap[ name ];
  23970. if ( animation ) {
  23971. animation.time = time;
  23972. }
  23973. };
  23974. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23975. var time = 0;
  23976. var animation = this.animationsMap[ name ];
  23977. if ( animation ) {
  23978. time = animation.time;
  23979. }
  23980. return time;
  23981. };
  23982. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23983. var duration = - 1;
  23984. var animation = this.animationsMap[ name ];
  23985. if ( animation ) {
  23986. duration = animation.duration;
  23987. }
  23988. return duration;
  23989. };
  23990. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23991. var animation = this.animationsMap[ name ];
  23992. if ( animation ) {
  23993. animation.time = 0;
  23994. animation.active = true;
  23995. } else {
  23996. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23997. }
  23998. };
  23999. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24000. var animation = this.animationsMap[ name ];
  24001. if ( animation ) {
  24002. animation.active = false;
  24003. }
  24004. };
  24005. MorphBlendMesh.prototype.update = function ( delta ) {
  24006. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24007. var animation = this.animationsList[ i ];
  24008. if ( ! animation.active ) continue;
  24009. var frameTime = animation.duration / animation.length;
  24010. animation.time += animation.direction * delta;
  24011. if ( animation.mirroredLoop ) {
  24012. if ( animation.time > animation.duration || animation.time < 0 ) {
  24013. animation.direction *= - 1;
  24014. if ( animation.time > animation.duration ) {
  24015. animation.time = animation.duration;
  24016. animation.directionBackwards = true;
  24017. }
  24018. if ( animation.time < 0 ) {
  24019. animation.time = 0;
  24020. animation.directionBackwards = false;
  24021. }
  24022. }
  24023. } else {
  24024. animation.time = animation.time % animation.duration;
  24025. if ( animation.time < 0 ) animation.time += animation.duration;
  24026. }
  24027. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24028. var weight = animation.weight;
  24029. if ( keyframe !== animation.currentFrame ) {
  24030. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24031. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24032. this.morphTargetInfluences[ keyframe ] = 0;
  24033. animation.lastFrame = animation.currentFrame;
  24034. animation.currentFrame = keyframe;
  24035. }
  24036. var mix = ( animation.time % frameTime ) / frameTime;
  24037. if ( animation.directionBackwards ) mix = 1 - mix;
  24038. if ( animation.currentFrame !== animation.lastFrame ) {
  24039. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24040. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24041. } else {
  24042. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24043. }
  24044. }
  24045. };
  24046. /**
  24047. * @author alteredq / http://alteredqualia.com/
  24048. */
  24049. function ImmediateRenderObject( material ) {
  24050. Object3D.call( this );
  24051. this.material = material;
  24052. this.render = function ( renderCallback ) {};
  24053. }
  24054. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  24055. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  24056. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  24057. /**
  24058. * @author mrdoob / http://mrdoob.com/
  24059. * @author WestLangley / http://github.com/WestLangley
  24060. */
  24061. function VertexNormalsHelper( object, size, hex, linewidth ) {
  24062. this.object = object;
  24063. this.size = ( size !== undefined ) ? size : 1;
  24064. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24065. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24066. //
  24067. var nNormals = 0;
  24068. var objGeometry = this.object.geometry;
  24069. if ( objGeometry && objGeometry.isGeometry ) {
  24070. nNormals = objGeometry.faces.length * 3;
  24071. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24072. nNormals = objGeometry.attributes.normal.count;
  24073. }
  24074. //
  24075. var geometry = new BufferGeometry();
  24076. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24077. geometry.addAttribute( 'position', positions );
  24078. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24079. //
  24080. this.matrixAutoUpdate = false;
  24081. this.update();
  24082. }
  24083. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24084. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  24085. VertexNormalsHelper.prototype.update = ( function () {
  24086. var v1 = new Vector3();
  24087. var v2 = new Vector3();
  24088. var normalMatrix = new Matrix3();
  24089. return function update() {
  24090. var keys = [ 'a', 'b', 'c' ];
  24091. this.object.updateMatrixWorld( true );
  24092. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24093. var matrixWorld = this.object.matrixWorld;
  24094. var position = this.geometry.attributes.position;
  24095. //
  24096. var objGeometry = this.object.geometry;
  24097. if ( objGeometry && objGeometry.isGeometry ) {
  24098. var vertices = objGeometry.vertices;
  24099. var faces = objGeometry.faces;
  24100. var idx = 0;
  24101. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24102. var face = faces[ i ];
  24103. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24104. var vertex = vertices[ face[ keys[ j ] ] ];
  24105. var normal = face.vertexNormals[ j ];
  24106. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24107. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24108. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24109. idx = idx + 1;
  24110. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24111. idx = idx + 1;
  24112. }
  24113. }
  24114. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  24115. var objPos = objGeometry.attributes.position;
  24116. var objNorm = objGeometry.attributes.normal;
  24117. var idx = 0;
  24118. // for simplicity, ignore index and drawcalls, and render every normal
  24119. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24120. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24121. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24122. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24123. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24124. idx = idx + 1;
  24125. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24126. idx = idx + 1;
  24127. }
  24128. }
  24129. position.needsUpdate = true;
  24130. };
  24131. }() );
  24132. /**
  24133. * @author alteredq / http://alteredqualia.com/
  24134. * @author mrdoob / http://mrdoob.com/
  24135. * @author WestLangley / http://github.com/WestLangley
  24136. */
  24137. function SpotLightHelper( light ) {
  24138. Object3D.call( this );
  24139. this.light = light;
  24140. this.light.updateMatrixWorld();
  24141. this.matrix = light.matrixWorld;
  24142. this.matrixAutoUpdate = false;
  24143. var geometry = new BufferGeometry();
  24144. var positions = [
  24145. 0, 0, 0, 0, 0, 1,
  24146. 0, 0, 0, 1, 0, 1,
  24147. 0, 0, 0, - 1, 0, 1,
  24148. 0, 0, 0, 0, 1, 1,
  24149. 0, 0, 0, 0, - 1, 1
  24150. ];
  24151. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24152. var p1 = ( i / l ) * Math.PI * 2;
  24153. var p2 = ( j / l ) * Math.PI * 2;
  24154. positions.push(
  24155. Math.cos( p1 ), Math.sin( p1 ), 1,
  24156. Math.cos( p2 ), Math.sin( p2 ), 1
  24157. );
  24158. }
  24159. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  24160. var material = new LineBasicMaterial( { fog: false } );
  24161. this.cone = new LineSegments( geometry, material );
  24162. this.add( this.cone );
  24163. this.update();
  24164. }
  24165. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  24166. SpotLightHelper.prototype.constructor = SpotLightHelper;
  24167. SpotLightHelper.prototype.dispose = function () {
  24168. this.cone.geometry.dispose();
  24169. this.cone.material.dispose();
  24170. };
  24171. SpotLightHelper.prototype.update = function () {
  24172. var vector = new Vector3();
  24173. var vector2 = new Vector3();
  24174. return function update() {
  24175. var coneLength = this.light.distance ? this.light.distance : 1000;
  24176. var coneWidth = coneLength * Math.tan( this.light.angle );
  24177. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24178. vector.setFromMatrixPosition( this.light.matrixWorld );
  24179. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24180. this.cone.lookAt( vector2.sub( vector ) );
  24181. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24182. };
  24183. }();
  24184. /**
  24185. * @author Sean Griffin / http://twitter.com/sgrif
  24186. * @author Michael Guerrero / http://realitymeltdown.com
  24187. * @author mrdoob / http://mrdoob.com/
  24188. * @author ikerr / http://verold.com
  24189. * @author Mugen87 / https://github.com/Mugen87
  24190. */
  24191. function SkeletonHelper( object ) {
  24192. this.bones = this.getBoneList( object );
  24193. var geometry = new BufferGeometry();
  24194. var vertices = [];
  24195. var colors = [];
  24196. var color1 = new Color( 0, 0, 1 );
  24197. var color2 = new Color( 0, 1, 0 );
  24198. for ( var i = 0; i < this.bones.length; i ++ ) {
  24199. var bone = this.bones[ i ];
  24200. if ( bone.parent && bone.parent.isBone ) {
  24201. vertices.push( 0, 0, 0 );
  24202. vertices.push( 0, 0, 0 );
  24203. colors.push( color1.r, color1.g, color1.b );
  24204. colors.push( color2.r, color2.g, color2.b );
  24205. }
  24206. }
  24207. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24208. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24209. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24210. LineSegments.call( this, geometry, material );
  24211. this.root = object;
  24212. this.matrix = object.matrixWorld;
  24213. this.matrixAutoUpdate = false;
  24214. this.update();
  24215. }
  24216. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24217. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24218. SkeletonHelper.prototype.getBoneList = function( object ) {
  24219. var boneList = [];
  24220. if ( object && object.isBone ) {
  24221. boneList.push( object );
  24222. }
  24223. for ( var i = 0; i < object.children.length; i ++ ) {
  24224. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24225. }
  24226. return boneList;
  24227. };
  24228. SkeletonHelper.prototype.update = function () {
  24229. var vector = new Vector3();
  24230. var boneMatrix = new Matrix4();
  24231. var matrixWorldInv = new Matrix4();
  24232. return function update() {
  24233. var geometry = this.geometry;
  24234. var position = geometry.getAttribute( 'position' );
  24235. matrixWorldInv.getInverse( this.root.matrixWorld );
  24236. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  24237. var bone = this.bones[ i ];
  24238. if ( bone.parent && bone.parent.isBone ) {
  24239. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24240. vector.setFromMatrixPosition( boneMatrix );
  24241. position.setXYZ( j, vector.x, vector.y, vector.z );
  24242. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24243. vector.setFromMatrixPosition( boneMatrix );
  24244. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24245. j += 2;
  24246. }
  24247. }
  24248. geometry.getAttribute( 'position' ).needsUpdate = true;
  24249. };
  24250. }();
  24251. /**
  24252. * @author alteredq / http://alteredqualia.com/
  24253. * @author mrdoob / http://mrdoob.com/
  24254. */
  24255. function PointLightHelper( light, sphereSize ) {
  24256. this.light = light;
  24257. this.light.updateMatrixWorld();
  24258. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24259. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24260. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24261. Mesh.call( this, geometry, material );
  24262. this.matrix = this.light.matrixWorld;
  24263. this.matrixAutoUpdate = false;
  24264. /*
  24265. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24266. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24267. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24268. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24269. var d = light.distance;
  24270. if ( d === 0.0 ) {
  24271. this.lightDistance.visible = false;
  24272. } else {
  24273. this.lightDistance.scale.set( d, d, d );
  24274. }
  24275. this.add( this.lightDistance );
  24276. */
  24277. }
  24278. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24279. PointLightHelper.prototype.constructor = PointLightHelper;
  24280. PointLightHelper.prototype.dispose = function () {
  24281. this.geometry.dispose();
  24282. this.material.dispose();
  24283. };
  24284. PointLightHelper.prototype.update = function () {
  24285. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24286. /*
  24287. var d = this.light.distance;
  24288. if ( d === 0.0 ) {
  24289. this.lightDistance.visible = false;
  24290. } else {
  24291. this.lightDistance.visible = true;
  24292. this.lightDistance.scale.set( d, d, d );
  24293. }
  24294. */
  24295. };
  24296. /**
  24297. * @author abelnation / http://github.com/abelnation
  24298. * @author Mugen87 / http://github.com/Mugen87
  24299. */
  24300. function RectAreaLightHelper( light ) {
  24301. Object3D.call( this );
  24302. this.light = light;
  24303. this.light.updateMatrixWorld();
  24304. var materialFront = new MeshBasicMaterial( {
  24305. color: light.color,
  24306. fog: false
  24307. } );
  24308. var materialBack = new MeshBasicMaterial( {
  24309. color: light.color,
  24310. fog: false,
  24311. wireframe: true
  24312. } );
  24313. var geometry = new BufferGeometry();
  24314. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  24315. // shows the "front" of the light, e.g. where light comes from
  24316. this.add( new Mesh( geometry, materialFront ) );
  24317. // shows the "back" of the light, which does not emit light
  24318. this.add( new Mesh( geometry, materialBack ) );
  24319. this.update();
  24320. }
  24321. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24322. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24323. RectAreaLightHelper.prototype.dispose = function () {
  24324. this.children[ 0 ].geometry.dispose();
  24325. this.children[ 0 ].material.dispose();
  24326. this.children[ 1 ].geometry.dispose();
  24327. this.children[ 1 ].material.dispose();
  24328. };
  24329. RectAreaLightHelper.prototype.update = function () {
  24330. var vector1 = new Vector3();
  24331. var vector2 = new Vector3();
  24332. return function update() {
  24333. var mesh1 = this.children[ 0 ];
  24334. var mesh2 = this.children[ 1 ];
  24335. if ( this.light.target ) {
  24336. vector1.setFromMatrixPosition( this.light.matrixWorld );
  24337. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24338. var lookVec = vector2.clone().sub( vector1 );
  24339. mesh1.lookAt( lookVec );
  24340. mesh2.lookAt( lookVec );
  24341. }
  24342. // update materials
  24343. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24344. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24345. // calculate new dimensions of the helper
  24346. var hx = this.light.width * 0.5;
  24347. var hy = this.light.height * 0.5;
  24348. // because the buffer attribute is shared over both geometries, we only have to update once
  24349. var position = mesh1.geometry.getAttribute( 'position' );
  24350. var array = position.array;
  24351. // first face
  24352. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24353. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24354. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24355. // second face
  24356. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  24357. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24358. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  24359. position.needsUpdate = true;
  24360. };
  24361. }();
  24362. /**
  24363. * @author alteredq / http://alteredqualia.com/
  24364. * @author mrdoob / http://mrdoob.com/
  24365. * @author Mugen87 / https://github.com/Mugen87
  24366. */
  24367. function HemisphereLightHelper( light, size ) {
  24368. Object3D.call( this );
  24369. this.light = light;
  24370. this.light.updateMatrixWorld();
  24371. this.matrix = light.matrixWorld;
  24372. this.matrixAutoUpdate = false;
  24373. var geometry = new OctahedronBufferGeometry( size );
  24374. geometry.rotateY( Math.PI * 0.5 );
  24375. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24376. var position = geometry.getAttribute( 'position' );
  24377. var colors = new Float32Array( position.count * 3 );
  24378. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24379. this.add( new Mesh( geometry, material ) );
  24380. this.update();
  24381. }
  24382. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24383. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24384. HemisphereLightHelper.prototype.dispose = function () {
  24385. this.children[ 0 ].geometry.dispose();
  24386. this.children[ 0 ].material.dispose();
  24387. };
  24388. HemisphereLightHelper.prototype.update = function () {
  24389. var vector = new Vector3();
  24390. var color1 = new Color();
  24391. var color2 = new Color();
  24392. return function update() {
  24393. var mesh = this.children[ 0 ];
  24394. var colors = mesh.geometry.getAttribute( 'color' );
  24395. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24396. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24397. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24398. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24399. colors.setXYZ( i, color.r, color.g, color.b );
  24400. }
  24401. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24402. colors.needsUpdate = true;
  24403. };
  24404. }();
  24405. /**
  24406. * @author mrdoob / http://mrdoob.com/
  24407. */
  24408. function GridHelper( size, divisions, color1, color2 ) {
  24409. size = size || 10;
  24410. divisions = divisions || 10;
  24411. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24412. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24413. var center = divisions / 2;
  24414. var step = size / divisions;
  24415. var halfSize = size / 2;
  24416. var vertices = [], colors = [];
  24417. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  24418. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  24419. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  24420. var color = i === center ? color1 : color2;
  24421. color.toArray( colors, j ); j += 3;
  24422. color.toArray( colors, j ); j += 3;
  24423. color.toArray( colors, j ); j += 3;
  24424. color.toArray( colors, j ); j += 3;
  24425. }
  24426. var geometry = new BufferGeometry();
  24427. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24428. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24429. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24430. LineSegments.call( this, geometry, material );
  24431. }
  24432. GridHelper.prototype = Object.create( LineSegments.prototype );
  24433. GridHelper.prototype.constructor = GridHelper;
  24434. /**
  24435. * @author mrdoob / http://mrdoob.com/
  24436. * @author Mugen87 / http://github.com/Mugen87
  24437. * @author Hectate / http://www.github.com/Hectate
  24438. */
  24439. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24440. radius = radius || 10;
  24441. radials = radials || 16;
  24442. circles = circles || 8;
  24443. divisions = divisions || 64;
  24444. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24445. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24446. var vertices = [];
  24447. var colors = [];
  24448. var x, z;
  24449. var v, i, j, r, color;
  24450. // create the radials
  24451. for ( i = 0; i <= radials; i ++ ) {
  24452. v = ( i / radials ) * ( Math.PI * 2 );
  24453. x = Math.sin( v ) * radius;
  24454. z = Math.cos( v ) * radius;
  24455. vertices.push( 0, 0, 0 );
  24456. vertices.push( x, 0, z );
  24457. color = ( i & 1 ) ? color1 : color2;
  24458. colors.push( color.r, color.g, color.b );
  24459. colors.push( color.r, color.g, color.b );
  24460. }
  24461. // create the circles
  24462. for ( i = 0; i <= circles; i ++ ) {
  24463. color = ( i & 1 ) ? color1 : color2;
  24464. r = radius - ( radius / circles * i );
  24465. for ( j = 0; j < divisions; j ++ ) {
  24466. // first vertex
  24467. v = ( j / divisions ) * ( Math.PI * 2 );
  24468. x = Math.sin( v ) * r;
  24469. z = Math.cos( v ) * r;
  24470. vertices.push( x, 0, z );
  24471. colors.push( color.r, color.g, color.b );
  24472. // second vertex
  24473. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24474. x = Math.sin( v ) * r;
  24475. z = Math.cos( v ) * r;
  24476. vertices.push( x, 0, z );
  24477. colors.push( color.r, color.g, color.b );
  24478. }
  24479. }
  24480. var geometry = new BufferGeometry();
  24481. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24482. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24483. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24484. LineSegments.call( this, geometry, material );
  24485. }
  24486. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24487. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24488. /**
  24489. * @author mrdoob / http://mrdoob.com/
  24490. * @author WestLangley / http://github.com/WestLangley
  24491. */
  24492. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24493. // FaceNormalsHelper only supports THREE.Geometry
  24494. this.object = object;
  24495. this.size = ( size !== undefined ) ? size : 1;
  24496. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24497. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24498. //
  24499. var nNormals = 0;
  24500. var objGeometry = this.object.geometry;
  24501. if ( objGeometry && objGeometry.isGeometry ) {
  24502. nNormals = objGeometry.faces.length;
  24503. } else {
  24504. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24505. }
  24506. //
  24507. var geometry = new BufferGeometry();
  24508. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24509. geometry.addAttribute( 'position', positions );
  24510. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24511. //
  24512. this.matrixAutoUpdate = false;
  24513. this.update();
  24514. }
  24515. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24516. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24517. FaceNormalsHelper.prototype.update = ( function () {
  24518. var v1 = new Vector3();
  24519. var v2 = new Vector3();
  24520. var normalMatrix = new Matrix3();
  24521. return function update() {
  24522. this.object.updateMatrixWorld( true );
  24523. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24524. var matrixWorld = this.object.matrixWorld;
  24525. var position = this.geometry.attributes.position;
  24526. //
  24527. var objGeometry = this.object.geometry;
  24528. var vertices = objGeometry.vertices;
  24529. var faces = objGeometry.faces;
  24530. var idx = 0;
  24531. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24532. var face = faces[ i ];
  24533. var normal = face.normal;
  24534. v1.copy( vertices[ face.a ] )
  24535. .add( vertices[ face.b ] )
  24536. .add( vertices[ face.c ] )
  24537. .divideScalar( 3 )
  24538. .applyMatrix4( matrixWorld );
  24539. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24540. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24541. idx = idx + 1;
  24542. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24543. idx = idx + 1;
  24544. }
  24545. position.needsUpdate = true;
  24546. };
  24547. }() );
  24548. /**
  24549. * @author alteredq / http://alteredqualia.com/
  24550. * @author mrdoob / http://mrdoob.com/
  24551. * @author WestLangley / http://github.com/WestLangley
  24552. */
  24553. function DirectionalLightHelper( light, size ) {
  24554. Object3D.call( this );
  24555. this.light = light;
  24556. this.light.updateMatrixWorld();
  24557. this.matrix = light.matrixWorld;
  24558. this.matrixAutoUpdate = false;
  24559. if ( size === undefined ) size = 1;
  24560. var geometry = new BufferGeometry();
  24561. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24562. - size, size, 0,
  24563. size, size, 0,
  24564. size, - size, 0,
  24565. - size, - size, 0,
  24566. - size, size, 0
  24567. ], 3 ) );
  24568. var material = new LineBasicMaterial( { fog: false } );
  24569. this.add( new Line( geometry, material ) );
  24570. geometry = new BufferGeometry();
  24571. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24572. this.add( new Line( geometry, material ));
  24573. this.update();
  24574. }
  24575. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24576. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24577. DirectionalLightHelper.prototype.dispose = function () {
  24578. var lightPlane = this.children[ 0 ];
  24579. var targetLine = this.children[ 1 ];
  24580. lightPlane.geometry.dispose();
  24581. lightPlane.material.dispose();
  24582. targetLine.geometry.dispose();
  24583. targetLine.material.dispose();
  24584. };
  24585. DirectionalLightHelper.prototype.update = function () {
  24586. var v1 = new Vector3();
  24587. var v2 = new Vector3();
  24588. var v3 = new Vector3();
  24589. return function update() {
  24590. v1.setFromMatrixPosition( this.light.matrixWorld );
  24591. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24592. v3.subVectors( v2, v1 );
  24593. var lightPlane = this.children[ 0 ];
  24594. var targetLine = this.children[ 1 ];
  24595. lightPlane.lookAt( v3 );
  24596. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24597. targetLine.lookAt( v3 );
  24598. targetLine.scale.z = v3.length();
  24599. };
  24600. }();
  24601. /**
  24602. * @author alteredq / http://alteredqualia.com/
  24603. * @author Mugen87 / https://github.com/Mugen87
  24604. *
  24605. * - shows frustum, line of sight and up of the camera
  24606. * - suitable for fast updates
  24607. * - based on frustum visualization in lightgl.js shadowmap example
  24608. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24609. */
  24610. function CameraHelper( camera ) {
  24611. var geometry = new BufferGeometry();
  24612. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24613. var vertices = [];
  24614. var colors = [];
  24615. var pointMap = {};
  24616. // colors
  24617. var colorFrustum = new Color( 0xffaa00 );
  24618. var colorCone = new Color( 0xff0000 );
  24619. var colorUp = new Color( 0x00aaff );
  24620. var colorTarget = new Color( 0xffffff );
  24621. var colorCross = new Color( 0x333333 );
  24622. // near
  24623. addLine( "n1", "n2", colorFrustum );
  24624. addLine( "n2", "n4", colorFrustum );
  24625. addLine( "n4", "n3", colorFrustum );
  24626. addLine( "n3", "n1", colorFrustum );
  24627. // far
  24628. addLine( "f1", "f2", colorFrustum );
  24629. addLine( "f2", "f4", colorFrustum );
  24630. addLine( "f4", "f3", colorFrustum );
  24631. addLine( "f3", "f1", colorFrustum );
  24632. // sides
  24633. addLine( "n1", "f1", colorFrustum );
  24634. addLine( "n2", "f2", colorFrustum );
  24635. addLine( "n3", "f3", colorFrustum );
  24636. addLine( "n4", "f4", colorFrustum );
  24637. // cone
  24638. addLine( "p", "n1", colorCone );
  24639. addLine( "p", "n2", colorCone );
  24640. addLine( "p", "n3", colorCone );
  24641. addLine( "p", "n4", colorCone );
  24642. // up
  24643. addLine( "u1", "u2", colorUp );
  24644. addLine( "u2", "u3", colorUp );
  24645. addLine( "u3", "u1", colorUp );
  24646. // target
  24647. addLine( "c", "t", colorTarget );
  24648. addLine( "p", "c", colorCross );
  24649. // cross
  24650. addLine( "cn1", "cn2", colorCross );
  24651. addLine( "cn3", "cn4", colorCross );
  24652. addLine( "cf1", "cf2", colorCross );
  24653. addLine( "cf3", "cf4", colorCross );
  24654. function addLine( a, b, color ) {
  24655. addPoint( a, color );
  24656. addPoint( b, color );
  24657. }
  24658. function addPoint( id, color ) {
  24659. vertices.push( 0, 0, 0 );
  24660. colors.push( color.r, color.g, color.b );
  24661. if ( pointMap[ id ] === undefined ) {
  24662. pointMap[ id ] = [];
  24663. }
  24664. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24665. }
  24666. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24667. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24668. LineSegments.call( this, geometry, material );
  24669. this.camera = camera;
  24670. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24671. this.matrix = camera.matrixWorld;
  24672. this.matrixAutoUpdate = false;
  24673. this.pointMap = pointMap;
  24674. this.update();
  24675. }
  24676. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24677. CameraHelper.prototype.constructor = CameraHelper;
  24678. CameraHelper.prototype.update = function () {
  24679. var geometry, pointMap;
  24680. var vector = new Vector3();
  24681. var camera = new Camera();
  24682. function setPoint( point, x, y, z ) {
  24683. vector.set( x, y, z ).unproject( camera );
  24684. var points = pointMap[ point ];
  24685. if ( points !== undefined ) {
  24686. var position = geometry.getAttribute( 'position' );
  24687. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24688. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24689. }
  24690. }
  24691. }
  24692. return function update() {
  24693. geometry = this.geometry;
  24694. pointMap = this.pointMap;
  24695. var w = 1, h = 1;
  24696. // we need just camera projection matrix
  24697. // world matrix must be identity
  24698. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24699. // center / target
  24700. setPoint( "c", 0, 0, - 1 );
  24701. setPoint( "t", 0, 0, 1 );
  24702. // near
  24703. setPoint( "n1", - w, - h, - 1 );
  24704. setPoint( "n2", w, - h, - 1 );
  24705. setPoint( "n3", - w, h, - 1 );
  24706. setPoint( "n4", w, h, - 1 );
  24707. // far
  24708. setPoint( "f1", - w, - h, 1 );
  24709. setPoint( "f2", w, - h, 1 );
  24710. setPoint( "f3", - w, h, 1 );
  24711. setPoint( "f4", w, h, 1 );
  24712. // up
  24713. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24714. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24715. setPoint( "u3", 0, h * 2, - 1 );
  24716. // cross
  24717. setPoint( "cf1", - w, 0, 1 );
  24718. setPoint( "cf2", w, 0, 1 );
  24719. setPoint( "cf3", 0, - h, 1 );
  24720. setPoint( "cf4", 0, h, 1 );
  24721. setPoint( "cn1", - w, 0, - 1 );
  24722. setPoint( "cn2", w, 0, - 1 );
  24723. setPoint( "cn3", 0, - h, - 1 );
  24724. setPoint( "cn4", 0, h, - 1 );
  24725. geometry.getAttribute( 'position' ).needsUpdate = true;
  24726. };
  24727. }();
  24728. /**
  24729. * @author mrdoob / http://mrdoob.com/
  24730. * @author Mugen87 / http://github.com/Mugen87
  24731. */
  24732. function BoxHelper( object, color ) {
  24733. this.object = object;
  24734. if ( color === undefined ) color = 0xffff00;
  24735. 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 ] );
  24736. var positions = new Float32Array( 8 * 3 );
  24737. var geometry = new BufferGeometry();
  24738. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24739. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24740. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24741. this.matrixAutoUpdate = false;
  24742. this.update();
  24743. }
  24744. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24745. BoxHelper.prototype.constructor = BoxHelper;
  24746. BoxHelper.prototype.update = ( function () {
  24747. var box = new Box3();
  24748. return function update( object ) {
  24749. if ( object !== undefined ) {
  24750. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  24751. }
  24752. if ( this.object !== undefined ) {
  24753. box.setFromObject( this.object );
  24754. }
  24755. if ( box.isEmpty() ) return;
  24756. var min = box.min;
  24757. var max = box.max;
  24758. /*
  24759. 5____4
  24760. 1/___0/|
  24761. | 6__|_7
  24762. 2/___3/
  24763. 0: max.x, max.y, max.z
  24764. 1: min.x, max.y, max.z
  24765. 2: min.x, min.y, max.z
  24766. 3: max.x, min.y, max.z
  24767. 4: max.x, max.y, min.z
  24768. 5: min.x, max.y, min.z
  24769. 6: min.x, min.y, min.z
  24770. 7: max.x, min.y, min.z
  24771. */
  24772. var position = this.geometry.attributes.position;
  24773. var array = position.array;
  24774. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24775. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24776. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24777. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24778. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24779. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24780. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24781. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24782. position.needsUpdate = true;
  24783. this.geometry.computeBoundingSphere();
  24784. };
  24785. } )();
  24786. BoxHelper.prototype.setFromObject = function ( object ) {
  24787. this.object = object;
  24788. this.update();
  24789. return this;
  24790. };
  24791. /**
  24792. * @author WestLangley / http://github.com/WestLangley
  24793. * @author zz85 / http://github.com/zz85
  24794. * @author bhouston / http://clara.io
  24795. *
  24796. * Creates an arrow for visualizing directions
  24797. *
  24798. * Parameters:
  24799. * dir - Vector3
  24800. * origin - Vector3
  24801. * length - Number
  24802. * color - color in hex value
  24803. * headLength - Number
  24804. * headWidth - Number
  24805. */
  24806. var lineGeometry;
  24807. var coneGeometry;
  24808. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24809. // dir is assumed to be normalized
  24810. Object3D.call( this );
  24811. if ( color === undefined ) color = 0xffff00;
  24812. if ( length === undefined ) length = 1;
  24813. if ( headLength === undefined ) headLength = 0.2 * length;
  24814. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24815. if ( lineGeometry === undefined ) {
  24816. lineGeometry = new BufferGeometry();
  24817. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24818. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24819. coneGeometry.translate( 0, - 0.5, 0 );
  24820. }
  24821. this.position.copy( origin );
  24822. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24823. this.line.matrixAutoUpdate = false;
  24824. this.add( this.line );
  24825. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24826. this.cone.matrixAutoUpdate = false;
  24827. this.add( this.cone );
  24828. this.setDirection( dir );
  24829. this.setLength( length, headLength, headWidth );
  24830. }
  24831. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24832. ArrowHelper.prototype.constructor = ArrowHelper;
  24833. ArrowHelper.prototype.setDirection = ( function () {
  24834. var axis = new Vector3();
  24835. var radians;
  24836. return function setDirection( dir ) {
  24837. // dir is assumed to be normalized
  24838. if ( dir.y > 0.99999 ) {
  24839. this.quaternion.set( 0, 0, 0, 1 );
  24840. } else if ( dir.y < - 0.99999 ) {
  24841. this.quaternion.set( 1, 0, 0, 0 );
  24842. } else {
  24843. axis.set( dir.z, 0, - dir.x ).normalize();
  24844. radians = Math.acos( dir.y );
  24845. this.quaternion.setFromAxisAngle( axis, radians );
  24846. }
  24847. };
  24848. }() );
  24849. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24850. if ( headLength === undefined ) headLength = 0.2 * length;
  24851. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24852. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24853. this.line.updateMatrix();
  24854. this.cone.scale.set( headWidth, headLength, headWidth );
  24855. this.cone.position.y = length;
  24856. this.cone.updateMatrix();
  24857. };
  24858. ArrowHelper.prototype.setColor = function ( color ) {
  24859. this.line.material.color.copy( color );
  24860. this.cone.material.color.copy( color );
  24861. };
  24862. /**
  24863. * @author sroucheray / http://sroucheray.org/
  24864. * @author mrdoob / http://mrdoob.com/
  24865. */
  24866. function AxisHelper( size ) {
  24867. size = size || 1;
  24868. var vertices = [
  24869. 0, 0, 0, size, 0, 0,
  24870. 0, 0, 0, 0, size, 0,
  24871. 0, 0, 0, 0, 0, size
  24872. ];
  24873. var colors = [
  24874. 1, 0, 0, 1, 0.6, 0,
  24875. 0, 1, 0, 0.6, 1, 0,
  24876. 0, 0, 1, 0, 0.6, 1
  24877. ];
  24878. var geometry = new BufferGeometry();
  24879. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24880. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24881. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24882. LineSegments.call( this, geometry, material );
  24883. }
  24884. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24885. AxisHelper.prototype.constructor = AxisHelper;
  24886. /**
  24887. * @author zz85 https://github.com/zz85
  24888. *
  24889. * Centripetal CatmullRom Curve - which is useful for avoiding
  24890. * cusps and self-intersections in non-uniform catmull rom curves.
  24891. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24892. *
  24893. * curve.type accepts centripetal(default), chordal and catmullrom
  24894. * curve.tension is used for catmullrom which defaults to 0.5
  24895. */
  24896. /*
  24897. Based on an optimized c++ solution in
  24898. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24899. - http://ideone.com/NoEbVM
  24900. This CubicPoly class could be used for reusing some variables and calculations,
  24901. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24902. which can be placed in CurveUtils.
  24903. */
  24904. function CubicPoly() {
  24905. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24906. /*
  24907. * Compute coefficients for a cubic polynomial
  24908. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24909. * such that
  24910. * p(0) = x0, p(1) = x1
  24911. * and
  24912. * p'(0) = t0, p'(1) = t1.
  24913. */
  24914. function init( x0, x1, t0, t1 ) {
  24915. c0 = x0;
  24916. c1 = t0;
  24917. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24918. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24919. }
  24920. return {
  24921. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24922. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24923. },
  24924. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24925. // compute tangents when parameterized in [t1,t2]
  24926. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24927. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24928. // rescale tangents for parametrization in [0,1]
  24929. t1 *= dt1;
  24930. t2 *= dt1;
  24931. init( x1, x2, t1, t2 );
  24932. },
  24933. calc: function ( t ) {
  24934. var t2 = t * t;
  24935. var t3 = t2 * t;
  24936. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24937. }
  24938. };
  24939. }
  24940. //
  24941. var tmp = new Vector3();
  24942. var px = new CubicPoly();
  24943. var py = new CubicPoly();
  24944. var pz = new CubicPoly();
  24945. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  24946. Curve.call( this );
  24947. this.points = p || [];
  24948. this.closed = false;
  24949. }
  24950. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  24951. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  24952. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  24953. var points = this.points;
  24954. var l = points.length;
  24955. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24956. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24957. var intPoint = Math.floor( point );
  24958. var weight = point - intPoint;
  24959. if ( this.closed ) {
  24960. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24961. } else if ( weight === 0 && intPoint === l - 1 ) {
  24962. intPoint = l - 2;
  24963. weight = 1;
  24964. }
  24965. var p0, p1, p2, p3; // 4 points
  24966. if ( this.closed || intPoint > 0 ) {
  24967. p0 = points[ ( intPoint - 1 ) % l ];
  24968. } else {
  24969. // extrapolate first point
  24970. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24971. p0 = tmp;
  24972. }
  24973. p1 = points[ intPoint % l ];
  24974. p2 = points[ ( intPoint + 1 ) % l ];
  24975. if ( this.closed || intPoint + 2 < l ) {
  24976. p3 = points[ ( intPoint + 2 ) % l ];
  24977. } else {
  24978. // extrapolate last point
  24979. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24980. p3 = tmp;
  24981. }
  24982. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24983. // init Centripetal / Chordal Catmull-Rom
  24984. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24985. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24986. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24987. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24988. // safety check for repeated points
  24989. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24990. if ( dt0 < 1e-4 ) dt0 = dt1;
  24991. if ( dt2 < 1e-4 ) dt2 = dt1;
  24992. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24993. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24994. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24995. } else if ( this.type === 'catmullrom' ) {
  24996. var tension = this.tension !== undefined ? this.tension : 0.5;
  24997. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24998. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24999. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  25000. }
  25001. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  25002. };
  25003. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25004. Curve.call( this );
  25005. this.v0 = v0;
  25006. this.v1 = v1;
  25007. this.v2 = v2;
  25008. this.v3 = v3;
  25009. }
  25010. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25011. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25012. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  25013. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25014. return new Vector3(
  25015. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25016. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25017. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25018. );
  25019. };
  25020. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25021. Curve.call( this );
  25022. this.v0 = v0;
  25023. this.v1 = v1;
  25024. this.v2 = v2;
  25025. }
  25026. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25027. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25028. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  25029. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25030. return new Vector3(
  25031. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25032. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25033. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25034. );
  25035. };
  25036. function LineCurve3( v1, v2 ) {
  25037. Curve.call( this );
  25038. this.v1 = v1;
  25039. this.v2 = v2;
  25040. }
  25041. LineCurve3.prototype = Object.create( Curve.prototype );
  25042. LineCurve3.prototype.constructor = LineCurve3;
  25043. LineCurve3.prototype.getPoint = function ( t ) {
  25044. if ( t === 1 ) {
  25045. return this.v2.clone();
  25046. }
  25047. var vector = new Vector3();
  25048. vector.subVectors( this.v2, this.v1 ); // diff
  25049. vector.multiplyScalar( t );
  25050. vector.add( this.v1 );
  25051. return vector;
  25052. };
  25053. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25054. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25055. }
  25056. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  25057. ArcCurve.prototype.constructor = ArcCurve;
  25058. /**
  25059. * @author alteredq / http://alteredqualia.com/
  25060. */
  25061. var SceneUtils = {
  25062. createMultiMaterialObject: function ( geometry, materials ) {
  25063. var group = new Group();
  25064. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  25065. group.add( new Mesh( geometry, materials[ i ] ) );
  25066. }
  25067. return group;
  25068. },
  25069. detach: function ( child, parent, scene ) {
  25070. child.applyMatrix( parent.matrixWorld );
  25071. parent.remove( child );
  25072. scene.add( child );
  25073. },
  25074. attach: function ( child, scene, parent ) {
  25075. var matrixWorldInverse = new Matrix4();
  25076. matrixWorldInverse.getInverse( parent.matrixWorld );
  25077. child.applyMatrix( matrixWorldInverse );
  25078. scene.remove( child );
  25079. parent.add( child );
  25080. }
  25081. };
  25082. /**
  25083. * @author mrdoob / http://mrdoob.com/
  25084. */
  25085. function Face4( a, b, c, d, normal, color, materialIndex ) {
  25086. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  25087. return new Face3( a, b, c, normal, color, materialIndex );
  25088. }
  25089. var LineStrip = 0;
  25090. var LinePieces = 1;
  25091. function MeshFaceMaterial( materials ) {
  25092. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  25093. return materials;
  25094. }
  25095. function MultiMaterial( materials ) {
  25096. if ( materials === undefined ) materials = [];
  25097. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  25098. materials.isMultiMaterial = true;
  25099. materials.materials = materials;
  25100. materials.clone = function () {
  25101. return materials.slice();
  25102. };
  25103. return materials;
  25104. }
  25105. function PointCloud( geometry, material ) {
  25106. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  25107. return new Points( geometry, material );
  25108. }
  25109. function Particle( material ) {
  25110. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  25111. return new Sprite( material );
  25112. }
  25113. function ParticleSystem( geometry, material ) {
  25114. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  25115. return new Points( geometry, material );
  25116. }
  25117. function PointCloudMaterial( parameters ) {
  25118. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  25119. return new PointsMaterial( parameters );
  25120. }
  25121. function ParticleBasicMaterial( parameters ) {
  25122. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  25123. return new PointsMaterial( parameters );
  25124. }
  25125. function ParticleSystemMaterial( parameters ) {
  25126. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  25127. return new PointsMaterial( parameters );
  25128. }
  25129. function Vertex( x, y, z ) {
  25130. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  25131. return new Vector3( x, y, z );
  25132. }
  25133. //
  25134. function DynamicBufferAttribute( array, itemSize ) {
  25135. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  25136. return new BufferAttribute( array, itemSize ).setDynamic( true );
  25137. }
  25138. function Int8Attribute( array, itemSize ) {
  25139. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  25140. return new Int8BufferAttribute( array, itemSize );
  25141. }
  25142. function Uint8Attribute( array, itemSize ) {
  25143. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  25144. return new Uint8BufferAttribute( array, itemSize );
  25145. }
  25146. function Uint8ClampedAttribute( array, itemSize ) {
  25147. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  25148. return new Uint8ClampedBufferAttribute( array, itemSize );
  25149. }
  25150. function Int16Attribute( array, itemSize ) {
  25151. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  25152. return new Int16BufferAttribute( array, itemSize );
  25153. }
  25154. function Uint16Attribute( array, itemSize ) {
  25155. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  25156. return new Uint16BufferAttribute( array, itemSize );
  25157. }
  25158. function Int32Attribute( array, itemSize ) {
  25159. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  25160. return new Int32BufferAttribute( array, itemSize );
  25161. }
  25162. function Uint32Attribute( array, itemSize ) {
  25163. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  25164. return new Uint32BufferAttribute( array, itemSize );
  25165. }
  25166. function Float32Attribute( array, itemSize ) {
  25167. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  25168. return new Float32BufferAttribute( array, itemSize );
  25169. }
  25170. function Float64Attribute( array, itemSize ) {
  25171. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  25172. return new Float64BufferAttribute( array, itemSize );
  25173. }
  25174. //
  25175. Curve.create = function ( construct, getPoint ) {
  25176. console.log( 'THREE.Curve.create() has been deprecated' );
  25177. construct.prototype = Object.create( Curve.prototype );
  25178. construct.prototype.constructor = construct;
  25179. construct.prototype.getPoint = getPoint;
  25180. return construct;
  25181. };
  25182. //
  25183. function ClosedSplineCurve3( points ) {
  25184. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25185. CatmullRomCurve3.call( this, points );
  25186. this.type = 'catmullrom';
  25187. this.closed = true;
  25188. }
  25189. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25190. //
  25191. function SplineCurve3( points ) {
  25192. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  25193. CatmullRomCurve3.call( this, points );
  25194. this.type = 'catmullrom';
  25195. }
  25196. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  25197. //
  25198. function Spline( points ) {
  25199. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  25200. CatmullRomCurve3.call( this, points );
  25201. this.type = 'catmullrom';
  25202. }
  25203. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  25204. Object.assign( Spline.prototype, {
  25205. initFromArray: function ( a ) {
  25206. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  25207. },
  25208. getControlPointsArray: function ( optionalTarget ) {
  25209. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  25210. },
  25211. reparametrizeByArcLength: function ( samplingCoef ) {
  25212. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  25213. }
  25214. } );
  25215. //
  25216. function BoundingBoxHelper( object, color ) {
  25217. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  25218. return new BoxHelper( object, color );
  25219. }
  25220. function EdgesHelper( object, hex ) {
  25221. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  25222. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25223. }
  25224. GridHelper.prototype.setColors = function () {
  25225. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  25226. };
  25227. function WireframeHelper( object, hex ) {
  25228. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  25229. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  25230. }
  25231. //
  25232. function XHRLoader( manager ) {
  25233. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  25234. return new FileLoader( manager );
  25235. }
  25236. function BinaryTextureLoader( manager ) {
  25237. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25238. return new DataTextureLoader( manager );
  25239. }
  25240. //
  25241. Object.assign( Box2.prototype, {
  25242. center: function ( optionalTarget ) {
  25243. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25244. return this.getCenter( optionalTarget );
  25245. },
  25246. empty: function () {
  25247. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25248. return this.isEmpty();
  25249. },
  25250. isIntersectionBox: function ( box ) {
  25251. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25252. return this.intersectsBox( box );
  25253. },
  25254. size: function ( optionalTarget ) {
  25255. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25256. return this.getSize( optionalTarget );
  25257. }
  25258. } );
  25259. Object.assign( Box3.prototype, {
  25260. center: function ( optionalTarget ) {
  25261. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25262. return this.getCenter( optionalTarget );
  25263. },
  25264. empty: function () {
  25265. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25266. return this.isEmpty();
  25267. },
  25268. isIntersectionBox: function ( box ) {
  25269. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25270. return this.intersectsBox( box );
  25271. },
  25272. isIntersectionSphere: function ( sphere ) {
  25273. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25274. return this.intersectsSphere( sphere );
  25275. },
  25276. size: function ( optionalTarget ) {
  25277. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25278. return this.getSize( optionalTarget );
  25279. }
  25280. } );
  25281. Line3.prototype.center = function ( optionalTarget ) {
  25282. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25283. return this.getCenter( optionalTarget );
  25284. };
  25285. _Math.random16 = function () {
  25286. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25287. return Math.random();
  25288. };
  25289. Object.assign( Matrix3.prototype, {
  25290. flattenToArrayOffset: function ( array, offset ) {
  25291. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25292. return this.toArray( array, offset );
  25293. },
  25294. multiplyVector3: function ( vector ) {
  25295. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25296. return vector.applyMatrix3( this );
  25297. },
  25298. multiplyVector3Array: function ( a ) {
  25299. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25300. return this.applyToVector3Array( a );
  25301. },
  25302. applyToBuffer: function( buffer, offset, length ) {
  25303. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25304. return this.applyToBufferAttribute( buffer );
  25305. },
  25306. applyToVector3Array: function( array, offset, length ) {
  25307. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25308. }
  25309. } );
  25310. Object.assign( Matrix4.prototype, {
  25311. extractPosition: function ( m ) {
  25312. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25313. return this.copyPosition( m );
  25314. },
  25315. flattenToArrayOffset: function ( array, offset ) {
  25316. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25317. return this.toArray( array, offset );
  25318. },
  25319. getPosition: function () {
  25320. var v1;
  25321. return function getPosition() {
  25322. if ( v1 === undefined ) v1 = new Vector3();
  25323. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25324. return v1.setFromMatrixColumn( this, 3 );
  25325. };
  25326. }(),
  25327. setRotationFromQuaternion: function ( q ) {
  25328. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25329. return this.makeRotationFromQuaternion( q );
  25330. },
  25331. multiplyToArray: function () {
  25332. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  25333. },
  25334. multiplyVector3: function ( vector ) {
  25335. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25336. return vector.applyMatrix4( this );
  25337. },
  25338. multiplyVector4: function ( vector ) {
  25339. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25340. return vector.applyMatrix4( this );
  25341. },
  25342. multiplyVector3Array: function ( a ) {
  25343. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25344. return this.applyToVector3Array( a );
  25345. },
  25346. rotateAxis: function ( v ) {
  25347. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25348. v.transformDirection( this );
  25349. },
  25350. crossVector: function ( vector ) {
  25351. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25352. return vector.applyMatrix4( this );
  25353. },
  25354. translate: function () {
  25355. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25356. },
  25357. rotateX: function () {
  25358. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25359. },
  25360. rotateY: function () {
  25361. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25362. },
  25363. rotateZ: function () {
  25364. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25365. },
  25366. rotateByAxis: function () {
  25367. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25368. },
  25369. applyToBuffer: function( buffer, offset, length ) {
  25370. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25371. return this.applyToBufferAttribute( buffer );
  25372. },
  25373. applyToVector3Array: function( array, offset, length ) {
  25374. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25375. },
  25376. makeFrustum: function( left, right, bottom, top, near, far ) {
  25377. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25378. return this.makePerspective( left, right, top, bottom, near, far );
  25379. }
  25380. } );
  25381. Plane.prototype.isIntersectionLine = function ( line ) {
  25382. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25383. return this.intersectsLine( line );
  25384. };
  25385. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25386. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25387. return vector.applyQuaternion( this );
  25388. };
  25389. Object.assign( Ray.prototype, {
  25390. isIntersectionBox: function ( box ) {
  25391. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25392. return this.intersectsBox( box );
  25393. },
  25394. isIntersectionPlane: function ( plane ) {
  25395. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25396. return this.intersectsPlane( plane );
  25397. },
  25398. isIntersectionSphere: function ( sphere ) {
  25399. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25400. return this.intersectsSphere( sphere );
  25401. }
  25402. } );
  25403. Object.assign( Shape.prototype, {
  25404. extrude: function ( options ) {
  25405. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25406. return new ExtrudeGeometry( this, options );
  25407. },
  25408. makeGeometry: function ( options ) {
  25409. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25410. return new ShapeGeometry( this, options );
  25411. }
  25412. } );
  25413. Object.assign( Vector2.prototype, {
  25414. fromAttribute: function ( attribute, index, offset ) {
  25415. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25416. return this.fromBufferAttribute( attribute, index, offset );
  25417. }
  25418. } );
  25419. Object.assign( Vector3.prototype, {
  25420. setEulerFromRotationMatrix: function () {
  25421. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25422. },
  25423. setEulerFromQuaternion: function () {
  25424. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25425. },
  25426. getPositionFromMatrix: function ( m ) {
  25427. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25428. return this.setFromMatrixPosition( m );
  25429. },
  25430. getScaleFromMatrix: function ( m ) {
  25431. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25432. return this.setFromMatrixScale( m );
  25433. },
  25434. getColumnFromMatrix: function ( index, matrix ) {
  25435. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25436. return this.setFromMatrixColumn( matrix, index );
  25437. },
  25438. applyProjection: function ( m ) {
  25439. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25440. return this.applyMatrix4( m );
  25441. },
  25442. fromAttribute: function ( attribute, index, offset ) {
  25443. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25444. return this.fromBufferAttribute( attribute, index, offset );
  25445. }
  25446. } );
  25447. Object.assign( Vector4.prototype, {
  25448. fromAttribute: function ( attribute, index, offset ) {
  25449. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25450. return this.fromBufferAttribute( attribute, index, offset );
  25451. }
  25452. } );
  25453. //
  25454. Geometry.prototype.computeTangents = function () {
  25455. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25456. };
  25457. Object.assign( Object3D.prototype, {
  25458. getChildByName: function ( name ) {
  25459. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25460. return this.getObjectByName( name );
  25461. },
  25462. renderDepth: function () {
  25463. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25464. },
  25465. translate: function ( distance, axis ) {
  25466. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25467. return this.translateOnAxis( axis, distance );
  25468. }
  25469. } );
  25470. Object.defineProperties( Object3D.prototype, {
  25471. eulerOrder: {
  25472. get: function () {
  25473. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25474. return this.rotation.order;
  25475. },
  25476. set: function ( value ) {
  25477. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25478. this.rotation.order = value;
  25479. }
  25480. },
  25481. useQuaternion: {
  25482. get: function () {
  25483. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25484. },
  25485. set: function () {
  25486. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25487. }
  25488. }
  25489. } );
  25490. Object.defineProperties( LOD.prototype, {
  25491. objects: {
  25492. get: function () {
  25493. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25494. return this.levels;
  25495. }
  25496. }
  25497. } );
  25498. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  25499. get: function () {
  25500. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25501. },
  25502. set: function () {
  25503. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  25504. }
  25505. } );
  25506. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  25507. get: function () {
  25508. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25509. return this.arcLengthDivisions;
  25510. },
  25511. set: function ( value ) {
  25512. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  25513. this.arcLengthDivisions = value;
  25514. }
  25515. } );
  25516. //
  25517. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25518. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25519. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25520. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25521. this.setFocalLength( focalLength );
  25522. };
  25523. //
  25524. Object.defineProperties( Light.prototype, {
  25525. onlyShadow: {
  25526. set: function () {
  25527. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25528. }
  25529. },
  25530. shadowCameraFov: {
  25531. set: function ( value ) {
  25532. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25533. this.shadow.camera.fov = value;
  25534. }
  25535. },
  25536. shadowCameraLeft: {
  25537. set: function ( value ) {
  25538. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25539. this.shadow.camera.left = value;
  25540. }
  25541. },
  25542. shadowCameraRight: {
  25543. set: function ( value ) {
  25544. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25545. this.shadow.camera.right = value;
  25546. }
  25547. },
  25548. shadowCameraTop: {
  25549. set: function ( value ) {
  25550. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25551. this.shadow.camera.top = value;
  25552. }
  25553. },
  25554. shadowCameraBottom: {
  25555. set: function ( value ) {
  25556. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25557. this.shadow.camera.bottom = value;
  25558. }
  25559. },
  25560. shadowCameraNear: {
  25561. set: function ( value ) {
  25562. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25563. this.shadow.camera.near = value;
  25564. }
  25565. },
  25566. shadowCameraFar: {
  25567. set: function ( value ) {
  25568. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25569. this.shadow.camera.far = value;
  25570. }
  25571. },
  25572. shadowCameraVisible: {
  25573. set: function () {
  25574. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25575. }
  25576. },
  25577. shadowBias: {
  25578. set: function ( value ) {
  25579. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25580. this.shadow.bias = value;
  25581. }
  25582. },
  25583. shadowDarkness: {
  25584. set: function () {
  25585. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25586. }
  25587. },
  25588. shadowMapWidth: {
  25589. set: function ( value ) {
  25590. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25591. this.shadow.mapSize.width = value;
  25592. }
  25593. },
  25594. shadowMapHeight: {
  25595. set: function ( value ) {
  25596. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25597. this.shadow.mapSize.height = value;
  25598. }
  25599. }
  25600. } );
  25601. //
  25602. Object.defineProperties( BufferAttribute.prototype, {
  25603. length: {
  25604. get: function () {
  25605. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25606. return this.array.length;
  25607. }
  25608. }
  25609. } );
  25610. Object.assign( BufferGeometry.prototype, {
  25611. addIndex: function ( index ) {
  25612. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25613. this.setIndex( index );
  25614. },
  25615. addDrawCall: function ( start, count, indexOffset ) {
  25616. if ( indexOffset !== undefined ) {
  25617. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25618. }
  25619. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25620. this.addGroup( start, count );
  25621. },
  25622. clearDrawCalls: function () {
  25623. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25624. this.clearGroups();
  25625. },
  25626. computeTangents: function () {
  25627. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25628. },
  25629. computeOffsets: function () {
  25630. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25631. }
  25632. } );
  25633. Object.defineProperties( BufferGeometry.prototype, {
  25634. drawcalls: {
  25635. get: function () {
  25636. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25637. return this.groups;
  25638. }
  25639. },
  25640. offsets: {
  25641. get: function () {
  25642. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25643. return this.groups;
  25644. }
  25645. }
  25646. } );
  25647. //
  25648. Object.defineProperties( Uniform.prototype, {
  25649. dynamic: {
  25650. set: function () {
  25651. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25652. }
  25653. },
  25654. onUpdate: {
  25655. value: function () {
  25656. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25657. return this;
  25658. }
  25659. }
  25660. } );
  25661. //
  25662. Object.defineProperties( Material.prototype, {
  25663. wrapAround: {
  25664. get: function () {
  25665. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25666. },
  25667. set: function () {
  25668. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  25669. }
  25670. },
  25671. wrapRGB: {
  25672. get: function () {
  25673. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  25674. return new Color();
  25675. }
  25676. }
  25677. } );
  25678. Object.defineProperties( MeshPhongMaterial.prototype, {
  25679. metal: {
  25680. get: function () {
  25681. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25682. return false;
  25683. },
  25684. set: function () {
  25685. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25686. }
  25687. }
  25688. } );
  25689. Object.defineProperties( ShaderMaterial.prototype, {
  25690. derivatives: {
  25691. get: function () {
  25692. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25693. return this.extensions.derivatives;
  25694. },
  25695. set: function ( value ) {
  25696. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25697. this.extensions.derivatives = value;
  25698. }
  25699. }
  25700. } );
  25701. //
  25702. Object.assign( WebGLRenderer.prototype, {
  25703. getCurrentRenderTarget: function () {
  25704. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  25705. return this.getRenderTarget();
  25706. },
  25707. supportsFloatTextures: function () {
  25708. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25709. return this.extensions.get( 'OES_texture_float' );
  25710. },
  25711. supportsHalfFloatTextures: function () {
  25712. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25713. return this.extensions.get( 'OES_texture_half_float' );
  25714. },
  25715. supportsStandardDerivatives: function () {
  25716. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25717. return this.extensions.get( 'OES_standard_derivatives' );
  25718. },
  25719. supportsCompressedTextureS3TC: function () {
  25720. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25721. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25722. },
  25723. supportsCompressedTexturePVRTC: function () {
  25724. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25725. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25726. },
  25727. supportsBlendMinMax: function () {
  25728. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25729. return this.extensions.get( 'EXT_blend_minmax' );
  25730. },
  25731. supportsVertexTextures: function () {
  25732. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25733. return this.capabilities.vertexTextures;
  25734. },
  25735. supportsInstancedArrays: function () {
  25736. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25737. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25738. },
  25739. enableScissorTest: function ( boolean ) {
  25740. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25741. this.setScissorTest( boolean );
  25742. },
  25743. initMaterial: function () {
  25744. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25745. },
  25746. addPrePlugin: function () {
  25747. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25748. },
  25749. addPostPlugin: function () {
  25750. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25751. },
  25752. updateShadowMap: function () {
  25753. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25754. }
  25755. } );
  25756. Object.defineProperties( WebGLRenderer.prototype, {
  25757. shadowMapEnabled: {
  25758. get: function () {
  25759. return this.shadowMap.enabled;
  25760. },
  25761. set: function ( value ) {
  25762. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25763. this.shadowMap.enabled = value;
  25764. }
  25765. },
  25766. shadowMapType: {
  25767. get: function () {
  25768. return this.shadowMap.type;
  25769. },
  25770. set: function ( value ) {
  25771. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25772. this.shadowMap.type = value;
  25773. }
  25774. },
  25775. shadowMapCullFace: {
  25776. get: function () {
  25777. return this.shadowMap.cullFace;
  25778. },
  25779. set: function ( value ) {
  25780. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25781. this.shadowMap.cullFace = value;
  25782. }
  25783. }
  25784. } );
  25785. Object.defineProperties( WebGLShadowMap.prototype, {
  25786. cullFace: {
  25787. get: function () {
  25788. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25789. },
  25790. set: function ( cullFace ) {
  25791. var value = ( cullFace !== CullFaceBack );
  25792. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25793. this.renderReverseSided = value;
  25794. }
  25795. }
  25796. } );
  25797. //
  25798. Object.defineProperties( WebGLRenderTarget.prototype, {
  25799. wrapS: {
  25800. get: function () {
  25801. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25802. return this.texture.wrapS;
  25803. },
  25804. set: function ( value ) {
  25805. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25806. this.texture.wrapS = value;
  25807. }
  25808. },
  25809. wrapT: {
  25810. get: function () {
  25811. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25812. return this.texture.wrapT;
  25813. },
  25814. set: function ( value ) {
  25815. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25816. this.texture.wrapT = value;
  25817. }
  25818. },
  25819. magFilter: {
  25820. get: function () {
  25821. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25822. return this.texture.magFilter;
  25823. },
  25824. set: function ( value ) {
  25825. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25826. this.texture.magFilter = value;
  25827. }
  25828. },
  25829. minFilter: {
  25830. get: function () {
  25831. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25832. return this.texture.minFilter;
  25833. },
  25834. set: function ( value ) {
  25835. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25836. this.texture.minFilter = value;
  25837. }
  25838. },
  25839. anisotropy: {
  25840. get: function () {
  25841. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25842. return this.texture.anisotropy;
  25843. },
  25844. set: function ( value ) {
  25845. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25846. this.texture.anisotropy = value;
  25847. }
  25848. },
  25849. offset: {
  25850. get: function () {
  25851. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25852. return this.texture.offset;
  25853. },
  25854. set: function ( value ) {
  25855. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25856. this.texture.offset = value;
  25857. }
  25858. },
  25859. repeat: {
  25860. get: function () {
  25861. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25862. return this.texture.repeat;
  25863. },
  25864. set: function ( value ) {
  25865. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25866. this.texture.repeat = value;
  25867. }
  25868. },
  25869. format: {
  25870. get: function () {
  25871. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25872. return this.texture.format;
  25873. },
  25874. set: function ( value ) {
  25875. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25876. this.texture.format = value;
  25877. }
  25878. },
  25879. type: {
  25880. get: function () {
  25881. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25882. return this.texture.type;
  25883. },
  25884. set: function ( value ) {
  25885. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25886. this.texture.type = value;
  25887. }
  25888. },
  25889. generateMipmaps: {
  25890. get: function () {
  25891. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25892. return this.texture.generateMipmaps;
  25893. },
  25894. set: function ( value ) {
  25895. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25896. this.texture.generateMipmaps = value;
  25897. }
  25898. }
  25899. } );
  25900. //
  25901. Audio.prototype.load = function ( file ) {
  25902. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25903. var scope = this;
  25904. var audioLoader = new AudioLoader();
  25905. audioLoader.load( file, function ( buffer ) {
  25906. scope.setBuffer( buffer );
  25907. } );
  25908. return this;
  25909. };
  25910. AudioAnalyser.prototype.getData = function () {
  25911. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25912. return this.getFrequencyData();
  25913. };
  25914. //
  25915. var GeometryUtils = {
  25916. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25917. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25918. var matrix;
  25919. if ( geometry2.isMesh ) {
  25920. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25921. matrix = geometry2.matrix;
  25922. geometry2 = geometry2.geometry;
  25923. }
  25924. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25925. },
  25926. center: function ( geometry ) {
  25927. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25928. return geometry.center();
  25929. }
  25930. };
  25931. var ImageUtils = {
  25932. crossOrigin: undefined,
  25933. loadTexture: function ( url, mapping, onLoad, onError ) {
  25934. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25935. var loader = new TextureLoader();
  25936. loader.setCrossOrigin( this.crossOrigin );
  25937. var texture = loader.load( url, onLoad, undefined, onError );
  25938. if ( mapping ) texture.mapping = mapping;
  25939. return texture;
  25940. },
  25941. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25942. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25943. var loader = new CubeTextureLoader();
  25944. loader.setCrossOrigin( this.crossOrigin );
  25945. var texture = loader.load( urls, onLoad, undefined, onError );
  25946. if ( mapping ) texture.mapping = mapping;
  25947. return texture;
  25948. },
  25949. loadCompressedTexture: function () {
  25950. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25951. },
  25952. loadCompressedTextureCube: function () {
  25953. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25954. }
  25955. };
  25956. //
  25957. function Projector() {
  25958. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25959. this.projectVector = function ( vector, camera ) {
  25960. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25961. vector.project( camera );
  25962. };
  25963. this.unprojectVector = function ( vector, camera ) {
  25964. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25965. vector.unproject( camera );
  25966. };
  25967. this.pickingRay = function () {
  25968. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25969. };
  25970. }
  25971. //
  25972. function CanvasRenderer() {
  25973. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25974. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25975. this.clear = function () {};
  25976. this.render = function () {};
  25977. this.setClearColor = function () {};
  25978. this.setSize = function () {};
  25979. }
  25980. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  25981. exports.WebGLRenderTarget = WebGLRenderTarget;
  25982. exports.WebGLRenderer = WebGLRenderer;
  25983. exports.ShaderLib = ShaderLib;
  25984. exports.UniformsLib = UniformsLib;
  25985. exports.UniformsUtils = UniformsUtils;
  25986. exports.ShaderChunk = ShaderChunk;
  25987. exports.FogExp2 = FogExp2;
  25988. exports.Fog = Fog;
  25989. exports.Scene = Scene;
  25990. exports.LensFlare = LensFlare;
  25991. exports.Sprite = Sprite;
  25992. exports.LOD = LOD;
  25993. exports.SkinnedMesh = SkinnedMesh;
  25994. exports.Skeleton = Skeleton;
  25995. exports.Bone = Bone;
  25996. exports.Mesh = Mesh;
  25997. exports.LineSegments = LineSegments;
  25998. exports.LineLoop = LineLoop;
  25999. exports.Line = Line;
  26000. exports.Points = Points;
  26001. exports.Group = Group;
  26002. exports.VideoTexture = VideoTexture;
  26003. exports.DataTexture = DataTexture;
  26004. exports.CompressedTexture = CompressedTexture;
  26005. exports.CubeTexture = CubeTexture;
  26006. exports.CanvasTexture = CanvasTexture;
  26007. exports.DepthTexture = DepthTexture;
  26008. exports.Texture = Texture;
  26009. exports.CompressedTextureLoader = CompressedTextureLoader;
  26010. exports.DataTextureLoader = DataTextureLoader;
  26011. exports.CubeTextureLoader = CubeTextureLoader;
  26012. exports.TextureLoader = TextureLoader;
  26013. exports.ObjectLoader = ObjectLoader;
  26014. exports.MaterialLoader = MaterialLoader;
  26015. exports.BufferGeometryLoader = BufferGeometryLoader;
  26016. exports.DefaultLoadingManager = DefaultLoadingManager;
  26017. exports.LoadingManager = LoadingManager;
  26018. exports.JSONLoader = JSONLoader;
  26019. exports.ImageLoader = ImageLoader;
  26020. exports.FontLoader = FontLoader;
  26021. exports.FileLoader = FileLoader;
  26022. exports.Loader = Loader;
  26023. exports.Cache = Cache;
  26024. exports.AudioLoader = AudioLoader;
  26025. exports.SpotLightShadow = SpotLightShadow;
  26026. exports.SpotLight = SpotLight;
  26027. exports.PointLight = PointLight;
  26028. exports.RectAreaLight = RectAreaLight;
  26029. exports.HemisphereLight = HemisphereLight;
  26030. exports.DirectionalLightShadow = DirectionalLightShadow;
  26031. exports.DirectionalLight = DirectionalLight;
  26032. exports.AmbientLight = AmbientLight;
  26033. exports.LightShadow = LightShadow;
  26034. exports.Light = Light;
  26035. exports.StereoCamera = StereoCamera;
  26036. exports.PerspectiveCamera = PerspectiveCamera;
  26037. exports.OrthographicCamera = OrthographicCamera;
  26038. exports.CubeCamera = CubeCamera;
  26039. exports.ArrayCamera = ArrayCamera;
  26040. exports.Camera = Camera;
  26041. exports.AudioListener = AudioListener;
  26042. exports.PositionalAudio = PositionalAudio;
  26043. exports.AudioContext = AudioContext;
  26044. exports.AudioAnalyser = AudioAnalyser;
  26045. exports.Audio = Audio;
  26046. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  26047. exports.StringKeyframeTrack = StringKeyframeTrack;
  26048. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  26049. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  26050. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  26051. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  26052. exports.PropertyMixer = PropertyMixer;
  26053. exports.PropertyBinding = PropertyBinding;
  26054. exports.KeyframeTrack = KeyframeTrack;
  26055. exports.AnimationUtils = AnimationUtils;
  26056. exports.AnimationObjectGroup = AnimationObjectGroup;
  26057. exports.AnimationMixer = AnimationMixer;
  26058. exports.AnimationClip = AnimationClip;
  26059. exports.Uniform = Uniform;
  26060. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  26061. exports.BufferGeometry = BufferGeometry;
  26062. exports.GeometryIdCount = GeometryIdCount;
  26063. exports.Geometry = Geometry;
  26064. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  26065. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  26066. exports.InterleavedBuffer = InterleavedBuffer;
  26067. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  26068. exports.Face3 = Face3;
  26069. exports.Object3D = Object3D;
  26070. exports.Raycaster = Raycaster;
  26071. exports.Layers = Layers;
  26072. exports.EventDispatcher = EventDispatcher;
  26073. exports.Clock = Clock;
  26074. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  26075. exports.LinearInterpolant = LinearInterpolant;
  26076. exports.DiscreteInterpolant = DiscreteInterpolant;
  26077. exports.CubicInterpolant = CubicInterpolant;
  26078. exports.Interpolant = Interpolant;
  26079. exports.Triangle = Triangle;
  26080. exports.Math = _Math;
  26081. exports.Spherical = Spherical;
  26082. exports.Cylindrical = Cylindrical;
  26083. exports.Plane = Plane;
  26084. exports.Frustum = Frustum;
  26085. exports.Sphere = Sphere;
  26086. exports.Ray = Ray;
  26087. exports.Matrix4 = Matrix4;
  26088. exports.Matrix3 = Matrix3;
  26089. exports.Box3 = Box3;
  26090. exports.Box2 = Box2;
  26091. exports.Line3 = Line3;
  26092. exports.Euler = Euler;
  26093. exports.Vector4 = Vector4;
  26094. exports.Vector3 = Vector3;
  26095. exports.Vector2 = Vector2;
  26096. exports.Quaternion = Quaternion;
  26097. exports.Color = Color;
  26098. exports.MorphBlendMesh = MorphBlendMesh;
  26099. exports.ImmediateRenderObject = ImmediateRenderObject;
  26100. exports.VertexNormalsHelper = VertexNormalsHelper;
  26101. exports.SpotLightHelper = SpotLightHelper;
  26102. exports.SkeletonHelper = SkeletonHelper;
  26103. exports.PointLightHelper = PointLightHelper;
  26104. exports.RectAreaLightHelper = RectAreaLightHelper;
  26105. exports.HemisphereLightHelper = HemisphereLightHelper;
  26106. exports.GridHelper = GridHelper;
  26107. exports.PolarGridHelper = PolarGridHelper;
  26108. exports.FaceNormalsHelper = FaceNormalsHelper;
  26109. exports.DirectionalLightHelper = DirectionalLightHelper;
  26110. exports.CameraHelper = CameraHelper;
  26111. exports.BoxHelper = BoxHelper;
  26112. exports.ArrowHelper = ArrowHelper;
  26113. exports.AxisHelper = AxisHelper;
  26114. exports.CatmullRomCurve3 = CatmullRomCurve3;
  26115. exports.CubicBezierCurve3 = CubicBezierCurve3;
  26116. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  26117. exports.LineCurve3 = LineCurve3;
  26118. exports.ArcCurve = ArcCurve;
  26119. exports.EllipseCurve = EllipseCurve;
  26120. exports.SplineCurve = SplineCurve;
  26121. exports.CubicBezierCurve = CubicBezierCurve;
  26122. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  26123. exports.LineCurve = LineCurve;
  26124. exports.Shape = Shape;
  26125. exports.Path = Path;
  26126. exports.ShapePath = ShapePath;
  26127. exports.Font = Font;
  26128. exports.CurvePath = CurvePath;
  26129. exports.Curve = Curve;
  26130. exports.ShapeUtils = ShapeUtils;
  26131. exports.SceneUtils = SceneUtils;
  26132. exports.WireframeGeometry = WireframeGeometry;
  26133. exports.ParametricGeometry = ParametricGeometry;
  26134. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  26135. exports.TetrahedronGeometry = TetrahedronGeometry;
  26136. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  26137. exports.OctahedronGeometry = OctahedronGeometry;
  26138. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  26139. exports.IcosahedronGeometry = IcosahedronGeometry;
  26140. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  26141. exports.DodecahedronGeometry = DodecahedronGeometry;
  26142. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  26143. exports.PolyhedronGeometry = PolyhedronGeometry;
  26144. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  26145. exports.TubeGeometry = TubeGeometry;
  26146. exports.TubeBufferGeometry = TubeBufferGeometry;
  26147. exports.TorusKnotGeometry = TorusKnotGeometry;
  26148. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  26149. exports.TorusGeometry = TorusGeometry;
  26150. exports.TorusBufferGeometry = TorusBufferGeometry;
  26151. exports.TextGeometry = TextGeometry;
  26152. exports.TextBufferGeometry = TextBufferGeometry;
  26153. exports.SphereGeometry = SphereGeometry;
  26154. exports.SphereBufferGeometry = SphereBufferGeometry;
  26155. exports.RingGeometry = RingGeometry;
  26156. exports.RingBufferGeometry = RingBufferGeometry;
  26157. exports.PlaneGeometry = PlaneGeometry;
  26158. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  26159. exports.LatheGeometry = LatheGeometry;
  26160. exports.LatheBufferGeometry = LatheBufferGeometry;
  26161. exports.ShapeGeometry = ShapeGeometry;
  26162. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  26163. exports.ExtrudeGeometry = ExtrudeGeometry;
  26164. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  26165. exports.EdgesGeometry = EdgesGeometry;
  26166. exports.ConeGeometry = ConeGeometry;
  26167. exports.ConeBufferGeometry = ConeBufferGeometry;
  26168. exports.CylinderGeometry = CylinderGeometry;
  26169. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  26170. exports.CircleGeometry = CircleGeometry;
  26171. exports.CircleBufferGeometry = CircleBufferGeometry;
  26172. exports.BoxGeometry = BoxGeometry;
  26173. exports.BoxBufferGeometry = BoxBufferGeometry;
  26174. exports.ShadowMaterial = ShadowMaterial;
  26175. exports.SpriteMaterial = SpriteMaterial;
  26176. exports.RawShaderMaterial = RawShaderMaterial;
  26177. exports.ShaderMaterial = ShaderMaterial;
  26178. exports.PointsMaterial = PointsMaterial;
  26179. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  26180. exports.MeshStandardMaterial = MeshStandardMaterial;
  26181. exports.MeshPhongMaterial = MeshPhongMaterial;
  26182. exports.MeshToonMaterial = MeshToonMaterial;
  26183. exports.MeshNormalMaterial = MeshNormalMaterial;
  26184. exports.MeshLambertMaterial = MeshLambertMaterial;
  26185. exports.MeshDepthMaterial = MeshDepthMaterial;
  26186. exports.MeshBasicMaterial = MeshBasicMaterial;
  26187. exports.LineDashedMaterial = LineDashedMaterial;
  26188. exports.LineBasicMaterial = LineBasicMaterial;
  26189. exports.Material = Material;
  26190. exports.Float64BufferAttribute = Float64BufferAttribute;
  26191. exports.Float32BufferAttribute = Float32BufferAttribute;
  26192. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  26193. exports.Int32BufferAttribute = Int32BufferAttribute;
  26194. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  26195. exports.Int16BufferAttribute = Int16BufferAttribute;
  26196. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  26197. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  26198. exports.Int8BufferAttribute = Int8BufferAttribute;
  26199. exports.BufferAttribute = BufferAttribute;
  26200. exports.REVISION = REVISION;
  26201. exports.MOUSE = MOUSE;
  26202. exports.CullFaceNone = CullFaceNone;
  26203. exports.CullFaceBack = CullFaceBack;
  26204. exports.CullFaceFront = CullFaceFront;
  26205. exports.CullFaceFrontBack = CullFaceFrontBack;
  26206. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  26207. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  26208. exports.BasicShadowMap = BasicShadowMap;
  26209. exports.PCFShadowMap = PCFShadowMap;
  26210. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  26211. exports.FrontSide = FrontSide;
  26212. exports.BackSide = BackSide;
  26213. exports.DoubleSide = DoubleSide;
  26214. exports.FlatShading = FlatShading;
  26215. exports.SmoothShading = SmoothShading;
  26216. exports.NoColors = NoColors;
  26217. exports.FaceColors = FaceColors;
  26218. exports.VertexColors = VertexColors;
  26219. exports.NoBlending = NoBlending;
  26220. exports.NormalBlending = NormalBlending;
  26221. exports.AdditiveBlending = AdditiveBlending;
  26222. exports.SubtractiveBlending = SubtractiveBlending;
  26223. exports.MultiplyBlending = MultiplyBlending;
  26224. exports.CustomBlending = CustomBlending;
  26225. exports.AddEquation = AddEquation;
  26226. exports.SubtractEquation = SubtractEquation;
  26227. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  26228. exports.MinEquation = MinEquation;
  26229. exports.MaxEquation = MaxEquation;
  26230. exports.ZeroFactor = ZeroFactor;
  26231. exports.OneFactor = OneFactor;
  26232. exports.SrcColorFactor = SrcColorFactor;
  26233. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  26234. exports.SrcAlphaFactor = SrcAlphaFactor;
  26235. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  26236. exports.DstAlphaFactor = DstAlphaFactor;
  26237. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  26238. exports.DstColorFactor = DstColorFactor;
  26239. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  26240. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  26241. exports.NeverDepth = NeverDepth;
  26242. exports.AlwaysDepth = AlwaysDepth;
  26243. exports.LessDepth = LessDepth;
  26244. exports.LessEqualDepth = LessEqualDepth;
  26245. exports.EqualDepth = EqualDepth;
  26246. exports.GreaterEqualDepth = GreaterEqualDepth;
  26247. exports.GreaterDepth = GreaterDepth;
  26248. exports.NotEqualDepth = NotEqualDepth;
  26249. exports.MultiplyOperation = MultiplyOperation;
  26250. exports.MixOperation = MixOperation;
  26251. exports.AddOperation = AddOperation;
  26252. exports.NoToneMapping = NoToneMapping;
  26253. exports.LinearToneMapping = LinearToneMapping;
  26254. exports.ReinhardToneMapping = ReinhardToneMapping;
  26255. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  26256. exports.CineonToneMapping = CineonToneMapping;
  26257. exports.UVMapping = UVMapping;
  26258. exports.CubeReflectionMapping = CubeReflectionMapping;
  26259. exports.CubeRefractionMapping = CubeRefractionMapping;
  26260. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  26261. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  26262. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  26263. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  26264. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  26265. exports.RepeatWrapping = RepeatWrapping;
  26266. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  26267. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  26268. exports.NearestFilter = NearestFilter;
  26269. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  26270. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  26271. exports.LinearFilter = LinearFilter;
  26272. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  26273. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  26274. exports.UnsignedByteType = UnsignedByteType;
  26275. exports.ByteType = ByteType;
  26276. exports.ShortType = ShortType;
  26277. exports.UnsignedShortType = UnsignedShortType;
  26278. exports.IntType = IntType;
  26279. exports.UnsignedIntType = UnsignedIntType;
  26280. exports.FloatType = FloatType;
  26281. exports.HalfFloatType = HalfFloatType;
  26282. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  26283. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  26284. exports.UnsignedShort565Type = UnsignedShort565Type;
  26285. exports.UnsignedInt248Type = UnsignedInt248Type;
  26286. exports.AlphaFormat = AlphaFormat;
  26287. exports.RGBFormat = RGBFormat;
  26288. exports.RGBAFormat = RGBAFormat;
  26289. exports.LuminanceFormat = LuminanceFormat;
  26290. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  26291. exports.RGBEFormat = RGBEFormat;
  26292. exports.DepthFormat = DepthFormat;
  26293. exports.DepthStencilFormat = DepthStencilFormat;
  26294. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  26295. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  26296. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  26297. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  26298. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  26299. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  26300. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  26301. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  26302. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  26303. exports.LoopOnce = LoopOnce;
  26304. exports.LoopRepeat = LoopRepeat;
  26305. exports.LoopPingPong = LoopPingPong;
  26306. exports.InterpolateDiscrete = InterpolateDiscrete;
  26307. exports.InterpolateLinear = InterpolateLinear;
  26308. exports.InterpolateSmooth = InterpolateSmooth;
  26309. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  26310. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  26311. exports.WrapAroundEnding = WrapAroundEnding;
  26312. exports.TrianglesDrawMode = TrianglesDrawMode;
  26313. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  26314. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  26315. exports.LinearEncoding = LinearEncoding;
  26316. exports.sRGBEncoding = sRGBEncoding;
  26317. exports.GammaEncoding = GammaEncoding;
  26318. exports.RGBEEncoding = RGBEEncoding;
  26319. exports.LogLuvEncoding = LogLuvEncoding;
  26320. exports.RGBM7Encoding = RGBM7Encoding;
  26321. exports.RGBM16Encoding = RGBM16Encoding;
  26322. exports.RGBDEncoding = RGBDEncoding;
  26323. exports.BasicDepthPacking = BasicDepthPacking;
  26324. exports.RGBADepthPacking = RGBADepthPacking;
  26325. exports.CubeGeometry = BoxGeometry;
  26326. exports.Face4 = Face4;
  26327. exports.LineStrip = LineStrip;
  26328. exports.LinePieces = LinePieces;
  26329. exports.MeshFaceMaterial = MeshFaceMaterial;
  26330. exports.MultiMaterial = MultiMaterial;
  26331. exports.PointCloud = PointCloud;
  26332. exports.Particle = Particle;
  26333. exports.ParticleSystem = ParticleSystem;
  26334. exports.PointCloudMaterial = PointCloudMaterial;
  26335. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  26336. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  26337. exports.Vertex = Vertex;
  26338. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  26339. exports.Int8Attribute = Int8Attribute;
  26340. exports.Uint8Attribute = Uint8Attribute;
  26341. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  26342. exports.Int16Attribute = Int16Attribute;
  26343. exports.Uint16Attribute = Uint16Attribute;
  26344. exports.Int32Attribute = Int32Attribute;
  26345. exports.Uint32Attribute = Uint32Attribute;
  26346. exports.Float32Attribute = Float32Attribute;
  26347. exports.Float64Attribute = Float64Attribute;
  26348. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  26349. exports.SplineCurve3 = SplineCurve3;
  26350. exports.Spline = Spline;
  26351. exports.BoundingBoxHelper = BoundingBoxHelper;
  26352. exports.EdgesHelper = EdgesHelper;
  26353. exports.WireframeHelper = WireframeHelper;
  26354. exports.XHRLoader = XHRLoader;
  26355. exports.BinaryTextureLoader = BinaryTextureLoader;
  26356. exports.GeometryUtils = GeometryUtils;
  26357. exports.ImageUtils = ImageUtils;
  26358. exports.Projector = Projector;
  26359. exports.CanvasRenderer = CanvasRenderer;
  26360. Object.defineProperty(exports, '__esModule', { value: true });
  26361. })));