three.js 1005 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119
  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. //
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  15. };
  16. }
  17. if ( Function.prototype.name === undefined ) {
  18. // Missing in IE9-11.
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  20. Object.defineProperty( Function.prototype, 'name', {
  21. get: function () {
  22. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  23. }
  24. } );
  25. }
  26. if ( Object.assign === undefined ) {
  27. // Missing in IE.
  28. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  29. ( function () {
  30. Object.assign = function ( target ) {
  31. 'use strict';
  32. if ( target === undefined || target === null ) {
  33. throw new TypeError( 'Cannot convert undefined or null to object' );
  34. }
  35. var output = Object( target );
  36. for ( var index = 1; index < arguments.length; index ++ ) {
  37. var source = arguments[ index ];
  38. if ( source !== undefined && source !== null ) {
  39. for ( var nextKey in source ) {
  40. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  41. output[ nextKey ] = source[ nextKey ];
  42. }
  43. }
  44. }
  45. }
  46. return output;
  47. };
  48. } )();
  49. }
  50. /**
  51. * https://github.com/mrdoob/eventdispatcher.js/
  52. */
  53. function EventDispatcher() {}
  54. EventDispatcher.prototype = {
  55. addEventListener: function ( type, listener ) {
  56. if ( this._listeners === undefined ) this._listeners = {};
  57. var listeners = this._listeners;
  58. if ( listeners[ type ] === undefined ) {
  59. listeners[ type ] = [];
  60. }
  61. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  62. listeners[ type ].push( listener );
  63. }
  64. },
  65. hasEventListener: function ( type, listener ) {
  66. if ( this._listeners === undefined ) return false;
  67. var listeners = this._listeners;
  68. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  69. },
  70. removeEventListener: function ( type, listener ) {
  71. if ( this._listeners === undefined ) return;
  72. var listeners = this._listeners;
  73. var listenerArray = listeners[ type ];
  74. if ( listenerArray !== undefined ) {
  75. var index = listenerArray.indexOf( listener );
  76. if ( index !== - 1 ) {
  77. listenerArray.splice( index, 1 );
  78. }
  79. }
  80. },
  81. dispatchEvent: function ( event ) {
  82. if ( this._listeners === undefined ) return;
  83. var listeners = this._listeners;
  84. var listenerArray = listeners[ event.type ];
  85. if ( listenerArray !== undefined ) {
  86. event.target = this;
  87. var array = [], i = 0;
  88. var length = listenerArray.length;
  89. for ( i = 0; i < length; i ++ ) {
  90. array[ i ] = listenerArray[ i ];
  91. }
  92. for ( i = 0; i < length; i ++ ) {
  93. array[ i ].call( this, event );
  94. }
  95. }
  96. }
  97. };
  98. var REVISION = '84dev';
  99. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  100. var CullFaceNone = 0;
  101. var CullFaceBack = 1;
  102. var CullFaceFront = 2;
  103. var CullFaceFrontBack = 3;
  104. var FrontFaceDirectionCW = 0;
  105. var FrontFaceDirectionCCW = 1;
  106. var BasicShadowMap = 0;
  107. var PCFShadowMap = 1;
  108. var PCFSoftShadowMap = 2;
  109. var FrontSide = 0;
  110. var BackSide = 1;
  111. var DoubleSide = 2;
  112. var FlatShading = 1;
  113. var SmoothShading = 2;
  114. var NoColors = 0;
  115. var FaceColors = 1;
  116. var VertexColors = 2;
  117. var NoBlending = 0;
  118. var NormalBlending = 1;
  119. var AdditiveBlending = 2;
  120. var SubtractiveBlending = 3;
  121. var MultiplyBlending = 4;
  122. var CustomBlending = 5;
  123. var AddEquation = 100;
  124. var SubtractEquation = 101;
  125. var ReverseSubtractEquation = 102;
  126. var MinEquation = 103;
  127. var MaxEquation = 104;
  128. var ZeroFactor = 200;
  129. var OneFactor = 201;
  130. var SrcColorFactor = 202;
  131. var OneMinusSrcColorFactor = 203;
  132. var SrcAlphaFactor = 204;
  133. var OneMinusSrcAlphaFactor = 205;
  134. var DstAlphaFactor = 206;
  135. var OneMinusDstAlphaFactor = 207;
  136. var DstColorFactor = 208;
  137. var OneMinusDstColorFactor = 209;
  138. var SrcAlphaSaturateFactor = 210;
  139. var NeverDepth = 0;
  140. var AlwaysDepth = 1;
  141. var LessDepth = 2;
  142. var LessEqualDepth = 3;
  143. var EqualDepth = 4;
  144. var GreaterEqualDepth = 5;
  145. var GreaterDepth = 6;
  146. var NotEqualDepth = 7;
  147. var MultiplyOperation = 0;
  148. var MixOperation = 1;
  149. var AddOperation = 2;
  150. var NoToneMapping = 0;
  151. var LinearToneMapping = 1;
  152. var ReinhardToneMapping = 2;
  153. var Uncharted2ToneMapping = 3;
  154. var CineonToneMapping = 4;
  155. var UVMapping = 300;
  156. var CubeReflectionMapping = 301;
  157. var CubeRefractionMapping = 302;
  158. var EquirectangularReflectionMapping = 303;
  159. var EquirectangularRefractionMapping = 304;
  160. var SphericalReflectionMapping = 305;
  161. var CubeUVReflectionMapping = 306;
  162. var CubeUVRefractionMapping = 307;
  163. var RepeatWrapping = 1000;
  164. var ClampToEdgeWrapping = 1001;
  165. var MirroredRepeatWrapping = 1002;
  166. var NearestFilter = 1003;
  167. var NearestMipMapNearestFilter = 1004;
  168. var NearestMipMapLinearFilter = 1005;
  169. var LinearFilter = 1006;
  170. var LinearMipMapNearestFilter = 1007;
  171. var LinearMipMapLinearFilter = 1008;
  172. var UnsignedByteType = 1009;
  173. var ByteType = 1010;
  174. var ShortType = 1011;
  175. var UnsignedShortType = 1012;
  176. var IntType = 1013;
  177. var UnsignedIntType = 1014;
  178. var FloatType = 1015;
  179. var HalfFloatType = 1016;
  180. var UnsignedShort4444Type = 1017;
  181. var UnsignedShort5551Type = 1018;
  182. var UnsignedShort565Type = 1019;
  183. var UnsignedInt248Type = 1020;
  184. var AlphaFormat = 1021;
  185. var RGBFormat = 1022;
  186. var RGBAFormat = 1023;
  187. var LuminanceFormat = 1024;
  188. var LuminanceAlphaFormat = 1025;
  189. var RGBEFormat = RGBAFormat;
  190. var DepthFormat = 1026;
  191. var DepthStencilFormat = 1027;
  192. var RGB_S3TC_DXT1_Format = 2001;
  193. var RGBA_S3TC_DXT1_Format = 2002;
  194. var RGBA_S3TC_DXT3_Format = 2003;
  195. var RGBA_S3TC_DXT5_Format = 2004;
  196. var RGB_PVRTC_4BPPV1_Format = 2100;
  197. var RGB_PVRTC_2BPPV1_Format = 2101;
  198. var RGBA_PVRTC_4BPPV1_Format = 2102;
  199. var RGBA_PVRTC_2BPPV1_Format = 2103;
  200. var RGB_ETC1_Format = 2151;
  201. var LoopOnce = 2200;
  202. var LoopRepeat = 2201;
  203. var LoopPingPong = 2202;
  204. var InterpolateDiscrete = 2300;
  205. var InterpolateLinear = 2301;
  206. var InterpolateSmooth = 2302;
  207. var ZeroCurvatureEnding = 2400;
  208. var ZeroSlopeEnding = 2401;
  209. var WrapAroundEnding = 2402;
  210. var TrianglesDrawMode = 0;
  211. var TriangleStripDrawMode = 1;
  212. var TriangleFanDrawMode = 2;
  213. var LinearEncoding = 3000;
  214. var sRGBEncoding = 3001;
  215. var GammaEncoding = 3007;
  216. var RGBEEncoding = 3002;
  217. var LogLuvEncoding = 3003;
  218. var RGBM7Encoding = 3004;
  219. var RGBM16Encoding = 3005;
  220. var RGBDEncoding = 3006;
  221. var BasicDepthPacking = 3200;
  222. var RGBADepthPacking = 3201;
  223. /**
  224. * @author alteredq / http://alteredqualia.com/
  225. * @author mrdoob / http://mrdoob.com/
  226. */
  227. var _Math = {
  228. DEG2RAD: Math.PI / 180,
  229. RAD2DEG: 180 / Math.PI,
  230. generateUUID: function () {
  231. // http://www.broofa.com/Tools/Math.uuid.htm
  232. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  233. var uuid = new Array( 36 );
  234. var rnd = 0, r;
  235. return function generateUUID() {
  236. for ( var i = 0; i < 36; i ++ ) {
  237. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  238. uuid[ i ] = '-';
  239. } else if ( i === 14 ) {
  240. uuid[ i ] = '4';
  241. } else {
  242. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  243. r = rnd & 0xf;
  244. rnd = rnd >> 4;
  245. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  246. }
  247. }
  248. return uuid.join( '' );
  249. };
  250. }(),
  251. clamp: function ( value, min, max ) {
  252. return Math.max( min, Math.min( max, value ) );
  253. },
  254. // compute euclidian modulo of m % n
  255. // https://en.wikipedia.org/wiki/Modulo_operation
  256. euclideanModulo: function ( n, m ) {
  257. return ( ( n % m ) + m ) % m;
  258. },
  259. // Linear mapping from range <a1, a2> to range <b1, b2>
  260. mapLinear: function ( x, a1, a2, b1, b2 ) {
  261. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  262. },
  263. // https://en.wikipedia.org/wiki/Linear_interpolation
  264. lerp: function ( x, y, t ) {
  265. return ( 1 - t ) * x + t * y;
  266. },
  267. // http://en.wikipedia.org/wiki/Smoothstep
  268. smoothstep: function ( x, min, max ) {
  269. if ( x <= min ) return 0;
  270. if ( x >= max ) return 1;
  271. x = ( x - min ) / ( max - min );
  272. return x * x * ( 3 - 2 * x );
  273. },
  274. smootherstep: function ( x, min, max ) {
  275. if ( x <= min ) return 0;
  276. if ( x >= max ) return 1;
  277. x = ( x - min ) / ( max - min );
  278. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  279. },
  280. // Random integer from <low, high> interval
  281. randInt: function ( low, high ) {
  282. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  283. },
  284. // Random float from <low, high> interval
  285. randFloat: function ( low, high ) {
  286. return low + Math.random() * ( high - low );
  287. },
  288. // Random float from <-range/2, range/2> interval
  289. randFloatSpread: function ( range ) {
  290. return range * ( 0.5 - Math.random() );
  291. },
  292. degToRad: function ( degrees ) {
  293. return degrees * _Math.DEG2RAD;
  294. },
  295. radToDeg: function ( radians ) {
  296. return radians * _Math.RAD2DEG;
  297. },
  298. isPowerOfTwo: function ( value ) {
  299. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  300. },
  301. nearestPowerOfTwo: function ( value ) {
  302. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  303. },
  304. nextPowerOfTwo: function ( value ) {
  305. value --;
  306. value |= value >> 1;
  307. value |= value >> 2;
  308. value |= value >> 4;
  309. value |= value >> 8;
  310. value |= value >> 16;
  311. value ++;
  312. return value;
  313. }
  314. };
  315. /**
  316. * @author mrdoob / http://mrdoob.com/
  317. * @author philogb / http://blog.thejit.org/
  318. * @author egraether / http://egraether.com/
  319. * @author zz85 / http://www.lab4games.net/zz85/blog
  320. */
  321. function Vector2( x, y ) {
  322. this.x = x || 0;
  323. this.y = y || 0;
  324. }
  325. Vector2.prototype = {
  326. constructor: Vector2,
  327. isVector2: true,
  328. get width() {
  329. return this.x;
  330. },
  331. set width( value ) {
  332. this.x = value;
  333. },
  334. get height() {
  335. return this.y;
  336. },
  337. set height( value ) {
  338. this.y = value;
  339. },
  340. //
  341. set: function ( x, y ) {
  342. this.x = x;
  343. this.y = y;
  344. return this;
  345. },
  346. setScalar: function ( scalar ) {
  347. this.x = scalar;
  348. this.y = scalar;
  349. return this;
  350. },
  351. setX: function ( x ) {
  352. this.x = x;
  353. return this;
  354. },
  355. setY: function ( y ) {
  356. this.y = y;
  357. return this;
  358. },
  359. setComponent: function ( index, value ) {
  360. switch ( index ) {
  361. case 0: this.x = value; break;
  362. case 1: this.y = value; break;
  363. default: throw new Error( 'index is out of range: ' + index );
  364. }
  365. return this;
  366. },
  367. getComponent: function ( index ) {
  368. switch ( index ) {
  369. case 0: return this.x;
  370. case 1: return this.y;
  371. default: throw new Error( 'index is out of range: ' + index );
  372. }
  373. },
  374. clone: function () {
  375. return new this.constructor( this.x, this.y );
  376. },
  377. copy: function ( v ) {
  378. this.x = v.x;
  379. this.y = v.y;
  380. return this;
  381. },
  382. add: function ( v, w ) {
  383. if ( w !== undefined ) {
  384. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  385. return this.addVectors( v, w );
  386. }
  387. this.x += v.x;
  388. this.y += v.y;
  389. return this;
  390. },
  391. addScalar: function ( s ) {
  392. this.x += s;
  393. this.y += s;
  394. return this;
  395. },
  396. addVectors: function ( a, b ) {
  397. this.x = a.x + b.x;
  398. this.y = a.y + b.y;
  399. return this;
  400. },
  401. addScaledVector: function ( v, s ) {
  402. this.x += v.x * s;
  403. this.y += v.y * s;
  404. return this;
  405. },
  406. sub: function ( v, w ) {
  407. if ( w !== undefined ) {
  408. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  409. return this.subVectors( v, w );
  410. }
  411. this.x -= v.x;
  412. this.y -= v.y;
  413. return this;
  414. },
  415. subScalar: function ( s ) {
  416. this.x -= s;
  417. this.y -= s;
  418. return this;
  419. },
  420. subVectors: function ( a, b ) {
  421. this.x = a.x - b.x;
  422. this.y = a.y - b.y;
  423. return this;
  424. },
  425. multiply: function ( v ) {
  426. this.x *= v.x;
  427. this.y *= v.y;
  428. return this;
  429. },
  430. multiplyScalar: function ( scalar ) {
  431. if ( isFinite( scalar ) ) {
  432. this.x *= scalar;
  433. this.y *= scalar;
  434. } else {
  435. this.x = 0;
  436. this.y = 0;
  437. }
  438. return this;
  439. },
  440. divide: function ( v ) {
  441. this.x /= v.x;
  442. this.y /= v.y;
  443. return this;
  444. },
  445. divideScalar: function ( scalar ) {
  446. return this.multiplyScalar( 1 / scalar );
  447. },
  448. min: function ( v ) {
  449. this.x = Math.min( this.x, v.x );
  450. this.y = Math.min( this.y, v.y );
  451. return this;
  452. },
  453. max: function ( v ) {
  454. this.x = Math.max( this.x, v.x );
  455. this.y = Math.max( this.y, v.y );
  456. return this;
  457. },
  458. clamp: function ( min, max ) {
  459. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  460. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  461. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  462. return this;
  463. },
  464. clampScalar: function () {
  465. var min, max;
  466. return function clampScalar( minVal, maxVal ) {
  467. if ( min === undefined ) {
  468. min = new Vector2();
  469. max = new Vector2();
  470. }
  471. min.set( minVal, minVal );
  472. max.set( maxVal, maxVal );
  473. return this.clamp( min, max );
  474. };
  475. }(),
  476. clampLength: function ( min, max ) {
  477. var length = this.length();
  478. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  479. },
  480. floor: function () {
  481. this.x = Math.floor( this.x );
  482. this.y = Math.floor( this.y );
  483. return this;
  484. },
  485. ceil: function () {
  486. this.x = Math.ceil( this.x );
  487. this.y = Math.ceil( this.y );
  488. return this;
  489. },
  490. round: function () {
  491. this.x = Math.round( this.x );
  492. this.y = Math.round( this.y );
  493. return this;
  494. },
  495. roundToZero: function () {
  496. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  497. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  498. return this;
  499. },
  500. negate: function () {
  501. this.x = - this.x;
  502. this.y = - this.y;
  503. return this;
  504. },
  505. dot: function ( v ) {
  506. return this.x * v.x + this.y * v.y;
  507. },
  508. lengthSq: function () {
  509. return this.x * this.x + this.y * this.y;
  510. },
  511. length: function () {
  512. return Math.sqrt( this.x * this.x + this.y * this.y );
  513. },
  514. lengthManhattan: function() {
  515. return Math.abs( this.x ) + Math.abs( this.y );
  516. },
  517. normalize: function () {
  518. return this.divideScalar( this.length() );
  519. },
  520. angle: function () {
  521. // computes the angle in radians with respect to the positive x-axis
  522. var angle = Math.atan2( this.y, this.x );
  523. if ( angle < 0 ) angle += 2 * Math.PI;
  524. return angle;
  525. },
  526. distanceTo: function ( v ) {
  527. return Math.sqrt( this.distanceToSquared( v ) );
  528. },
  529. distanceToSquared: function ( v ) {
  530. var dx = this.x - v.x, dy = this.y - v.y;
  531. return dx * dx + dy * dy;
  532. },
  533. distanceToManhattan: function ( v ) {
  534. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  535. },
  536. setLength: function ( length ) {
  537. return this.multiplyScalar( length / this.length() );
  538. },
  539. lerp: function ( v, alpha ) {
  540. this.x += ( v.x - this.x ) * alpha;
  541. this.y += ( v.y - this.y ) * alpha;
  542. return this;
  543. },
  544. lerpVectors: function ( v1, v2, alpha ) {
  545. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  546. },
  547. equals: function ( v ) {
  548. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  549. },
  550. fromArray: function ( array, offset ) {
  551. if ( offset === undefined ) offset = 0;
  552. this.x = array[ offset ];
  553. this.y = array[ offset + 1 ];
  554. return this;
  555. },
  556. toArray: function ( array, offset ) {
  557. if ( array === undefined ) array = [];
  558. if ( offset === undefined ) offset = 0;
  559. array[ offset ] = this.x;
  560. array[ offset + 1 ] = this.y;
  561. return array;
  562. },
  563. fromBufferAttribute: function ( attribute, index, offset ) {
  564. if ( offset !== undefined ) {
  565. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  566. }
  567. this.x = attribute.getX( index );
  568. this.y = attribute.getY( index );
  569. return this;
  570. },
  571. rotateAround: function ( center, angle ) {
  572. var c = Math.cos( angle ), s = Math.sin( angle );
  573. var x = this.x - center.x;
  574. var y = this.y - center.y;
  575. this.x = x * c - y * s + center.x;
  576. this.y = x * s + y * c + center.y;
  577. return this;
  578. }
  579. };
  580. /**
  581. * @author mrdoob / http://mrdoob.com/
  582. * @author alteredq / http://alteredqualia.com/
  583. * @author szimek / https://github.com/szimek/
  584. */
  585. var textureId = 0;
  586. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  587. Object.defineProperty( this, 'id', { value: textureId ++ } );
  588. this.uuid = _Math.generateUUID();
  589. this.name = '';
  590. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  591. this.mipmaps = [];
  592. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  593. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  594. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  595. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  596. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  597. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  598. this.format = format !== undefined ? format : RGBAFormat;
  599. this.type = type !== undefined ? type : UnsignedByteType;
  600. this.offset = new Vector2( 0, 0 );
  601. this.repeat = new Vector2( 1, 1 );
  602. this.generateMipmaps = true;
  603. this.premultiplyAlpha = false;
  604. this.flipY = true;
  605. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  606. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  607. //
  608. // Also changing the encoding after already used by a Material will not automatically make the Material
  609. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  610. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  611. this.version = 0;
  612. this.onUpdate = null;
  613. }
  614. Texture.DEFAULT_IMAGE = undefined;
  615. Texture.DEFAULT_MAPPING = UVMapping;
  616. Texture.prototype = {
  617. constructor: Texture,
  618. isTexture: true,
  619. set needsUpdate( value ) {
  620. if ( value === true ) this.version ++;
  621. },
  622. clone: function () {
  623. return new this.constructor().copy( this );
  624. },
  625. copy: function ( source ) {
  626. this.image = source.image;
  627. this.mipmaps = source.mipmaps.slice( 0 );
  628. this.mapping = source.mapping;
  629. this.wrapS = source.wrapS;
  630. this.wrapT = source.wrapT;
  631. this.magFilter = source.magFilter;
  632. this.minFilter = source.minFilter;
  633. this.anisotropy = source.anisotropy;
  634. this.format = source.format;
  635. this.type = source.type;
  636. this.offset.copy( source.offset );
  637. this.repeat.copy( source.repeat );
  638. this.generateMipmaps = source.generateMipmaps;
  639. this.premultiplyAlpha = source.premultiplyAlpha;
  640. this.flipY = source.flipY;
  641. this.unpackAlignment = source.unpackAlignment;
  642. this.encoding = source.encoding;
  643. return this;
  644. },
  645. toJSON: function ( meta ) {
  646. if ( meta.textures[ this.uuid ] !== undefined ) {
  647. return meta.textures[ this.uuid ];
  648. }
  649. function getDataURL( image ) {
  650. var canvas;
  651. if ( image.toDataURL !== undefined ) {
  652. canvas = image;
  653. } else {
  654. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  655. canvas.width = image.width;
  656. canvas.height = image.height;
  657. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  658. }
  659. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  660. return canvas.toDataURL( 'image/jpeg', 0.6 );
  661. } else {
  662. return canvas.toDataURL( 'image/png' );
  663. }
  664. }
  665. var output = {
  666. metadata: {
  667. version: 4.4,
  668. type: 'Texture',
  669. generator: 'Texture.toJSON'
  670. },
  671. uuid: this.uuid,
  672. name: this.name,
  673. mapping: this.mapping,
  674. repeat: [ this.repeat.x, this.repeat.y ],
  675. offset: [ this.offset.x, this.offset.y ],
  676. wrap: [ this.wrapS, this.wrapT ],
  677. minFilter: this.minFilter,
  678. magFilter: this.magFilter,
  679. anisotropy: this.anisotropy,
  680. flipY: this.flipY
  681. };
  682. if ( this.image !== undefined ) {
  683. // TODO: Move to THREE.Image
  684. var image = this.image;
  685. if ( image.uuid === undefined ) {
  686. image.uuid = _Math.generateUUID(); // UGH
  687. }
  688. if ( meta.images[ image.uuid ] === undefined ) {
  689. meta.images[ image.uuid ] = {
  690. uuid: image.uuid,
  691. url: getDataURL( image )
  692. };
  693. }
  694. output.image = image.uuid;
  695. }
  696. meta.textures[ this.uuid ] = output;
  697. return output;
  698. },
  699. dispose: function () {
  700. this.dispatchEvent( { type: 'dispose' } );
  701. },
  702. transformUv: function ( uv ) {
  703. if ( this.mapping !== UVMapping ) return;
  704. uv.multiply( this.repeat );
  705. uv.add( this.offset );
  706. if ( uv.x < 0 || uv.x > 1 ) {
  707. switch ( this.wrapS ) {
  708. case RepeatWrapping:
  709. uv.x = uv.x - Math.floor( uv.x );
  710. break;
  711. case ClampToEdgeWrapping:
  712. uv.x = uv.x < 0 ? 0 : 1;
  713. break;
  714. case MirroredRepeatWrapping:
  715. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  716. uv.x = Math.ceil( uv.x ) - uv.x;
  717. } else {
  718. uv.x = uv.x - Math.floor( uv.x );
  719. }
  720. break;
  721. }
  722. }
  723. if ( uv.y < 0 || uv.y > 1 ) {
  724. switch ( this.wrapT ) {
  725. case RepeatWrapping:
  726. uv.y = uv.y - Math.floor( uv.y );
  727. break;
  728. case ClampToEdgeWrapping:
  729. uv.y = uv.y < 0 ? 0 : 1;
  730. break;
  731. case MirroredRepeatWrapping:
  732. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  733. uv.y = Math.ceil( uv.y ) - uv.y;
  734. } else {
  735. uv.y = uv.y - Math.floor( uv.y );
  736. }
  737. break;
  738. }
  739. }
  740. if ( this.flipY ) {
  741. uv.y = 1 - uv.y;
  742. }
  743. }
  744. };
  745. Object.assign( Texture.prototype, EventDispatcher.prototype );
  746. /**
  747. * @author supereggbert / http://www.paulbrunt.co.uk/
  748. * @author philogb / http://blog.thejit.org/
  749. * @author mikael emtinger / http://gomo.se/
  750. * @author egraether / http://egraether.com/
  751. * @author WestLangley / http://github.com/WestLangley
  752. */
  753. function Vector4( x, y, z, w ) {
  754. this.x = x || 0;
  755. this.y = y || 0;
  756. this.z = z || 0;
  757. this.w = ( w !== undefined ) ? w : 1;
  758. }
  759. Vector4.prototype = {
  760. constructor: Vector4,
  761. isVector4: true,
  762. set: function ( x, y, z, w ) {
  763. this.x = x;
  764. this.y = y;
  765. this.z = z;
  766. this.w = w;
  767. return this;
  768. },
  769. setScalar: function ( scalar ) {
  770. this.x = scalar;
  771. this.y = scalar;
  772. this.z = scalar;
  773. this.w = scalar;
  774. return this;
  775. },
  776. setX: function ( x ) {
  777. this.x = x;
  778. return this;
  779. },
  780. setY: function ( y ) {
  781. this.y = y;
  782. return this;
  783. },
  784. setZ: function ( z ) {
  785. this.z = z;
  786. return this;
  787. },
  788. setW: function ( w ) {
  789. this.w = w;
  790. return this;
  791. },
  792. setComponent: function ( index, value ) {
  793. switch ( index ) {
  794. case 0: this.x = value; break;
  795. case 1: this.y = value; break;
  796. case 2: this.z = value; break;
  797. case 3: this.w = value; break;
  798. default: throw new Error( 'index is out of range: ' + index );
  799. }
  800. return this;
  801. },
  802. getComponent: function ( index ) {
  803. switch ( index ) {
  804. case 0: return this.x;
  805. case 1: return this.y;
  806. case 2: return this.z;
  807. case 3: return this.w;
  808. default: throw new Error( 'index is out of range: ' + index );
  809. }
  810. },
  811. clone: function () {
  812. return new this.constructor( this.x, this.y, this.z, this.w );
  813. },
  814. copy: function ( v ) {
  815. this.x = v.x;
  816. this.y = v.y;
  817. this.z = v.z;
  818. this.w = ( v.w !== undefined ) ? v.w : 1;
  819. return this;
  820. },
  821. add: function ( v, w ) {
  822. if ( w !== undefined ) {
  823. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  824. return this.addVectors( v, w );
  825. }
  826. this.x += v.x;
  827. this.y += v.y;
  828. this.z += v.z;
  829. this.w += v.w;
  830. return this;
  831. },
  832. addScalar: function ( s ) {
  833. this.x += s;
  834. this.y += s;
  835. this.z += s;
  836. this.w += s;
  837. return this;
  838. },
  839. addVectors: function ( a, b ) {
  840. this.x = a.x + b.x;
  841. this.y = a.y + b.y;
  842. this.z = a.z + b.z;
  843. this.w = a.w + b.w;
  844. return this;
  845. },
  846. addScaledVector: function ( v, s ) {
  847. this.x += v.x * s;
  848. this.y += v.y * s;
  849. this.z += v.z * s;
  850. this.w += v.w * s;
  851. return this;
  852. },
  853. sub: function ( v, w ) {
  854. if ( w !== undefined ) {
  855. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  856. return this.subVectors( v, w );
  857. }
  858. this.x -= v.x;
  859. this.y -= v.y;
  860. this.z -= v.z;
  861. this.w -= v.w;
  862. return this;
  863. },
  864. subScalar: function ( s ) {
  865. this.x -= s;
  866. this.y -= s;
  867. this.z -= s;
  868. this.w -= s;
  869. return this;
  870. },
  871. subVectors: function ( a, b ) {
  872. this.x = a.x - b.x;
  873. this.y = a.y - b.y;
  874. this.z = a.z - b.z;
  875. this.w = a.w - b.w;
  876. return this;
  877. },
  878. multiplyScalar: function ( scalar ) {
  879. if ( isFinite( scalar ) ) {
  880. this.x *= scalar;
  881. this.y *= scalar;
  882. this.z *= scalar;
  883. this.w *= scalar;
  884. } else {
  885. this.x = 0;
  886. this.y = 0;
  887. this.z = 0;
  888. this.w = 0;
  889. }
  890. return this;
  891. },
  892. applyMatrix4: function ( m ) {
  893. var x = this.x, y = this.y, z = this.z, w = this.w;
  894. var e = m.elements;
  895. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  896. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  897. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  898. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  899. return this;
  900. },
  901. divideScalar: function ( scalar ) {
  902. return this.multiplyScalar( 1 / scalar );
  903. },
  904. setAxisAngleFromQuaternion: function ( q ) {
  905. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  906. // q is assumed to be normalized
  907. this.w = 2 * Math.acos( q.w );
  908. var s = Math.sqrt( 1 - q.w * q.w );
  909. if ( s < 0.0001 ) {
  910. this.x = 1;
  911. this.y = 0;
  912. this.z = 0;
  913. } else {
  914. this.x = q.x / s;
  915. this.y = q.y / s;
  916. this.z = q.z / s;
  917. }
  918. return this;
  919. },
  920. setAxisAngleFromRotationMatrix: function ( m ) {
  921. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  922. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  923. var angle, x, y, z, // variables for result
  924. epsilon = 0.01, // margin to allow for rounding errors
  925. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  926. te = m.elements,
  927. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  928. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  929. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  930. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  931. ( Math.abs( m13 - m31 ) < epsilon ) &&
  932. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  933. // singularity found
  934. // first check for identity matrix which must have +1 for all terms
  935. // in leading diagonal and zero in other terms
  936. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  937. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  938. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  939. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  940. // this singularity is identity matrix so angle = 0
  941. this.set( 1, 0, 0, 0 );
  942. return this; // zero angle, arbitrary axis
  943. }
  944. // otherwise this singularity is angle = 180
  945. angle = Math.PI;
  946. var xx = ( m11 + 1 ) / 2;
  947. var yy = ( m22 + 1 ) / 2;
  948. var zz = ( m33 + 1 ) / 2;
  949. var xy = ( m12 + m21 ) / 4;
  950. var xz = ( m13 + m31 ) / 4;
  951. var yz = ( m23 + m32 ) / 4;
  952. if ( ( xx > yy ) && ( xx > zz ) ) {
  953. // m11 is the largest diagonal term
  954. if ( xx < epsilon ) {
  955. x = 0;
  956. y = 0.707106781;
  957. z = 0.707106781;
  958. } else {
  959. x = Math.sqrt( xx );
  960. y = xy / x;
  961. z = xz / x;
  962. }
  963. } else if ( yy > zz ) {
  964. // m22 is the largest diagonal term
  965. if ( yy < epsilon ) {
  966. x = 0.707106781;
  967. y = 0;
  968. z = 0.707106781;
  969. } else {
  970. y = Math.sqrt( yy );
  971. x = xy / y;
  972. z = yz / y;
  973. }
  974. } else {
  975. // m33 is the largest diagonal term so base result on this
  976. if ( zz < epsilon ) {
  977. x = 0.707106781;
  978. y = 0.707106781;
  979. z = 0;
  980. } else {
  981. z = Math.sqrt( zz );
  982. x = xz / z;
  983. y = yz / z;
  984. }
  985. }
  986. this.set( x, y, z, angle );
  987. return this; // return 180 deg rotation
  988. }
  989. // as we have reached here there are no singularities so we can handle normally
  990. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  991. ( m13 - m31 ) * ( m13 - m31 ) +
  992. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  993. if ( Math.abs( s ) < 0.001 ) s = 1;
  994. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  995. // caught by singularity test above, but I've left it in just in case
  996. this.x = ( m32 - m23 ) / s;
  997. this.y = ( m13 - m31 ) / s;
  998. this.z = ( m21 - m12 ) / s;
  999. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1000. return this;
  1001. },
  1002. min: function ( v ) {
  1003. this.x = Math.min( this.x, v.x );
  1004. this.y = Math.min( this.y, v.y );
  1005. this.z = Math.min( this.z, v.z );
  1006. this.w = Math.min( this.w, v.w );
  1007. return this;
  1008. },
  1009. max: function ( v ) {
  1010. this.x = Math.max( this.x, v.x );
  1011. this.y = Math.max( this.y, v.y );
  1012. this.z = Math.max( this.z, v.z );
  1013. this.w = Math.max( this.w, v.w );
  1014. return this;
  1015. },
  1016. clamp: function ( min, max ) {
  1017. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1018. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1019. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1020. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1021. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1022. return this;
  1023. },
  1024. clampScalar: function () {
  1025. var min, max;
  1026. return function clampScalar( minVal, maxVal ) {
  1027. if ( min === undefined ) {
  1028. min = new Vector4();
  1029. max = new Vector4();
  1030. }
  1031. min.set( minVal, minVal, minVal, minVal );
  1032. max.set( maxVal, maxVal, maxVal, maxVal );
  1033. return this.clamp( min, max );
  1034. };
  1035. }(),
  1036. floor: function () {
  1037. this.x = Math.floor( this.x );
  1038. this.y = Math.floor( this.y );
  1039. this.z = Math.floor( this.z );
  1040. this.w = Math.floor( this.w );
  1041. return this;
  1042. },
  1043. ceil: function () {
  1044. this.x = Math.ceil( this.x );
  1045. this.y = Math.ceil( this.y );
  1046. this.z = Math.ceil( this.z );
  1047. this.w = Math.ceil( this.w );
  1048. return this;
  1049. },
  1050. round: function () {
  1051. this.x = Math.round( this.x );
  1052. this.y = Math.round( this.y );
  1053. this.z = Math.round( this.z );
  1054. this.w = Math.round( this.w );
  1055. return this;
  1056. },
  1057. roundToZero: function () {
  1058. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1059. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1060. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1061. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1062. return this;
  1063. },
  1064. negate: function () {
  1065. this.x = - this.x;
  1066. this.y = - this.y;
  1067. this.z = - this.z;
  1068. this.w = - this.w;
  1069. return this;
  1070. },
  1071. dot: function ( v ) {
  1072. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1073. },
  1074. lengthSq: function () {
  1075. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1076. },
  1077. length: function () {
  1078. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1079. },
  1080. lengthManhattan: function () {
  1081. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1082. },
  1083. normalize: function () {
  1084. return this.divideScalar( this.length() );
  1085. },
  1086. setLength: function ( length ) {
  1087. return this.multiplyScalar( length / this.length() );
  1088. },
  1089. lerp: function ( v, alpha ) {
  1090. this.x += ( v.x - this.x ) * alpha;
  1091. this.y += ( v.y - this.y ) * alpha;
  1092. this.z += ( v.z - this.z ) * alpha;
  1093. this.w += ( v.w - this.w ) * alpha;
  1094. return this;
  1095. },
  1096. lerpVectors: function ( v1, v2, alpha ) {
  1097. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1098. },
  1099. equals: function ( v ) {
  1100. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1101. },
  1102. fromArray: function ( array, offset ) {
  1103. if ( offset === undefined ) offset = 0;
  1104. this.x = array[ offset ];
  1105. this.y = array[ offset + 1 ];
  1106. this.z = array[ offset + 2 ];
  1107. this.w = array[ offset + 3 ];
  1108. return this;
  1109. },
  1110. toArray: function ( array, offset ) {
  1111. if ( array === undefined ) array = [];
  1112. if ( offset === undefined ) offset = 0;
  1113. array[ offset ] = this.x;
  1114. array[ offset + 1 ] = this.y;
  1115. array[ offset + 2 ] = this.z;
  1116. array[ offset + 3 ] = this.w;
  1117. return array;
  1118. },
  1119. fromBufferAttribute: function ( attribute, index, offset ) {
  1120. if ( offset !== undefined ) {
  1121. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1122. }
  1123. this.x = attribute.getX( index );
  1124. this.y = attribute.getY( index );
  1125. this.z = attribute.getZ( index );
  1126. this.w = attribute.getW( index );
  1127. return this;
  1128. }
  1129. };
  1130. /**
  1131. * @author szimek / https://github.com/szimek/
  1132. * @author alteredq / http://alteredqualia.com/
  1133. * @author Marius Kintel / https://github.com/kintel
  1134. */
  1135. /*
  1136. In options, we can specify:
  1137. * Texture parameters for an auto-generated target texture
  1138. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1139. */
  1140. function WebGLRenderTarget( width, height, options ) {
  1141. this.uuid = _Math.generateUUID();
  1142. this.width = width;
  1143. this.height = height;
  1144. this.scissor = new Vector4( 0, 0, width, height );
  1145. this.scissorTest = false;
  1146. this.viewport = new Vector4( 0, 0, width, height );
  1147. options = options || {};
  1148. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  1149. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1150. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1151. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  1152. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1153. }
  1154. WebGLRenderTarget.prototype = {
  1155. constructor: WebGLRenderTarget,
  1156. isWebGLRenderTarget: true,
  1157. setSize: function ( width, height ) {
  1158. if ( this.width !== width || this.height !== height ) {
  1159. this.width = width;
  1160. this.height = height;
  1161. this.dispose();
  1162. }
  1163. this.viewport.set( 0, 0, width, height );
  1164. this.scissor.set( 0, 0, width, height );
  1165. },
  1166. clone: function () {
  1167. return new this.constructor().copy( this );
  1168. },
  1169. copy: function ( source ) {
  1170. this.width = source.width;
  1171. this.height = source.height;
  1172. this.viewport.copy( source.viewport );
  1173. this.texture = source.texture.clone();
  1174. this.depthBuffer = source.depthBuffer;
  1175. this.stencilBuffer = source.stencilBuffer;
  1176. this.depthTexture = source.depthTexture;
  1177. return this;
  1178. },
  1179. dispose: function () {
  1180. this.dispatchEvent( { type: 'dispose' } );
  1181. }
  1182. };
  1183. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype );
  1184. /**
  1185. * @author alteredq / http://alteredqualia.com
  1186. */
  1187. function WebGLRenderTargetCube( width, height, options ) {
  1188. WebGLRenderTarget.call( this, width, height, options );
  1189. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  1190. this.activeMipMapLevel = 0;
  1191. }
  1192. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  1193. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  1194. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  1195. /**
  1196. * @author mikael emtinger / http://gomo.se/
  1197. * @author alteredq / http://alteredqualia.com/
  1198. * @author WestLangley / http://github.com/WestLangley
  1199. * @author bhouston / http://clara.io
  1200. */
  1201. function Quaternion( x, y, z, w ) {
  1202. this._x = x || 0;
  1203. this._y = y || 0;
  1204. this._z = z || 0;
  1205. this._w = ( w !== undefined ) ? w : 1;
  1206. }
  1207. Quaternion.prototype = {
  1208. constructor: Quaternion,
  1209. get x () {
  1210. return this._x;
  1211. },
  1212. set x ( value ) {
  1213. this._x = value;
  1214. this.onChangeCallback();
  1215. },
  1216. get y () {
  1217. return this._y;
  1218. },
  1219. set y ( value ) {
  1220. this._y = value;
  1221. this.onChangeCallback();
  1222. },
  1223. get z () {
  1224. return this._z;
  1225. },
  1226. set z ( value ) {
  1227. this._z = value;
  1228. this.onChangeCallback();
  1229. },
  1230. get w () {
  1231. return this._w;
  1232. },
  1233. set w ( value ) {
  1234. this._w = value;
  1235. this.onChangeCallback();
  1236. },
  1237. set: function ( x, y, z, w ) {
  1238. this._x = x;
  1239. this._y = y;
  1240. this._z = z;
  1241. this._w = w;
  1242. this.onChangeCallback();
  1243. return this;
  1244. },
  1245. clone: function () {
  1246. return new this.constructor( this._x, this._y, this._z, this._w );
  1247. },
  1248. copy: function ( quaternion ) {
  1249. this._x = quaternion.x;
  1250. this._y = quaternion.y;
  1251. this._z = quaternion.z;
  1252. this._w = quaternion.w;
  1253. this.onChangeCallback();
  1254. return this;
  1255. },
  1256. setFromEuler: function ( euler, update ) {
  1257. if ( (euler && euler.isEuler) === false ) {
  1258. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1259. }
  1260. // http://www.mathworks.com/matlabcentral/fileexchange/
  1261. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1262. // content/SpinCalc.m
  1263. var c1 = Math.cos( euler._x / 2 );
  1264. var c2 = Math.cos( euler._y / 2 );
  1265. var c3 = Math.cos( euler._z / 2 );
  1266. var s1 = Math.sin( euler._x / 2 );
  1267. var s2 = Math.sin( euler._y / 2 );
  1268. var s3 = Math.sin( euler._z / 2 );
  1269. var order = euler.order;
  1270. if ( order === 'XYZ' ) {
  1271. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1272. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1273. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1274. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1275. } else if ( order === 'YXZ' ) {
  1276. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1277. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1278. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1279. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1280. } else if ( order === 'ZXY' ) {
  1281. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1282. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1283. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1284. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1285. } else if ( order === 'ZYX' ) {
  1286. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1287. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1288. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1289. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1290. } else if ( order === 'YZX' ) {
  1291. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1292. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1293. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1294. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1295. } else if ( order === 'XZY' ) {
  1296. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1297. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1298. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1299. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1300. }
  1301. if ( update !== false ) this.onChangeCallback();
  1302. return this;
  1303. },
  1304. setFromAxisAngle: function ( axis, angle ) {
  1305. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1306. // assumes axis is normalized
  1307. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1308. this._x = axis.x * s;
  1309. this._y = axis.y * s;
  1310. this._z = axis.z * s;
  1311. this._w = Math.cos( halfAngle );
  1312. this.onChangeCallback();
  1313. return this;
  1314. },
  1315. setFromRotationMatrix: function ( m ) {
  1316. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1317. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1318. var te = m.elements,
  1319. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1320. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1321. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1322. trace = m11 + m22 + m33,
  1323. s;
  1324. if ( trace > 0 ) {
  1325. s = 0.5 / Math.sqrt( trace + 1.0 );
  1326. this._w = 0.25 / s;
  1327. this._x = ( m32 - m23 ) * s;
  1328. this._y = ( m13 - m31 ) * s;
  1329. this._z = ( m21 - m12 ) * s;
  1330. } else if ( m11 > m22 && m11 > m33 ) {
  1331. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1332. this._w = ( m32 - m23 ) / s;
  1333. this._x = 0.25 * s;
  1334. this._y = ( m12 + m21 ) / s;
  1335. this._z = ( m13 + m31 ) / s;
  1336. } else if ( m22 > m33 ) {
  1337. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1338. this._w = ( m13 - m31 ) / s;
  1339. this._x = ( m12 + m21 ) / s;
  1340. this._y = 0.25 * s;
  1341. this._z = ( m23 + m32 ) / s;
  1342. } else {
  1343. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1344. this._w = ( m21 - m12 ) / s;
  1345. this._x = ( m13 + m31 ) / s;
  1346. this._y = ( m23 + m32 ) / s;
  1347. this._z = 0.25 * s;
  1348. }
  1349. this.onChangeCallback();
  1350. return this;
  1351. },
  1352. setFromUnitVectors: function () {
  1353. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1354. // assumes direction vectors vFrom and vTo are normalized
  1355. var v1, r;
  1356. var EPS = 0.000001;
  1357. return function setFromUnitVectors( vFrom, vTo ) {
  1358. if ( v1 === undefined ) v1 = new Vector3();
  1359. r = vFrom.dot( vTo ) + 1;
  1360. if ( r < EPS ) {
  1361. r = 0;
  1362. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1363. v1.set( - vFrom.y, vFrom.x, 0 );
  1364. } else {
  1365. v1.set( 0, - vFrom.z, vFrom.y );
  1366. }
  1367. } else {
  1368. v1.crossVectors( vFrom, vTo );
  1369. }
  1370. this._x = v1.x;
  1371. this._y = v1.y;
  1372. this._z = v1.z;
  1373. this._w = r;
  1374. return this.normalize();
  1375. };
  1376. }(),
  1377. inverse: function () {
  1378. return this.conjugate().normalize();
  1379. },
  1380. conjugate: function () {
  1381. this._x *= - 1;
  1382. this._y *= - 1;
  1383. this._z *= - 1;
  1384. this.onChangeCallback();
  1385. return this;
  1386. },
  1387. dot: function ( v ) {
  1388. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1389. },
  1390. lengthSq: function () {
  1391. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1392. },
  1393. length: function () {
  1394. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1395. },
  1396. normalize: function () {
  1397. var l = this.length();
  1398. if ( l === 0 ) {
  1399. this._x = 0;
  1400. this._y = 0;
  1401. this._z = 0;
  1402. this._w = 1;
  1403. } else {
  1404. l = 1 / l;
  1405. this._x = this._x * l;
  1406. this._y = this._y * l;
  1407. this._z = this._z * l;
  1408. this._w = this._w * l;
  1409. }
  1410. this.onChangeCallback();
  1411. return this;
  1412. },
  1413. multiply: function ( q, p ) {
  1414. if ( p !== undefined ) {
  1415. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1416. return this.multiplyQuaternions( q, p );
  1417. }
  1418. return this.multiplyQuaternions( this, q );
  1419. },
  1420. premultiply: function ( q ) {
  1421. return this.multiplyQuaternions( q, this );
  1422. },
  1423. multiplyQuaternions: function ( a, b ) {
  1424. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1425. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1426. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1427. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1428. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1429. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1430. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1431. this.onChangeCallback();
  1432. return this;
  1433. },
  1434. slerp: function ( qb, t ) {
  1435. if ( t === 0 ) return this;
  1436. if ( t === 1 ) return this.copy( qb );
  1437. var x = this._x, y = this._y, z = this._z, w = this._w;
  1438. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1439. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1440. if ( cosHalfTheta < 0 ) {
  1441. this._w = - qb._w;
  1442. this._x = - qb._x;
  1443. this._y = - qb._y;
  1444. this._z = - qb._z;
  1445. cosHalfTheta = - cosHalfTheta;
  1446. } else {
  1447. this.copy( qb );
  1448. }
  1449. if ( cosHalfTheta >= 1.0 ) {
  1450. this._w = w;
  1451. this._x = x;
  1452. this._y = y;
  1453. this._z = z;
  1454. return this;
  1455. }
  1456. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1457. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1458. this._w = 0.5 * ( w + this._w );
  1459. this._x = 0.5 * ( x + this._x );
  1460. this._y = 0.5 * ( y + this._y );
  1461. this._z = 0.5 * ( z + this._z );
  1462. return this;
  1463. }
  1464. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1465. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1466. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1467. this._w = ( w * ratioA + this._w * ratioB );
  1468. this._x = ( x * ratioA + this._x * ratioB );
  1469. this._y = ( y * ratioA + this._y * ratioB );
  1470. this._z = ( z * ratioA + this._z * ratioB );
  1471. this.onChangeCallback();
  1472. return this;
  1473. },
  1474. equals: function ( quaternion ) {
  1475. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1476. },
  1477. fromArray: function ( array, offset ) {
  1478. if ( offset === undefined ) offset = 0;
  1479. this._x = array[ offset ];
  1480. this._y = array[ offset + 1 ];
  1481. this._z = array[ offset + 2 ];
  1482. this._w = array[ offset + 3 ];
  1483. this.onChangeCallback();
  1484. return this;
  1485. },
  1486. toArray: function ( array, offset ) {
  1487. if ( array === undefined ) array = [];
  1488. if ( offset === undefined ) offset = 0;
  1489. array[ offset ] = this._x;
  1490. array[ offset + 1 ] = this._y;
  1491. array[ offset + 2 ] = this._z;
  1492. array[ offset + 3 ] = this._w;
  1493. return array;
  1494. },
  1495. onChange: function ( callback ) {
  1496. this.onChangeCallback = callback;
  1497. return this;
  1498. },
  1499. onChangeCallback: function () {}
  1500. };
  1501. Object.assign( Quaternion, {
  1502. slerp: function( qa, qb, qm, t ) {
  1503. return qm.copy( qa ).slerp( qb, t );
  1504. },
  1505. slerpFlat: function(
  1506. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1507. // fuzz-free, array-based Quaternion SLERP operation
  1508. var x0 = src0[ srcOffset0 + 0 ],
  1509. y0 = src0[ srcOffset0 + 1 ],
  1510. z0 = src0[ srcOffset0 + 2 ],
  1511. w0 = src0[ srcOffset0 + 3 ],
  1512. x1 = src1[ srcOffset1 + 0 ],
  1513. y1 = src1[ srcOffset1 + 1 ],
  1514. z1 = src1[ srcOffset1 + 2 ],
  1515. w1 = src1[ srcOffset1 + 3 ];
  1516. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1517. var s = 1 - t,
  1518. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1519. dir = ( cos >= 0 ? 1 : - 1 ),
  1520. sqrSin = 1 - cos * cos;
  1521. // Skip the Slerp for tiny steps to avoid numeric problems:
  1522. if ( sqrSin > Number.EPSILON ) {
  1523. var sin = Math.sqrt( sqrSin ),
  1524. len = Math.atan2( sin, cos * dir );
  1525. s = Math.sin( s * len ) / sin;
  1526. t = Math.sin( t * len ) / sin;
  1527. }
  1528. var tDir = t * dir;
  1529. x0 = x0 * s + x1 * tDir;
  1530. y0 = y0 * s + y1 * tDir;
  1531. z0 = z0 * s + z1 * tDir;
  1532. w0 = w0 * s + w1 * tDir;
  1533. // Normalize in case we just did a lerp:
  1534. if ( s === 1 - t ) {
  1535. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1536. x0 *= f;
  1537. y0 *= f;
  1538. z0 *= f;
  1539. w0 *= f;
  1540. }
  1541. }
  1542. dst[ dstOffset ] = x0;
  1543. dst[ dstOffset + 1 ] = y0;
  1544. dst[ dstOffset + 2 ] = z0;
  1545. dst[ dstOffset + 3 ] = w0;
  1546. }
  1547. } );
  1548. /**
  1549. * @author mrdoob / http://mrdoob.com/
  1550. * @author *kile / http://kile.stravaganza.org/
  1551. * @author philogb / http://blog.thejit.org/
  1552. * @author mikael emtinger / http://gomo.se/
  1553. * @author egraether / http://egraether.com/
  1554. * @author WestLangley / http://github.com/WestLangley
  1555. */
  1556. function Vector3( x, y, z ) {
  1557. this.x = x || 0;
  1558. this.y = y || 0;
  1559. this.z = z || 0;
  1560. }
  1561. Vector3.prototype = {
  1562. constructor: Vector3,
  1563. isVector3: true,
  1564. set: function ( x, y, z ) {
  1565. this.x = x;
  1566. this.y = y;
  1567. this.z = z;
  1568. return this;
  1569. },
  1570. setScalar: function ( scalar ) {
  1571. this.x = scalar;
  1572. this.y = scalar;
  1573. this.z = scalar;
  1574. return this;
  1575. },
  1576. setX: function ( x ) {
  1577. this.x = x;
  1578. return this;
  1579. },
  1580. setY: function ( y ) {
  1581. this.y = y;
  1582. return this;
  1583. },
  1584. setZ: function ( z ) {
  1585. this.z = z;
  1586. return this;
  1587. },
  1588. setComponent: function ( index, value ) {
  1589. switch ( index ) {
  1590. case 0: this.x = value; break;
  1591. case 1: this.y = value; break;
  1592. case 2: this.z = value; break;
  1593. default: throw new Error( 'index is out of range: ' + index );
  1594. }
  1595. return this;
  1596. },
  1597. getComponent: function ( index ) {
  1598. switch ( index ) {
  1599. case 0: return this.x;
  1600. case 1: return this.y;
  1601. case 2: return this.z;
  1602. default: throw new Error( 'index is out of range: ' + index );
  1603. }
  1604. },
  1605. clone: function () {
  1606. return new this.constructor( this.x, this.y, this.z );
  1607. },
  1608. copy: function ( v ) {
  1609. this.x = v.x;
  1610. this.y = v.y;
  1611. this.z = v.z;
  1612. return this;
  1613. },
  1614. add: function ( v, w ) {
  1615. if ( w !== undefined ) {
  1616. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1617. return this.addVectors( v, w );
  1618. }
  1619. this.x += v.x;
  1620. this.y += v.y;
  1621. this.z += v.z;
  1622. return this;
  1623. },
  1624. addScalar: function ( s ) {
  1625. this.x += s;
  1626. this.y += s;
  1627. this.z += s;
  1628. return this;
  1629. },
  1630. addVectors: function ( a, b ) {
  1631. this.x = a.x + b.x;
  1632. this.y = a.y + b.y;
  1633. this.z = a.z + b.z;
  1634. return this;
  1635. },
  1636. addScaledVector: function ( v, s ) {
  1637. this.x += v.x * s;
  1638. this.y += v.y * s;
  1639. this.z += v.z * s;
  1640. return this;
  1641. },
  1642. sub: function ( v, w ) {
  1643. if ( w !== undefined ) {
  1644. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1645. return this.subVectors( v, w );
  1646. }
  1647. this.x -= v.x;
  1648. this.y -= v.y;
  1649. this.z -= v.z;
  1650. return this;
  1651. },
  1652. subScalar: function ( s ) {
  1653. this.x -= s;
  1654. this.y -= s;
  1655. this.z -= s;
  1656. return this;
  1657. },
  1658. subVectors: function ( a, b ) {
  1659. this.x = a.x - b.x;
  1660. this.y = a.y - b.y;
  1661. this.z = a.z - b.z;
  1662. return this;
  1663. },
  1664. multiply: function ( v, w ) {
  1665. if ( w !== undefined ) {
  1666. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1667. return this.multiplyVectors( v, w );
  1668. }
  1669. this.x *= v.x;
  1670. this.y *= v.y;
  1671. this.z *= v.z;
  1672. return this;
  1673. },
  1674. multiplyScalar: function ( scalar ) {
  1675. if ( isFinite( scalar ) ) {
  1676. this.x *= scalar;
  1677. this.y *= scalar;
  1678. this.z *= scalar;
  1679. } else {
  1680. this.x = 0;
  1681. this.y = 0;
  1682. this.z = 0;
  1683. }
  1684. return this;
  1685. },
  1686. multiplyVectors: function ( a, b ) {
  1687. this.x = a.x * b.x;
  1688. this.y = a.y * b.y;
  1689. this.z = a.z * b.z;
  1690. return this;
  1691. },
  1692. applyEuler: function () {
  1693. var quaternion;
  1694. return function applyEuler( euler ) {
  1695. if ( (euler && euler.isEuler) === false ) {
  1696. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1697. }
  1698. if ( quaternion === undefined ) quaternion = new Quaternion();
  1699. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1700. };
  1701. }(),
  1702. applyAxisAngle: function () {
  1703. var quaternion;
  1704. return function applyAxisAngle( axis, angle ) {
  1705. if ( quaternion === undefined ) quaternion = new Quaternion();
  1706. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1707. };
  1708. }(),
  1709. applyMatrix3: function ( m ) {
  1710. var x = this.x, y = this.y, z = this.z;
  1711. var e = m.elements;
  1712. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1713. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1714. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1715. return this;
  1716. },
  1717. applyMatrix4: function ( m ) {
  1718. var x = this.x, y = this.y, z = this.z;
  1719. var e = m.elements;
  1720. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1721. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1722. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1723. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  1724. return this.divideScalar( w );
  1725. },
  1726. applyQuaternion: function ( q ) {
  1727. var x = this.x, y = this.y, z = this.z;
  1728. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1729. // calculate quat * vector
  1730. var ix = qw * x + qy * z - qz * y;
  1731. var iy = qw * y + qz * x - qx * z;
  1732. var iz = qw * z + qx * y - qy * x;
  1733. var iw = - qx * x - qy * y - qz * z;
  1734. // calculate result * inverse quat
  1735. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1736. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1737. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1738. return this;
  1739. },
  1740. project: function () {
  1741. var matrix;
  1742. return function project( camera ) {
  1743. if ( matrix === undefined ) matrix = new Matrix4();
  1744. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1745. return this.applyMatrix4( matrix );
  1746. };
  1747. }(),
  1748. unproject: function () {
  1749. var matrix;
  1750. return function unproject( camera ) {
  1751. if ( matrix === undefined ) matrix = new Matrix4();
  1752. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1753. return this.applyMatrix4( matrix );
  1754. };
  1755. }(),
  1756. transformDirection: function ( m ) {
  1757. // input: THREE.Matrix4 affine matrix
  1758. // vector interpreted as a direction
  1759. var x = this.x, y = this.y, z = this.z;
  1760. var e = m.elements;
  1761. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1762. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1763. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1764. return this.normalize();
  1765. },
  1766. divide: function ( v ) {
  1767. this.x /= v.x;
  1768. this.y /= v.y;
  1769. this.z /= v.z;
  1770. return this;
  1771. },
  1772. divideScalar: function ( scalar ) {
  1773. return this.multiplyScalar( 1 / scalar );
  1774. },
  1775. min: function ( v ) {
  1776. this.x = Math.min( this.x, v.x );
  1777. this.y = Math.min( this.y, v.y );
  1778. this.z = Math.min( this.z, v.z );
  1779. return this;
  1780. },
  1781. max: function ( v ) {
  1782. this.x = Math.max( this.x, v.x );
  1783. this.y = Math.max( this.y, v.y );
  1784. this.z = Math.max( this.z, v.z );
  1785. return this;
  1786. },
  1787. clamp: function ( min, max ) {
  1788. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1789. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1790. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1791. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1792. return this;
  1793. },
  1794. clampScalar: function () {
  1795. var min, max;
  1796. return function clampScalar( minVal, maxVal ) {
  1797. if ( min === undefined ) {
  1798. min = new Vector3();
  1799. max = new Vector3();
  1800. }
  1801. min.set( minVal, minVal, minVal );
  1802. max.set( maxVal, maxVal, maxVal );
  1803. return this.clamp( min, max );
  1804. };
  1805. }(),
  1806. clampLength: function ( min, max ) {
  1807. var length = this.length();
  1808. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1809. },
  1810. floor: function () {
  1811. this.x = Math.floor( this.x );
  1812. this.y = Math.floor( this.y );
  1813. this.z = Math.floor( this.z );
  1814. return this;
  1815. },
  1816. ceil: function () {
  1817. this.x = Math.ceil( this.x );
  1818. this.y = Math.ceil( this.y );
  1819. this.z = Math.ceil( this.z );
  1820. return this;
  1821. },
  1822. round: function () {
  1823. this.x = Math.round( this.x );
  1824. this.y = Math.round( this.y );
  1825. this.z = Math.round( this.z );
  1826. return this;
  1827. },
  1828. roundToZero: function () {
  1829. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1830. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1831. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1832. return this;
  1833. },
  1834. negate: function () {
  1835. this.x = - this.x;
  1836. this.y = - this.y;
  1837. this.z = - this.z;
  1838. return this;
  1839. },
  1840. dot: function ( v ) {
  1841. return this.x * v.x + this.y * v.y + this.z * v.z;
  1842. },
  1843. lengthSq: function () {
  1844. return this.x * this.x + this.y * this.y + this.z * this.z;
  1845. },
  1846. length: function () {
  1847. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1848. },
  1849. lengthManhattan: function () {
  1850. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1851. },
  1852. normalize: function () {
  1853. return this.divideScalar( this.length() );
  1854. },
  1855. setLength: function ( length ) {
  1856. return this.multiplyScalar( length / this.length() );
  1857. },
  1858. lerp: function ( v, alpha ) {
  1859. this.x += ( v.x - this.x ) * alpha;
  1860. this.y += ( v.y - this.y ) * alpha;
  1861. this.z += ( v.z - this.z ) * alpha;
  1862. return this;
  1863. },
  1864. lerpVectors: function ( v1, v2, alpha ) {
  1865. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1866. },
  1867. cross: function ( v, w ) {
  1868. if ( w !== undefined ) {
  1869. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1870. return this.crossVectors( v, w );
  1871. }
  1872. var x = this.x, y = this.y, z = this.z;
  1873. this.x = y * v.z - z * v.y;
  1874. this.y = z * v.x - x * v.z;
  1875. this.z = x * v.y - y * v.x;
  1876. return this;
  1877. },
  1878. crossVectors: function ( a, b ) {
  1879. var ax = a.x, ay = a.y, az = a.z;
  1880. var bx = b.x, by = b.y, bz = b.z;
  1881. this.x = ay * bz - az * by;
  1882. this.y = az * bx - ax * bz;
  1883. this.z = ax * by - ay * bx;
  1884. return this;
  1885. },
  1886. projectOnVector: function ( vector ) {
  1887. var scalar = vector.dot( this ) / vector.lengthSq();
  1888. return this.copy( vector ).multiplyScalar( scalar );
  1889. },
  1890. projectOnPlane: function () {
  1891. var v1;
  1892. return function projectOnPlane( planeNormal ) {
  1893. if ( v1 === undefined ) v1 = new Vector3();
  1894. v1.copy( this ).projectOnVector( planeNormal );
  1895. return this.sub( v1 );
  1896. };
  1897. }(),
  1898. reflect: function () {
  1899. // reflect incident vector off plane orthogonal to normal
  1900. // normal is assumed to have unit length
  1901. var v1;
  1902. return function reflect( normal ) {
  1903. if ( v1 === undefined ) v1 = new Vector3();
  1904. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1905. };
  1906. }(),
  1907. angleTo: function ( v ) {
  1908. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1909. // clamp, to handle numerical problems
  1910. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1911. },
  1912. distanceTo: function ( v ) {
  1913. return Math.sqrt( this.distanceToSquared( v ) );
  1914. },
  1915. distanceToSquared: function ( v ) {
  1916. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1917. return dx * dx + dy * dy + dz * dz;
  1918. },
  1919. distanceToManhattan: function ( v ) {
  1920. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1921. },
  1922. setFromSpherical: function( s ) {
  1923. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1924. this.x = sinPhiRadius * Math.sin( s.theta );
  1925. this.y = Math.cos( s.phi ) * s.radius;
  1926. this.z = sinPhiRadius * Math.cos( s.theta );
  1927. return this;
  1928. },
  1929. setFromCylindrical: function( c ) {
  1930. this.x = c.radius * Math.sin( c.theta );
  1931. this.y = c.y;
  1932. this.z = c.radius * Math.cos( c.theta );
  1933. return this;
  1934. },
  1935. setFromMatrixPosition: function ( m ) {
  1936. return this.setFromMatrixColumn( m, 3 );
  1937. },
  1938. setFromMatrixScale: function ( m ) {
  1939. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1940. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1941. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1942. this.x = sx;
  1943. this.y = sy;
  1944. this.z = sz;
  1945. return this;
  1946. },
  1947. setFromMatrixColumn: function ( m, index ) {
  1948. if ( typeof m === 'number' ) {
  1949. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1950. var temp = m;
  1951. m = index;
  1952. index = temp;
  1953. }
  1954. return this.fromArray( m.elements, index * 4 );
  1955. },
  1956. equals: function ( v ) {
  1957. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1958. },
  1959. fromArray: function ( array, offset ) {
  1960. if ( offset === undefined ) offset = 0;
  1961. this.x = array[ offset ];
  1962. this.y = array[ offset + 1 ];
  1963. this.z = array[ offset + 2 ];
  1964. return this;
  1965. },
  1966. toArray: function ( array, offset ) {
  1967. if ( array === undefined ) array = [];
  1968. if ( offset === undefined ) offset = 0;
  1969. array[ offset ] = this.x;
  1970. array[ offset + 1 ] = this.y;
  1971. array[ offset + 2 ] = this.z;
  1972. return array;
  1973. },
  1974. fromBufferAttribute: function ( attribute, index, offset ) {
  1975. if ( offset !== undefined ) {
  1976. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1977. }
  1978. this.x = attribute.getX( index );
  1979. this.y = attribute.getY( index );
  1980. this.z = attribute.getZ( index );
  1981. return this;
  1982. }
  1983. };
  1984. /**
  1985. * @author mrdoob / http://mrdoob.com/
  1986. * @author supereggbert / http://www.paulbrunt.co.uk/
  1987. * @author philogb / http://blog.thejit.org/
  1988. * @author jordi_ros / http://plattsoft.com
  1989. * @author D1plo1d / http://github.com/D1plo1d
  1990. * @author alteredq / http://alteredqualia.com/
  1991. * @author mikael emtinger / http://gomo.se/
  1992. * @author timknip / http://www.floorplanner.com/
  1993. * @author bhouston / http://clara.io
  1994. * @author WestLangley / http://github.com/WestLangley
  1995. */
  1996. function Matrix4() {
  1997. this.elements = new Float32Array( [
  1998. 1, 0, 0, 0,
  1999. 0, 1, 0, 0,
  2000. 0, 0, 1, 0,
  2001. 0, 0, 0, 1
  2002. ] );
  2003. if ( arguments.length > 0 ) {
  2004. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2005. }
  2006. }
  2007. Matrix4.prototype = {
  2008. constructor: Matrix4,
  2009. isMatrix4: true,
  2010. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2011. var te = this.elements;
  2012. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2013. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2014. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2015. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2016. return this;
  2017. },
  2018. identity: function () {
  2019. this.set(
  2020. 1, 0, 0, 0,
  2021. 0, 1, 0, 0,
  2022. 0, 0, 1, 0,
  2023. 0, 0, 0, 1
  2024. );
  2025. return this;
  2026. },
  2027. clone: function () {
  2028. return new Matrix4().fromArray( this.elements );
  2029. },
  2030. copy: function ( m ) {
  2031. this.elements.set( m.elements );
  2032. return this;
  2033. },
  2034. copyPosition: function ( m ) {
  2035. var te = this.elements;
  2036. var me = m.elements;
  2037. te[ 12 ] = me[ 12 ];
  2038. te[ 13 ] = me[ 13 ];
  2039. te[ 14 ] = me[ 14 ];
  2040. return this;
  2041. },
  2042. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2043. xAxis.setFromMatrixColumn( this, 0 );
  2044. yAxis.setFromMatrixColumn( this, 1 );
  2045. zAxis.setFromMatrixColumn( this, 2 );
  2046. return this;
  2047. },
  2048. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2049. this.set(
  2050. xAxis.x, yAxis.x, zAxis.x, 0,
  2051. xAxis.y, yAxis.y, zAxis.y, 0,
  2052. xAxis.z, yAxis.z, zAxis.z, 0,
  2053. 0, 0, 0, 1
  2054. );
  2055. return this;
  2056. },
  2057. extractRotation: function () {
  2058. var v1;
  2059. return function extractRotation( m ) {
  2060. if ( v1 === undefined ) v1 = new Vector3();
  2061. var te = this.elements;
  2062. var me = m.elements;
  2063. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2064. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2065. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2066. te[ 0 ] = me[ 0 ] * scaleX;
  2067. te[ 1 ] = me[ 1 ] * scaleX;
  2068. te[ 2 ] = me[ 2 ] * scaleX;
  2069. te[ 4 ] = me[ 4 ] * scaleY;
  2070. te[ 5 ] = me[ 5 ] * scaleY;
  2071. te[ 6 ] = me[ 6 ] * scaleY;
  2072. te[ 8 ] = me[ 8 ] * scaleZ;
  2073. te[ 9 ] = me[ 9 ] * scaleZ;
  2074. te[ 10 ] = me[ 10 ] * scaleZ;
  2075. return this;
  2076. };
  2077. }(),
  2078. makeRotationFromEuler: function ( euler ) {
  2079. if ( (euler && euler.isEuler) === false ) {
  2080. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2081. }
  2082. var te = this.elements;
  2083. var x = euler.x, y = euler.y, z = euler.z;
  2084. var a = Math.cos( x ), b = Math.sin( x );
  2085. var c = Math.cos( y ), d = Math.sin( y );
  2086. var e = Math.cos( z ), f = Math.sin( z );
  2087. if ( euler.order === 'XYZ' ) {
  2088. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2089. te[ 0 ] = c * e;
  2090. te[ 4 ] = - c * f;
  2091. te[ 8 ] = d;
  2092. te[ 1 ] = af + be * d;
  2093. te[ 5 ] = ae - bf * d;
  2094. te[ 9 ] = - b * c;
  2095. te[ 2 ] = bf - ae * d;
  2096. te[ 6 ] = be + af * d;
  2097. te[ 10 ] = a * c;
  2098. } else if ( euler.order === 'YXZ' ) {
  2099. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2100. te[ 0 ] = ce + df * b;
  2101. te[ 4 ] = de * b - cf;
  2102. te[ 8 ] = a * d;
  2103. te[ 1 ] = a * f;
  2104. te[ 5 ] = a * e;
  2105. te[ 9 ] = - b;
  2106. te[ 2 ] = cf * b - de;
  2107. te[ 6 ] = df + ce * b;
  2108. te[ 10 ] = a * c;
  2109. } else if ( euler.order === 'ZXY' ) {
  2110. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2111. te[ 0 ] = ce - df * b;
  2112. te[ 4 ] = - a * f;
  2113. te[ 8 ] = de + cf * b;
  2114. te[ 1 ] = cf + de * b;
  2115. te[ 5 ] = a * e;
  2116. te[ 9 ] = df - ce * b;
  2117. te[ 2 ] = - a * d;
  2118. te[ 6 ] = b;
  2119. te[ 10 ] = a * c;
  2120. } else if ( euler.order === 'ZYX' ) {
  2121. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2122. te[ 0 ] = c * e;
  2123. te[ 4 ] = be * d - af;
  2124. te[ 8 ] = ae * d + bf;
  2125. te[ 1 ] = c * f;
  2126. te[ 5 ] = bf * d + ae;
  2127. te[ 9 ] = af * d - be;
  2128. te[ 2 ] = - d;
  2129. te[ 6 ] = b * c;
  2130. te[ 10 ] = a * c;
  2131. } else if ( euler.order === 'YZX' ) {
  2132. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2133. te[ 0 ] = c * e;
  2134. te[ 4 ] = bd - ac * f;
  2135. te[ 8 ] = bc * f + ad;
  2136. te[ 1 ] = f;
  2137. te[ 5 ] = a * e;
  2138. te[ 9 ] = - b * e;
  2139. te[ 2 ] = - d * e;
  2140. te[ 6 ] = ad * f + bc;
  2141. te[ 10 ] = ac - bd * f;
  2142. } else if ( euler.order === 'XZY' ) {
  2143. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2144. te[ 0 ] = c * e;
  2145. te[ 4 ] = - f;
  2146. te[ 8 ] = d * e;
  2147. te[ 1 ] = ac * f + bd;
  2148. te[ 5 ] = a * e;
  2149. te[ 9 ] = ad * f - bc;
  2150. te[ 2 ] = bc * f - ad;
  2151. te[ 6 ] = b * e;
  2152. te[ 10 ] = bd * f + ac;
  2153. }
  2154. // last column
  2155. te[ 3 ] = 0;
  2156. te[ 7 ] = 0;
  2157. te[ 11 ] = 0;
  2158. // bottom row
  2159. te[ 12 ] = 0;
  2160. te[ 13 ] = 0;
  2161. te[ 14 ] = 0;
  2162. te[ 15 ] = 1;
  2163. return this;
  2164. },
  2165. makeRotationFromQuaternion: function ( q ) {
  2166. var te = this.elements;
  2167. var x = q.x, y = q.y, z = q.z, w = q.w;
  2168. var x2 = x + x, y2 = y + y, z2 = z + z;
  2169. var xx = x * x2, xy = x * y2, xz = x * z2;
  2170. var yy = y * y2, yz = y * z2, zz = z * z2;
  2171. var wx = w * x2, wy = w * y2, wz = w * z2;
  2172. te[ 0 ] = 1 - ( yy + zz );
  2173. te[ 4 ] = xy - wz;
  2174. te[ 8 ] = xz + wy;
  2175. te[ 1 ] = xy + wz;
  2176. te[ 5 ] = 1 - ( xx + zz );
  2177. te[ 9 ] = yz - wx;
  2178. te[ 2 ] = xz - wy;
  2179. te[ 6 ] = yz + wx;
  2180. te[ 10 ] = 1 - ( xx + yy );
  2181. // last column
  2182. te[ 3 ] = 0;
  2183. te[ 7 ] = 0;
  2184. te[ 11 ] = 0;
  2185. // bottom row
  2186. te[ 12 ] = 0;
  2187. te[ 13 ] = 0;
  2188. te[ 14 ] = 0;
  2189. te[ 15 ] = 1;
  2190. return this;
  2191. },
  2192. lookAt: function () {
  2193. var x, y, z;
  2194. return function lookAt( eye, target, up ) {
  2195. if ( x === undefined ) {
  2196. x = new Vector3();
  2197. y = new Vector3();
  2198. z = new Vector3();
  2199. }
  2200. var te = this.elements;
  2201. z.subVectors( eye, target ).normalize();
  2202. if ( z.lengthSq() === 0 ) {
  2203. z.z = 1;
  2204. }
  2205. x.crossVectors( up, z ).normalize();
  2206. if ( x.lengthSq() === 0 ) {
  2207. z.z += 0.0001;
  2208. x.crossVectors( up, z ).normalize();
  2209. }
  2210. y.crossVectors( z, x );
  2211. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2212. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2213. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2214. return this;
  2215. };
  2216. }(),
  2217. multiply: function ( m, n ) {
  2218. if ( n !== undefined ) {
  2219. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2220. return this.multiplyMatrices( m, n );
  2221. }
  2222. return this.multiplyMatrices( this, m );
  2223. },
  2224. premultiply: function ( m ) {
  2225. return this.multiplyMatrices( m, this );
  2226. },
  2227. multiplyMatrices: function ( a, b ) {
  2228. var ae = a.elements;
  2229. var be = b.elements;
  2230. var te = this.elements;
  2231. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2232. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2233. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2234. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2235. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2236. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2237. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2238. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2239. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2240. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2241. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2242. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2243. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2244. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2245. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2246. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2247. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2248. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2249. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2250. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2251. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2252. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2253. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2254. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2255. return this;
  2256. },
  2257. multiplyToArray: function ( a, b, r ) {
  2258. var te = this.elements;
  2259. this.multiplyMatrices( a, b );
  2260. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2261. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2262. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2263. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2264. return this;
  2265. },
  2266. multiplyScalar: function ( s ) {
  2267. var te = this.elements;
  2268. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2269. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2270. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2271. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2272. return this;
  2273. },
  2274. applyToBufferAttribute: function () {
  2275. var v1;
  2276. return function applyToBufferAttribute( attribute ) {
  2277. if ( v1 === undefined ) v1 = new Vector3();
  2278. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  2279. v1.x = attribute.getX( i );
  2280. v1.y = attribute.getY( i );
  2281. v1.z = attribute.getZ( i );
  2282. v1.applyMatrix4( this );
  2283. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  2284. }
  2285. return attribute;
  2286. };
  2287. }(),
  2288. determinant: function () {
  2289. var te = this.elements;
  2290. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2291. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2292. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2293. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2294. //TODO: make this more efficient
  2295. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2296. return (
  2297. n41 * (
  2298. + n14 * n23 * n32
  2299. - n13 * n24 * n32
  2300. - n14 * n22 * n33
  2301. + n12 * n24 * n33
  2302. + n13 * n22 * n34
  2303. - n12 * n23 * n34
  2304. ) +
  2305. n42 * (
  2306. + n11 * n23 * n34
  2307. - n11 * n24 * n33
  2308. + n14 * n21 * n33
  2309. - n13 * n21 * n34
  2310. + n13 * n24 * n31
  2311. - n14 * n23 * n31
  2312. ) +
  2313. n43 * (
  2314. + n11 * n24 * n32
  2315. - n11 * n22 * n34
  2316. - n14 * n21 * n32
  2317. + n12 * n21 * n34
  2318. + n14 * n22 * n31
  2319. - n12 * n24 * n31
  2320. ) +
  2321. n44 * (
  2322. - n13 * n22 * n31
  2323. - n11 * n23 * n32
  2324. + n11 * n22 * n33
  2325. + n13 * n21 * n32
  2326. - n12 * n21 * n33
  2327. + n12 * n23 * n31
  2328. )
  2329. );
  2330. },
  2331. transpose: function () {
  2332. var te = this.elements;
  2333. var tmp;
  2334. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2335. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2336. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2337. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2338. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2339. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2340. return this;
  2341. },
  2342. setPosition: function ( v ) {
  2343. var te = this.elements;
  2344. te[ 12 ] = v.x;
  2345. te[ 13 ] = v.y;
  2346. te[ 14 ] = v.z;
  2347. return this;
  2348. },
  2349. getInverse: function ( m, throwOnDegenerate ) {
  2350. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2351. var te = this.elements,
  2352. me = m.elements,
  2353. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  2354. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  2355. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  2356. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  2357. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  2358. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  2359. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  2360. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2361. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  2362. if ( det === 0 ) {
  2363. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2364. if ( throwOnDegenerate === true ) {
  2365. throw new Error( msg );
  2366. } else {
  2367. console.warn( msg );
  2368. }
  2369. return this.identity();
  2370. }
  2371. var detInv = 1 / det;
  2372. te[ 0 ] = t11 * detInv;
  2373. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  2374. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  2375. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  2376. te[ 4 ] = t12 * detInv;
  2377. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  2378. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  2379. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  2380. te[ 8 ] = t13 * detInv;
  2381. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  2382. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  2383. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  2384. te[ 12 ] = t14 * detInv;
  2385. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  2386. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  2387. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  2388. return this;
  2389. },
  2390. scale: function ( v ) {
  2391. var te = this.elements;
  2392. var x = v.x, y = v.y, z = v.z;
  2393. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2394. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2395. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2396. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2397. return this;
  2398. },
  2399. getMaxScaleOnAxis: function () {
  2400. var te = this.elements;
  2401. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2402. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2403. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2404. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  2405. },
  2406. makeTranslation: function ( x, y, z ) {
  2407. this.set(
  2408. 1, 0, 0, x,
  2409. 0, 1, 0, y,
  2410. 0, 0, 1, z,
  2411. 0, 0, 0, 1
  2412. );
  2413. return this;
  2414. },
  2415. makeRotationX: function ( theta ) {
  2416. var c = Math.cos( theta ), s = Math.sin( theta );
  2417. this.set(
  2418. 1, 0, 0, 0,
  2419. 0, c, - s, 0,
  2420. 0, s, c, 0,
  2421. 0, 0, 0, 1
  2422. );
  2423. return this;
  2424. },
  2425. makeRotationY: function ( theta ) {
  2426. var c = Math.cos( theta ), s = Math.sin( theta );
  2427. this.set(
  2428. c, 0, s, 0,
  2429. 0, 1, 0, 0,
  2430. - s, 0, c, 0,
  2431. 0, 0, 0, 1
  2432. );
  2433. return this;
  2434. },
  2435. makeRotationZ: function ( theta ) {
  2436. var c = Math.cos( theta ), s = Math.sin( theta );
  2437. this.set(
  2438. c, - s, 0, 0,
  2439. s, c, 0, 0,
  2440. 0, 0, 1, 0,
  2441. 0, 0, 0, 1
  2442. );
  2443. return this;
  2444. },
  2445. makeRotationAxis: function ( axis, angle ) {
  2446. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2447. var c = Math.cos( angle );
  2448. var s = Math.sin( angle );
  2449. var t = 1 - c;
  2450. var x = axis.x, y = axis.y, z = axis.z;
  2451. var tx = t * x, ty = t * y;
  2452. this.set(
  2453. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2454. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2455. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2456. 0, 0, 0, 1
  2457. );
  2458. return this;
  2459. },
  2460. makeScale: function ( x, y, z ) {
  2461. this.set(
  2462. x, 0, 0, 0,
  2463. 0, y, 0, 0,
  2464. 0, 0, z, 0,
  2465. 0, 0, 0, 1
  2466. );
  2467. return this;
  2468. },
  2469. makeShear: function ( x, y, z ) {
  2470. this.set(
  2471. 1, y, z, 0,
  2472. x, 1, z, 0,
  2473. x, y, 1, 0,
  2474. 0, 0, 0, 1
  2475. );
  2476. return this;
  2477. },
  2478. compose: function ( position, quaternion, scale ) {
  2479. this.makeRotationFromQuaternion( quaternion );
  2480. this.scale( scale );
  2481. this.setPosition( position );
  2482. return this;
  2483. },
  2484. decompose: function () {
  2485. var vector, matrix;
  2486. return function decompose( position, quaternion, scale ) {
  2487. if ( vector === undefined ) {
  2488. vector = new Vector3();
  2489. matrix = new Matrix4();
  2490. }
  2491. var te = this.elements;
  2492. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  2493. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  2494. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  2495. // if determine is negative, we need to invert one scale
  2496. var det = this.determinant();
  2497. if ( det < 0 ) {
  2498. sx = - sx;
  2499. }
  2500. position.x = te[ 12 ];
  2501. position.y = te[ 13 ];
  2502. position.z = te[ 14 ];
  2503. // scale the rotation part
  2504. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2505. var invSX = 1 / sx;
  2506. var invSY = 1 / sy;
  2507. var invSZ = 1 / sz;
  2508. matrix.elements[ 0 ] *= invSX;
  2509. matrix.elements[ 1 ] *= invSX;
  2510. matrix.elements[ 2 ] *= invSX;
  2511. matrix.elements[ 4 ] *= invSY;
  2512. matrix.elements[ 5 ] *= invSY;
  2513. matrix.elements[ 6 ] *= invSY;
  2514. matrix.elements[ 8 ] *= invSZ;
  2515. matrix.elements[ 9 ] *= invSZ;
  2516. matrix.elements[ 10 ] *= invSZ;
  2517. quaternion.setFromRotationMatrix( matrix );
  2518. scale.x = sx;
  2519. scale.y = sy;
  2520. scale.z = sz;
  2521. return this;
  2522. };
  2523. }(),
  2524. makePerspective: function ( left, right, top, bottom, near, far ) {
  2525. if ( far === undefined ) {
  2526. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  2527. }
  2528. var te = this.elements;
  2529. var x = 2 * near / ( right - left );
  2530. var y = 2 * near / ( top - bottom );
  2531. var a = ( right + left ) / ( right - left );
  2532. var b = ( top + bottom ) / ( top - bottom );
  2533. var c = - ( far + near ) / ( far - near );
  2534. var d = - 2 * far * near / ( far - near );
  2535. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  2536. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  2537. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  2538. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  2539. return this;
  2540. },
  2541. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2542. var te = this.elements;
  2543. var w = 1.0 / ( right - left );
  2544. var h = 1.0 / ( top - bottom );
  2545. var p = 1.0 / ( far - near );
  2546. var x = ( right + left ) * w;
  2547. var y = ( top + bottom ) * h;
  2548. var z = ( far + near ) * p;
  2549. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  2550. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  2551. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  2552. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  2553. return this;
  2554. },
  2555. equals: function ( matrix ) {
  2556. var te = this.elements;
  2557. var me = matrix.elements;
  2558. for ( var i = 0; i < 16; i ++ ) {
  2559. if ( te[ i ] !== me[ i ] ) return false;
  2560. }
  2561. return true;
  2562. },
  2563. fromArray: function ( array, offset ) {
  2564. if ( offset === undefined ) offset = 0;
  2565. for( var i = 0; i < 16; i ++ ) {
  2566. this.elements[ i ] = array[ i + offset ];
  2567. }
  2568. return this;
  2569. },
  2570. toArray: function ( array, offset ) {
  2571. if ( array === undefined ) array = [];
  2572. if ( offset === undefined ) offset = 0;
  2573. var te = this.elements;
  2574. array[ offset ] = te[ 0 ];
  2575. array[ offset + 1 ] = te[ 1 ];
  2576. array[ offset + 2 ] = te[ 2 ];
  2577. array[ offset + 3 ] = te[ 3 ];
  2578. array[ offset + 4 ] = te[ 4 ];
  2579. array[ offset + 5 ] = te[ 5 ];
  2580. array[ offset + 6 ] = te[ 6 ];
  2581. array[ offset + 7 ] = te[ 7 ];
  2582. array[ offset + 8 ] = te[ 8 ];
  2583. array[ offset + 9 ] = te[ 9 ];
  2584. array[ offset + 10 ] = te[ 10 ];
  2585. array[ offset + 11 ] = te[ 11 ];
  2586. array[ offset + 12 ] = te[ 12 ];
  2587. array[ offset + 13 ] = te[ 13 ];
  2588. array[ offset + 14 ] = te[ 14 ];
  2589. array[ offset + 15 ] = te[ 15 ];
  2590. return array;
  2591. }
  2592. };
  2593. /**
  2594. * @author mrdoob / http://mrdoob.com/
  2595. */
  2596. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2597. images = images !== undefined ? images : [];
  2598. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2599. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2600. this.flipY = false;
  2601. }
  2602. CubeTexture.prototype = Object.create( Texture.prototype );
  2603. CubeTexture.prototype.constructor = CubeTexture;
  2604. CubeTexture.prototype.isCubeTexture = true;
  2605. Object.defineProperty( CubeTexture.prototype, 'images', {
  2606. get: function () {
  2607. return this.image;
  2608. },
  2609. set: function ( value ) {
  2610. this.image = value;
  2611. }
  2612. } );
  2613. /**
  2614. * @author tschw
  2615. *
  2616. * Uniforms of a program.
  2617. * Those form a tree structure with a special top-level container for the root,
  2618. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2619. *
  2620. *
  2621. * Properties of inner nodes including the top-level container:
  2622. *
  2623. * .seq - array of nested uniforms
  2624. * .map - nested uniforms by name
  2625. *
  2626. *
  2627. * Methods of all nodes except the top-level container:
  2628. *
  2629. * .setValue( gl, value, [renderer] )
  2630. *
  2631. * uploads a uniform value(s)
  2632. * the 'renderer' parameter is needed for sampler uniforms
  2633. *
  2634. *
  2635. * Static methods of the top-level container (renderer factorizations):
  2636. *
  2637. * .upload( gl, seq, values, renderer )
  2638. *
  2639. * sets uniforms in 'seq' to 'values[id].value'
  2640. *
  2641. * .seqWithValue( seq, values ) : filteredSeq
  2642. *
  2643. * filters 'seq' entries with corresponding entry in values
  2644. *
  2645. *
  2646. * Methods of the top-level container (renderer factorizations):
  2647. *
  2648. * .setValue( gl, name, value )
  2649. *
  2650. * sets uniform with name 'name' to 'value'
  2651. *
  2652. * .set( gl, obj, prop )
  2653. *
  2654. * sets uniform from object and property with same name than uniform
  2655. *
  2656. * .setOptional( gl, obj, prop )
  2657. *
  2658. * like .set for an optional property of the object
  2659. *
  2660. */
  2661. var emptyTexture = new Texture();
  2662. var emptyCubeTexture = new CubeTexture();
  2663. // --- Base for inner nodes (including the root) ---
  2664. function UniformContainer() {
  2665. this.seq = [];
  2666. this.map = {};
  2667. }
  2668. // --- Utilities ---
  2669. // Array Caches (provide typed arrays for temporary by size)
  2670. var arrayCacheF32 = [];
  2671. var arrayCacheI32 = [];
  2672. // Flattening for arrays of vectors and matrices
  2673. function flatten( array, nBlocks, blockSize ) {
  2674. var firstElem = array[ 0 ];
  2675. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2676. // unoptimized: ! isNaN( firstElem )
  2677. // see http://jacksondunstan.com/articles/983
  2678. var n = nBlocks * blockSize,
  2679. r = arrayCacheF32[ n ];
  2680. if ( r === undefined ) {
  2681. r = new Float32Array( n );
  2682. arrayCacheF32[ n ] = r;
  2683. }
  2684. if ( nBlocks !== 0 ) {
  2685. firstElem.toArray( r, 0 );
  2686. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2687. offset += blockSize;
  2688. array[ i ].toArray( r, offset );
  2689. }
  2690. }
  2691. return r;
  2692. }
  2693. // Texture unit allocation
  2694. function allocTexUnits( renderer, n ) {
  2695. var r = arrayCacheI32[ n ];
  2696. if ( r === undefined ) {
  2697. r = new Int32Array( n );
  2698. arrayCacheI32[ n ] = r;
  2699. }
  2700. for ( var i = 0; i !== n; ++ i )
  2701. r[ i ] = renderer.allocTextureUnit();
  2702. return r;
  2703. }
  2704. // --- Setters ---
  2705. // Note: Defining these methods externally, because they come in a bunch
  2706. // and this way their names minify.
  2707. // Single scalar
  2708. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  2709. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  2710. // Single float vector (from flat array or THREE.VectorN)
  2711. function setValue2fv( gl, v ) {
  2712. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2713. else gl.uniform2f( this.addr, v.x, v.y );
  2714. }
  2715. function setValue3fv( gl, v ) {
  2716. if ( v.x !== undefined )
  2717. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2718. else if ( v.r !== undefined )
  2719. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2720. else
  2721. gl.uniform3fv( this.addr, v );
  2722. }
  2723. function setValue4fv( gl, v ) {
  2724. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2725. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2726. }
  2727. // Single matrix (from flat array or MatrixN)
  2728. function setValue2fm( gl, v ) {
  2729. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2730. }
  2731. function setValue3fm( gl, v ) {
  2732. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2733. }
  2734. function setValue4fm( gl, v ) {
  2735. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2736. }
  2737. // Single texture (2D / Cube)
  2738. function setValueT1( gl, v, renderer ) {
  2739. var unit = renderer.allocTextureUnit();
  2740. gl.uniform1i( this.addr, unit );
  2741. renderer.setTexture2D( v || emptyTexture, unit );
  2742. }
  2743. function setValueT6( gl, v, renderer ) {
  2744. var unit = renderer.allocTextureUnit();
  2745. gl.uniform1i( this.addr, unit );
  2746. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2747. }
  2748. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2749. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  2750. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  2751. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  2752. // Helper to pick the right setter for the singular case
  2753. function getSingularSetter( type ) {
  2754. switch ( type ) {
  2755. case 0x1406: return setValue1f; // FLOAT
  2756. case 0x8b50: return setValue2fv; // _VEC2
  2757. case 0x8b51: return setValue3fv; // _VEC3
  2758. case 0x8b52: return setValue4fv; // _VEC4
  2759. case 0x8b5a: return setValue2fm; // _MAT2
  2760. case 0x8b5b: return setValue3fm; // _MAT3
  2761. case 0x8b5c: return setValue4fm; // _MAT4
  2762. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2763. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2764. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2765. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2766. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2767. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2768. }
  2769. }
  2770. // Array of scalars
  2771. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  2772. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  2773. // Array of vectors (flat or from THREE classes)
  2774. function setValueV2a( gl, v ) {
  2775. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2776. }
  2777. function setValueV3a( gl, v ) {
  2778. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2779. }
  2780. function setValueV4a( gl, v ) {
  2781. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2782. }
  2783. // Array of matrices (flat or from THREE clases)
  2784. function setValueM2a( gl, v ) {
  2785. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2786. }
  2787. function setValueM3a( gl, v ) {
  2788. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2789. }
  2790. function setValueM4a( gl, v ) {
  2791. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2792. }
  2793. // Array of textures (2D / Cube)
  2794. function setValueT1a( gl, v, renderer ) {
  2795. var n = v.length,
  2796. units = allocTexUnits( renderer, n );
  2797. gl.uniform1iv( this.addr, units );
  2798. for ( var i = 0; i !== n; ++ i ) {
  2799. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2800. }
  2801. }
  2802. function setValueT6a( gl, v, renderer ) {
  2803. var n = v.length,
  2804. units = allocTexUnits( renderer, n );
  2805. gl.uniform1iv( this.addr, units );
  2806. for ( var i = 0; i !== n; ++ i ) {
  2807. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2808. }
  2809. }
  2810. // Helper to pick the right setter for a pure (bottom-level) array
  2811. function getPureArraySetter( type ) {
  2812. switch ( type ) {
  2813. case 0x1406: return setValue1fv; // FLOAT
  2814. case 0x8b50: return setValueV2a; // _VEC2
  2815. case 0x8b51: return setValueV3a; // _VEC3
  2816. case 0x8b52: return setValueV4a; // _VEC4
  2817. case 0x8b5a: return setValueM2a; // _MAT2
  2818. case 0x8b5b: return setValueM3a; // _MAT3
  2819. case 0x8b5c: return setValueM4a; // _MAT4
  2820. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  2821. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  2822. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  2823. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2824. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2825. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2826. }
  2827. }
  2828. // --- Uniform Classes ---
  2829. function SingleUniform( id, activeInfo, addr ) {
  2830. this.id = id;
  2831. this.addr = addr;
  2832. this.setValue = getSingularSetter( activeInfo.type );
  2833. // this.path = activeInfo.name; // DEBUG
  2834. }
  2835. function PureArrayUniform( id, activeInfo, addr ) {
  2836. this.id = id;
  2837. this.addr = addr;
  2838. this.size = activeInfo.size;
  2839. this.setValue = getPureArraySetter( activeInfo.type );
  2840. // this.path = activeInfo.name; // DEBUG
  2841. }
  2842. function StructuredUniform( id ) {
  2843. this.id = id;
  2844. UniformContainer.call( this ); // mix-in
  2845. }
  2846. StructuredUniform.prototype.setValue = function( gl, value ) {
  2847. // Note: Don't need an extra 'renderer' parameter, since samplers
  2848. // are not allowed in structured uniforms.
  2849. var seq = this.seq;
  2850. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2851. var u = seq[ i ];
  2852. u.setValue( gl, value[ u.id ] );
  2853. }
  2854. };
  2855. // --- Top-level ---
  2856. // Parser - builds up the property tree from the path strings
  2857. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  2858. // extracts
  2859. // - the identifier (member name or array index)
  2860. // - followed by an optional right bracket (found when array index)
  2861. // - followed by an optional left bracket or dot (type of subscript)
  2862. //
  2863. // Note: These portions can be read in a non-overlapping fashion and
  2864. // allow straightforward parsing of the hierarchy that WebGL encodes
  2865. // in the uniform names.
  2866. function addUniform( container, uniformObject ) {
  2867. container.seq.push( uniformObject );
  2868. container.map[ uniformObject.id ] = uniformObject;
  2869. }
  2870. function parseUniform( activeInfo, addr, container ) {
  2871. var path = activeInfo.name,
  2872. pathLength = path.length;
  2873. // reset RegExp object, because of the early exit of a previous run
  2874. RePathPart.lastIndex = 0;
  2875. for (; ;) {
  2876. var match = RePathPart.exec( path ),
  2877. matchEnd = RePathPart.lastIndex,
  2878. id = match[ 1 ],
  2879. idIsIndex = match[ 2 ] === ']',
  2880. subscript = match[ 3 ];
  2881. if ( idIsIndex ) id = id | 0; // convert to integer
  2882. if ( subscript === undefined ||
  2883. subscript === '[' && matchEnd + 2 === pathLength ) {
  2884. // bare name or "pure" bottom-level array "[0]" suffix
  2885. addUniform( container, subscript === undefined ?
  2886. new SingleUniform( id, activeInfo, addr ) :
  2887. new PureArrayUniform( id, activeInfo, addr ) );
  2888. break;
  2889. } else {
  2890. // step into inner node / create it in case it doesn't exist
  2891. var map = container.map,
  2892. next = map[ id ];
  2893. if ( next === undefined ) {
  2894. next = new StructuredUniform( id );
  2895. addUniform( container, next );
  2896. }
  2897. container = next;
  2898. }
  2899. }
  2900. }
  2901. // Root Container
  2902. function WebGLUniforms( gl, program, renderer ) {
  2903. UniformContainer.call( this );
  2904. this.renderer = renderer;
  2905. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  2906. for ( var i = 0; i !== n; ++ i ) {
  2907. var info = gl.getActiveUniform( program, i ),
  2908. path = info.name,
  2909. addr = gl.getUniformLocation( program, path );
  2910. parseUniform( info, addr, this );
  2911. }
  2912. }
  2913. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  2914. var u = this.map[ name ];
  2915. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  2916. };
  2917. WebGLUniforms.prototype.set = function( gl, object, name ) {
  2918. var u = this.map[ name ];
  2919. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  2920. };
  2921. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  2922. var v = object[ name ];
  2923. if ( v !== undefined ) this.setValue( gl, name, v );
  2924. };
  2925. // Static interface
  2926. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  2927. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2928. var u = seq[ i ],
  2929. v = values[ u.id ];
  2930. if ( v.needsUpdate !== false ) {
  2931. // note: always updating when .needsUpdate is undefined
  2932. u.setValue( gl, v.value, renderer );
  2933. }
  2934. }
  2935. };
  2936. WebGLUniforms.seqWithValue = function( seq, values ) {
  2937. var r = [];
  2938. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  2939. var u = seq[ i ];
  2940. if ( u.id in values ) r.push( u );
  2941. }
  2942. return r;
  2943. };
  2944. /**
  2945. * Uniform Utilities
  2946. */
  2947. var UniformsUtils = {
  2948. merge: function ( uniforms ) {
  2949. var merged = {};
  2950. for ( var u = 0; u < uniforms.length; u ++ ) {
  2951. var tmp = this.clone( uniforms[ u ] );
  2952. for ( var p in tmp ) {
  2953. merged[ p ] = tmp[ p ];
  2954. }
  2955. }
  2956. return merged;
  2957. },
  2958. clone: function ( uniforms_src ) {
  2959. var uniforms_dst = {};
  2960. for ( var u in uniforms_src ) {
  2961. uniforms_dst[ u ] = {};
  2962. for ( var p in uniforms_src[ u ] ) {
  2963. var parameter_src = uniforms_src[ u ][ p ];
  2964. if ( parameter_src && ( parameter_src.isColor ||
  2965. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  2966. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  2967. parameter_src.isTexture ) ) {
  2968. uniforms_dst[ u ][ p ] = parameter_src.clone();
  2969. } else if ( Array.isArray( parameter_src ) ) {
  2970. uniforms_dst[ u ][ p ] = parameter_src.slice();
  2971. } else {
  2972. uniforms_dst[ u ][ p ] = parameter_src;
  2973. }
  2974. }
  2975. }
  2976. return uniforms_dst;
  2977. }
  2978. };
  2979. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  2980. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  2981. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  2982. 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";
  2983. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  2984. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  2985. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  2986. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 ltcTextureCoords( const in GeometricContext geometry, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = (LUT_SIZE - 1.0)/LUT_SIZE;\n\tconst float LUT_BIAS = 0.5/LUT_SIZE;\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  2987. 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";
  2988. 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";
  2989. 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";
  2990. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  2991. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  2992. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  2993. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  2994. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  2995. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  2996. 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";
  2997. 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";
  2998. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  2999. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  3000. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  3001. 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";
  3002. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  3003. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  3004. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  3005. 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";
  3006. 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";
  3007. 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";
  3008. 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";
  3009. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  3010. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  3011. 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";
  3012. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  3013. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  3014. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  3015. 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";
  3016. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  3017. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n }\n#endif\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  3018. 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";
  3019. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.specularRoughness;\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff;\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  3020. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  3021. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  3022. 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";
  3023. 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";
  3024. 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";
  3025. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  3026. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  3027. 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";
  3028. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  3029. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  3030. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  3031. 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";
  3032. 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";
  3033. 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";
  3034. 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";
  3035. 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";
  3036. 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";
  3037. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  3038. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  3039. 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";
  3040. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  3041. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  3042. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  3043. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  3044. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  3045. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  3046. 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";
  3047. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  3048. 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";
  3049. 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";
  3050. 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";
  3051. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  3052. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  3053. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  3054. 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";
  3055. 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";
  3056. 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";
  3057. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  3058. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  3059. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  3060. 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";
  3061. 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";
  3062. 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";
  3063. 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";
  3064. 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";
  3065. 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";
  3066. 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";
  3067. 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";
  3068. 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";
  3069. 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";
  3070. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  3071. 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";
  3072. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n}\n";
  3073. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3074. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3075. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3076. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3077. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3078. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3079. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#include <premultiplied_alpha_fragment>\n\t#include <encodings_fragment>\n}\n";
  3080. 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";
  3081. 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";
  3082. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3083. 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";
  3084. 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";
  3085. var ShaderChunk = {
  3086. alphamap_fragment: alphamap_fragment,
  3087. alphamap_pars_fragment: alphamap_pars_fragment,
  3088. alphatest_fragment: alphatest_fragment,
  3089. aomap_fragment: aomap_fragment,
  3090. aomap_pars_fragment: aomap_pars_fragment,
  3091. begin_vertex: begin_vertex,
  3092. beginnormal_vertex: beginnormal_vertex,
  3093. bsdfs: bsdfs,
  3094. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3095. clipping_planes_fragment: clipping_planes_fragment,
  3096. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3097. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3098. clipping_planes_vertex: clipping_planes_vertex,
  3099. color_fragment: color_fragment,
  3100. color_pars_fragment: color_pars_fragment,
  3101. color_pars_vertex: color_pars_vertex,
  3102. color_vertex: color_vertex,
  3103. common: common,
  3104. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3105. defaultnormal_vertex: defaultnormal_vertex,
  3106. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3107. displacementmap_vertex: displacementmap_vertex,
  3108. emissivemap_fragment: emissivemap_fragment,
  3109. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3110. encodings_fragment: encodings_fragment,
  3111. encodings_pars_fragment: encodings_pars_fragment,
  3112. envmap_fragment: envmap_fragment,
  3113. envmap_pars_fragment: envmap_pars_fragment,
  3114. envmap_pars_vertex: envmap_pars_vertex,
  3115. envmap_vertex: envmap_vertex,
  3116. fog_fragment: fog_fragment,
  3117. fog_pars_fragment: fog_pars_fragment,
  3118. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3119. lightmap_fragment: lightmap_fragment,
  3120. lightmap_pars_fragment: lightmap_pars_fragment,
  3121. lights_lambert_vertex: lights_lambert_vertex,
  3122. lights_pars: lights_pars,
  3123. lights_phong_fragment: lights_phong_fragment,
  3124. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3125. lights_physical_fragment: lights_physical_fragment,
  3126. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3127. lights_template: lights_template,
  3128. logdepthbuf_fragment: logdepthbuf_fragment,
  3129. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3130. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3131. logdepthbuf_vertex: logdepthbuf_vertex,
  3132. map_fragment: map_fragment,
  3133. map_pars_fragment: map_pars_fragment,
  3134. map_particle_fragment: map_particle_fragment,
  3135. map_particle_pars_fragment: map_particle_pars_fragment,
  3136. metalnessmap_fragment: metalnessmap_fragment,
  3137. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3138. morphnormal_vertex: morphnormal_vertex,
  3139. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3140. morphtarget_vertex: morphtarget_vertex,
  3141. normal_flip: normal_flip,
  3142. normal_fragment: normal_fragment,
  3143. normalmap_pars_fragment: normalmap_pars_fragment,
  3144. packing: packing,
  3145. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3146. project_vertex: project_vertex,
  3147. roughnessmap_fragment: roughnessmap_fragment,
  3148. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3149. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3150. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3151. shadowmap_vertex: shadowmap_vertex,
  3152. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3153. skinbase_vertex: skinbase_vertex,
  3154. skinning_pars_vertex: skinning_pars_vertex,
  3155. skinning_vertex: skinning_vertex,
  3156. skinnormal_vertex: skinnormal_vertex,
  3157. specularmap_fragment: specularmap_fragment,
  3158. specularmap_pars_fragment: specularmap_pars_fragment,
  3159. tonemapping_fragment: tonemapping_fragment,
  3160. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3161. uv_pars_fragment: uv_pars_fragment,
  3162. uv_pars_vertex: uv_pars_vertex,
  3163. uv_vertex: uv_vertex,
  3164. uv2_pars_fragment: uv2_pars_fragment,
  3165. uv2_pars_vertex: uv2_pars_vertex,
  3166. uv2_vertex: uv2_vertex,
  3167. worldpos_vertex: worldpos_vertex,
  3168. cube_frag: cube_frag,
  3169. cube_vert: cube_vert,
  3170. depth_frag: depth_frag,
  3171. depth_vert: depth_vert,
  3172. distanceRGBA_frag: distanceRGBA_frag,
  3173. distanceRGBA_vert: distanceRGBA_vert,
  3174. equirect_frag: equirect_frag,
  3175. equirect_vert: equirect_vert,
  3176. linedashed_frag: linedashed_frag,
  3177. linedashed_vert: linedashed_vert,
  3178. meshbasic_frag: meshbasic_frag,
  3179. meshbasic_vert: meshbasic_vert,
  3180. meshlambert_frag: meshlambert_frag,
  3181. meshlambert_vert: meshlambert_vert,
  3182. meshphong_frag: meshphong_frag,
  3183. meshphong_vert: meshphong_vert,
  3184. meshphysical_frag: meshphysical_frag,
  3185. meshphysical_vert: meshphysical_vert,
  3186. normal_frag: normal_frag,
  3187. normal_vert: normal_vert,
  3188. points_frag: points_frag,
  3189. points_vert: points_vert,
  3190. shadow_frag: shadow_frag,
  3191. shadow_vert: shadow_vert
  3192. };
  3193. /**
  3194. * @author mrdoob / http://mrdoob.com/
  3195. */
  3196. function Color( r, g, b ) {
  3197. if ( g === undefined && b === undefined ) {
  3198. // r is THREE.Color, hex or string
  3199. return this.set( r );
  3200. }
  3201. return this.setRGB( r, g, b );
  3202. }
  3203. Color.prototype = {
  3204. constructor: Color,
  3205. isColor: true,
  3206. r: 1, g: 1, b: 1,
  3207. set: function ( value ) {
  3208. if ( value && value.isColor ) {
  3209. this.copy( value );
  3210. } else if ( typeof value === 'number' ) {
  3211. this.setHex( value );
  3212. } else if ( typeof value === 'string' ) {
  3213. this.setStyle( value );
  3214. }
  3215. return this;
  3216. },
  3217. setScalar: function ( scalar ) {
  3218. this.r = scalar;
  3219. this.g = scalar;
  3220. this.b = scalar;
  3221. return this;
  3222. },
  3223. setHex: function ( hex ) {
  3224. hex = Math.floor( hex );
  3225. this.r = ( hex >> 16 & 255 ) / 255;
  3226. this.g = ( hex >> 8 & 255 ) / 255;
  3227. this.b = ( hex & 255 ) / 255;
  3228. return this;
  3229. },
  3230. setRGB: function ( r, g, b ) {
  3231. this.r = r;
  3232. this.g = g;
  3233. this.b = b;
  3234. return this;
  3235. },
  3236. setHSL: function () {
  3237. function hue2rgb( p, q, t ) {
  3238. if ( t < 0 ) t += 1;
  3239. if ( t > 1 ) t -= 1;
  3240. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3241. if ( t < 1 / 2 ) return q;
  3242. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3243. return p;
  3244. }
  3245. return function setHSL( h, s, l ) {
  3246. // h,s,l ranges are in 0.0 - 1.0
  3247. h = _Math.euclideanModulo( h, 1 );
  3248. s = _Math.clamp( s, 0, 1 );
  3249. l = _Math.clamp( l, 0, 1 );
  3250. if ( s === 0 ) {
  3251. this.r = this.g = this.b = l;
  3252. } else {
  3253. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3254. var q = ( 2 * l ) - p;
  3255. this.r = hue2rgb( q, p, h + 1 / 3 );
  3256. this.g = hue2rgb( q, p, h );
  3257. this.b = hue2rgb( q, p, h - 1 / 3 );
  3258. }
  3259. return this;
  3260. };
  3261. }(),
  3262. setStyle: function ( style ) {
  3263. function handleAlpha( string ) {
  3264. if ( string === undefined ) return;
  3265. if ( parseFloat( string ) < 1 ) {
  3266. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3267. }
  3268. }
  3269. var m;
  3270. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3271. // rgb / hsl
  3272. var color;
  3273. var name = m[ 1 ];
  3274. var components = m[ 2 ];
  3275. switch ( name ) {
  3276. case 'rgb':
  3277. case 'rgba':
  3278. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3279. // rgb(255,0,0) rgba(255,0,0,0.5)
  3280. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3281. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3282. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3283. handleAlpha( color[ 5 ] );
  3284. return this;
  3285. }
  3286. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3287. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3288. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3289. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3290. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3291. handleAlpha( color[ 5 ] );
  3292. return this;
  3293. }
  3294. break;
  3295. case 'hsl':
  3296. case 'hsla':
  3297. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3298. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3299. var h = parseFloat( color[ 1 ] ) / 360;
  3300. var s = parseInt( color[ 2 ], 10 ) / 100;
  3301. var l = parseInt( color[ 3 ], 10 ) / 100;
  3302. handleAlpha( color[ 5 ] );
  3303. return this.setHSL( h, s, l );
  3304. }
  3305. break;
  3306. }
  3307. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3308. // hex color
  3309. var hex = m[ 1 ];
  3310. var size = hex.length;
  3311. if ( size === 3 ) {
  3312. // #ff0
  3313. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3314. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3315. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3316. return this;
  3317. } else if ( size === 6 ) {
  3318. // #ff0000
  3319. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3320. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3321. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3322. return this;
  3323. }
  3324. }
  3325. if ( style && style.length > 0 ) {
  3326. // color keywords
  3327. var hex = ColorKeywords[ style ];
  3328. if ( hex !== undefined ) {
  3329. // red
  3330. this.setHex( hex );
  3331. } else {
  3332. // unknown color
  3333. console.warn( 'THREE.Color: Unknown color ' + style );
  3334. }
  3335. }
  3336. return this;
  3337. },
  3338. clone: function () {
  3339. return new this.constructor( this.r, this.g, this.b );
  3340. },
  3341. copy: function ( color ) {
  3342. this.r = color.r;
  3343. this.g = color.g;
  3344. this.b = color.b;
  3345. return this;
  3346. },
  3347. copyGammaToLinear: function ( color, gammaFactor ) {
  3348. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3349. this.r = Math.pow( color.r, gammaFactor );
  3350. this.g = Math.pow( color.g, gammaFactor );
  3351. this.b = Math.pow( color.b, gammaFactor );
  3352. return this;
  3353. },
  3354. copyLinearToGamma: function ( color, gammaFactor ) {
  3355. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3356. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3357. this.r = Math.pow( color.r, safeInverse );
  3358. this.g = Math.pow( color.g, safeInverse );
  3359. this.b = Math.pow( color.b, safeInverse );
  3360. return this;
  3361. },
  3362. convertGammaToLinear: function () {
  3363. var r = this.r, g = this.g, b = this.b;
  3364. this.r = r * r;
  3365. this.g = g * g;
  3366. this.b = b * b;
  3367. return this;
  3368. },
  3369. convertLinearToGamma: function () {
  3370. this.r = Math.sqrt( this.r );
  3371. this.g = Math.sqrt( this.g );
  3372. this.b = Math.sqrt( this.b );
  3373. return this;
  3374. },
  3375. getHex: function () {
  3376. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3377. },
  3378. getHexString: function () {
  3379. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3380. },
  3381. getHSL: function ( optionalTarget ) {
  3382. // h,s,l ranges are in 0.0 - 1.0
  3383. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3384. var r = this.r, g = this.g, b = this.b;
  3385. var max = Math.max( r, g, b );
  3386. var min = Math.min( r, g, b );
  3387. var hue, saturation;
  3388. var lightness = ( min + max ) / 2.0;
  3389. if ( min === max ) {
  3390. hue = 0;
  3391. saturation = 0;
  3392. } else {
  3393. var delta = max - min;
  3394. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3395. switch ( max ) {
  3396. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3397. case g: hue = ( b - r ) / delta + 2; break;
  3398. case b: hue = ( r - g ) / delta + 4; break;
  3399. }
  3400. hue /= 6;
  3401. }
  3402. hsl.h = hue;
  3403. hsl.s = saturation;
  3404. hsl.l = lightness;
  3405. return hsl;
  3406. },
  3407. getStyle: function () {
  3408. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3409. },
  3410. offsetHSL: function ( h, s, l ) {
  3411. var hsl = this.getHSL();
  3412. hsl.h += h; hsl.s += s; hsl.l += l;
  3413. this.setHSL( hsl.h, hsl.s, hsl.l );
  3414. return this;
  3415. },
  3416. add: function ( color ) {
  3417. this.r += color.r;
  3418. this.g += color.g;
  3419. this.b += color.b;
  3420. return this;
  3421. },
  3422. addColors: function ( color1, color2 ) {
  3423. this.r = color1.r + color2.r;
  3424. this.g = color1.g + color2.g;
  3425. this.b = color1.b + color2.b;
  3426. return this;
  3427. },
  3428. addScalar: function ( s ) {
  3429. this.r += s;
  3430. this.g += s;
  3431. this.b += s;
  3432. return this;
  3433. },
  3434. sub: function( color ) {
  3435. this.r = Math.max( 0, this.r - color.r );
  3436. this.g = Math.max( 0, this.g - color.g );
  3437. this.b = Math.max( 0, this.b - color.b );
  3438. return this;
  3439. },
  3440. multiply: function ( color ) {
  3441. this.r *= color.r;
  3442. this.g *= color.g;
  3443. this.b *= color.b;
  3444. return this;
  3445. },
  3446. multiplyScalar: function ( s ) {
  3447. this.r *= s;
  3448. this.g *= s;
  3449. this.b *= s;
  3450. return this;
  3451. },
  3452. lerp: function ( color, alpha ) {
  3453. this.r += ( color.r - this.r ) * alpha;
  3454. this.g += ( color.g - this.g ) * alpha;
  3455. this.b += ( color.b - this.b ) * alpha;
  3456. return this;
  3457. },
  3458. equals: function ( c ) {
  3459. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3460. },
  3461. fromArray: function ( array, offset ) {
  3462. if ( offset === undefined ) offset = 0;
  3463. this.r = array[ offset ];
  3464. this.g = array[ offset + 1 ];
  3465. this.b = array[ offset + 2 ];
  3466. return this;
  3467. },
  3468. toArray: function ( array, offset ) {
  3469. if ( array === undefined ) array = [];
  3470. if ( offset === undefined ) offset = 0;
  3471. array[ offset ] = this.r;
  3472. array[ offset + 1 ] = this.g;
  3473. array[ offset + 2 ] = this.b;
  3474. return array;
  3475. },
  3476. toJSON: function () {
  3477. return this.getHex();
  3478. }
  3479. };
  3480. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3481. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3482. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3483. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3484. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3485. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3486. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3487. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3488. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3489. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3490. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3491. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3492. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3493. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3494. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3495. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3496. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3497. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3498. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3499. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3500. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3501. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3502. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3503. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3504. /**
  3505. * @author alteredq / http://alteredqualia.com/
  3506. */
  3507. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  3508. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  3509. this.image = { data: data, width: width, height: height };
  3510. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  3511. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  3512. this.generateMipmaps = false;
  3513. this.flipY = false;
  3514. this.unpackAlignment = 1;
  3515. }
  3516. DataTexture.prototype = Object.create( Texture.prototype );
  3517. DataTexture.prototype.constructor = DataTexture;
  3518. DataTexture.prototype.isDataTexture = true;
  3519. /**
  3520. * Uniforms library for shared webgl shaders
  3521. */
  3522. var UniformsLib = {
  3523. common: {
  3524. diffuse: { value: new Color( 0xeeeeee ) },
  3525. opacity: { value: 1.0 },
  3526. map: { value: null },
  3527. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  3528. specularMap: { value: null },
  3529. alphaMap: { value: null },
  3530. envMap: { value: null },
  3531. flipEnvMap: { value: - 1 },
  3532. reflectivity: { value: 1.0 },
  3533. refractionRatio: { value: 0.98 }
  3534. },
  3535. aomap: {
  3536. aoMap: { value: null },
  3537. aoMapIntensity: { value: 1 }
  3538. },
  3539. lightmap: {
  3540. lightMap: { value: null },
  3541. lightMapIntensity: { value: 1 }
  3542. },
  3543. emissivemap: {
  3544. emissiveMap: { value: null }
  3545. },
  3546. bumpmap: {
  3547. bumpMap: { value: null },
  3548. bumpScale: { value: 1 }
  3549. },
  3550. normalmap: {
  3551. normalMap: { value: null },
  3552. normalScale: { value: new Vector2( 1, 1 ) }
  3553. },
  3554. displacementmap: {
  3555. displacementMap: { value: null },
  3556. displacementScale: { value: 1 },
  3557. displacementBias: { value: 0 }
  3558. },
  3559. roughnessmap: {
  3560. roughnessMap: { value: null }
  3561. },
  3562. metalnessmap: {
  3563. metalnessMap: { value: null }
  3564. },
  3565. gradientmap: {
  3566. gradientMap: { value: null }
  3567. },
  3568. fog: {
  3569. fogDensity: { value: 0.00025 },
  3570. fogNear: { value: 1 },
  3571. fogFar: { value: 2000 },
  3572. fogColor: { value: new Color( 0xffffff ) }
  3573. },
  3574. lights: {
  3575. ambientLightColor: { value: [] },
  3576. directionalLights: { value: [], properties: {
  3577. direction: {},
  3578. color: {},
  3579. shadow: {},
  3580. shadowBias: {},
  3581. shadowRadius: {},
  3582. shadowMapSize: {}
  3583. } },
  3584. directionalShadowMap: { value: [] },
  3585. directionalShadowMatrix: { value: [] },
  3586. spotLights: { value: [], properties: {
  3587. color: {},
  3588. position: {},
  3589. direction: {},
  3590. distance: {},
  3591. coneCos: {},
  3592. penumbraCos: {},
  3593. decay: {},
  3594. shadow: {},
  3595. shadowBias: {},
  3596. shadowRadius: {},
  3597. shadowMapSize: {}
  3598. } },
  3599. spotShadowMap: { value: [] },
  3600. spotShadowMatrix: { value: [] },
  3601. pointLights: { value: [], properties: {
  3602. color: {},
  3603. position: {},
  3604. decay: {},
  3605. distance: {},
  3606. shadow: {},
  3607. shadowBias: {},
  3608. shadowRadius: {},
  3609. shadowMapSize: {}
  3610. } },
  3611. pointShadowMap: { value: [] },
  3612. pointShadowMatrix: { value: [] },
  3613. hemisphereLights: { value: [], properties: {
  3614. direction: {},
  3615. skyColor: {},
  3616. groundColor: {}
  3617. } },
  3618. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3619. rectAreaLights: { value: [], properties: {
  3620. color: {},
  3621. position: {},
  3622. width: {},
  3623. height: {},
  3624. } }
  3625. },
  3626. points: {
  3627. diffuse: { value: new Color( 0xeeeeee ) },
  3628. opacity: { value: 1.0 },
  3629. size: { value: 1.0 },
  3630. scale: { value: 1.0 },
  3631. map: { value: null },
  3632. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  3633. }
  3634. };
  3635. /**
  3636. * @author alteredq / http://alteredqualia.com/
  3637. * @author mrdoob / http://mrdoob.com/
  3638. * @author mikael emtinger / http://gomo.se/
  3639. */
  3640. var ShaderLib = {
  3641. basic: {
  3642. uniforms: UniformsUtils.merge( [
  3643. UniformsLib.common,
  3644. UniformsLib.aomap,
  3645. UniformsLib.lightmap,
  3646. UniformsLib.fog
  3647. ] ),
  3648. vertexShader: ShaderChunk.meshbasic_vert,
  3649. fragmentShader: ShaderChunk.meshbasic_frag
  3650. },
  3651. lambert: {
  3652. uniforms: UniformsUtils.merge( [
  3653. UniformsLib.common,
  3654. UniformsLib.aomap,
  3655. UniformsLib.lightmap,
  3656. UniformsLib.emissivemap,
  3657. UniformsLib.fog,
  3658. UniformsLib.lights,
  3659. {
  3660. emissive: { value: new Color( 0x000000 ) }
  3661. }
  3662. ] ),
  3663. vertexShader: ShaderChunk.meshlambert_vert,
  3664. fragmentShader: ShaderChunk.meshlambert_frag
  3665. },
  3666. phong: {
  3667. uniforms: UniformsUtils.merge( [
  3668. UniformsLib.common,
  3669. UniformsLib.aomap,
  3670. UniformsLib.lightmap,
  3671. UniformsLib.emissivemap,
  3672. UniformsLib.bumpmap,
  3673. UniformsLib.normalmap,
  3674. UniformsLib.displacementmap,
  3675. UniformsLib.gradientmap,
  3676. UniformsLib.fog,
  3677. UniformsLib.lights,
  3678. {
  3679. emissive: { value: new Color( 0x000000 ) },
  3680. specular: { value: new Color( 0x111111 ) },
  3681. shininess: { value: 30 }
  3682. }
  3683. ] ),
  3684. vertexShader: ShaderChunk.meshphong_vert,
  3685. fragmentShader: ShaderChunk.meshphong_frag
  3686. },
  3687. standard: {
  3688. uniforms: UniformsUtils.merge( [
  3689. UniformsLib.common,
  3690. UniformsLib.aomap,
  3691. UniformsLib.lightmap,
  3692. UniformsLib.emissivemap,
  3693. UniformsLib.bumpmap,
  3694. UniformsLib.normalmap,
  3695. UniformsLib.displacementmap,
  3696. UniformsLib.roughnessmap,
  3697. UniformsLib.metalnessmap,
  3698. UniformsLib.fog,
  3699. UniformsLib.lights,
  3700. {
  3701. emissive: { value: new Color( 0x000000 ) },
  3702. roughness: { value: 0.5 },
  3703. metalness: { value: 0 },
  3704. envMapIntensity: { value: 1 } // temporary
  3705. }
  3706. ] ),
  3707. vertexShader: ShaderChunk.meshphysical_vert,
  3708. fragmentShader: ShaderChunk.meshphysical_frag
  3709. },
  3710. points: {
  3711. uniforms: UniformsUtils.merge( [
  3712. UniformsLib.points,
  3713. UniformsLib.fog
  3714. ] ),
  3715. vertexShader: ShaderChunk.points_vert,
  3716. fragmentShader: ShaderChunk.points_frag
  3717. },
  3718. dashed: {
  3719. uniforms: UniformsUtils.merge( [
  3720. UniformsLib.common,
  3721. UniformsLib.fog,
  3722. {
  3723. scale: { value: 1 },
  3724. dashSize: { value: 1 },
  3725. totalSize: { value: 2 }
  3726. }
  3727. ] ),
  3728. vertexShader: ShaderChunk.linedashed_vert,
  3729. fragmentShader: ShaderChunk.linedashed_frag
  3730. },
  3731. depth: {
  3732. uniforms: UniformsUtils.merge( [
  3733. UniformsLib.common,
  3734. UniformsLib.displacementmap
  3735. ] ),
  3736. vertexShader: ShaderChunk.depth_vert,
  3737. fragmentShader: ShaderChunk.depth_frag
  3738. },
  3739. normal: {
  3740. uniforms: UniformsUtils.merge( [
  3741. UniformsLib.common,
  3742. UniformsLib.bumpmap,
  3743. UniformsLib.normalmap,
  3744. UniformsLib.displacementmap,
  3745. {
  3746. opacity: { value: 1.0 }
  3747. }
  3748. ] ),
  3749. vertexShader: ShaderChunk.normal_vert,
  3750. fragmentShader: ShaderChunk.normal_frag
  3751. },
  3752. /* -------------------------------------------------------------------------
  3753. // Cube map shader
  3754. ------------------------------------------------------------------------- */
  3755. cube: {
  3756. uniforms: {
  3757. tCube: { value: null },
  3758. tFlip: { value: - 1 },
  3759. opacity: { value: 1.0 }
  3760. },
  3761. vertexShader: ShaderChunk.cube_vert,
  3762. fragmentShader: ShaderChunk.cube_frag
  3763. },
  3764. /* -------------------------------------------------------------------------
  3765. // Cube map shader
  3766. ------------------------------------------------------------------------- */
  3767. equirect: {
  3768. uniforms: {
  3769. tEquirect: { value: null },
  3770. tFlip: { value: - 1 }
  3771. },
  3772. vertexShader: ShaderChunk.equirect_vert,
  3773. fragmentShader: ShaderChunk.equirect_frag
  3774. },
  3775. distanceRGBA: {
  3776. uniforms: {
  3777. lightPos: { value: new Vector3() }
  3778. },
  3779. vertexShader: ShaderChunk.distanceRGBA_vert,
  3780. fragmentShader: ShaderChunk.distanceRGBA_frag
  3781. }
  3782. };
  3783. ShaderLib.physical = {
  3784. uniforms: UniformsUtils.merge( [
  3785. ShaderLib.standard.uniforms,
  3786. {
  3787. clearCoat: { value: 0 },
  3788. clearCoatRoughness: { value: 0 }
  3789. }
  3790. ] ),
  3791. vertexShader: ShaderChunk.meshphysical_vert,
  3792. fragmentShader: ShaderChunk.meshphysical_frag
  3793. };
  3794. /**
  3795. * @author bhouston / http://clara.io
  3796. */
  3797. function Box2( min, max ) {
  3798. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  3799. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  3800. }
  3801. Box2.prototype = {
  3802. constructor: Box2,
  3803. set: function ( min, max ) {
  3804. this.min.copy( min );
  3805. this.max.copy( max );
  3806. return this;
  3807. },
  3808. setFromPoints: function ( points ) {
  3809. this.makeEmpty();
  3810. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3811. this.expandByPoint( points[ i ] );
  3812. }
  3813. return this;
  3814. },
  3815. setFromCenterAndSize: function () {
  3816. var v1 = new Vector2();
  3817. return function setFromCenterAndSize( center, size ) {
  3818. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  3819. this.min.copy( center ).sub( halfSize );
  3820. this.max.copy( center ).add( halfSize );
  3821. return this;
  3822. };
  3823. }(),
  3824. clone: function () {
  3825. return new this.constructor().copy( this );
  3826. },
  3827. copy: function ( box ) {
  3828. this.min.copy( box.min );
  3829. this.max.copy( box.max );
  3830. return this;
  3831. },
  3832. makeEmpty: function () {
  3833. this.min.x = this.min.y = + Infinity;
  3834. this.max.x = this.max.y = - Infinity;
  3835. return this;
  3836. },
  3837. isEmpty: function () {
  3838. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3839. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  3840. },
  3841. getCenter: function ( optionalTarget ) {
  3842. var result = optionalTarget || new Vector2();
  3843. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3844. },
  3845. getSize: function ( optionalTarget ) {
  3846. var result = optionalTarget || new Vector2();
  3847. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  3848. },
  3849. expandByPoint: function ( point ) {
  3850. this.min.min( point );
  3851. this.max.max( point );
  3852. return this;
  3853. },
  3854. expandByVector: function ( vector ) {
  3855. this.min.sub( vector );
  3856. this.max.add( vector );
  3857. return this;
  3858. },
  3859. expandByScalar: function ( scalar ) {
  3860. this.min.addScalar( - scalar );
  3861. this.max.addScalar( scalar );
  3862. return this;
  3863. },
  3864. containsPoint: function ( point ) {
  3865. return point.x < this.min.x || point.x > this.max.x ||
  3866. point.y < this.min.y || point.y > this.max.y ? false : true;
  3867. },
  3868. containsBox: function ( box ) {
  3869. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3870. this.min.y <= box.min.y && box.max.y <= this.max.y;
  3871. },
  3872. getParameter: function ( point, optionalTarget ) {
  3873. // This can potentially have a divide by zero if the box
  3874. // has a size dimension of 0.
  3875. var result = optionalTarget || new Vector2();
  3876. return result.set(
  3877. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3878. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  3879. );
  3880. },
  3881. intersectsBox: function ( box ) {
  3882. // using 6 splitting planes to rule out intersections.
  3883. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3884. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  3885. },
  3886. clampPoint: function ( point, optionalTarget ) {
  3887. var result = optionalTarget || new Vector2();
  3888. return result.copy( point ).clamp( this.min, this.max );
  3889. },
  3890. distanceToPoint: function () {
  3891. var v1 = new Vector2();
  3892. return function distanceToPoint( point ) {
  3893. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  3894. return clampedPoint.sub( point ).length();
  3895. };
  3896. }(),
  3897. intersect: function ( box ) {
  3898. this.min.max( box.min );
  3899. this.max.min( box.max );
  3900. return this;
  3901. },
  3902. union: function ( box ) {
  3903. this.min.min( box.min );
  3904. this.max.max( box.max );
  3905. return this;
  3906. },
  3907. translate: function ( offset ) {
  3908. this.min.add( offset );
  3909. this.max.add( offset );
  3910. return this;
  3911. },
  3912. equals: function ( box ) {
  3913. return box.min.equals( this.min ) && box.max.equals( this.max );
  3914. }
  3915. };
  3916. /**
  3917. * @author mikael emtinger / http://gomo.se/
  3918. * @author alteredq / http://alteredqualia.com/
  3919. */
  3920. function LensFlarePlugin( renderer, flares ) {
  3921. var gl = renderer.context;
  3922. var state = renderer.state;
  3923. var vertexBuffer, elementBuffer;
  3924. var shader, program, attributes, uniforms;
  3925. var tempTexture, occlusionTexture;
  3926. function init() {
  3927. var vertices = new Float32Array( [
  3928. - 1, - 1, 0, 0,
  3929. 1, - 1, 1, 0,
  3930. 1, 1, 1, 1,
  3931. - 1, 1, 0, 1
  3932. ] );
  3933. var faces = new Uint16Array( [
  3934. 0, 1, 2,
  3935. 0, 2, 3
  3936. ] );
  3937. // buffers
  3938. vertexBuffer = gl.createBuffer();
  3939. elementBuffer = gl.createBuffer();
  3940. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  3941. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  3942. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  3943. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  3944. // textures
  3945. tempTexture = gl.createTexture();
  3946. occlusionTexture = gl.createTexture();
  3947. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  3948. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  3949. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3950. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3951. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3952. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3953. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  3954. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  3955. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  3956. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  3957. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3958. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3959. shader = {
  3960. vertexShader: [
  3961. "uniform lowp int renderType;",
  3962. "uniform vec3 screenPosition;",
  3963. "uniform vec2 scale;",
  3964. "uniform float rotation;",
  3965. "uniform sampler2D occlusionMap;",
  3966. "attribute vec2 position;",
  3967. "attribute vec2 uv;",
  3968. "varying vec2 vUV;",
  3969. "varying float vVisibility;",
  3970. "void main() {",
  3971. "vUV = uv;",
  3972. "vec2 pos = position;",
  3973. "if ( renderType == 2 ) {",
  3974. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  3975. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  3976. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  3977. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  3978. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  3979. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  3980. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  3981. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  3982. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  3983. "vVisibility = visibility.r / 9.0;",
  3984. "vVisibility *= 1.0 - visibility.g / 9.0;",
  3985. "vVisibility *= visibility.b / 9.0;",
  3986. "vVisibility *= 1.0 - visibility.a / 9.0;",
  3987. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  3988. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  3989. "}",
  3990. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  3991. "}"
  3992. ].join( "\n" ),
  3993. fragmentShader: [
  3994. "uniform lowp int renderType;",
  3995. "uniform sampler2D map;",
  3996. "uniform float opacity;",
  3997. "uniform vec3 color;",
  3998. "varying vec2 vUV;",
  3999. "varying float vVisibility;",
  4000. "void main() {",
  4001. // pink square
  4002. "if ( renderType == 0 ) {",
  4003. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  4004. // restore
  4005. "} else if ( renderType == 1 ) {",
  4006. "gl_FragColor = texture2D( map, vUV );",
  4007. // flare
  4008. "} else {",
  4009. "vec4 texture = texture2D( map, vUV );",
  4010. "texture.a *= opacity * vVisibility;",
  4011. "gl_FragColor = texture;",
  4012. "gl_FragColor.rgb *= color;",
  4013. "}",
  4014. "}"
  4015. ].join( "\n" )
  4016. };
  4017. program = createProgram( shader );
  4018. attributes = {
  4019. vertex: gl.getAttribLocation ( program, "position" ),
  4020. uv: gl.getAttribLocation ( program, "uv" )
  4021. };
  4022. uniforms = {
  4023. renderType: gl.getUniformLocation( program, "renderType" ),
  4024. map: gl.getUniformLocation( program, "map" ),
  4025. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  4026. opacity: gl.getUniformLocation( program, "opacity" ),
  4027. color: gl.getUniformLocation( program, "color" ),
  4028. scale: gl.getUniformLocation( program, "scale" ),
  4029. rotation: gl.getUniformLocation( program, "rotation" ),
  4030. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  4031. };
  4032. }
  4033. /*
  4034. * Render lens flares
  4035. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  4036. * reads these back and calculates occlusion.
  4037. */
  4038. this.render = function ( scene, camera, viewport ) {
  4039. if ( flares.length === 0 ) return;
  4040. var tempPosition = new Vector3();
  4041. var invAspect = viewport.w / viewport.z,
  4042. halfViewportWidth = viewport.z * 0.5,
  4043. halfViewportHeight = viewport.w * 0.5;
  4044. var size = 16 / viewport.w,
  4045. scale = new Vector2( size * invAspect, size );
  4046. var screenPosition = new Vector3( 1, 1, 0 ),
  4047. screenPositionPixels = new Vector2( 1, 1 );
  4048. var validArea = new Box2();
  4049. validArea.min.set( viewport.x, viewport.y );
  4050. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  4051. if ( program === undefined ) {
  4052. init();
  4053. }
  4054. gl.useProgram( program );
  4055. state.initAttributes();
  4056. state.enableAttribute( attributes.vertex );
  4057. state.enableAttribute( attributes.uv );
  4058. state.disableUnusedAttributes();
  4059. // loop through all lens flares to update their occlusion and positions
  4060. // setup gl and common used attribs/uniforms
  4061. gl.uniform1i( uniforms.occlusionMap, 0 );
  4062. gl.uniform1i( uniforms.map, 1 );
  4063. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4064. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  4065. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4066. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4067. state.disable( gl.CULL_FACE );
  4068. state.setDepthWrite( false );
  4069. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  4070. size = 16 / viewport.w;
  4071. scale.set( size * invAspect, size );
  4072. // calc object screen position
  4073. var flare = flares[ i ];
  4074. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  4075. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  4076. tempPosition.applyMatrix4( camera.projectionMatrix );
  4077. // setup arrays for gl programs
  4078. screenPosition.copy( tempPosition );
  4079. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  4080. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  4081. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  4082. // screen cull
  4083. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  4084. // save current RGB to temp texture
  4085. state.activeTexture( gl.TEXTURE0 );
  4086. state.bindTexture( gl.TEXTURE_2D, null );
  4087. state.activeTexture( gl.TEXTURE1 );
  4088. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4089. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4090. // render pink quad
  4091. gl.uniform1i( uniforms.renderType, 0 );
  4092. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4093. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4094. state.disable( gl.BLEND );
  4095. state.enable( gl.DEPTH_TEST );
  4096. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4097. // copy result to occlusionMap
  4098. state.activeTexture( gl.TEXTURE0 );
  4099. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  4100. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  4101. // restore graphics
  4102. gl.uniform1i( uniforms.renderType, 1 );
  4103. state.disable( gl.DEPTH_TEST );
  4104. state.activeTexture( gl.TEXTURE1 );
  4105. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  4106. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4107. // update object positions
  4108. flare.positionScreen.copy( screenPosition );
  4109. if ( flare.customUpdateCallback ) {
  4110. flare.customUpdateCallback( flare );
  4111. } else {
  4112. flare.updateLensFlares();
  4113. }
  4114. // render flares
  4115. gl.uniform1i( uniforms.renderType, 2 );
  4116. state.enable( gl.BLEND );
  4117. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  4118. var sprite = flare.lensFlares[ j ];
  4119. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  4120. screenPosition.x = sprite.x;
  4121. screenPosition.y = sprite.y;
  4122. screenPosition.z = sprite.z;
  4123. size = sprite.size * sprite.scale / viewport.w;
  4124. scale.x = size * invAspect;
  4125. scale.y = size;
  4126. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  4127. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  4128. gl.uniform1f( uniforms.rotation, sprite.rotation );
  4129. gl.uniform1f( uniforms.opacity, sprite.opacity );
  4130. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  4131. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  4132. renderer.setTexture2D( sprite.texture, 1 );
  4133. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4134. }
  4135. }
  4136. }
  4137. }
  4138. // restore gl
  4139. state.enable( gl.CULL_FACE );
  4140. state.enable( gl.DEPTH_TEST );
  4141. state.setDepthWrite( true );
  4142. renderer.resetGLState();
  4143. };
  4144. function createProgram( shader ) {
  4145. var program = gl.createProgram();
  4146. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4147. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4148. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  4149. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  4150. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  4151. gl.compileShader( fragmentShader );
  4152. gl.compileShader( vertexShader );
  4153. gl.attachShader( program, fragmentShader );
  4154. gl.attachShader( program, vertexShader );
  4155. gl.linkProgram( program );
  4156. return program;
  4157. }
  4158. }
  4159. /**
  4160. * @author mikael emtinger / http://gomo.se/
  4161. * @author alteredq / http://alteredqualia.com/
  4162. */
  4163. function SpritePlugin( renderer, sprites ) {
  4164. var gl = renderer.context;
  4165. var state = renderer.state;
  4166. var vertexBuffer, elementBuffer;
  4167. var program, attributes, uniforms;
  4168. var texture;
  4169. // decompose matrixWorld
  4170. var spritePosition = new Vector3();
  4171. var spriteRotation = new Quaternion();
  4172. var spriteScale = new Vector3();
  4173. function init() {
  4174. var vertices = new Float32Array( [
  4175. - 0.5, - 0.5, 0, 0,
  4176. 0.5, - 0.5, 1, 0,
  4177. 0.5, 0.5, 1, 1,
  4178. - 0.5, 0.5, 0, 1
  4179. ] );
  4180. var faces = new Uint16Array( [
  4181. 0, 1, 2,
  4182. 0, 2, 3
  4183. ] );
  4184. vertexBuffer = gl.createBuffer();
  4185. elementBuffer = gl.createBuffer();
  4186. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4187. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  4188. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4189. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  4190. program = createProgram();
  4191. attributes = {
  4192. position: gl.getAttribLocation ( program, 'position' ),
  4193. uv: gl.getAttribLocation ( program, 'uv' )
  4194. };
  4195. uniforms = {
  4196. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  4197. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  4198. rotation: gl.getUniformLocation( program, 'rotation' ),
  4199. scale: gl.getUniformLocation( program, 'scale' ),
  4200. color: gl.getUniformLocation( program, 'color' ),
  4201. map: gl.getUniformLocation( program, 'map' ),
  4202. opacity: gl.getUniformLocation( program, 'opacity' ),
  4203. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  4204. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  4205. fogType: gl.getUniformLocation( program, 'fogType' ),
  4206. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  4207. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  4208. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  4209. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  4210. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  4211. };
  4212. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4213. canvas.width = 8;
  4214. canvas.height = 8;
  4215. var context = canvas.getContext( '2d' );
  4216. context.fillStyle = 'white';
  4217. context.fillRect( 0, 0, 8, 8 );
  4218. texture = new Texture( canvas );
  4219. texture.needsUpdate = true;
  4220. }
  4221. this.render = function ( scene, camera ) {
  4222. if ( sprites.length === 0 ) return;
  4223. // setup gl
  4224. if ( program === undefined ) {
  4225. init();
  4226. }
  4227. gl.useProgram( program );
  4228. state.initAttributes();
  4229. state.enableAttribute( attributes.position );
  4230. state.enableAttribute( attributes.uv );
  4231. state.disableUnusedAttributes();
  4232. state.disable( gl.CULL_FACE );
  4233. state.enable( gl.BLEND );
  4234. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  4235. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  4236. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  4237. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  4238. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  4239. state.activeTexture( gl.TEXTURE0 );
  4240. gl.uniform1i( uniforms.map, 0 );
  4241. var oldFogType = 0;
  4242. var sceneFogType = 0;
  4243. var fog = scene.fog;
  4244. if ( fog ) {
  4245. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  4246. if ( fog.isFog ) {
  4247. gl.uniform1f( uniforms.fogNear, fog.near );
  4248. gl.uniform1f( uniforms.fogFar, fog.far );
  4249. gl.uniform1i( uniforms.fogType, 1 );
  4250. oldFogType = 1;
  4251. sceneFogType = 1;
  4252. } else if ( fog.isFogExp2 ) {
  4253. gl.uniform1f( uniforms.fogDensity, fog.density );
  4254. gl.uniform1i( uniforms.fogType, 2 );
  4255. oldFogType = 2;
  4256. sceneFogType = 2;
  4257. }
  4258. } else {
  4259. gl.uniform1i( uniforms.fogType, 0 );
  4260. oldFogType = 0;
  4261. sceneFogType = 0;
  4262. }
  4263. // update positions and sort
  4264. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4265. var sprite = sprites[ i ];
  4266. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  4267. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  4268. }
  4269. sprites.sort( painterSortStable );
  4270. // render all sprites
  4271. var scale = [];
  4272. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  4273. var sprite = sprites[ i ];
  4274. var material = sprite.material;
  4275. if ( material.visible === false ) continue;
  4276. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  4277. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  4278. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  4279. scale[ 0 ] = spriteScale.x;
  4280. scale[ 1 ] = spriteScale.y;
  4281. var fogType = 0;
  4282. if ( scene.fog && material.fog ) {
  4283. fogType = sceneFogType;
  4284. }
  4285. if ( oldFogType !== fogType ) {
  4286. gl.uniform1i( uniforms.fogType, fogType );
  4287. oldFogType = fogType;
  4288. }
  4289. if ( material.map !== null ) {
  4290. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  4291. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  4292. } else {
  4293. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  4294. gl.uniform2f( uniforms.uvScale, 1, 1 );
  4295. }
  4296. gl.uniform1f( uniforms.opacity, material.opacity );
  4297. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  4298. gl.uniform1f( uniforms.rotation, material.rotation );
  4299. gl.uniform2fv( uniforms.scale, scale );
  4300. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  4301. state.setDepthTest( material.depthTest );
  4302. state.setDepthWrite( material.depthWrite );
  4303. if ( material.map ) {
  4304. renderer.setTexture2D( material.map, 0 );
  4305. } else {
  4306. renderer.setTexture2D( texture, 0 );
  4307. }
  4308. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  4309. }
  4310. // restore gl
  4311. state.enable( gl.CULL_FACE );
  4312. renderer.resetGLState();
  4313. };
  4314. function createProgram() {
  4315. var program = gl.createProgram();
  4316. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  4317. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  4318. gl.shaderSource( vertexShader, [
  4319. 'precision ' + renderer.getPrecision() + ' float;',
  4320. 'uniform mat4 modelViewMatrix;',
  4321. 'uniform mat4 projectionMatrix;',
  4322. 'uniform float rotation;',
  4323. 'uniform vec2 scale;',
  4324. 'uniform vec2 uvOffset;',
  4325. 'uniform vec2 uvScale;',
  4326. 'attribute vec2 position;',
  4327. 'attribute vec2 uv;',
  4328. 'varying vec2 vUV;',
  4329. 'void main() {',
  4330. 'vUV = uvOffset + uv * uvScale;',
  4331. 'vec2 alignedPosition = position * scale;',
  4332. 'vec2 rotatedPosition;',
  4333. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  4334. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  4335. 'vec4 finalPosition;',
  4336. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  4337. 'finalPosition.xy += rotatedPosition;',
  4338. 'finalPosition = projectionMatrix * finalPosition;',
  4339. 'gl_Position = finalPosition;',
  4340. '}'
  4341. ].join( '\n' ) );
  4342. gl.shaderSource( fragmentShader, [
  4343. 'precision ' + renderer.getPrecision() + ' float;',
  4344. 'uniform vec3 color;',
  4345. 'uniform sampler2D map;',
  4346. 'uniform float opacity;',
  4347. 'uniform int fogType;',
  4348. 'uniform vec3 fogColor;',
  4349. 'uniform float fogDensity;',
  4350. 'uniform float fogNear;',
  4351. 'uniform float fogFar;',
  4352. 'uniform float alphaTest;',
  4353. 'varying vec2 vUV;',
  4354. 'void main() {',
  4355. 'vec4 texture = texture2D( map, vUV );',
  4356. 'if ( texture.a < alphaTest ) discard;',
  4357. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  4358. 'if ( fogType > 0 ) {',
  4359. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  4360. 'float fogFactor = 0.0;',
  4361. 'if ( fogType == 1 ) {',
  4362. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  4363. '} else {',
  4364. 'const float LOG2 = 1.442695;',
  4365. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  4366. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  4367. '}',
  4368. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  4369. '}',
  4370. '}'
  4371. ].join( '\n' ) );
  4372. gl.compileShader( vertexShader );
  4373. gl.compileShader( fragmentShader );
  4374. gl.attachShader( program, vertexShader );
  4375. gl.attachShader( program, fragmentShader );
  4376. gl.linkProgram( program );
  4377. return program;
  4378. }
  4379. function painterSortStable( a, b ) {
  4380. if ( a.renderOrder !== b.renderOrder ) {
  4381. return a.renderOrder - b.renderOrder;
  4382. } else if ( a.z !== b.z ) {
  4383. return b.z - a.z;
  4384. } else {
  4385. return b.id - a.id;
  4386. }
  4387. }
  4388. }
  4389. /**
  4390. * @author mrdoob / http://mrdoob.com/
  4391. * @author alteredq / http://alteredqualia.com/
  4392. */
  4393. var materialId = 0;
  4394. function Material() {
  4395. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4396. this.uuid = _Math.generateUUID();
  4397. this.name = '';
  4398. this.type = 'Material';
  4399. this.fog = true;
  4400. this.lights = true;
  4401. this.blending = NormalBlending;
  4402. this.side = FrontSide;
  4403. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4404. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4405. this.opacity = 1;
  4406. this.transparent = false;
  4407. this.blendSrc = SrcAlphaFactor;
  4408. this.blendDst = OneMinusSrcAlphaFactor;
  4409. this.blendEquation = AddEquation;
  4410. this.blendSrcAlpha = null;
  4411. this.blendDstAlpha = null;
  4412. this.blendEquationAlpha = null;
  4413. this.depthFunc = LessEqualDepth;
  4414. this.depthTest = true;
  4415. this.depthWrite = true;
  4416. this.clippingPlanes = null;
  4417. this.clipIntersection = false;
  4418. this.clipShadows = false;
  4419. this.colorWrite = true;
  4420. this.precision = null; // override the renderer's default precision for this material
  4421. this.polygonOffset = false;
  4422. this.polygonOffsetFactor = 0;
  4423. this.polygonOffsetUnits = 0;
  4424. this.alphaTest = 0;
  4425. this.premultipliedAlpha = false;
  4426. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4427. this.visible = true;
  4428. this._needsUpdate = true;
  4429. }
  4430. Material.prototype = {
  4431. constructor: Material,
  4432. isMaterial: true,
  4433. get needsUpdate() {
  4434. return this._needsUpdate;
  4435. },
  4436. set needsUpdate( value ) {
  4437. if ( value === true ) this.update();
  4438. this._needsUpdate = value;
  4439. },
  4440. setValues: function ( values ) {
  4441. if ( values === undefined ) return;
  4442. for ( var key in values ) {
  4443. var newValue = values[ key ];
  4444. if ( newValue === undefined ) {
  4445. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4446. continue;
  4447. }
  4448. var currentValue = this[ key ];
  4449. if ( currentValue === undefined ) {
  4450. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4451. continue;
  4452. }
  4453. if ( currentValue && currentValue.isColor ) {
  4454. currentValue.set( newValue );
  4455. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4456. currentValue.copy( newValue );
  4457. } else if ( key === 'overdraw' ) {
  4458. // ensure overdraw is backwards-compatible with legacy boolean type
  4459. this[ key ] = Number( newValue );
  4460. } else {
  4461. this[ key ] = newValue;
  4462. }
  4463. }
  4464. },
  4465. toJSON: function ( meta ) {
  4466. var isRoot = meta === undefined;
  4467. if ( isRoot ) {
  4468. meta = {
  4469. textures: {},
  4470. images: {}
  4471. };
  4472. }
  4473. var data = {
  4474. metadata: {
  4475. version: 4.4,
  4476. type: 'Material',
  4477. generator: 'Material.toJSON'
  4478. }
  4479. };
  4480. // standard Material serialization
  4481. data.uuid = this.uuid;
  4482. data.type = this.type;
  4483. if ( this.name !== '' ) data.name = this.name;
  4484. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4485. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4486. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4487. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4488. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4489. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4490. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  4491. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  4492. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4493. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4494. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4495. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4496. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4497. data.bumpScale = this.bumpScale;
  4498. }
  4499. if ( this.normalMap && this.normalMap.isTexture ) {
  4500. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4501. data.normalScale = this.normalScale.toArray();
  4502. }
  4503. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4504. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4505. data.displacementScale = this.displacementScale;
  4506. data.displacementBias = this.displacementBias;
  4507. }
  4508. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4509. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4510. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4511. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4512. if ( this.envMap && this.envMap.isTexture ) {
  4513. data.envMap = this.envMap.toJSON( meta ).uuid;
  4514. data.reflectivity = this.reflectivity; // Scale behind envMap
  4515. }
  4516. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4517. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4518. }
  4519. if ( this.size !== undefined ) data.size = this.size;
  4520. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4521. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4522. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4523. if ( this.side !== FrontSide ) data.side = this.side;
  4524. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4525. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4526. if ( this.transparent === true ) data.transparent = this.transparent;
  4527. data.depthFunc = this.depthFunc;
  4528. data.depthTest = this.depthTest;
  4529. data.depthWrite = this.depthWrite;
  4530. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4531. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4532. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4533. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4534. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4535. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4536. data.skinning = this.skinning;
  4537. data.morphTargets = this.morphTargets;
  4538. // TODO: Copied from Object3D.toJSON
  4539. function extractFromCache( cache ) {
  4540. var values = [];
  4541. for ( var key in cache ) {
  4542. var data = cache[ key ];
  4543. delete data.metadata;
  4544. values.push( data );
  4545. }
  4546. return values;
  4547. }
  4548. if ( isRoot ) {
  4549. var textures = extractFromCache( meta.textures );
  4550. var images = extractFromCache( meta.images );
  4551. if ( textures.length > 0 ) data.textures = textures;
  4552. if ( images.length > 0 ) data.images = images;
  4553. }
  4554. return data;
  4555. },
  4556. clone: function () {
  4557. return new this.constructor().copy( this );
  4558. },
  4559. copy: function ( source ) {
  4560. this.name = source.name;
  4561. this.fog = source.fog;
  4562. this.lights = source.lights;
  4563. this.blending = source.blending;
  4564. this.side = source.side;
  4565. this.shading = source.shading;
  4566. this.vertexColors = source.vertexColors;
  4567. this.opacity = source.opacity;
  4568. this.transparent = source.transparent;
  4569. this.blendSrc = source.blendSrc;
  4570. this.blendDst = source.blendDst;
  4571. this.blendEquation = source.blendEquation;
  4572. this.blendSrcAlpha = source.blendSrcAlpha;
  4573. this.blendDstAlpha = source.blendDstAlpha;
  4574. this.blendEquationAlpha = source.blendEquationAlpha;
  4575. this.depthFunc = source.depthFunc;
  4576. this.depthTest = source.depthTest;
  4577. this.depthWrite = source.depthWrite;
  4578. this.colorWrite = source.colorWrite;
  4579. this.precision = source.precision;
  4580. this.polygonOffset = source.polygonOffset;
  4581. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4582. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4583. this.alphaTest = source.alphaTest;
  4584. this.premultipliedAlpha = source.premultipliedAlpha;
  4585. this.overdraw = source.overdraw;
  4586. this.visible = source.visible;
  4587. this.clipShadows = source.clipShadows;
  4588. this.clipIntersection = source.clipIntersection;
  4589. var srcPlanes = source.clippingPlanes,
  4590. dstPlanes = null;
  4591. if ( srcPlanes !== null ) {
  4592. var n = srcPlanes.length;
  4593. dstPlanes = new Array( n );
  4594. for ( var i = 0; i !== n; ++ i )
  4595. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4596. }
  4597. this.clippingPlanes = dstPlanes;
  4598. return this;
  4599. },
  4600. update: function () {
  4601. this.dispatchEvent( { type: 'update' } );
  4602. },
  4603. dispose: function () {
  4604. this.dispatchEvent( { type: 'dispose' } );
  4605. }
  4606. };
  4607. Object.assign( Material.prototype, EventDispatcher.prototype );
  4608. /**
  4609. * @author alteredq / http://alteredqualia.com/
  4610. *
  4611. * parameters = {
  4612. * defines: { "label" : "value" },
  4613. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4614. *
  4615. * fragmentShader: <string>,
  4616. * vertexShader: <string>,
  4617. *
  4618. * wireframe: <boolean>,
  4619. * wireframeLinewidth: <float>,
  4620. *
  4621. * lights: <bool>,
  4622. *
  4623. * skinning: <bool>,
  4624. * morphTargets: <bool>,
  4625. * morphNormals: <bool>
  4626. * }
  4627. */
  4628. function ShaderMaterial( parameters ) {
  4629. Material.call( this );
  4630. this.type = 'ShaderMaterial';
  4631. this.defines = {};
  4632. this.uniforms = {};
  4633. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4634. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4635. this.linewidth = 1;
  4636. this.wireframe = false;
  4637. this.wireframeLinewidth = 1;
  4638. this.fog = false; // set to use scene fog
  4639. this.lights = false; // set to use scene lights
  4640. this.clipping = false; // set to use user-defined clipping planes
  4641. this.skinning = false; // set to use skinning attribute streams
  4642. this.morphTargets = false; // set to use morph targets
  4643. this.morphNormals = false; // set to use morph normals
  4644. this.extensions = {
  4645. derivatives: false, // set to use derivatives
  4646. fragDepth: false, // set to use fragment depth values
  4647. drawBuffers: false, // set to use draw buffers
  4648. shaderTextureLOD: false // set to use shader texture LOD
  4649. };
  4650. // When rendered geometry doesn't include these attributes but the material does,
  4651. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4652. this.defaultAttributeValues = {
  4653. 'color': [ 1, 1, 1 ],
  4654. 'uv': [ 0, 0 ],
  4655. 'uv2': [ 0, 0 ]
  4656. };
  4657. this.index0AttributeName = undefined;
  4658. if ( parameters !== undefined ) {
  4659. if ( parameters.attributes !== undefined ) {
  4660. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4661. }
  4662. this.setValues( parameters );
  4663. }
  4664. }
  4665. ShaderMaterial.prototype = Object.create( Material.prototype );
  4666. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4667. ShaderMaterial.prototype.isShaderMaterial = true;
  4668. ShaderMaterial.prototype.copy = function ( source ) {
  4669. Material.prototype.copy.call( this, source );
  4670. this.fragmentShader = source.fragmentShader;
  4671. this.vertexShader = source.vertexShader;
  4672. this.uniforms = UniformsUtils.clone( source.uniforms );
  4673. this.defines = source.defines;
  4674. this.wireframe = source.wireframe;
  4675. this.wireframeLinewidth = source.wireframeLinewidth;
  4676. this.lights = source.lights;
  4677. this.clipping = source.clipping;
  4678. this.skinning = source.skinning;
  4679. this.morphTargets = source.morphTargets;
  4680. this.morphNormals = source.morphNormals;
  4681. this.extensions = source.extensions;
  4682. return this;
  4683. };
  4684. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4685. var data = Material.prototype.toJSON.call( this, meta );
  4686. data.uniforms = this.uniforms;
  4687. data.vertexShader = this.vertexShader;
  4688. data.fragmentShader = this.fragmentShader;
  4689. return data;
  4690. };
  4691. /**
  4692. * @author mrdoob / http://mrdoob.com/
  4693. * @author alteredq / http://alteredqualia.com/
  4694. * @author bhouston / https://clara.io
  4695. * @author WestLangley / http://github.com/WestLangley
  4696. *
  4697. * parameters = {
  4698. *
  4699. * opacity: <float>,
  4700. *
  4701. * map: new THREE.Texture( <Image> ),
  4702. *
  4703. * alphaMap: new THREE.Texture( <Image> ),
  4704. *
  4705. * displacementMap: new THREE.Texture( <Image> ),
  4706. * displacementScale: <float>,
  4707. * displacementBias: <float>,
  4708. *
  4709. * wireframe: <boolean>,
  4710. * wireframeLinewidth: <float>
  4711. * }
  4712. */
  4713. function MeshDepthMaterial( parameters ) {
  4714. Material.call( this );
  4715. this.type = 'MeshDepthMaterial';
  4716. this.depthPacking = BasicDepthPacking;
  4717. this.skinning = false;
  4718. this.morphTargets = false;
  4719. this.map = null;
  4720. this.alphaMap = null;
  4721. this.displacementMap = null;
  4722. this.displacementScale = 1;
  4723. this.displacementBias = 0;
  4724. this.wireframe = false;
  4725. this.wireframeLinewidth = 1;
  4726. this.fog = false;
  4727. this.lights = false;
  4728. this.setValues( parameters );
  4729. }
  4730. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  4731. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  4732. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  4733. MeshDepthMaterial.prototype.copy = function ( source ) {
  4734. Material.prototype.copy.call( this, source );
  4735. this.depthPacking = source.depthPacking;
  4736. this.skinning = source.skinning;
  4737. this.morphTargets = source.morphTargets;
  4738. this.map = source.map;
  4739. this.alphaMap = source.alphaMap;
  4740. this.displacementMap = source.displacementMap;
  4741. this.displacementScale = source.displacementScale;
  4742. this.displacementBias = source.displacementBias;
  4743. this.wireframe = source.wireframe;
  4744. this.wireframeLinewidth = source.wireframeLinewidth;
  4745. return this;
  4746. };
  4747. /**
  4748. * @author bhouston / http://clara.io
  4749. * @author WestLangley / http://github.com/WestLangley
  4750. */
  4751. function Box3( min, max ) {
  4752. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4753. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4754. }
  4755. Box3.prototype = {
  4756. constructor: Box3,
  4757. isBox3: true,
  4758. set: function ( min, max ) {
  4759. this.min.copy( min );
  4760. this.max.copy( max );
  4761. return this;
  4762. },
  4763. setFromArray: function ( array ) {
  4764. var minX = + Infinity;
  4765. var minY = + Infinity;
  4766. var minZ = + Infinity;
  4767. var maxX = - Infinity;
  4768. var maxY = - Infinity;
  4769. var maxZ = - Infinity;
  4770. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4771. var x = array[ i ];
  4772. var y = array[ i + 1 ];
  4773. var z = array[ i + 2 ];
  4774. if ( x < minX ) minX = x;
  4775. if ( y < minY ) minY = y;
  4776. if ( z < minZ ) minZ = z;
  4777. if ( x > maxX ) maxX = x;
  4778. if ( y > maxY ) maxY = y;
  4779. if ( z > maxZ ) maxZ = z;
  4780. }
  4781. this.min.set( minX, minY, minZ );
  4782. this.max.set( maxX, maxY, maxZ );
  4783. },
  4784. setFromBufferAttribute: function ( attribute ) {
  4785. var minX = + Infinity;
  4786. var minY = + Infinity;
  4787. var minZ = + Infinity;
  4788. var maxX = - Infinity;
  4789. var maxY = - Infinity;
  4790. var maxZ = - Infinity;
  4791. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4792. var x = attribute.getX( i );
  4793. var y = attribute.getY( i );
  4794. var z = attribute.getZ( i );
  4795. if ( x < minX ) minX = x;
  4796. if ( y < minY ) minY = y;
  4797. if ( z < minZ ) minZ = z;
  4798. if ( x > maxX ) maxX = x;
  4799. if ( y > maxY ) maxY = y;
  4800. if ( z > maxZ ) maxZ = z;
  4801. }
  4802. this.min.set( minX, minY, minZ );
  4803. this.max.set( maxX, maxY, maxZ );
  4804. },
  4805. setFromPoints: function ( points ) {
  4806. this.makeEmpty();
  4807. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4808. this.expandByPoint( points[ i ] );
  4809. }
  4810. return this;
  4811. },
  4812. setFromCenterAndSize: function () {
  4813. var v1 = new Vector3();
  4814. return function setFromCenterAndSize( center, size ) {
  4815. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4816. this.min.copy( center ).sub( halfSize );
  4817. this.max.copy( center ).add( halfSize );
  4818. return this;
  4819. };
  4820. }(),
  4821. setFromObject: function () {
  4822. // Computes the world-axis-aligned bounding box of an object (including its children),
  4823. // accounting for both the object's, and children's, world transforms
  4824. var v1 = new Vector3();
  4825. return function setFromObject( object ) {
  4826. var scope = this;
  4827. object.updateMatrixWorld( true );
  4828. this.makeEmpty();
  4829. object.traverse( function ( node ) {
  4830. var i, l;
  4831. var geometry = node.geometry;
  4832. if ( geometry !== undefined ) {
  4833. if ( geometry.isGeometry ) {
  4834. var vertices = geometry.vertices;
  4835. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4836. v1.copy( vertices[ i ] );
  4837. v1.applyMatrix4( node.matrixWorld );
  4838. scope.expandByPoint( v1 );
  4839. }
  4840. } else if ( geometry.isBufferGeometry ) {
  4841. var attribute = geometry.attributes.position;
  4842. if ( attribute !== undefined ) {
  4843. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4844. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4845. scope.expandByPoint( v1 );
  4846. }
  4847. }
  4848. }
  4849. }
  4850. } );
  4851. return this;
  4852. };
  4853. }(),
  4854. clone: function () {
  4855. return new this.constructor().copy( this );
  4856. },
  4857. copy: function ( box ) {
  4858. this.min.copy( box.min );
  4859. this.max.copy( box.max );
  4860. return this;
  4861. },
  4862. makeEmpty: function () {
  4863. this.min.x = this.min.y = this.min.z = + Infinity;
  4864. this.max.x = this.max.y = this.max.z = - Infinity;
  4865. return this;
  4866. },
  4867. isEmpty: function () {
  4868. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4869. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4870. },
  4871. getCenter: function ( optionalTarget ) {
  4872. var result = optionalTarget || new Vector3();
  4873. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4874. },
  4875. getSize: function ( optionalTarget ) {
  4876. var result = optionalTarget || new Vector3();
  4877. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4878. },
  4879. expandByPoint: function ( point ) {
  4880. this.min.min( point );
  4881. this.max.max( point );
  4882. return this;
  4883. },
  4884. expandByVector: function ( vector ) {
  4885. this.min.sub( vector );
  4886. this.max.add( vector );
  4887. return this;
  4888. },
  4889. expandByScalar: function ( scalar ) {
  4890. this.min.addScalar( - scalar );
  4891. this.max.addScalar( scalar );
  4892. return this;
  4893. },
  4894. containsPoint: function ( point ) {
  4895. return point.x < this.min.x || point.x > this.max.x ||
  4896. point.y < this.min.y || point.y > this.max.y ||
  4897. point.z < this.min.z || point.z > this.max.z ? false : true;
  4898. },
  4899. containsBox: function ( box ) {
  4900. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4901. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4902. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4903. },
  4904. getParameter: function ( point, optionalTarget ) {
  4905. // This can potentially have a divide by zero if the box
  4906. // has a size dimension of 0.
  4907. var result = optionalTarget || new Vector3();
  4908. return result.set(
  4909. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4910. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4911. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4912. );
  4913. },
  4914. intersectsBox: function ( box ) {
  4915. // using 6 splitting planes to rule out intersections.
  4916. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4917. box.max.y < this.min.y || box.min.y > this.max.y ||
  4918. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4919. },
  4920. intersectsSphere: ( function () {
  4921. var closestPoint;
  4922. return function intersectsSphere( sphere ) {
  4923. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4924. // Find the point on the AABB closest to the sphere center.
  4925. this.clampPoint( sphere.center, closestPoint );
  4926. // If that point is inside the sphere, the AABB and sphere intersect.
  4927. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4928. };
  4929. } )(),
  4930. intersectsPlane: function ( plane ) {
  4931. // We compute the minimum and maximum dot product values. If those values
  4932. // are on the same side (back or front) of the plane, then there is no intersection.
  4933. var min, max;
  4934. if ( plane.normal.x > 0 ) {
  4935. min = plane.normal.x * this.min.x;
  4936. max = plane.normal.x * this.max.x;
  4937. } else {
  4938. min = plane.normal.x * this.max.x;
  4939. max = plane.normal.x * this.min.x;
  4940. }
  4941. if ( plane.normal.y > 0 ) {
  4942. min += plane.normal.y * this.min.y;
  4943. max += plane.normal.y * this.max.y;
  4944. } else {
  4945. min += plane.normal.y * this.max.y;
  4946. max += plane.normal.y * this.min.y;
  4947. }
  4948. if ( plane.normal.z > 0 ) {
  4949. min += plane.normal.z * this.min.z;
  4950. max += plane.normal.z * this.max.z;
  4951. } else {
  4952. min += plane.normal.z * this.max.z;
  4953. max += plane.normal.z * this.min.z;
  4954. }
  4955. return ( min <= plane.constant && max >= plane.constant );
  4956. },
  4957. clampPoint: function ( point, optionalTarget ) {
  4958. var result = optionalTarget || new Vector3();
  4959. return result.copy( point ).clamp( this.min, this.max );
  4960. },
  4961. distanceToPoint: function () {
  4962. var v1 = new Vector3();
  4963. return function distanceToPoint( point ) {
  4964. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4965. return clampedPoint.sub( point ).length();
  4966. };
  4967. }(),
  4968. getBoundingSphere: function () {
  4969. var v1 = new Vector3();
  4970. return function getBoundingSphere( optionalTarget ) {
  4971. var result = optionalTarget || new Sphere();
  4972. this.getCenter( result.center );
  4973. result.radius = this.getSize( v1 ).length() * 0.5;
  4974. return result;
  4975. };
  4976. }(),
  4977. intersect: function ( box ) {
  4978. this.min.max( box.min );
  4979. this.max.min( box.max );
  4980. // 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.
  4981. if( this.isEmpty() ) this.makeEmpty();
  4982. return this;
  4983. },
  4984. union: function ( box ) {
  4985. this.min.min( box.min );
  4986. this.max.max( box.max );
  4987. return this;
  4988. },
  4989. applyMatrix4: function () {
  4990. var points = [
  4991. new Vector3(),
  4992. new Vector3(),
  4993. new Vector3(),
  4994. new Vector3(),
  4995. new Vector3(),
  4996. new Vector3(),
  4997. new Vector3(),
  4998. new Vector3()
  4999. ];
  5000. return function applyMatrix4( matrix ) {
  5001. // transform of empty box is an empty box.
  5002. if( this.isEmpty() ) return this;
  5003. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5004. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5005. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5006. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5007. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5008. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5009. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5010. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5011. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5012. this.setFromPoints( points );
  5013. return this;
  5014. };
  5015. }(),
  5016. translate: function ( offset ) {
  5017. this.min.add( offset );
  5018. this.max.add( offset );
  5019. return this;
  5020. },
  5021. equals: function ( box ) {
  5022. return box.min.equals( this.min ) && box.max.equals( this.max );
  5023. }
  5024. };
  5025. /**
  5026. * @author bhouston / http://clara.io
  5027. * @author mrdoob / http://mrdoob.com/
  5028. */
  5029. function Sphere( center, radius ) {
  5030. this.center = ( center !== undefined ) ? center : new Vector3();
  5031. this.radius = ( radius !== undefined ) ? radius : 0;
  5032. }
  5033. Sphere.prototype = {
  5034. constructor: Sphere,
  5035. set: function ( center, radius ) {
  5036. this.center.copy( center );
  5037. this.radius = radius;
  5038. return this;
  5039. },
  5040. setFromPoints: function () {
  5041. var box = new Box3();
  5042. return function setFromPoints( points, optionalCenter ) {
  5043. var center = this.center;
  5044. if ( optionalCenter !== undefined ) {
  5045. center.copy( optionalCenter );
  5046. } else {
  5047. box.setFromPoints( points ).getCenter( center );
  5048. }
  5049. var maxRadiusSq = 0;
  5050. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5051. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5052. }
  5053. this.radius = Math.sqrt( maxRadiusSq );
  5054. return this;
  5055. };
  5056. }(),
  5057. clone: function () {
  5058. return new this.constructor().copy( this );
  5059. },
  5060. copy: function ( sphere ) {
  5061. this.center.copy( sphere.center );
  5062. this.radius = sphere.radius;
  5063. return this;
  5064. },
  5065. empty: function () {
  5066. return ( this.radius <= 0 );
  5067. },
  5068. containsPoint: function ( point ) {
  5069. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5070. },
  5071. distanceToPoint: function ( point ) {
  5072. return ( point.distanceTo( this.center ) - this.radius );
  5073. },
  5074. intersectsSphere: function ( sphere ) {
  5075. var radiusSum = this.radius + sphere.radius;
  5076. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5077. },
  5078. intersectsBox: function ( box ) {
  5079. return box.intersectsSphere( this );
  5080. },
  5081. intersectsPlane: function ( plane ) {
  5082. // We use the following equation to compute the signed distance from
  5083. // the center of the sphere to the plane.
  5084. //
  5085. // distance = q * n - d
  5086. //
  5087. // If this distance is greater than the radius of the sphere,
  5088. // then there is no intersection.
  5089. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  5090. },
  5091. clampPoint: function ( point, optionalTarget ) {
  5092. var deltaLengthSq = this.center.distanceToSquared( point );
  5093. var result = optionalTarget || new Vector3();
  5094. result.copy( point );
  5095. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5096. result.sub( this.center ).normalize();
  5097. result.multiplyScalar( this.radius ).add( this.center );
  5098. }
  5099. return result;
  5100. },
  5101. getBoundingBox: function ( optionalTarget ) {
  5102. var box = optionalTarget || new Box3();
  5103. box.set( this.center, this.center );
  5104. box.expandByScalar( this.radius );
  5105. return box;
  5106. },
  5107. applyMatrix4: function ( matrix ) {
  5108. this.center.applyMatrix4( matrix );
  5109. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5110. return this;
  5111. },
  5112. translate: function ( offset ) {
  5113. this.center.add( offset );
  5114. return this;
  5115. },
  5116. equals: function ( sphere ) {
  5117. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  5118. }
  5119. };
  5120. /**
  5121. * @author alteredq / http://alteredqualia.com/
  5122. * @author WestLangley / http://github.com/WestLangley
  5123. * @author bhouston / http://clara.io
  5124. * @author tschw
  5125. */
  5126. function Matrix3() {
  5127. this.elements = new Float32Array( [
  5128. 1, 0, 0,
  5129. 0, 1, 0,
  5130. 0, 0, 1
  5131. ] );
  5132. if ( arguments.length > 0 ) {
  5133. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5134. }
  5135. }
  5136. Matrix3.prototype = {
  5137. constructor: Matrix3,
  5138. isMatrix3: true,
  5139. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5140. var te = this.elements;
  5141. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5142. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5143. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5144. return this;
  5145. },
  5146. identity: function () {
  5147. this.set(
  5148. 1, 0, 0,
  5149. 0, 1, 0,
  5150. 0, 0, 1
  5151. );
  5152. return this;
  5153. },
  5154. clone: function () {
  5155. return new this.constructor().fromArray( this.elements );
  5156. },
  5157. copy: function ( m ) {
  5158. var me = m.elements;
  5159. this.set(
  5160. me[ 0 ], me[ 3 ], me[ 6 ],
  5161. me[ 1 ], me[ 4 ], me[ 7 ],
  5162. me[ 2 ], me[ 5 ], me[ 8 ]
  5163. );
  5164. return this;
  5165. },
  5166. setFromMatrix4: function( m ) {
  5167. var me = m.elements;
  5168. this.set(
  5169. me[ 0 ], me[ 4 ], me[ 8 ],
  5170. me[ 1 ], me[ 5 ], me[ 9 ],
  5171. me[ 2 ], me[ 6 ], me[ 10 ]
  5172. );
  5173. return this;
  5174. },
  5175. applyToBufferAttribute: function () {
  5176. var v1;
  5177. return function applyToBufferAttribute( attribute ) {
  5178. if ( v1 === undefined ) v1 = new Vector3();
  5179. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5180. v1.x = attribute.getX( i );
  5181. v1.y = attribute.getY( i );
  5182. v1.z = attribute.getZ( i );
  5183. v1.applyMatrix3( this );
  5184. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5185. }
  5186. return attribute;
  5187. };
  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. fromArray: function ( array, offset ) {
  5261. if ( offset === undefined ) offset = 0;
  5262. for( var i = 0; i < 9; i ++ ) {
  5263. this.elements[ i ] = array[ i + offset ];
  5264. }
  5265. return this;
  5266. },
  5267. toArray: function ( array, offset ) {
  5268. if ( array === undefined ) array = [];
  5269. if ( offset === undefined ) offset = 0;
  5270. var te = this.elements;
  5271. array[ offset ] = te[ 0 ];
  5272. array[ offset + 1 ] = te[ 1 ];
  5273. array[ offset + 2 ] = te[ 2 ];
  5274. array[ offset + 3 ] = te[ 3 ];
  5275. array[ offset + 4 ] = te[ 4 ];
  5276. array[ offset + 5 ] = te[ 5 ];
  5277. array[ offset + 6 ] = te[ 6 ];
  5278. array[ offset + 7 ] = te[ 7 ];
  5279. array[ offset + 8 ] = te[ 8 ];
  5280. return array;
  5281. }
  5282. };
  5283. /**
  5284. * @author bhouston / http://clara.io
  5285. */
  5286. function Plane( normal, constant ) {
  5287. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5288. this.constant = ( constant !== undefined ) ? constant : 0;
  5289. }
  5290. Plane.prototype = {
  5291. constructor: Plane,
  5292. set: function ( normal, constant ) {
  5293. this.normal.copy( normal );
  5294. this.constant = constant;
  5295. return this;
  5296. },
  5297. setComponents: function ( x, y, z, w ) {
  5298. this.normal.set( x, y, z );
  5299. this.constant = w;
  5300. return this;
  5301. },
  5302. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  5303. this.normal.copy( normal );
  5304. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  5305. return this;
  5306. },
  5307. setFromCoplanarPoints: function () {
  5308. var v1 = new Vector3();
  5309. var v2 = new Vector3();
  5310. return function setFromCoplanarPoints( a, b, c ) {
  5311. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  5312. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5313. this.setFromNormalAndCoplanarPoint( normal, a );
  5314. return this;
  5315. };
  5316. }(),
  5317. clone: function () {
  5318. return new this.constructor().copy( this );
  5319. },
  5320. copy: function ( plane ) {
  5321. this.normal.copy( plane.normal );
  5322. this.constant = plane.constant;
  5323. return this;
  5324. },
  5325. normalize: function () {
  5326. // Note: will lead to a divide by zero if the plane is invalid.
  5327. var inverseNormalLength = 1.0 / this.normal.length();
  5328. this.normal.multiplyScalar( inverseNormalLength );
  5329. this.constant *= inverseNormalLength;
  5330. return this;
  5331. },
  5332. negate: function () {
  5333. this.constant *= - 1;
  5334. this.normal.negate();
  5335. return this;
  5336. },
  5337. distanceToPoint: function ( point ) {
  5338. return this.normal.dot( point ) + this.constant;
  5339. },
  5340. distanceToSphere: function ( sphere ) {
  5341. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5342. },
  5343. projectPoint: function ( point, optionalTarget ) {
  5344. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  5345. },
  5346. orthoPoint: function ( point, optionalTarget ) {
  5347. var perpendicularMagnitude = this.distanceToPoint( point );
  5348. var result = optionalTarget || new Vector3();
  5349. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  5350. },
  5351. intersectLine: function () {
  5352. var v1 = new Vector3();
  5353. return function intersectLine( line, optionalTarget ) {
  5354. var result = optionalTarget || new Vector3();
  5355. var direction = line.delta( v1 );
  5356. var denominator = this.normal.dot( direction );
  5357. if ( denominator === 0 ) {
  5358. // line is coplanar, return origin
  5359. if ( this.distanceToPoint( line.start ) === 0 ) {
  5360. return result.copy( line.start );
  5361. }
  5362. // Unsure if this is the correct method to handle this case.
  5363. return undefined;
  5364. }
  5365. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5366. if ( t < 0 || t > 1 ) {
  5367. return undefined;
  5368. }
  5369. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  5370. };
  5371. }(),
  5372. intersectsLine: function ( line ) {
  5373. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5374. var startSign = this.distanceToPoint( line.start );
  5375. var endSign = this.distanceToPoint( line.end );
  5376. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5377. },
  5378. intersectsBox: function ( box ) {
  5379. return box.intersectsPlane( this );
  5380. },
  5381. intersectsSphere: function ( sphere ) {
  5382. return sphere.intersectsPlane( this );
  5383. },
  5384. coplanarPoint: function ( optionalTarget ) {
  5385. var result = optionalTarget || new Vector3();
  5386. return result.copy( this.normal ).multiplyScalar( - this.constant );
  5387. },
  5388. applyMatrix4: function () {
  5389. var v1 = new Vector3();
  5390. var m1 = new Matrix3();
  5391. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  5392. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  5393. // transform normal based on theory here:
  5394. // http://www.songho.ca/opengl/gl_normaltransform.html
  5395. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  5396. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5397. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  5398. this.constant = - referencePoint.dot( normal );
  5399. return this;
  5400. };
  5401. }(),
  5402. translate: function ( offset ) {
  5403. this.constant = this.constant - offset.dot( this.normal );
  5404. return this;
  5405. },
  5406. equals: function ( plane ) {
  5407. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5408. }
  5409. };
  5410. /**
  5411. * @author mrdoob / http://mrdoob.com/
  5412. * @author alteredq / http://alteredqualia.com/
  5413. * @author bhouston / http://clara.io
  5414. */
  5415. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  5416. this.planes = [
  5417. ( p0 !== undefined ) ? p0 : new Plane(),
  5418. ( p1 !== undefined ) ? p1 : new Plane(),
  5419. ( p2 !== undefined ) ? p2 : new Plane(),
  5420. ( p3 !== undefined ) ? p3 : new Plane(),
  5421. ( p4 !== undefined ) ? p4 : new Plane(),
  5422. ( p5 !== undefined ) ? p5 : new Plane()
  5423. ];
  5424. }
  5425. Frustum.prototype = {
  5426. constructor: Frustum,
  5427. set: function ( p0, p1, p2, p3, p4, p5 ) {
  5428. var planes = this.planes;
  5429. planes[ 0 ].copy( p0 );
  5430. planes[ 1 ].copy( p1 );
  5431. planes[ 2 ].copy( p2 );
  5432. planes[ 3 ].copy( p3 );
  5433. planes[ 4 ].copy( p4 );
  5434. planes[ 5 ].copy( p5 );
  5435. return this;
  5436. },
  5437. clone: function () {
  5438. return new this.constructor().copy( this );
  5439. },
  5440. copy: function ( frustum ) {
  5441. var planes = this.planes;
  5442. for ( var i = 0; i < 6; i ++ ) {
  5443. planes[ i ].copy( frustum.planes[ i ] );
  5444. }
  5445. return this;
  5446. },
  5447. setFromMatrix: function ( m ) {
  5448. var planes = this.planes;
  5449. var me = m.elements;
  5450. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  5451. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  5452. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  5453. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  5454. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  5455. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  5456. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  5457. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  5458. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  5459. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  5460. return this;
  5461. },
  5462. intersectsObject: function () {
  5463. var sphere = new Sphere();
  5464. return function intersectsObject( object ) {
  5465. var geometry = object.geometry;
  5466. if ( geometry.boundingSphere === null )
  5467. geometry.computeBoundingSphere();
  5468. sphere.copy( geometry.boundingSphere )
  5469. .applyMatrix4( object.matrixWorld );
  5470. return this.intersectsSphere( sphere );
  5471. };
  5472. }(),
  5473. intersectsSprite: function () {
  5474. var sphere = new Sphere();
  5475. return function intersectsSprite( sprite ) {
  5476. sphere.center.set( 0, 0, 0 );
  5477. sphere.radius = 0.7071067811865476;
  5478. sphere.applyMatrix4( sprite.matrixWorld );
  5479. return this.intersectsSphere( sphere );
  5480. };
  5481. }(),
  5482. intersectsSphere: function ( sphere ) {
  5483. var planes = this.planes;
  5484. var center = sphere.center;
  5485. var negRadius = - sphere.radius;
  5486. for ( var i = 0; i < 6; i ++ ) {
  5487. var distance = planes[ i ].distanceToPoint( center );
  5488. if ( distance < negRadius ) {
  5489. return false;
  5490. }
  5491. }
  5492. return true;
  5493. },
  5494. intersectsBox: function () {
  5495. var p1 = new Vector3(),
  5496. p2 = new Vector3();
  5497. return function intersectsBox( box ) {
  5498. var planes = this.planes;
  5499. for ( var i = 0; i < 6 ; i ++ ) {
  5500. var plane = planes[ i ];
  5501. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  5502. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  5503. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  5504. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  5505. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  5506. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  5507. var d1 = plane.distanceToPoint( p1 );
  5508. var d2 = plane.distanceToPoint( p2 );
  5509. // if both outside plane, no intersection
  5510. if ( d1 < 0 && d2 < 0 ) {
  5511. return false;
  5512. }
  5513. }
  5514. return true;
  5515. };
  5516. }(),
  5517. containsPoint: function ( point ) {
  5518. var planes = this.planes;
  5519. for ( var i = 0; i < 6; i ++ ) {
  5520. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  5521. return false;
  5522. }
  5523. }
  5524. return true;
  5525. }
  5526. };
  5527. /**
  5528. * @author alteredq / http://alteredqualia.com/
  5529. * @author mrdoob / http://mrdoob.com/
  5530. */
  5531. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  5532. var _gl = _renderer.context,
  5533. _state = _renderer.state,
  5534. _frustum = new Frustum(),
  5535. _projScreenMatrix = new Matrix4(),
  5536. _lightShadows = _lights.shadows,
  5537. _shadowMapSize = new Vector2(),
  5538. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  5539. _lookTarget = new Vector3(),
  5540. _lightPositionWorld = new Vector3(),
  5541. _renderList = [],
  5542. _MorphingFlag = 1,
  5543. _SkinningFlag = 2,
  5544. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  5545. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  5546. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  5547. _materialCache = {};
  5548. var cubeDirections = [
  5549. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  5550. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  5551. ];
  5552. var cubeUps = [
  5553. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  5554. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  5555. ];
  5556. var cube2DViewPorts = [
  5557. new Vector4(), new Vector4(), new Vector4(),
  5558. new Vector4(), new Vector4(), new Vector4()
  5559. ];
  5560. // init
  5561. var depthMaterialTemplate = new MeshDepthMaterial();
  5562. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  5563. depthMaterialTemplate.clipping = true;
  5564. var distanceShader = ShaderLib[ "distanceRGBA" ];
  5565. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  5566. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  5567. var useMorphing = ( i & _MorphingFlag ) !== 0;
  5568. var useSkinning = ( i & _SkinningFlag ) !== 0;
  5569. var depthMaterial = depthMaterialTemplate.clone();
  5570. depthMaterial.morphTargets = useMorphing;
  5571. depthMaterial.skinning = useSkinning;
  5572. _depthMaterials[ i ] = depthMaterial;
  5573. var distanceMaterial = new ShaderMaterial( {
  5574. defines: {
  5575. 'USE_SHADOWMAP': ''
  5576. },
  5577. uniforms: distanceUniforms,
  5578. vertexShader: distanceShader.vertexShader,
  5579. fragmentShader: distanceShader.fragmentShader,
  5580. morphTargets: useMorphing,
  5581. skinning: useSkinning,
  5582. clipping: true
  5583. } );
  5584. _distanceMaterials[ i ] = distanceMaterial;
  5585. }
  5586. //
  5587. var scope = this;
  5588. this.enabled = false;
  5589. this.autoUpdate = true;
  5590. this.needsUpdate = false;
  5591. this.type = PCFShadowMap;
  5592. this.renderReverseSided = true;
  5593. this.renderSingleSided = true;
  5594. this.render = function ( scene, camera ) {
  5595. if ( scope.enabled === false ) return;
  5596. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5597. if ( _lightShadows.length === 0 ) return;
  5598. // Set GL state for depth map.
  5599. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5600. _state.disable( _gl.BLEND );
  5601. _state.setDepthTest( true );
  5602. _state.setScissorTest( false );
  5603. // render depth map
  5604. var faceCount, isPointLight;
  5605. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  5606. var light = _lightShadows[ i ];
  5607. var shadow = light.shadow;
  5608. if ( shadow === undefined ) {
  5609. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  5610. continue;
  5611. }
  5612. var shadowCamera = shadow.camera;
  5613. _shadowMapSize.copy( shadow.mapSize );
  5614. _shadowMapSize.min( _maxShadowMapSize );
  5615. if ( light && light.isPointLight ) {
  5616. faceCount = 6;
  5617. isPointLight = true;
  5618. var vpWidth = _shadowMapSize.x;
  5619. var vpHeight = _shadowMapSize.y;
  5620. // These viewports map a cube-map onto a 2D texture with the
  5621. // following orientation:
  5622. //
  5623. // xzXZ
  5624. // y Y
  5625. //
  5626. // X - Positive x direction
  5627. // x - Negative x direction
  5628. // Y - Positive y direction
  5629. // y - Negative y direction
  5630. // Z - Positive z direction
  5631. // z - Negative z direction
  5632. // positive X
  5633. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  5634. // negative X
  5635. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  5636. // positive Z
  5637. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  5638. // negative Z
  5639. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  5640. // positive Y
  5641. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  5642. // negative Y
  5643. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  5644. _shadowMapSize.x *= 4.0;
  5645. _shadowMapSize.y *= 2.0;
  5646. } else {
  5647. faceCount = 1;
  5648. isPointLight = false;
  5649. }
  5650. if ( shadow.map === null ) {
  5651. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  5652. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  5653. shadowCamera.updateProjectionMatrix();
  5654. }
  5655. if ( shadow.isSpotLightShadow ) {
  5656. shadow.update( light );
  5657. }
  5658. // TODO (abelnation / sam-g-steel): is this needed?
  5659. if (shadow && shadow.isRectAreaLightShadow ) {
  5660. shadow.update( light );
  5661. }
  5662. var shadowMap = shadow.map;
  5663. var shadowMatrix = shadow.matrix;
  5664. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5665. shadowCamera.position.copy( _lightPositionWorld );
  5666. _renderer.setRenderTarget( shadowMap );
  5667. _renderer.clear();
  5668. // render shadow map for each cube face (if omni-directional) or
  5669. // run a single pass if not
  5670. for ( var face = 0; face < faceCount; face ++ ) {
  5671. if ( isPointLight ) {
  5672. _lookTarget.copy( shadowCamera.position );
  5673. _lookTarget.add( cubeDirections[ face ] );
  5674. shadowCamera.up.copy( cubeUps[ face ] );
  5675. shadowCamera.lookAt( _lookTarget );
  5676. var vpDimensions = cube2DViewPorts[ face ];
  5677. _state.viewport( vpDimensions );
  5678. } else {
  5679. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  5680. shadowCamera.lookAt( _lookTarget );
  5681. }
  5682. shadowCamera.updateMatrixWorld();
  5683. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  5684. // compute shadow matrix
  5685. shadowMatrix.set(
  5686. 0.5, 0.0, 0.0, 0.5,
  5687. 0.0, 0.5, 0.0, 0.5,
  5688. 0.0, 0.0, 0.5, 0.5,
  5689. 0.0, 0.0, 0.0, 1.0
  5690. );
  5691. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  5692. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  5693. // update camera matrices and frustum
  5694. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  5695. _frustum.setFromMatrix( _projScreenMatrix );
  5696. // set object matrices & frustum culling
  5697. _renderList.length = 0;
  5698. projectObject( scene, camera, shadowCamera );
  5699. // render shadow map
  5700. // render regular objects
  5701. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  5702. var object = _renderList[ j ];
  5703. var geometry = _objects.update( object );
  5704. var material = object.material;
  5705. if ( material && material.isMultiMaterial ) {
  5706. var groups = geometry.groups;
  5707. var materials = material.materials;
  5708. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  5709. var group = groups[ k ];
  5710. var groupMaterial = materials[ group.materialIndex ];
  5711. if ( groupMaterial.visible === true ) {
  5712. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  5713. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5714. }
  5715. }
  5716. } else {
  5717. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  5718. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5719. }
  5720. }
  5721. }
  5722. }
  5723. // Restore GL state.
  5724. var clearColor = _renderer.getClearColor(),
  5725. clearAlpha = _renderer.getClearAlpha();
  5726. _renderer.setClearColor( clearColor, clearAlpha );
  5727. scope.needsUpdate = false;
  5728. };
  5729. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  5730. var geometry = object.geometry;
  5731. var result = null;
  5732. var materialVariants = _depthMaterials;
  5733. var customMaterial = object.customDepthMaterial;
  5734. if ( isPointLight ) {
  5735. materialVariants = _distanceMaterials;
  5736. customMaterial = object.customDistanceMaterial;
  5737. }
  5738. if ( ! customMaterial ) {
  5739. var useMorphing = false;
  5740. if ( material.morphTargets ) {
  5741. if ( geometry && geometry.isBufferGeometry ) {
  5742. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  5743. } else if ( geometry && geometry.isGeometry ) {
  5744. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  5745. }
  5746. }
  5747. var useSkinning = object.isSkinnedMesh && material.skinning;
  5748. var variantIndex = 0;
  5749. if ( useMorphing ) variantIndex |= _MorphingFlag;
  5750. if ( useSkinning ) variantIndex |= _SkinningFlag;
  5751. result = materialVariants[ variantIndex ];
  5752. } else {
  5753. result = customMaterial;
  5754. }
  5755. if ( _renderer.localClippingEnabled &&
  5756. material.clipShadows === true &&
  5757. material.clippingPlanes.length !== 0 ) {
  5758. // in this case we need a unique material instance reflecting the
  5759. // appropriate state
  5760. var keyA = result.uuid, keyB = material.uuid;
  5761. var materialsForVariant = _materialCache[ keyA ];
  5762. if ( materialsForVariant === undefined ) {
  5763. materialsForVariant = {};
  5764. _materialCache[ keyA ] = materialsForVariant;
  5765. }
  5766. var cachedMaterial = materialsForVariant[ keyB ];
  5767. if ( cachedMaterial === undefined ) {
  5768. cachedMaterial = result.clone();
  5769. materialsForVariant[ keyB ] = cachedMaterial;
  5770. }
  5771. result = cachedMaterial;
  5772. }
  5773. result.visible = material.visible;
  5774. result.wireframe = material.wireframe;
  5775. var side = material.side;
  5776. if ( scope.renderSingleSided && side == DoubleSide ) {
  5777. side = FrontSide;
  5778. }
  5779. if ( scope.renderReverseSided ) {
  5780. if ( side === FrontSide ) side = BackSide;
  5781. else if ( side === BackSide ) side = FrontSide;
  5782. }
  5783. result.side = side;
  5784. result.clipShadows = material.clipShadows;
  5785. result.clippingPlanes = material.clippingPlanes;
  5786. result.wireframeLinewidth = material.wireframeLinewidth;
  5787. result.linewidth = material.linewidth;
  5788. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  5789. result.uniforms.lightPos.value.copy( lightPositionWorld );
  5790. }
  5791. return result;
  5792. }
  5793. function projectObject( object, camera, shadowCamera ) {
  5794. if ( object.visible === false ) return;
  5795. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  5796. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5797. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  5798. var material = object.material;
  5799. if ( material.visible === true ) {
  5800. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5801. _renderList.push( object );
  5802. }
  5803. }
  5804. }
  5805. var children = object.children;
  5806. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5807. projectObject( children[ i ], camera, shadowCamera );
  5808. }
  5809. }
  5810. }
  5811. /**
  5812. * @author bhouston / http://clara.io
  5813. */
  5814. function Ray( origin, direction ) {
  5815. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  5816. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  5817. }
  5818. Ray.prototype = {
  5819. constructor: Ray,
  5820. set: function ( origin, direction ) {
  5821. this.origin.copy( origin );
  5822. this.direction.copy( direction );
  5823. return this;
  5824. },
  5825. clone: function () {
  5826. return new this.constructor().copy( this );
  5827. },
  5828. copy: function ( ray ) {
  5829. this.origin.copy( ray.origin );
  5830. this.direction.copy( ray.direction );
  5831. return this;
  5832. },
  5833. at: function ( t, optionalTarget ) {
  5834. var result = optionalTarget || new Vector3();
  5835. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  5836. },
  5837. lookAt: function ( v ) {
  5838. this.direction.copy( v ).sub( this.origin ).normalize();
  5839. return this;
  5840. },
  5841. recast: function () {
  5842. var v1 = new Vector3();
  5843. return function recast( t ) {
  5844. this.origin.copy( this.at( t, v1 ) );
  5845. return this;
  5846. };
  5847. }(),
  5848. closestPointToPoint: function ( point, optionalTarget ) {
  5849. var result = optionalTarget || new Vector3();
  5850. result.subVectors( point, this.origin );
  5851. var directionDistance = result.dot( this.direction );
  5852. if ( directionDistance < 0 ) {
  5853. return result.copy( this.origin );
  5854. }
  5855. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5856. },
  5857. distanceToPoint: function ( point ) {
  5858. return Math.sqrt( this.distanceSqToPoint( point ) );
  5859. },
  5860. distanceSqToPoint: function () {
  5861. var v1 = new Vector3();
  5862. return function distanceSqToPoint( point ) {
  5863. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  5864. // point behind the ray
  5865. if ( directionDistance < 0 ) {
  5866. return this.origin.distanceToSquared( point );
  5867. }
  5868. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  5869. return v1.distanceToSquared( point );
  5870. };
  5871. }(),
  5872. distanceSqToSegment: function () {
  5873. var segCenter = new Vector3();
  5874. var segDir = new Vector3();
  5875. var diff = new Vector3();
  5876. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  5877. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5878. // It returns the min distance between the ray and the segment
  5879. // defined by v0 and v1
  5880. // It can also set two optional targets :
  5881. // - The closest point on the ray
  5882. // - The closest point on the segment
  5883. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  5884. segDir.copy( v1 ).sub( v0 ).normalize();
  5885. diff.copy( this.origin ).sub( segCenter );
  5886. var segExtent = v0.distanceTo( v1 ) * 0.5;
  5887. var a01 = - this.direction.dot( segDir );
  5888. var b0 = diff.dot( this.direction );
  5889. var b1 = - diff.dot( segDir );
  5890. var c = diff.lengthSq();
  5891. var det = Math.abs( 1 - a01 * a01 );
  5892. var s0, s1, sqrDist, extDet;
  5893. if ( det > 0 ) {
  5894. // The ray and segment are not parallel.
  5895. s0 = a01 * b1 - b0;
  5896. s1 = a01 * b0 - b1;
  5897. extDet = segExtent * det;
  5898. if ( s0 >= 0 ) {
  5899. if ( s1 >= - extDet ) {
  5900. if ( s1 <= extDet ) {
  5901. // region 0
  5902. // Minimum at interior points of ray and segment.
  5903. var invDet = 1 / det;
  5904. s0 *= invDet;
  5905. s1 *= invDet;
  5906. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  5907. } else {
  5908. // region 1
  5909. s1 = segExtent;
  5910. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5911. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5912. }
  5913. } else {
  5914. // region 5
  5915. s1 = - segExtent;
  5916. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5917. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5918. }
  5919. } else {
  5920. if ( s1 <= - extDet ) {
  5921. // region 4
  5922. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  5923. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5924. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5925. } else if ( s1 <= extDet ) {
  5926. // region 3
  5927. s0 = 0;
  5928. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5929. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  5930. } else {
  5931. // region 2
  5932. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  5933. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  5934. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5935. }
  5936. }
  5937. } else {
  5938. // Ray and segment are parallel.
  5939. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  5940. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  5941. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  5942. }
  5943. if ( optionalPointOnRay ) {
  5944. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  5945. }
  5946. if ( optionalPointOnSegment ) {
  5947. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  5948. }
  5949. return sqrDist;
  5950. };
  5951. }(),
  5952. intersectSphere: function () {
  5953. var v1 = new Vector3();
  5954. return function intersectSphere( sphere, optionalTarget ) {
  5955. v1.subVectors( sphere.center, this.origin );
  5956. var tca = v1.dot( this.direction );
  5957. var d2 = v1.dot( v1 ) - tca * tca;
  5958. var radius2 = sphere.radius * sphere.radius;
  5959. if ( d2 > radius2 ) return null;
  5960. var thc = Math.sqrt( radius2 - d2 );
  5961. // t0 = first intersect point - entrance on front of sphere
  5962. var t0 = tca - thc;
  5963. // t1 = second intersect point - exit point on back of sphere
  5964. var t1 = tca + thc;
  5965. // test to see if both t0 and t1 are behind the ray - if so, return null
  5966. if ( t0 < 0 && t1 < 0 ) return null;
  5967. // test to see if t0 is behind the ray:
  5968. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5969. // in order to always return an intersect point that is in front of the ray.
  5970. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  5971. // else t0 is in front of the ray, so return the first collision point scaled by t0
  5972. return this.at( t0, optionalTarget );
  5973. };
  5974. }(),
  5975. intersectsSphere: function ( sphere ) {
  5976. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  5977. },
  5978. distanceToPlane: function ( plane ) {
  5979. var denominator = plane.normal.dot( this.direction );
  5980. if ( denominator === 0 ) {
  5981. // line is coplanar, return origin
  5982. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  5983. return 0;
  5984. }
  5985. // Null is preferable to undefined since undefined means.... it is undefined
  5986. return null;
  5987. }
  5988. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  5989. // Return if the ray never intersects the plane
  5990. return t >= 0 ? t : null;
  5991. },
  5992. intersectPlane: function ( plane, optionalTarget ) {
  5993. var t = this.distanceToPlane( plane );
  5994. if ( t === null ) {
  5995. return null;
  5996. }
  5997. return this.at( t, optionalTarget );
  5998. },
  5999. intersectsPlane: function ( plane ) {
  6000. // check if the ray lies on the plane first
  6001. var distToPoint = plane.distanceToPoint( this.origin );
  6002. if ( distToPoint === 0 ) {
  6003. return true;
  6004. }
  6005. var denominator = plane.normal.dot( this.direction );
  6006. if ( denominator * distToPoint < 0 ) {
  6007. return true;
  6008. }
  6009. // ray origin is behind the plane (and is pointing behind it)
  6010. return false;
  6011. },
  6012. intersectBox: function ( box, optionalTarget ) {
  6013. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6014. var invdirx = 1 / this.direction.x,
  6015. invdiry = 1 / this.direction.y,
  6016. invdirz = 1 / this.direction.z;
  6017. var origin = this.origin;
  6018. if ( invdirx >= 0 ) {
  6019. tmin = ( box.min.x - origin.x ) * invdirx;
  6020. tmax = ( box.max.x - origin.x ) * invdirx;
  6021. } else {
  6022. tmin = ( box.max.x - origin.x ) * invdirx;
  6023. tmax = ( box.min.x - origin.x ) * invdirx;
  6024. }
  6025. if ( invdiry >= 0 ) {
  6026. tymin = ( box.min.y - origin.y ) * invdiry;
  6027. tymax = ( box.max.y - origin.y ) * invdiry;
  6028. } else {
  6029. tymin = ( box.max.y - origin.y ) * invdiry;
  6030. tymax = ( box.min.y - origin.y ) * invdiry;
  6031. }
  6032. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6033. // These lines also handle the case where tmin or tmax is NaN
  6034. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6035. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6036. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6037. if ( invdirz >= 0 ) {
  6038. tzmin = ( box.min.z - origin.z ) * invdirz;
  6039. tzmax = ( box.max.z - origin.z ) * invdirz;
  6040. } else {
  6041. tzmin = ( box.max.z - origin.z ) * invdirz;
  6042. tzmax = ( box.min.z - origin.z ) * invdirz;
  6043. }
  6044. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6045. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6046. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6047. //return point closest to the ray (positive side)
  6048. if ( tmax < 0 ) return null;
  6049. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6050. },
  6051. intersectsBox: ( function () {
  6052. var v = new Vector3();
  6053. return function intersectsBox( box ) {
  6054. return this.intersectBox( box, v ) !== null;
  6055. };
  6056. } )(),
  6057. intersectTriangle: function () {
  6058. // Compute the offset origin, edges, and normal.
  6059. var diff = new Vector3();
  6060. var edge1 = new Vector3();
  6061. var edge2 = new Vector3();
  6062. var normal = new Vector3();
  6063. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6064. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6065. edge1.subVectors( b, a );
  6066. edge2.subVectors( c, a );
  6067. normal.crossVectors( edge1, edge2 );
  6068. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6069. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6070. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6071. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6072. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6073. var DdN = this.direction.dot( normal );
  6074. var sign;
  6075. if ( DdN > 0 ) {
  6076. if ( backfaceCulling ) return null;
  6077. sign = 1;
  6078. } else if ( DdN < 0 ) {
  6079. sign = - 1;
  6080. DdN = - DdN;
  6081. } else {
  6082. return null;
  6083. }
  6084. diff.subVectors( this.origin, a );
  6085. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6086. // b1 < 0, no intersection
  6087. if ( DdQxE2 < 0 ) {
  6088. return null;
  6089. }
  6090. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6091. // b2 < 0, no intersection
  6092. if ( DdE1xQ < 0 ) {
  6093. return null;
  6094. }
  6095. // b1+b2 > 1, no intersection
  6096. if ( DdQxE2 + DdE1xQ > DdN ) {
  6097. return null;
  6098. }
  6099. // Line intersects triangle, check if ray does.
  6100. var QdN = - sign * diff.dot( normal );
  6101. // t < 0, no intersection
  6102. if ( QdN < 0 ) {
  6103. return null;
  6104. }
  6105. // Ray intersects triangle.
  6106. return this.at( QdN / DdN, optionalTarget );
  6107. };
  6108. }(),
  6109. applyMatrix4: function ( matrix4 ) {
  6110. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6111. this.origin.applyMatrix4( matrix4 );
  6112. this.direction.sub( this.origin );
  6113. this.direction.normalize();
  6114. return this;
  6115. },
  6116. equals: function ( ray ) {
  6117. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6118. }
  6119. };
  6120. /**
  6121. * @author mrdoob / http://mrdoob.com/
  6122. * @author WestLangley / http://github.com/WestLangley
  6123. * @author bhouston / http://clara.io
  6124. */
  6125. function Euler( x, y, z, order ) {
  6126. this._x = x || 0;
  6127. this._y = y || 0;
  6128. this._z = z || 0;
  6129. this._order = order || Euler.DefaultOrder;
  6130. }
  6131. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  6132. Euler.DefaultOrder = 'XYZ';
  6133. Euler.prototype = {
  6134. constructor: Euler,
  6135. isEuler: true,
  6136. get x () {
  6137. return this._x;
  6138. },
  6139. set x ( value ) {
  6140. this._x = value;
  6141. this.onChangeCallback();
  6142. },
  6143. get y () {
  6144. return this._y;
  6145. },
  6146. set y ( value ) {
  6147. this._y = value;
  6148. this.onChangeCallback();
  6149. },
  6150. get z () {
  6151. return this._z;
  6152. },
  6153. set z ( value ) {
  6154. this._z = value;
  6155. this.onChangeCallback();
  6156. },
  6157. get order () {
  6158. return this._order;
  6159. },
  6160. set order ( value ) {
  6161. this._order = value;
  6162. this.onChangeCallback();
  6163. },
  6164. set: function ( x, y, z, order ) {
  6165. this._x = x;
  6166. this._y = y;
  6167. this._z = z;
  6168. this._order = order || this._order;
  6169. this.onChangeCallback();
  6170. return this;
  6171. },
  6172. clone: function () {
  6173. return new this.constructor( this._x, this._y, this._z, this._order );
  6174. },
  6175. copy: function ( euler ) {
  6176. this._x = euler._x;
  6177. this._y = euler._y;
  6178. this._z = euler._z;
  6179. this._order = euler._order;
  6180. this.onChangeCallback();
  6181. return this;
  6182. },
  6183. setFromRotationMatrix: function ( m, order, update ) {
  6184. var clamp = _Math.clamp;
  6185. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6186. var te = m.elements;
  6187. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  6188. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  6189. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6190. order = order || this._order;
  6191. if ( order === 'XYZ' ) {
  6192. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  6193. if ( Math.abs( m13 ) < 0.99999 ) {
  6194. this._x = Math.atan2( - m23, m33 );
  6195. this._z = Math.atan2( - m12, m11 );
  6196. } else {
  6197. this._x = Math.atan2( m32, m22 );
  6198. this._z = 0;
  6199. }
  6200. } else if ( order === 'YXZ' ) {
  6201. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  6202. if ( Math.abs( m23 ) < 0.99999 ) {
  6203. this._y = Math.atan2( m13, m33 );
  6204. this._z = Math.atan2( m21, m22 );
  6205. } else {
  6206. this._y = Math.atan2( - m31, m11 );
  6207. this._z = 0;
  6208. }
  6209. } else if ( order === 'ZXY' ) {
  6210. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  6211. if ( Math.abs( m32 ) < 0.99999 ) {
  6212. this._y = Math.atan2( - m31, m33 );
  6213. this._z = Math.atan2( - m12, m22 );
  6214. } else {
  6215. this._y = 0;
  6216. this._z = Math.atan2( m21, m11 );
  6217. }
  6218. } else if ( order === 'ZYX' ) {
  6219. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  6220. if ( Math.abs( m31 ) < 0.99999 ) {
  6221. this._x = Math.atan2( m32, m33 );
  6222. this._z = Math.atan2( m21, m11 );
  6223. } else {
  6224. this._x = 0;
  6225. this._z = Math.atan2( - m12, m22 );
  6226. }
  6227. } else if ( order === 'YZX' ) {
  6228. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  6229. if ( Math.abs( m21 ) < 0.99999 ) {
  6230. this._x = Math.atan2( - m23, m22 );
  6231. this._y = Math.atan2( - m31, m11 );
  6232. } else {
  6233. this._x = 0;
  6234. this._y = Math.atan2( m13, m33 );
  6235. }
  6236. } else if ( order === 'XZY' ) {
  6237. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  6238. if ( Math.abs( m12 ) < 0.99999 ) {
  6239. this._x = Math.atan2( m32, m22 );
  6240. this._y = Math.atan2( m13, m11 );
  6241. } else {
  6242. this._x = Math.atan2( - m23, m33 );
  6243. this._y = 0;
  6244. }
  6245. } else {
  6246. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  6247. }
  6248. this._order = order;
  6249. if ( update !== false ) this.onChangeCallback();
  6250. return this;
  6251. },
  6252. setFromQuaternion: function () {
  6253. var matrix;
  6254. return function setFromQuaternion( q, order, update ) {
  6255. if ( matrix === undefined ) matrix = new Matrix4();
  6256. matrix.makeRotationFromQuaternion( q );
  6257. return this.setFromRotationMatrix( matrix, order, update );
  6258. };
  6259. }(),
  6260. setFromVector3: function ( v, order ) {
  6261. return this.set( v.x, v.y, v.z, order || this._order );
  6262. },
  6263. reorder: function () {
  6264. // WARNING: this discards revolution information -bhouston
  6265. var q = new Quaternion();
  6266. return function reorder( newOrder ) {
  6267. q.setFromEuler( this );
  6268. return this.setFromQuaternion( q, newOrder );
  6269. };
  6270. }(),
  6271. equals: function ( euler ) {
  6272. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  6273. },
  6274. fromArray: function ( array ) {
  6275. this._x = array[ 0 ];
  6276. this._y = array[ 1 ];
  6277. this._z = array[ 2 ];
  6278. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  6279. this.onChangeCallback();
  6280. return this;
  6281. },
  6282. toArray: function ( array, offset ) {
  6283. if ( array === undefined ) array = [];
  6284. if ( offset === undefined ) offset = 0;
  6285. array[ offset ] = this._x;
  6286. array[ offset + 1 ] = this._y;
  6287. array[ offset + 2 ] = this._z;
  6288. array[ offset + 3 ] = this._order;
  6289. return array;
  6290. },
  6291. toVector3: function ( optionalResult ) {
  6292. if ( optionalResult ) {
  6293. return optionalResult.set( this._x, this._y, this._z );
  6294. } else {
  6295. return new Vector3( this._x, this._y, this._z );
  6296. }
  6297. },
  6298. onChange: function ( callback ) {
  6299. this.onChangeCallback = callback;
  6300. return this;
  6301. },
  6302. onChangeCallback: function () {}
  6303. };
  6304. /**
  6305. * @author mrdoob / http://mrdoob.com/
  6306. */
  6307. function Layers() {
  6308. this.mask = 1;
  6309. }
  6310. Layers.prototype = {
  6311. constructor: Layers,
  6312. set: function ( channel ) {
  6313. this.mask = 1 << channel;
  6314. },
  6315. enable: function ( channel ) {
  6316. this.mask |= 1 << channel;
  6317. },
  6318. toggle: function ( channel ) {
  6319. this.mask ^= 1 << channel;
  6320. },
  6321. disable: function ( channel ) {
  6322. this.mask &= ~ ( 1 << channel );
  6323. },
  6324. test: function ( layers ) {
  6325. return ( this.mask & layers.mask ) !== 0;
  6326. }
  6327. };
  6328. /**
  6329. * @author mrdoob / http://mrdoob.com/
  6330. * @author mikael emtinger / http://gomo.se/
  6331. * @author alteredq / http://alteredqualia.com/
  6332. * @author WestLangley / http://github.com/WestLangley
  6333. * @author elephantatwork / www.elephantatwork.ch
  6334. */
  6335. var object3DId = 0;
  6336. function Object3D() {
  6337. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  6338. this.uuid = _Math.generateUUID();
  6339. this.name = '';
  6340. this.type = 'Object3D';
  6341. this.parent = null;
  6342. this.children = [];
  6343. this.up = Object3D.DefaultUp.clone();
  6344. var position = new Vector3();
  6345. var rotation = new Euler();
  6346. var quaternion = new Quaternion();
  6347. var scale = new Vector3( 1, 1, 1 );
  6348. function onRotationChange() {
  6349. quaternion.setFromEuler( rotation, false );
  6350. }
  6351. function onQuaternionChange() {
  6352. rotation.setFromQuaternion( quaternion, undefined, false );
  6353. }
  6354. rotation.onChange( onRotationChange );
  6355. quaternion.onChange( onQuaternionChange );
  6356. Object.defineProperties( this, {
  6357. position: {
  6358. enumerable: true,
  6359. value: position
  6360. },
  6361. rotation: {
  6362. enumerable: true,
  6363. value: rotation
  6364. },
  6365. quaternion: {
  6366. enumerable: true,
  6367. value: quaternion
  6368. },
  6369. scale: {
  6370. enumerable: true,
  6371. value: scale
  6372. },
  6373. modelViewMatrix: {
  6374. value: new Matrix4()
  6375. },
  6376. normalMatrix: {
  6377. value: new Matrix3()
  6378. }
  6379. } );
  6380. this.matrix = new Matrix4();
  6381. this.matrixWorld = new Matrix4();
  6382. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  6383. this.matrixWorldNeedsUpdate = false;
  6384. this.layers = new Layers();
  6385. this.visible = true;
  6386. this.castShadow = false;
  6387. this.receiveShadow = false;
  6388. this.frustumCulled = true;
  6389. this.renderOrder = 0;
  6390. this.userData = {};
  6391. this.onBeforeRender = function () {};
  6392. this.onAfterRender = function () {};
  6393. }
  6394. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  6395. Object3D.DefaultMatrixAutoUpdate = true;
  6396. Object3D.prototype = {
  6397. constructor: Object3D,
  6398. isObject3D: true,
  6399. applyMatrix: function ( matrix ) {
  6400. this.matrix.multiplyMatrices( matrix, this.matrix );
  6401. this.matrix.decompose( this.position, this.quaternion, this.scale );
  6402. },
  6403. setRotationFromAxisAngle: function ( axis, angle ) {
  6404. // assumes axis is normalized
  6405. this.quaternion.setFromAxisAngle( axis, angle );
  6406. },
  6407. setRotationFromEuler: function ( euler ) {
  6408. this.quaternion.setFromEuler( euler, true );
  6409. },
  6410. setRotationFromMatrix: function ( m ) {
  6411. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6412. this.quaternion.setFromRotationMatrix( m );
  6413. },
  6414. setRotationFromQuaternion: function ( q ) {
  6415. // assumes q is normalized
  6416. this.quaternion.copy( q );
  6417. },
  6418. rotateOnAxis: function () {
  6419. // rotate object on axis in object space
  6420. // axis is assumed to be normalized
  6421. var q1 = new Quaternion();
  6422. return function rotateOnAxis( axis, angle ) {
  6423. q1.setFromAxisAngle( axis, angle );
  6424. this.quaternion.multiply( q1 );
  6425. return this;
  6426. };
  6427. }(),
  6428. rotateX: function () {
  6429. var v1 = new Vector3( 1, 0, 0 );
  6430. return function rotateX( angle ) {
  6431. return this.rotateOnAxis( v1, angle );
  6432. };
  6433. }(),
  6434. rotateY: function () {
  6435. var v1 = new Vector3( 0, 1, 0 );
  6436. return function rotateY( angle ) {
  6437. return this.rotateOnAxis( v1, angle );
  6438. };
  6439. }(),
  6440. rotateZ: function () {
  6441. var v1 = new Vector3( 0, 0, 1 );
  6442. return function rotateZ( angle ) {
  6443. return this.rotateOnAxis( v1, angle );
  6444. };
  6445. }(),
  6446. translateOnAxis: function () {
  6447. // translate object by distance along axis in object space
  6448. // axis is assumed to be normalized
  6449. var v1 = new Vector3();
  6450. return function translateOnAxis( axis, distance ) {
  6451. v1.copy( axis ).applyQuaternion( this.quaternion );
  6452. this.position.add( v1.multiplyScalar( distance ) );
  6453. return this;
  6454. };
  6455. }(),
  6456. translateX: function () {
  6457. var v1 = new Vector3( 1, 0, 0 );
  6458. return function translateX( distance ) {
  6459. return this.translateOnAxis( v1, distance );
  6460. };
  6461. }(),
  6462. translateY: function () {
  6463. var v1 = new Vector3( 0, 1, 0 );
  6464. return function translateY( distance ) {
  6465. return this.translateOnAxis( v1, distance );
  6466. };
  6467. }(),
  6468. translateZ: function () {
  6469. var v1 = new Vector3( 0, 0, 1 );
  6470. return function translateZ( distance ) {
  6471. return this.translateOnAxis( v1, distance );
  6472. };
  6473. }(),
  6474. localToWorld: function ( vector ) {
  6475. return vector.applyMatrix4( this.matrixWorld );
  6476. },
  6477. worldToLocal: function () {
  6478. var m1 = new Matrix4();
  6479. return function worldToLocal( vector ) {
  6480. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  6481. };
  6482. }(),
  6483. lookAt: function () {
  6484. // This routine does not support objects with rotated and/or translated parent(s)
  6485. var m1 = new Matrix4();
  6486. return function lookAt( vector ) {
  6487. m1.lookAt( vector, this.position, this.up );
  6488. this.quaternion.setFromRotationMatrix( m1 );
  6489. };
  6490. }(),
  6491. add: function ( object ) {
  6492. if ( arguments.length > 1 ) {
  6493. for ( var i = 0; i < arguments.length; i ++ ) {
  6494. this.add( arguments[ i ] );
  6495. }
  6496. return this;
  6497. }
  6498. if ( object === this ) {
  6499. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  6500. return this;
  6501. }
  6502. if ( ( object && object.isObject3D ) ) {
  6503. if ( object.parent !== null ) {
  6504. object.parent.remove( object );
  6505. }
  6506. object.parent = this;
  6507. object.dispatchEvent( { type: 'added' } );
  6508. this.children.push( object );
  6509. } else {
  6510. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  6511. }
  6512. return this;
  6513. },
  6514. remove: function ( object ) {
  6515. if ( arguments.length > 1 ) {
  6516. for ( var i = 0; i < arguments.length; i ++ ) {
  6517. this.remove( arguments[ i ] );
  6518. }
  6519. }
  6520. var index = this.children.indexOf( object );
  6521. if ( index !== - 1 ) {
  6522. object.parent = null;
  6523. object.dispatchEvent( { type: 'removed' } );
  6524. this.children.splice( index, 1 );
  6525. }
  6526. },
  6527. getObjectById: function ( id ) {
  6528. return this.getObjectByProperty( 'id', id );
  6529. },
  6530. getObjectByName: function ( name ) {
  6531. return this.getObjectByProperty( 'name', name );
  6532. },
  6533. getObjectByProperty: function ( name, value ) {
  6534. if ( this[ name ] === value ) return this;
  6535. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6536. var child = this.children[ i ];
  6537. var object = child.getObjectByProperty( name, value );
  6538. if ( object !== undefined ) {
  6539. return object;
  6540. }
  6541. }
  6542. return undefined;
  6543. },
  6544. getWorldPosition: function ( optionalTarget ) {
  6545. var result = optionalTarget || new Vector3();
  6546. this.updateMatrixWorld( true );
  6547. return result.setFromMatrixPosition( this.matrixWorld );
  6548. },
  6549. getWorldQuaternion: function () {
  6550. var position = new Vector3();
  6551. var scale = new Vector3();
  6552. return function getWorldQuaternion( optionalTarget ) {
  6553. var result = optionalTarget || new Quaternion();
  6554. this.updateMatrixWorld( true );
  6555. this.matrixWorld.decompose( position, result, scale );
  6556. return result;
  6557. };
  6558. }(),
  6559. getWorldRotation: function () {
  6560. var quaternion = new Quaternion();
  6561. return function getWorldRotation( optionalTarget ) {
  6562. var result = optionalTarget || new Euler();
  6563. this.getWorldQuaternion( quaternion );
  6564. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  6565. };
  6566. }(),
  6567. getWorldScale: function () {
  6568. var position = new Vector3();
  6569. var quaternion = new Quaternion();
  6570. return function getWorldScale( optionalTarget ) {
  6571. var result = optionalTarget || new Vector3();
  6572. this.updateMatrixWorld( true );
  6573. this.matrixWorld.decompose( position, quaternion, result );
  6574. return result;
  6575. };
  6576. }(),
  6577. getWorldDirection: function () {
  6578. var quaternion = new Quaternion();
  6579. return function getWorldDirection( optionalTarget ) {
  6580. var result = optionalTarget || new Vector3();
  6581. this.getWorldQuaternion( quaternion );
  6582. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  6583. };
  6584. }(),
  6585. raycast: function () {},
  6586. traverse: function ( callback ) {
  6587. callback( this );
  6588. var children = this.children;
  6589. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6590. children[ i ].traverse( callback );
  6591. }
  6592. },
  6593. traverseVisible: function ( callback ) {
  6594. if ( this.visible === false ) return;
  6595. callback( this );
  6596. var children = this.children;
  6597. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6598. children[ i ].traverseVisible( callback );
  6599. }
  6600. },
  6601. traverseAncestors: function ( callback ) {
  6602. var parent = this.parent;
  6603. if ( parent !== null ) {
  6604. callback( parent );
  6605. parent.traverseAncestors( callback );
  6606. }
  6607. },
  6608. updateMatrix: function () {
  6609. this.matrix.compose( this.position, this.quaternion, this.scale );
  6610. this.matrixWorldNeedsUpdate = true;
  6611. },
  6612. updateMatrixWorld: function ( force ) {
  6613. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  6614. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  6615. if ( this.parent === null ) {
  6616. this.matrixWorld.copy( this.matrix );
  6617. } else {
  6618. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  6619. }
  6620. this.matrixWorldNeedsUpdate = false;
  6621. force = true;
  6622. }
  6623. // update children
  6624. var children = this.children;
  6625. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6626. children[ i ].updateMatrixWorld( force );
  6627. }
  6628. },
  6629. toJSON: function ( meta ) {
  6630. // meta is '' when called from JSON.stringify
  6631. var isRootObject = ( meta === undefined || meta === '' );
  6632. var output = {};
  6633. // meta is a hash used to collect geometries, materials.
  6634. // not providing it implies that this is the root object
  6635. // being serialized.
  6636. if ( isRootObject ) {
  6637. // initialize meta obj
  6638. meta = {
  6639. geometries: {},
  6640. materials: {},
  6641. textures: {},
  6642. images: {}
  6643. };
  6644. output.metadata = {
  6645. version: 4.4,
  6646. type: 'Object',
  6647. generator: 'Object3D.toJSON'
  6648. };
  6649. }
  6650. // standard Object3D serialization
  6651. var object = {};
  6652. object.uuid = this.uuid;
  6653. object.type = this.type;
  6654. if ( this.name !== '' ) object.name = this.name;
  6655. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  6656. if ( this.castShadow === true ) object.castShadow = true;
  6657. if ( this.receiveShadow === true ) object.receiveShadow = true;
  6658. if ( this.visible === false ) object.visible = false;
  6659. object.matrix = this.matrix.toArray();
  6660. //
  6661. if ( this.geometry !== undefined ) {
  6662. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  6663. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  6664. }
  6665. object.geometry = this.geometry.uuid;
  6666. }
  6667. if ( this.material !== undefined ) {
  6668. if ( meta.materials[ this.material.uuid ] === undefined ) {
  6669. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  6670. }
  6671. object.material = this.material.uuid;
  6672. }
  6673. //
  6674. if ( this.children.length > 0 ) {
  6675. object.children = [];
  6676. for ( var i = 0; i < this.children.length; i ++ ) {
  6677. object.children.push( this.children[ i ].toJSON( meta ).object );
  6678. }
  6679. }
  6680. if ( isRootObject ) {
  6681. var geometries = extractFromCache( meta.geometries );
  6682. var materials = extractFromCache( meta.materials );
  6683. var textures = extractFromCache( meta.textures );
  6684. var images = extractFromCache( meta.images );
  6685. if ( geometries.length > 0 ) output.geometries = geometries;
  6686. if ( materials.length > 0 ) output.materials = materials;
  6687. if ( textures.length > 0 ) output.textures = textures;
  6688. if ( images.length > 0 ) output.images = images;
  6689. }
  6690. output.object = object;
  6691. return output;
  6692. // extract data from the cache hash
  6693. // remove metadata on each item
  6694. // and return as array
  6695. function extractFromCache( cache ) {
  6696. var values = [];
  6697. for ( var key in cache ) {
  6698. var data = cache[ key ];
  6699. delete data.metadata;
  6700. values.push( data );
  6701. }
  6702. return values;
  6703. }
  6704. },
  6705. clone: function ( recursive ) {
  6706. return new this.constructor().copy( this, recursive );
  6707. },
  6708. copy: function ( source, recursive ) {
  6709. if ( recursive === undefined ) recursive = true;
  6710. this.name = source.name;
  6711. this.up.copy( source.up );
  6712. this.position.copy( source.position );
  6713. this.quaternion.copy( source.quaternion );
  6714. this.scale.copy( source.scale );
  6715. this.matrix.copy( source.matrix );
  6716. this.matrixWorld.copy( source.matrixWorld );
  6717. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6718. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6719. this.layers.mask = source.layers.mask;
  6720. this.visible = source.visible;
  6721. this.castShadow = source.castShadow;
  6722. this.receiveShadow = source.receiveShadow;
  6723. this.frustumCulled = source.frustumCulled;
  6724. this.renderOrder = source.renderOrder;
  6725. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6726. if ( recursive === true ) {
  6727. for ( var i = 0; i < source.children.length; i ++ ) {
  6728. var child = source.children[ i ];
  6729. this.add( child.clone() );
  6730. }
  6731. }
  6732. return this;
  6733. }
  6734. };
  6735. Object.assign( Object3D.prototype, EventDispatcher.prototype );
  6736. /**
  6737. * @author bhouston / http://clara.io
  6738. */
  6739. function Line3( start, end ) {
  6740. this.start = ( start !== undefined ) ? start : new Vector3();
  6741. this.end = ( end !== undefined ) ? end : new Vector3();
  6742. }
  6743. Line3.prototype = {
  6744. constructor: Line3,
  6745. set: function ( start, end ) {
  6746. this.start.copy( start );
  6747. this.end.copy( end );
  6748. return this;
  6749. },
  6750. clone: function () {
  6751. return new this.constructor().copy( this );
  6752. },
  6753. copy: function ( line ) {
  6754. this.start.copy( line.start );
  6755. this.end.copy( line.end );
  6756. return this;
  6757. },
  6758. getCenter: function ( optionalTarget ) {
  6759. var result = optionalTarget || new Vector3();
  6760. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  6761. },
  6762. delta: function ( optionalTarget ) {
  6763. var result = optionalTarget || new Vector3();
  6764. return result.subVectors( this.end, this.start );
  6765. },
  6766. distanceSq: function () {
  6767. return this.start.distanceToSquared( this.end );
  6768. },
  6769. distance: function () {
  6770. return this.start.distanceTo( this.end );
  6771. },
  6772. at: function ( t, optionalTarget ) {
  6773. var result = optionalTarget || new Vector3();
  6774. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6775. },
  6776. closestPointToPointParameter: function () {
  6777. var startP = new Vector3();
  6778. var startEnd = new Vector3();
  6779. return function closestPointToPointParameter( point, clampToLine ) {
  6780. startP.subVectors( point, this.start );
  6781. startEnd.subVectors( this.end, this.start );
  6782. var startEnd2 = startEnd.dot( startEnd );
  6783. var startEnd_startP = startEnd.dot( startP );
  6784. var t = startEnd_startP / startEnd2;
  6785. if ( clampToLine ) {
  6786. t = _Math.clamp( t, 0, 1 );
  6787. }
  6788. return t;
  6789. };
  6790. }(),
  6791. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  6792. var t = this.closestPointToPointParameter( point, clampToLine );
  6793. var result = optionalTarget || new Vector3();
  6794. return this.delta( result ).multiplyScalar( t ).add( this.start );
  6795. },
  6796. applyMatrix4: function ( matrix ) {
  6797. this.start.applyMatrix4( matrix );
  6798. this.end.applyMatrix4( matrix );
  6799. return this;
  6800. },
  6801. equals: function ( line ) {
  6802. return line.start.equals( this.start ) && line.end.equals( this.end );
  6803. }
  6804. };
  6805. /**
  6806. * @author bhouston / http://clara.io
  6807. * @author mrdoob / http://mrdoob.com/
  6808. */
  6809. function Triangle( a, b, c ) {
  6810. this.a = ( a !== undefined ) ? a : new Vector3();
  6811. this.b = ( b !== undefined ) ? b : new Vector3();
  6812. this.c = ( c !== undefined ) ? c : new Vector3();
  6813. }
  6814. Triangle.normal = function () {
  6815. var v0 = new Vector3();
  6816. return function normal( a, b, c, optionalTarget ) {
  6817. var result = optionalTarget || new Vector3();
  6818. result.subVectors( c, b );
  6819. v0.subVectors( a, b );
  6820. result.cross( v0 );
  6821. var resultLengthSq = result.lengthSq();
  6822. if ( resultLengthSq > 0 ) {
  6823. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  6824. }
  6825. return result.set( 0, 0, 0 );
  6826. };
  6827. }();
  6828. // static/instance method to calculate barycentric coordinates
  6829. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6830. Triangle.barycoordFromPoint = function () {
  6831. var v0 = new Vector3();
  6832. var v1 = new Vector3();
  6833. var v2 = new Vector3();
  6834. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  6835. v0.subVectors( c, a );
  6836. v1.subVectors( b, a );
  6837. v2.subVectors( point, a );
  6838. var dot00 = v0.dot( v0 );
  6839. var dot01 = v0.dot( v1 );
  6840. var dot02 = v0.dot( v2 );
  6841. var dot11 = v1.dot( v1 );
  6842. var dot12 = v1.dot( v2 );
  6843. var denom = ( dot00 * dot11 - dot01 * dot01 );
  6844. var result = optionalTarget || new Vector3();
  6845. // collinear or singular triangle
  6846. if ( denom === 0 ) {
  6847. // arbitrary location outside of triangle?
  6848. // not sure if this is the best idea, maybe should be returning undefined
  6849. return result.set( - 2, - 1, - 1 );
  6850. }
  6851. var invDenom = 1 / denom;
  6852. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6853. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6854. // barycentric coordinates must always sum to 1
  6855. return result.set( 1 - u - v, v, u );
  6856. };
  6857. }();
  6858. Triangle.containsPoint = function () {
  6859. var v1 = new Vector3();
  6860. return function containsPoint( point, a, b, c ) {
  6861. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  6862. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  6863. };
  6864. }();
  6865. Triangle.prototype = {
  6866. constructor: Triangle,
  6867. set: function ( a, b, c ) {
  6868. this.a.copy( a );
  6869. this.b.copy( b );
  6870. this.c.copy( c );
  6871. return this;
  6872. },
  6873. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  6874. this.a.copy( points[ i0 ] );
  6875. this.b.copy( points[ i1 ] );
  6876. this.c.copy( points[ i2 ] );
  6877. return this;
  6878. },
  6879. clone: function () {
  6880. return new this.constructor().copy( this );
  6881. },
  6882. copy: function ( triangle ) {
  6883. this.a.copy( triangle.a );
  6884. this.b.copy( triangle.b );
  6885. this.c.copy( triangle.c );
  6886. return this;
  6887. },
  6888. area: function () {
  6889. var v0 = new Vector3();
  6890. var v1 = new Vector3();
  6891. return function area() {
  6892. v0.subVectors( this.c, this.b );
  6893. v1.subVectors( this.a, this.b );
  6894. return v0.cross( v1 ).length() * 0.5;
  6895. };
  6896. }(),
  6897. midpoint: function ( optionalTarget ) {
  6898. var result = optionalTarget || new Vector3();
  6899. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6900. },
  6901. normal: function ( optionalTarget ) {
  6902. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  6903. },
  6904. plane: function ( optionalTarget ) {
  6905. var result = optionalTarget || new Plane();
  6906. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  6907. },
  6908. barycoordFromPoint: function ( point, optionalTarget ) {
  6909. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  6910. },
  6911. containsPoint: function ( point ) {
  6912. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6913. },
  6914. closestPointToPoint: function () {
  6915. var plane, edgeList, projectedPoint, closestPoint;
  6916. return function closestPointToPoint( point, optionalTarget ) {
  6917. if ( plane === undefined ) {
  6918. plane = new Plane();
  6919. edgeList = [ new Line3(), new Line3(), new Line3() ];
  6920. projectedPoint = new Vector3();
  6921. closestPoint = new Vector3();
  6922. }
  6923. var result = optionalTarget || new Vector3();
  6924. var minDistance = Infinity;
  6925. // project the point onto the plane of the triangle
  6926. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  6927. plane.projectPoint( point, projectedPoint );
  6928. // check if the projection lies within the triangle
  6929. if( this.containsPoint( projectedPoint ) === true ) {
  6930. // if so, this is the closest point
  6931. result.copy( projectedPoint );
  6932. } else {
  6933. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  6934. edgeList[ 0 ].set( this.a, this.b );
  6935. edgeList[ 1 ].set( this.b, this.c );
  6936. edgeList[ 2 ].set( this.c, this.a );
  6937. for( var i = 0; i < edgeList.length; i ++ ) {
  6938. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  6939. var distance = projectedPoint.distanceToSquared( closestPoint );
  6940. if( distance < minDistance ) {
  6941. minDistance = distance;
  6942. result.copy( closestPoint );
  6943. }
  6944. }
  6945. }
  6946. return result;
  6947. };
  6948. }(),
  6949. equals: function ( triangle ) {
  6950. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6951. }
  6952. };
  6953. /**
  6954. * @author mrdoob / http://mrdoob.com/
  6955. * @author alteredq / http://alteredqualia.com/
  6956. */
  6957. function Face3( a, b, c, normal, color, materialIndex ) {
  6958. this.a = a;
  6959. this.b = b;
  6960. this.c = c;
  6961. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  6962. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  6963. this.color = (color && color.isColor) ? color : new Color();
  6964. this.vertexColors = Array.isArray( color ) ? color : [];
  6965. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6966. }
  6967. Face3.prototype = {
  6968. constructor: Face3,
  6969. clone: function () {
  6970. return new this.constructor().copy( this );
  6971. },
  6972. copy: function ( source ) {
  6973. this.a = source.a;
  6974. this.b = source.b;
  6975. this.c = source.c;
  6976. this.normal.copy( source.normal );
  6977. this.color.copy( source.color );
  6978. this.materialIndex = source.materialIndex;
  6979. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  6980. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  6981. }
  6982. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  6983. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  6984. }
  6985. return this;
  6986. }
  6987. };
  6988. /**
  6989. * @author mrdoob / http://mrdoob.com/
  6990. * @author alteredq / http://alteredqualia.com/
  6991. *
  6992. * parameters = {
  6993. * color: <hex>,
  6994. * opacity: <float>,
  6995. * map: new THREE.Texture( <Image> ),
  6996. *
  6997. * lightMap: new THREE.Texture( <Image> ),
  6998. * lightMapIntensity: <float>
  6999. *
  7000. * aoMap: new THREE.Texture( <Image> ),
  7001. * aoMapIntensity: <float>
  7002. *
  7003. * specularMap: new THREE.Texture( <Image> ),
  7004. *
  7005. * alphaMap: new THREE.Texture( <Image> ),
  7006. *
  7007. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7008. * combine: THREE.Multiply,
  7009. * reflectivity: <float>,
  7010. * refractionRatio: <float>,
  7011. *
  7012. * shading: THREE.SmoothShading,
  7013. * depthTest: <bool>,
  7014. * depthWrite: <bool>,
  7015. *
  7016. * wireframe: <boolean>,
  7017. * wireframeLinewidth: <float>,
  7018. *
  7019. * skinning: <bool>,
  7020. * morphTargets: <bool>
  7021. * }
  7022. */
  7023. function MeshBasicMaterial( parameters ) {
  7024. Material.call( this );
  7025. this.type = 'MeshBasicMaterial';
  7026. this.color = new Color( 0xffffff ); // emissive
  7027. this.map = null;
  7028. this.lightMap = null;
  7029. this.lightMapIntensity = 1.0;
  7030. this.aoMap = null;
  7031. this.aoMapIntensity = 1.0;
  7032. this.specularMap = null;
  7033. this.alphaMap = null;
  7034. this.envMap = null;
  7035. this.combine = MultiplyOperation;
  7036. this.reflectivity = 1;
  7037. this.refractionRatio = 0.98;
  7038. this.wireframe = false;
  7039. this.wireframeLinewidth = 1;
  7040. this.wireframeLinecap = 'round';
  7041. this.wireframeLinejoin = 'round';
  7042. this.skinning = false;
  7043. this.morphTargets = false;
  7044. this.lights = false;
  7045. this.setValues( parameters );
  7046. }
  7047. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  7048. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7049. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7050. MeshBasicMaterial.prototype.copy = function ( source ) {
  7051. Material.prototype.copy.call( this, source );
  7052. this.color.copy( source.color );
  7053. this.map = source.map;
  7054. this.lightMap = source.lightMap;
  7055. this.lightMapIntensity = source.lightMapIntensity;
  7056. this.aoMap = source.aoMap;
  7057. this.aoMapIntensity = source.aoMapIntensity;
  7058. this.specularMap = source.specularMap;
  7059. this.alphaMap = source.alphaMap;
  7060. this.envMap = source.envMap;
  7061. this.combine = source.combine;
  7062. this.reflectivity = source.reflectivity;
  7063. this.refractionRatio = source.refractionRatio;
  7064. this.wireframe = source.wireframe;
  7065. this.wireframeLinewidth = source.wireframeLinewidth;
  7066. this.wireframeLinecap = source.wireframeLinecap;
  7067. this.wireframeLinejoin = source.wireframeLinejoin;
  7068. this.skinning = source.skinning;
  7069. this.morphTargets = source.morphTargets;
  7070. return this;
  7071. };
  7072. /**
  7073. * @author mrdoob / http://mrdoob.com/
  7074. */
  7075. function BufferAttribute( array, itemSize, normalized ) {
  7076. if ( Array.isArray( array ) ) {
  7077. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7078. }
  7079. this.uuid = _Math.generateUUID();
  7080. this.array = array;
  7081. this.itemSize = itemSize;
  7082. this.count = array !== undefined ? array.length / itemSize : 0;
  7083. this.normalized = normalized === true;
  7084. this.dynamic = false;
  7085. this.updateRange = { offset: 0, count: - 1 };
  7086. this.onUploadCallback = function () {};
  7087. this.version = 0;
  7088. }
  7089. BufferAttribute.prototype = {
  7090. constructor: BufferAttribute,
  7091. isBufferAttribute: true,
  7092. set needsUpdate( value ) {
  7093. if ( value === true ) this.version ++;
  7094. },
  7095. setArray: function ( array ) {
  7096. if ( Array.isArray( array ) ) {
  7097. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7098. }
  7099. this.count = array !== undefined ? array.length / this.itemSize : 0;
  7100. this.array = array;
  7101. },
  7102. setDynamic: function ( value ) {
  7103. this.dynamic = value;
  7104. return this;
  7105. },
  7106. copy: function ( source ) {
  7107. this.array = new source.array.constructor( source.array );
  7108. this.itemSize = source.itemSize;
  7109. this.count = source.count;
  7110. this.normalized = source.normalized;
  7111. this.dynamic = source.dynamic;
  7112. return this;
  7113. },
  7114. copyAt: function ( index1, attribute, index2 ) {
  7115. index1 *= this.itemSize;
  7116. index2 *= attribute.itemSize;
  7117. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7118. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7119. }
  7120. return this;
  7121. },
  7122. copyArray: function ( array ) {
  7123. this.array.set( array );
  7124. return this;
  7125. },
  7126. copyColorsArray: function ( colors ) {
  7127. var array = this.array, offset = 0;
  7128. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7129. var color = colors[ i ];
  7130. if ( color === undefined ) {
  7131. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7132. color = new Color();
  7133. }
  7134. array[ offset ++ ] = color.r;
  7135. array[ offset ++ ] = color.g;
  7136. array[ offset ++ ] = color.b;
  7137. }
  7138. return this;
  7139. },
  7140. copyIndicesArray: function ( indices ) {
  7141. var array = this.array, offset = 0;
  7142. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7143. var index = indices[ i ];
  7144. array[ offset ++ ] = index.a;
  7145. array[ offset ++ ] = index.b;
  7146. array[ offset ++ ] = index.c;
  7147. }
  7148. return this;
  7149. },
  7150. copyVector2sArray: function ( vectors ) {
  7151. var array = this.array, offset = 0;
  7152. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7153. var vector = vectors[ i ];
  7154. if ( vector === undefined ) {
  7155. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7156. vector = new Vector2();
  7157. }
  7158. array[ offset ++ ] = vector.x;
  7159. array[ offset ++ ] = vector.y;
  7160. }
  7161. return this;
  7162. },
  7163. copyVector3sArray: function ( vectors ) {
  7164. var array = this.array, offset = 0;
  7165. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7166. var vector = vectors[ i ];
  7167. if ( vector === undefined ) {
  7168. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7169. vector = new Vector3();
  7170. }
  7171. array[ offset ++ ] = vector.x;
  7172. array[ offset ++ ] = vector.y;
  7173. array[ offset ++ ] = vector.z;
  7174. }
  7175. return this;
  7176. },
  7177. copyVector4sArray: function ( vectors ) {
  7178. var array = this.array, offset = 0;
  7179. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7180. var vector = vectors[ i ];
  7181. if ( vector === undefined ) {
  7182. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7183. vector = new Vector4();
  7184. }
  7185. array[ offset ++ ] = vector.x;
  7186. array[ offset ++ ] = vector.y;
  7187. array[ offset ++ ] = vector.z;
  7188. array[ offset ++ ] = vector.w;
  7189. }
  7190. return this;
  7191. },
  7192. set: function ( value, offset ) {
  7193. if ( offset === undefined ) offset = 0;
  7194. this.array.set( value, offset );
  7195. return this;
  7196. },
  7197. getX: function ( index ) {
  7198. return this.array[ index * this.itemSize ];
  7199. },
  7200. setX: function ( index, x ) {
  7201. this.array[ index * this.itemSize ] = x;
  7202. return this;
  7203. },
  7204. getY: function ( index ) {
  7205. return this.array[ index * this.itemSize + 1 ];
  7206. },
  7207. setY: function ( index, y ) {
  7208. this.array[ index * this.itemSize + 1 ] = y;
  7209. return this;
  7210. },
  7211. getZ: function ( index ) {
  7212. return this.array[ index * this.itemSize + 2 ];
  7213. },
  7214. setZ: function ( index, z ) {
  7215. this.array[ index * this.itemSize + 2 ] = z;
  7216. return this;
  7217. },
  7218. getW: function ( index ) {
  7219. return this.array[ index * this.itemSize + 3 ];
  7220. },
  7221. setW: function ( index, w ) {
  7222. this.array[ index * this.itemSize + 3 ] = w;
  7223. return this;
  7224. },
  7225. setXY: function ( index, x, y ) {
  7226. index *= this.itemSize;
  7227. this.array[ index + 0 ] = x;
  7228. this.array[ index + 1 ] = y;
  7229. return this;
  7230. },
  7231. setXYZ: function ( index, x, y, z ) {
  7232. index *= this.itemSize;
  7233. this.array[ index + 0 ] = x;
  7234. this.array[ index + 1 ] = y;
  7235. this.array[ index + 2 ] = z;
  7236. return this;
  7237. },
  7238. setXYZW: function ( index, x, y, z, w ) {
  7239. index *= this.itemSize;
  7240. this.array[ index + 0 ] = x;
  7241. this.array[ index + 1 ] = y;
  7242. this.array[ index + 2 ] = z;
  7243. this.array[ index + 3 ] = w;
  7244. return this;
  7245. },
  7246. onUpload: function ( callback ) {
  7247. this.onUploadCallback = callback;
  7248. return this;
  7249. },
  7250. clone: function () {
  7251. return new this.constructor().copy( this );
  7252. }
  7253. };
  7254. //
  7255. function Int8BufferAttribute( array, itemSize ) {
  7256. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  7257. }
  7258. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7259. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7260. function Uint8BufferAttribute( array, itemSize ) {
  7261. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  7262. }
  7263. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7264. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7265. function Uint8ClampedBufferAttribute( array, itemSize ) {
  7266. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  7267. }
  7268. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7269. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7270. function Int16BufferAttribute( array, itemSize ) {
  7271. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  7272. }
  7273. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7274. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7275. function Uint16BufferAttribute( array, itemSize ) {
  7276. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  7277. }
  7278. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7279. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7280. function Int32BufferAttribute( array, itemSize ) {
  7281. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  7282. }
  7283. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7284. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7285. function Uint32BufferAttribute( array, itemSize ) {
  7286. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  7287. }
  7288. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7289. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7290. function Float32BufferAttribute( array, itemSize ) {
  7291. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  7292. }
  7293. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7294. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7295. function Float64BufferAttribute( array, itemSize ) {
  7296. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  7297. }
  7298. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7299. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7300. /**
  7301. * @author mrdoob / http://mrdoob.com/
  7302. */
  7303. function DirectGeometry() {
  7304. this.indices = [];
  7305. this.vertices = [];
  7306. this.normals = [];
  7307. this.colors = [];
  7308. this.uvs = [];
  7309. this.uvs2 = [];
  7310. this.groups = [];
  7311. this.morphTargets = {};
  7312. this.skinWeights = [];
  7313. this.skinIndices = [];
  7314. // this.lineDistances = [];
  7315. this.boundingBox = null;
  7316. this.boundingSphere = null;
  7317. // update flags
  7318. this.verticesNeedUpdate = false;
  7319. this.normalsNeedUpdate = false;
  7320. this.colorsNeedUpdate = false;
  7321. this.uvsNeedUpdate = false;
  7322. this.groupsNeedUpdate = false;
  7323. }
  7324. Object.assign( DirectGeometry.prototype, {
  7325. computeGroups: function ( geometry ) {
  7326. var group;
  7327. var groups = [];
  7328. var materialIndex = undefined;
  7329. var faces = geometry.faces;
  7330. for ( var i = 0; i < faces.length; i ++ ) {
  7331. var face = faces[ i ];
  7332. // materials
  7333. if ( face.materialIndex !== materialIndex ) {
  7334. materialIndex = face.materialIndex;
  7335. if ( group !== undefined ) {
  7336. group.count = ( i * 3 ) - group.start;
  7337. groups.push( group );
  7338. }
  7339. group = {
  7340. start: i * 3,
  7341. materialIndex: materialIndex
  7342. };
  7343. }
  7344. }
  7345. if ( group !== undefined ) {
  7346. group.count = ( i * 3 ) - group.start;
  7347. groups.push( group );
  7348. }
  7349. this.groups = groups;
  7350. },
  7351. fromGeometry: function ( geometry ) {
  7352. var faces = geometry.faces;
  7353. var vertices = geometry.vertices;
  7354. var faceVertexUvs = geometry.faceVertexUvs;
  7355. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  7356. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  7357. // morphs
  7358. var morphTargets = geometry.morphTargets;
  7359. var morphTargetsLength = morphTargets.length;
  7360. var morphTargetsPosition;
  7361. if ( morphTargetsLength > 0 ) {
  7362. morphTargetsPosition = [];
  7363. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  7364. morphTargetsPosition[ i ] = [];
  7365. }
  7366. this.morphTargets.position = morphTargetsPosition;
  7367. }
  7368. var morphNormals = geometry.morphNormals;
  7369. var morphNormalsLength = morphNormals.length;
  7370. var morphTargetsNormal;
  7371. if ( morphNormalsLength > 0 ) {
  7372. morphTargetsNormal = [];
  7373. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  7374. morphTargetsNormal[ i ] = [];
  7375. }
  7376. this.morphTargets.normal = morphTargetsNormal;
  7377. }
  7378. // skins
  7379. var skinIndices = geometry.skinIndices;
  7380. var skinWeights = geometry.skinWeights;
  7381. var hasSkinIndices = skinIndices.length === vertices.length;
  7382. var hasSkinWeights = skinWeights.length === vertices.length;
  7383. //
  7384. for ( var i = 0; i < faces.length; i ++ ) {
  7385. var face = faces[ i ];
  7386. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  7387. var vertexNormals = face.vertexNormals;
  7388. if ( vertexNormals.length === 3 ) {
  7389. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  7390. } else {
  7391. var normal = face.normal;
  7392. this.normals.push( normal, normal, normal );
  7393. }
  7394. var vertexColors = face.vertexColors;
  7395. if ( vertexColors.length === 3 ) {
  7396. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  7397. } else {
  7398. var color = face.color;
  7399. this.colors.push( color, color, color );
  7400. }
  7401. if ( hasFaceVertexUv === true ) {
  7402. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  7403. if ( vertexUvs !== undefined ) {
  7404. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7405. } else {
  7406. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  7407. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  7408. }
  7409. }
  7410. if ( hasFaceVertexUv2 === true ) {
  7411. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  7412. if ( vertexUvs !== undefined ) {
  7413. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  7414. } else {
  7415. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  7416. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  7417. }
  7418. }
  7419. // morphs
  7420. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  7421. var morphTarget = morphTargets[ j ].vertices;
  7422. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  7423. }
  7424. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  7425. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  7426. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  7427. }
  7428. // skins
  7429. if ( hasSkinIndices ) {
  7430. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  7431. }
  7432. if ( hasSkinWeights ) {
  7433. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  7434. }
  7435. }
  7436. this.computeGroups( geometry );
  7437. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7438. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7439. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7440. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7441. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7442. return this;
  7443. }
  7444. } );
  7445. /**
  7446. * @author mrdoob / http://mrdoob.com/
  7447. * @author kile / http://kile.stravaganza.org/
  7448. * @author alteredq / http://alteredqualia.com/
  7449. * @author mikael emtinger / http://gomo.se/
  7450. * @author zz85 / http://www.lab4games.net/zz85/blog
  7451. * @author bhouston / http://clara.io
  7452. */
  7453. var count = 0;
  7454. function GeometryIdCount() { return count++; }
  7455. function Geometry() {
  7456. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  7457. this.uuid = _Math.generateUUID();
  7458. this.name = '';
  7459. this.type = 'Geometry';
  7460. this.vertices = [];
  7461. this.colors = [];
  7462. this.faces = [];
  7463. this.faceVertexUvs = [[]];
  7464. this.morphTargets = [];
  7465. this.morphNormals = [];
  7466. this.skinWeights = [];
  7467. this.skinIndices = [];
  7468. this.lineDistances = [];
  7469. this.boundingBox = null;
  7470. this.boundingSphere = null;
  7471. // update flags
  7472. this.elementsNeedUpdate = false;
  7473. this.verticesNeedUpdate = false;
  7474. this.uvsNeedUpdate = false;
  7475. this.normalsNeedUpdate = false;
  7476. this.colorsNeedUpdate = false;
  7477. this.lineDistancesNeedUpdate = false;
  7478. this.groupsNeedUpdate = false;
  7479. }
  7480. Geometry.prototype = {
  7481. constructor: Geometry,
  7482. isGeometry: true,
  7483. applyMatrix: function ( matrix ) {
  7484. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7485. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  7486. var vertex = this.vertices[ i ];
  7487. vertex.applyMatrix4( matrix );
  7488. }
  7489. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  7490. var face = this.faces[ i ];
  7491. face.normal.applyMatrix3( normalMatrix ).normalize();
  7492. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  7493. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  7494. }
  7495. }
  7496. if ( this.boundingBox !== null ) {
  7497. this.computeBoundingBox();
  7498. }
  7499. if ( this.boundingSphere !== null ) {
  7500. this.computeBoundingSphere();
  7501. }
  7502. this.verticesNeedUpdate = true;
  7503. this.normalsNeedUpdate = true;
  7504. return this;
  7505. },
  7506. rotateX: function () {
  7507. // rotate geometry around world x-axis
  7508. var m1;
  7509. return function rotateX( angle ) {
  7510. if ( m1 === undefined ) m1 = new Matrix4();
  7511. m1.makeRotationX( angle );
  7512. this.applyMatrix( m1 );
  7513. return this;
  7514. };
  7515. }(),
  7516. rotateY: function () {
  7517. // rotate geometry around world y-axis
  7518. var m1;
  7519. return function rotateY( angle ) {
  7520. if ( m1 === undefined ) m1 = new Matrix4();
  7521. m1.makeRotationY( angle );
  7522. this.applyMatrix( m1 );
  7523. return this;
  7524. };
  7525. }(),
  7526. rotateZ: function () {
  7527. // rotate geometry around world z-axis
  7528. var m1;
  7529. return function rotateZ( angle ) {
  7530. if ( m1 === undefined ) m1 = new Matrix4();
  7531. m1.makeRotationZ( angle );
  7532. this.applyMatrix( m1 );
  7533. return this;
  7534. };
  7535. }(),
  7536. translate: function () {
  7537. // translate geometry
  7538. var m1;
  7539. return function translate( x, y, z ) {
  7540. if ( m1 === undefined ) m1 = new Matrix4();
  7541. m1.makeTranslation( x, y, z );
  7542. this.applyMatrix( m1 );
  7543. return this;
  7544. };
  7545. }(),
  7546. scale: function () {
  7547. // scale geometry
  7548. var m1;
  7549. return function scale( x, y, z ) {
  7550. if ( m1 === undefined ) m1 = new Matrix4();
  7551. m1.makeScale( x, y, z );
  7552. this.applyMatrix( m1 );
  7553. return this;
  7554. };
  7555. }(),
  7556. lookAt: function () {
  7557. var obj;
  7558. return function lookAt( vector ) {
  7559. if ( obj === undefined ) obj = new Object3D();
  7560. obj.lookAt( vector );
  7561. obj.updateMatrix();
  7562. this.applyMatrix( obj.matrix );
  7563. };
  7564. }(),
  7565. fromBufferGeometry: function ( geometry ) {
  7566. var scope = this;
  7567. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7568. var attributes = geometry.attributes;
  7569. var positions = attributes.position.array;
  7570. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7571. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7572. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7573. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7574. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  7575. var tempNormals = [];
  7576. var tempUVs = [];
  7577. var tempUVs2 = [];
  7578. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  7579. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  7580. if ( normals !== undefined ) {
  7581. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  7582. }
  7583. if ( colors !== undefined ) {
  7584. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  7585. }
  7586. if ( uvs !== undefined ) {
  7587. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  7588. }
  7589. if ( uvs2 !== undefined ) {
  7590. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  7591. }
  7592. }
  7593. function addFace( a, b, c, materialIndex ) {
  7594. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  7595. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  7596. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  7597. scope.faces.push( face );
  7598. if ( uvs !== undefined ) {
  7599. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  7600. }
  7601. if ( uvs2 !== undefined ) {
  7602. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  7603. }
  7604. }
  7605. if ( indices !== undefined ) {
  7606. var groups = geometry.groups;
  7607. if ( groups.length > 0 ) {
  7608. for ( var i = 0; i < groups.length; i ++ ) {
  7609. var group = groups[ i ];
  7610. var start = group.start;
  7611. var count = group.count;
  7612. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  7613. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  7614. }
  7615. }
  7616. } else {
  7617. for ( var i = 0; i < indices.length; i += 3 ) {
  7618. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  7619. }
  7620. }
  7621. } else {
  7622. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  7623. addFace( i, i + 1, i + 2 );
  7624. }
  7625. }
  7626. this.computeFaceNormals();
  7627. if ( geometry.boundingBox !== null ) {
  7628. this.boundingBox = geometry.boundingBox.clone();
  7629. }
  7630. if ( geometry.boundingSphere !== null ) {
  7631. this.boundingSphere = geometry.boundingSphere.clone();
  7632. }
  7633. return this;
  7634. },
  7635. center: function () {
  7636. this.computeBoundingBox();
  7637. var offset = this.boundingBox.getCenter().negate();
  7638. this.translate( offset.x, offset.y, offset.z );
  7639. return offset;
  7640. },
  7641. normalize: function () {
  7642. this.computeBoundingSphere();
  7643. var center = this.boundingSphere.center;
  7644. var radius = this.boundingSphere.radius;
  7645. var s = radius === 0 ? 1 : 1.0 / radius;
  7646. var matrix = new Matrix4();
  7647. matrix.set(
  7648. s, 0, 0, - s * center.x,
  7649. 0, s, 0, - s * center.y,
  7650. 0, 0, s, - s * center.z,
  7651. 0, 0, 0, 1
  7652. );
  7653. this.applyMatrix( matrix );
  7654. return this;
  7655. },
  7656. computeFaceNormals: function () {
  7657. var cb = new Vector3(), ab = new Vector3();
  7658. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7659. var face = this.faces[ f ];
  7660. var vA = this.vertices[ face.a ];
  7661. var vB = this.vertices[ face.b ];
  7662. var vC = this.vertices[ face.c ];
  7663. cb.subVectors( vC, vB );
  7664. ab.subVectors( vA, vB );
  7665. cb.cross( ab );
  7666. cb.normalize();
  7667. face.normal.copy( cb );
  7668. }
  7669. },
  7670. computeVertexNormals: function ( areaWeighted ) {
  7671. if ( areaWeighted === undefined ) areaWeighted = true;
  7672. var v, vl, f, fl, face, vertices;
  7673. vertices = new Array( this.vertices.length );
  7674. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7675. vertices[ v ] = new Vector3();
  7676. }
  7677. if ( areaWeighted ) {
  7678. // vertex normals weighted by triangle areas
  7679. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7680. var vA, vB, vC;
  7681. var cb = new Vector3(), ab = new Vector3();
  7682. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7683. face = this.faces[ f ];
  7684. vA = this.vertices[ face.a ];
  7685. vB = this.vertices[ face.b ];
  7686. vC = this.vertices[ face.c ];
  7687. cb.subVectors( vC, vB );
  7688. ab.subVectors( vA, vB );
  7689. cb.cross( ab );
  7690. vertices[ face.a ].add( cb );
  7691. vertices[ face.b ].add( cb );
  7692. vertices[ face.c ].add( cb );
  7693. }
  7694. } else {
  7695. this.computeFaceNormals();
  7696. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7697. face = this.faces[ f ];
  7698. vertices[ face.a ].add( face.normal );
  7699. vertices[ face.b ].add( face.normal );
  7700. vertices[ face.c ].add( face.normal );
  7701. }
  7702. }
  7703. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  7704. vertices[ v ].normalize();
  7705. }
  7706. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7707. face = this.faces[ f ];
  7708. var vertexNormals = face.vertexNormals;
  7709. if ( vertexNormals.length === 3 ) {
  7710. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  7711. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  7712. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  7713. } else {
  7714. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  7715. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  7716. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  7717. }
  7718. }
  7719. if ( this.faces.length > 0 ) {
  7720. this.normalsNeedUpdate = true;
  7721. }
  7722. },
  7723. computeFlatVertexNormals: function () {
  7724. var f, fl, face;
  7725. this.computeFaceNormals();
  7726. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7727. face = this.faces[ f ];
  7728. var vertexNormals = face.vertexNormals;
  7729. if ( vertexNormals.length === 3 ) {
  7730. vertexNormals[ 0 ].copy( face.normal );
  7731. vertexNormals[ 1 ].copy( face.normal );
  7732. vertexNormals[ 2 ].copy( face.normal );
  7733. } else {
  7734. vertexNormals[ 0 ] = face.normal.clone();
  7735. vertexNormals[ 1 ] = face.normal.clone();
  7736. vertexNormals[ 2 ] = face.normal.clone();
  7737. }
  7738. }
  7739. if ( this.faces.length > 0 ) {
  7740. this.normalsNeedUpdate = true;
  7741. }
  7742. },
  7743. computeMorphNormals: function () {
  7744. var i, il, f, fl, face;
  7745. // save original normals
  7746. // - create temp variables on first access
  7747. // otherwise just copy (for faster repeated calls)
  7748. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7749. face = this.faces[ f ];
  7750. if ( ! face.__originalFaceNormal ) {
  7751. face.__originalFaceNormal = face.normal.clone();
  7752. } else {
  7753. face.__originalFaceNormal.copy( face.normal );
  7754. }
  7755. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  7756. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  7757. if ( ! face.__originalVertexNormals[ i ] ) {
  7758. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  7759. } else {
  7760. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  7761. }
  7762. }
  7763. }
  7764. // use temp geometry to compute face and vertex normals for each morph
  7765. var tmpGeo = new Geometry();
  7766. tmpGeo.faces = this.faces;
  7767. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  7768. // create on first access
  7769. if ( ! this.morphNormals[ i ] ) {
  7770. this.morphNormals[ i ] = {};
  7771. this.morphNormals[ i ].faceNormals = [];
  7772. this.morphNormals[ i ].vertexNormals = [];
  7773. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  7774. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  7775. var faceNormal, vertexNormals;
  7776. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7777. faceNormal = new Vector3();
  7778. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  7779. dstNormalsFace.push( faceNormal );
  7780. dstNormalsVertex.push( vertexNormals );
  7781. }
  7782. }
  7783. var morphNormals = this.morphNormals[ i ];
  7784. // set vertices to morph target
  7785. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  7786. // compute morph normals
  7787. tmpGeo.computeFaceNormals();
  7788. tmpGeo.computeVertexNormals();
  7789. // store morph normals
  7790. var faceNormal, vertexNormals;
  7791. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7792. face = this.faces[ f ];
  7793. faceNormal = morphNormals.faceNormals[ f ];
  7794. vertexNormals = morphNormals.vertexNormals[ f ];
  7795. faceNormal.copy( face.normal );
  7796. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  7797. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  7798. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  7799. }
  7800. }
  7801. // restore original normals
  7802. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  7803. face = this.faces[ f ];
  7804. face.normal = face.__originalFaceNormal;
  7805. face.vertexNormals = face.__originalVertexNormals;
  7806. }
  7807. },
  7808. computeLineDistances: function () {
  7809. var d = 0;
  7810. var vertices = this.vertices;
  7811. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  7812. if ( i > 0 ) {
  7813. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  7814. }
  7815. this.lineDistances[ i ] = d;
  7816. }
  7817. },
  7818. computeBoundingBox: function () {
  7819. if ( this.boundingBox === null ) {
  7820. this.boundingBox = new Box3();
  7821. }
  7822. this.boundingBox.setFromPoints( this.vertices );
  7823. },
  7824. computeBoundingSphere: function () {
  7825. if ( this.boundingSphere === null ) {
  7826. this.boundingSphere = new Sphere();
  7827. }
  7828. this.boundingSphere.setFromPoints( this.vertices );
  7829. },
  7830. merge: function ( geometry, matrix, materialIndexOffset ) {
  7831. if ( ( geometry && geometry.isGeometry ) === false ) {
  7832. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  7833. return;
  7834. }
  7835. var normalMatrix,
  7836. vertexOffset = this.vertices.length,
  7837. vertices1 = this.vertices,
  7838. vertices2 = geometry.vertices,
  7839. faces1 = this.faces,
  7840. faces2 = geometry.faces,
  7841. uvs1 = this.faceVertexUvs[ 0 ],
  7842. uvs2 = geometry.faceVertexUvs[ 0 ],
  7843. colors1 = this.colors,
  7844. colors2 = geometry.colors;
  7845. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  7846. if ( matrix !== undefined ) {
  7847. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  7848. }
  7849. // vertices
  7850. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  7851. var vertex = vertices2[ i ];
  7852. var vertexCopy = vertex.clone();
  7853. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  7854. vertices1.push( vertexCopy );
  7855. }
  7856. // colors
  7857. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  7858. colors1.push( colors2[ i ].clone() );
  7859. }
  7860. // faces
  7861. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  7862. var face = faces2[ i ], faceCopy, normal, color,
  7863. faceVertexNormals = face.vertexNormals,
  7864. faceVertexColors = face.vertexColors;
  7865. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  7866. faceCopy.normal.copy( face.normal );
  7867. if ( normalMatrix !== undefined ) {
  7868. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  7869. }
  7870. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  7871. normal = faceVertexNormals[ j ].clone();
  7872. if ( normalMatrix !== undefined ) {
  7873. normal.applyMatrix3( normalMatrix ).normalize();
  7874. }
  7875. faceCopy.vertexNormals.push( normal );
  7876. }
  7877. faceCopy.color.copy( face.color );
  7878. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  7879. color = faceVertexColors[ j ];
  7880. faceCopy.vertexColors.push( color.clone() );
  7881. }
  7882. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  7883. faces1.push( faceCopy );
  7884. }
  7885. // uvs
  7886. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  7887. var uv = uvs2[ i ], uvCopy = [];
  7888. if ( uv === undefined ) {
  7889. continue;
  7890. }
  7891. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  7892. uvCopy.push( uv[ j ].clone() );
  7893. }
  7894. uvs1.push( uvCopy );
  7895. }
  7896. },
  7897. mergeMesh: function ( mesh ) {
  7898. if ( ( mesh && mesh.isMesh ) === false ) {
  7899. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  7900. return;
  7901. }
  7902. mesh.matrixAutoUpdate && mesh.updateMatrix();
  7903. this.merge( mesh.geometry, mesh.matrix );
  7904. },
  7905. /*
  7906. * Checks for duplicate vertices with hashmap.
  7907. * Duplicated vertices are removed
  7908. * and faces' vertices are updated.
  7909. */
  7910. mergeVertices: function () {
  7911. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  7912. var unique = [], changes = [];
  7913. var v, key;
  7914. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  7915. var precision = Math.pow( 10, precisionPoints );
  7916. var i, il, face;
  7917. var indices, j, jl;
  7918. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  7919. v = this.vertices[ i ];
  7920. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  7921. if ( verticesMap[ key ] === undefined ) {
  7922. verticesMap[ key ] = i;
  7923. unique.push( this.vertices[ i ] );
  7924. changes[ i ] = unique.length - 1;
  7925. } else {
  7926. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  7927. changes[ i ] = changes[ verticesMap[ key ] ];
  7928. }
  7929. }
  7930. // if faces are completely degenerate after merging vertices, we
  7931. // have to remove them from the geometry.
  7932. var faceIndicesToRemove = [];
  7933. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  7934. face = this.faces[ i ];
  7935. face.a = changes[ face.a ];
  7936. face.b = changes[ face.b ];
  7937. face.c = changes[ face.c ];
  7938. indices = [ face.a, face.b, face.c ];
  7939. // if any duplicate vertices are found in a Face3
  7940. // we have to remove the face as nothing can be saved
  7941. for ( var n = 0; n < 3; n ++ ) {
  7942. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  7943. faceIndicesToRemove.push( i );
  7944. break;
  7945. }
  7946. }
  7947. }
  7948. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  7949. var idx = faceIndicesToRemove[ i ];
  7950. this.faces.splice( idx, 1 );
  7951. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  7952. this.faceVertexUvs[ j ].splice( idx, 1 );
  7953. }
  7954. }
  7955. // Use unique set of vertices
  7956. var diff = this.vertices.length - unique.length;
  7957. this.vertices = unique;
  7958. return diff;
  7959. },
  7960. sortFacesByMaterialIndex: function () {
  7961. var faces = this.faces;
  7962. var length = faces.length;
  7963. // tag faces
  7964. for ( var i = 0; i < length; i ++ ) {
  7965. faces[ i ]._id = i;
  7966. }
  7967. // sort faces
  7968. function materialIndexSort( a, b ) {
  7969. return a.materialIndex - b.materialIndex;
  7970. }
  7971. faces.sort( materialIndexSort );
  7972. // sort uvs
  7973. var uvs1 = this.faceVertexUvs[ 0 ];
  7974. var uvs2 = this.faceVertexUvs[ 1 ];
  7975. var newUvs1, newUvs2;
  7976. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  7977. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  7978. for ( var i = 0; i < length; i ++ ) {
  7979. var id = faces[ i ]._id;
  7980. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  7981. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  7982. }
  7983. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  7984. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  7985. },
  7986. toJSON: function () {
  7987. var data = {
  7988. metadata: {
  7989. version: 4.4,
  7990. type: 'Geometry',
  7991. generator: 'Geometry.toJSON'
  7992. }
  7993. };
  7994. // standard Geometry serialization
  7995. data.uuid = this.uuid;
  7996. data.type = this.type;
  7997. if ( this.name !== '' ) data.name = this.name;
  7998. if ( this.parameters !== undefined ) {
  7999. var parameters = this.parameters;
  8000. for ( var key in parameters ) {
  8001. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8002. }
  8003. return data;
  8004. }
  8005. var vertices = [];
  8006. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8007. var vertex = this.vertices[ i ];
  8008. vertices.push( vertex.x, vertex.y, vertex.z );
  8009. }
  8010. var faces = [];
  8011. var normals = [];
  8012. var normalsHash = {};
  8013. var colors = [];
  8014. var colorsHash = {};
  8015. var uvs = [];
  8016. var uvsHash = {};
  8017. for ( var i = 0; i < this.faces.length; i ++ ) {
  8018. var face = this.faces[ i ];
  8019. var hasMaterial = true;
  8020. var hasFaceUv = false; // deprecated
  8021. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8022. var hasFaceNormal = face.normal.length() > 0;
  8023. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8024. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8025. var hasFaceVertexColor = face.vertexColors.length > 0;
  8026. var faceType = 0;
  8027. faceType = setBit( faceType, 0, 0 ); // isQuad
  8028. faceType = setBit( faceType, 1, hasMaterial );
  8029. faceType = setBit( faceType, 2, hasFaceUv );
  8030. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8031. faceType = setBit( faceType, 4, hasFaceNormal );
  8032. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8033. faceType = setBit( faceType, 6, hasFaceColor );
  8034. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8035. faces.push( faceType );
  8036. faces.push( face.a, face.b, face.c );
  8037. faces.push( face.materialIndex );
  8038. if ( hasFaceVertexUv ) {
  8039. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8040. faces.push(
  8041. getUvIndex( faceVertexUvs[ 0 ] ),
  8042. getUvIndex( faceVertexUvs[ 1 ] ),
  8043. getUvIndex( faceVertexUvs[ 2 ] )
  8044. );
  8045. }
  8046. if ( hasFaceNormal ) {
  8047. faces.push( getNormalIndex( face.normal ) );
  8048. }
  8049. if ( hasFaceVertexNormal ) {
  8050. var vertexNormals = face.vertexNormals;
  8051. faces.push(
  8052. getNormalIndex( vertexNormals[ 0 ] ),
  8053. getNormalIndex( vertexNormals[ 1 ] ),
  8054. getNormalIndex( vertexNormals[ 2 ] )
  8055. );
  8056. }
  8057. if ( hasFaceColor ) {
  8058. faces.push( getColorIndex( face.color ) );
  8059. }
  8060. if ( hasFaceVertexColor ) {
  8061. var vertexColors = face.vertexColors;
  8062. faces.push(
  8063. getColorIndex( vertexColors[ 0 ] ),
  8064. getColorIndex( vertexColors[ 1 ] ),
  8065. getColorIndex( vertexColors[ 2 ] )
  8066. );
  8067. }
  8068. }
  8069. function setBit( value, position, enabled ) {
  8070. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8071. }
  8072. function getNormalIndex( normal ) {
  8073. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8074. if ( normalsHash[ hash ] !== undefined ) {
  8075. return normalsHash[ hash ];
  8076. }
  8077. normalsHash[ hash ] = normals.length / 3;
  8078. normals.push( normal.x, normal.y, normal.z );
  8079. return normalsHash[ hash ];
  8080. }
  8081. function getColorIndex( color ) {
  8082. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8083. if ( colorsHash[ hash ] !== undefined ) {
  8084. return colorsHash[ hash ];
  8085. }
  8086. colorsHash[ hash ] = colors.length;
  8087. colors.push( color.getHex() );
  8088. return colorsHash[ hash ];
  8089. }
  8090. function getUvIndex( uv ) {
  8091. var hash = uv.x.toString() + uv.y.toString();
  8092. if ( uvsHash[ hash ] !== undefined ) {
  8093. return uvsHash[ hash ];
  8094. }
  8095. uvsHash[ hash ] = uvs.length / 2;
  8096. uvs.push( uv.x, uv.y );
  8097. return uvsHash[ hash ];
  8098. }
  8099. data.data = {};
  8100. data.data.vertices = vertices;
  8101. data.data.normals = normals;
  8102. if ( colors.length > 0 ) data.data.colors = colors;
  8103. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8104. data.data.faces = faces;
  8105. return data;
  8106. },
  8107. clone: function () {
  8108. /*
  8109. // Handle primitives
  8110. var parameters = this.parameters;
  8111. if ( parameters !== undefined ) {
  8112. var values = [];
  8113. for ( var key in parameters ) {
  8114. values.push( parameters[ key ] );
  8115. }
  8116. var geometry = Object.create( this.constructor.prototype );
  8117. this.constructor.apply( geometry, values );
  8118. return geometry;
  8119. }
  8120. return new this.constructor().copy( this );
  8121. */
  8122. return new Geometry().copy( this );
  8123. },
  8124. copy: function ( source ) {
  8125. this.vertices = [];
  8126. this.faces = [];
  8127. this.faceVertexUvs = [ [] ];
  8128. this.colors = [];
  8129. var vertices = source.vertices;
  8130. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8131. this.vertices.push( vertices[ i ].clone() );
  8132. }
  8133. var colors = source.colors;
  8134. for ( var i = 0, il = colors.length; i < il; i ++ ) {
  8135. this.colors.push( colors[ i ].clone() );
  8136. }
  8137. var faces = source.faces;
  8138. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  8139. this.faces.push( faces[ i ].clone() );
  8140. }
  8141. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8142. var faceVertexUvs = source.faceVertexUvs[ i ];
  8143. if ( this.faceVertexUvs[ i ] === undefined ) {
  8144. this.faceVertexUvs[ i ] = [];
  8145. }
  8146. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8147. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8148. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  8149. var uv = uvs[ k ];
  8150. uvsCopy.push( uv.clone() );
  8151. }
  8152. this.faceVertexUvs[ i ].push( uvsCopy );
  8153. }
  8154. }
  8155. return this;
  8156. },
  8157. dispose: function () {
  8158. this.dispatchEvent( { type: 'dispose' } );
  8159. }
  8160. };
  8161. Object.assign( Geometry.prototype, EventDispatcher.prototype );
  8162. /**
  8163. * @author alteredq / http://alteredqualia.com/
  8164. * @author mrdoob / http://mrdoob.com/
  8165. */
  8166. function BufferGeometry() {
  8167. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8168. this.uuid = _Math.generateUUID();
  8169. this.name = '';
  8170. this.type = 'BufferGeometry';
  8171. this.index = null;
  8172. this.attributes = {};
  8173. this.morphAttributes = {};
  8174. this.groups = [];
  8175. this.boundingBox = null;
  8176. this.boundingSphere = null;
  8177. this.drawRange = { start: 0, count: Infinity };
  8178. }
  8179. BufferGeometry.prototype = {
  8180. constructor: BufferGeometry,
  8181. isBufferGeometry: true,
  8182. getIndex: function () {
  8183. return this.index;
  8184. },
  8185. setIndex: function ( index ) {
  8186. this.index = index;
  8187. },
  8188. addAttribute: function ( name, attribute ) {
  8189. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  8190. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  8191. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  8192. return;
  8193. }
  8194. if ( name === 'index' ) {
  8195. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  8196. this.setIndex( attribute );
  8197. return;
  8198. }
  8199. this.attributes[ name ] = attribute;
  8200. return this;
  8201. },
  8202. getAttribute: function ( name ) {
  8203. return this.attributes[ name ];
  8204. },
  8205. removeAttribute: function ( name ) {
  8206. delete this.attributes[ name ];
  8207. return this;
  8208. },
  8209. addGroup: function ( start, count, materialIndex ) {
  8210. this.groups.push( {
  8211. start: start,
  8212. count: count,
  8213. materialIndex: materialIndex !== undefined ? materialIndex : 0
  8214. } );
  8215. },
  8216. clearGroups: function () {
  8217. this.groups = [];
  8218. },
  8219. setDrawRange: function ( start, count ) {
  8220. this.drawRange.start = start;
  8221. this.drawRange.count = count;
  8222. },
  8223. applyMatrix: function ( matrix ) {
  8224. var position = this.attributes.position;
  8225. if ( position !== undefined ) {
  8226. matrix.applyToBufferAttribute( position );
  8227. position.needsUpdate = true;
  8228. }
  8229. var normal = this.attributes.normal;
  8230. if ( normal !== undefined ) {
  8231. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8232. normalMatrix.applyToBufferAttribute( normal );
  8233. normal.needsUpdate = true;
  8234. }
  8235. if ( this.boundingBox !== null ) {
  8236. this.computeBoundingBox();
  8237. }
  8238. if ( this.boundingSphere !== null ) {
  8239. this.computeBoundingSphere();
  8240. }
  8241. return this;
  8242. },
  8243. rotateX: function () {
  8244. // rotate geometry around world x-axis
  8245. var m1;
  8246. return function rotateX( angle ) {
  8247. if ( m1 === undefined ) m1 = new Matrix4();
  8248. m1.makeRotationX( angle );
  8249. this.applyMatrix( m1 );
  8250. return this;
  8251. };
  8252. }(),
  8253. rotateY: function () {
  8254. // rotate geometry around world y-axis
  8255. var m1;
  8256. return function rotateY( angle ) {
  8257. if ( m1 === undefined ) m1 = new Matrix4();
  8258. m1.makeRotationY( angle );
  8259. this.applyMatrix( m1 );
  8260. return this;
  8261. };
  8262. }(),
  8263. rotateZ: function () {
  8264. // rotate geometry around world z-axis
  8265. var m1;
  8266. return function rotateZ( angle ) {
  8267. if ( m1 === undefined ) m1 = new Matrix4();
  8268. m1.makeRotationZ( angle );
  8269. this.applyMatrix( m1 );
  8270. return this;
  8271. };
  8272. }(),
  8273. translate: function () {
  8274. // translate geometry
  8275. var m1;
  8276. return function translate( x, y, z ) {
  8277. if ( m1 === undefined ) m1 = new Matrix4();
  8278. m1.makeTranslation( x, y, z );
  8279. this.applyMatrix( m1 );
  8280. return this;
  8281. };
  8282. }(),
  8283. scale: function () {
  8284. // scale geometry
  8285. var m1;
  8286. return function scale( x, y, z ) {
  8287. if ( m1 === undefined ) m1 = new Matrix4();
  8288. m1.makeScale( x, y, z );
  8289. this.applyMatrix( m1 );
  8290. return this;
  8291. };
  8292. }(),
  8293. lookAt: function () {
  8294. var obj;
  8295. return function lookAt( vector ) {
  8296. if ( obj === undefined ) obj = new Object3D();
  8297. obj.lookAt( vector );
  8298. obj.updateMatrix();
  8299. this.applyMatrix( obj.matrix );
  8300. };
  8301. }(),
  8302. center: function () {
  8303. this.computeBoundingBox();
  8304. var offset = this.boundingBox.getCenter().negate();
  8305. this.translate( offset.x, offset.y, offset.z );
  8306. return offset;
  8307. },
  8308. setFromObject: function ( object ) {
  8309. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  8310. var geometry = object.geometry;
  8311. if ( object.isPoints || object.isLine ) {
  8312. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  8313. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  8314. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  8315. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  8316. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  8317. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  8318. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  8319. }
  8320. if ( geometry.boundingSphere !== null ) {
  8321. this.boundingSphere = geometry.boundingSphere.clone();
  8322. }
  8323. if ( geometry.boundingBox !== null ) {
  8324. this.boundingBox = geometry.boundingBox.clone();
  8325. }
  8326. } else if ( object.isMesh ) {
  8327. if ( geometry && geometry.isGeometry ) {
  8328. this.fromGeometry( geometry );
  8329. }
  8330. }
  8331. return this;
  8332. },
  8333. updateFromObject: function ( object ) {
  8334. var geometry = object.geometry;
  8335. if ( object.isMesh ) {
  8336. var direct = geometry.__directGeometry;
  8337. if ( geometry.elementsNeedUpdate === true ) {
  8338. direct = undefined;
  8339. geometry.elementsNeedUpdate = false;
  8340. }
  8341. if ( direct === undefined ) {
  8342. return this.fromGeometry( geometry );
  8343. }
  8344. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  8345. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  8346. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  8347. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  8348. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  8349. geometry.verticesNeedUpdate = false;
  8350. geometry.normalsNeedUpdate = false;
  8351. geometry.colorsNeedUpdate = false;
  8352. geometry.uvsNeedUpdate = false;
  8353. geometry.groupsNeedUpdate = false;
  8354. geometry = direct;
  8355. }
  8356. var attribute;
  8357. if ( geometry.verticesNeedUpdate === true ) {
  8358. attribute = this.attributes.position;
  8359. if ( attribute !== undefined ) {
  8360. attribute.copyVector3sArray( geometry.vertices );
  8361. attribute.needsUpdate = true;
  8362. }
  8363. geometry.verticesNeedUpdate = false;
  8364. }
  8365. if ( geometry.normalsNeedUpdate === true ) {
  8366. attribute = this.attributes.normal;
  8367. if ( attribute !== undefined ) {
  8368. attribute.copyVector3sArray( geometry.normals );
  8369. attribute.needsUpdate = true;
  8370. }
  8371. geometry.normalsNeedUpdate = false;
  8372. }
  8373. if ( geometry.colorsNeedUpdate === true ) {
  8374. attribute = this.attributes.color;
  8375. if ( attribute !== undefined ) {
  8376. attribute.copyColorsArray( geometry.colors );
  8377. attribute.needsUpdate = true;
  8378. }
  8379. geometry.colorsNeedUpdate = false;
  8380. }
  8381. if ( geometry.uvsNeedUpdate ) {
  8382. attribute = this.attributes.uv;
  8383. if ( attribute !== undefined ) {
  8384. attribute.copyVector2sArray( geometry.uvs );
  8385. attribute.needsUpdate = true;
  8386. }
  8387. geometry.uvsNeedUpdate = false;
  8388. }
  8389. if ( geometry.lineDistancesNeedUpdate ) {
  8390. attribute = this.attributes.lineDistance;
  8391. if ( attribute !== undefined ) {
  8392. attribute.copyArray( geometry.lineDistances );
  8393. attribute.needsUpdate = true;
  8394. }
  8395. geometry.lineDistancesNeedUpdate = false;
  8396. }
  8397. if ( geometry.groupsNeedUpdate ) {
  8398. geometry.computeGroups( object.geometry );
  8399. this.groups = geometry.groups;
  8400. geometry.groupsNeedUpdate = false;
  8401. }
  8402. return this;
  8403. },
  8404. fromGeometry: function ( geometry ) {
  8405. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  8406. return this.fromDirectGeometry( geometry.__directGeometry );
  8407. },
  8408. fromDirectGeometry: function ( geometry ) {
  8409. var positions = new Float32Array( geometry.vertices.length * 3 );
  8410. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  8411. if ( geometry.normals.length > 0 ) {
  8412. var normals = new Float32Array( geometry.normals.length * 3 );
  8413. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  8414. }
  8415. if ( geometry.colors.length > 0 ) {
  8416. var colors = new Float32Array( geometry.colors.length * 3 );
  8417. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  8418. }
  8419. if ( geometry.uvs.length > 0 ) {
  8420. var uvs = new Float32Array( geometry.uvs.length * 2 );
  8421. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  8422. }
  8423. if ( geometry.uvs2.length > 0 ) {
  8424. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  8425. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  8426. }
  8427. if ( geometry.indices.length > 0 ) {
  8428. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  8429. var indices = new TypeArray( geometry.indices.length * 3 );
  8430. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  8431. }
  8432. // groups
  8433. this.groups = geometry.groups;
  8434. // morphs
  8435. for ( var name in geometry.morphTargets ) {
  8436. var array = [];
  8437. var morphTargets = geometry.morphTargets[ name ];
  8438. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  8439. var morphTarget = morphTargets[ i ];
  8440. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  8441. array.push( attribute.copyVector3sArray( morphTarget ) );
  8442. }
  8443. this.morphAttributes[ name ] = array;
  8444. }
  8445. // skinning
  8446. if ( geometry.skinIndices.length > 0 ) {
  8447. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  8448. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  8449. }
  8450. if ( geometry.skinWeights.length > 0 ) {
  8451. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  8452. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  8453. }
  8454. //
  8455. if ( geometry.boundingSphere !== null ) {
  8456. this.boundingSphere = geometry.boundingSphere.clone();
  8457. }
  8458. if ( geometry.boundingBox !== null ) {
  8459. this.boundingBox = geometry.boundingBox.clone();
  8460. }
  8461. return this;
  8462. },
  8463. computeBoundingBox: function () {
  8464. if ( this.boundingBox === null ) {
  8465. this.boundingBox = new Box3();
  8466. }
  8467. var position = this.attributes.position;
  8468. if ( position !== undefined ) {
  8469. this.boundingBox.setFromBufferAttribute( position );
  8470. } else {
  8471. this.boundingBox.makeEmpty();
  8472. }
  8473. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8474. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8475. }
  8476. },
  8477. computeBoundingSphere: function () {
  8478. var box = new Box3();
  8479. var vector = new Vector3();
  8480. return function computeBoundingSphere() {
  8481. if ( this.boundingSphere === null ) {
  8482. this.boundingSphere = new Sphere();
  8483. }
  8484. var position = this.attributes.position;
  8485. if ( position ) {
  8486. var center = this.boundingSphere.center;
  8487. box.setFromBufferAttribute( position );
  8488. box.getCenter( center );
  8489. // hoping to find a boundingSphere with a radius smaller than the
  8490. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8491. var maxRadiusSq = 0;
  8492. for ( var i = 0, il = position.count; i < il; i ++ ) {
  8493. vector.x = position.getX( i );
  8494. vector.y = position.getY( i );
  8495. vector.z = position.getZ( i );
  8496. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  8497. }
  8498. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8499. if ( isNaN( this.boundingSphere.radius ) ) {
  8500. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8501. }
  8502. }
  8503. };
  8504. }(),
  8505. computeFaceNormals: function () {
  8506. // backwards compatibility
  8507. },
  8508. computeVertexNormals: function () {
  8509. var index = this.index;
  8510. var attributes = this.attributes;
  8511. var groups = this.groups;
  8512. if ( attributes.position ) {
  8513. var positions = attributes.position.array;
  8514. if ( attributes.normal === undefined ) {
  8515. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  8516. } else {
  8517. // reset existing normals to zero
  8518. var array = attributes.normal.array;
  8519. for ( var i = 0, il = array.length; i < il; i ++ ) {
  8520. array[ i ] = 0;
  8521. }
  8522. }
  8523. var normals = attributes.normal.array;
  8524. var vA, vB, vC;
  8525. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8526. var cb = new Vector3(), ab = new Vector3();
  8527. // indexed elements
  8528. if ( index ) {
  8529. var indices = index.array;
  8530. if ( groups.length === 0 ) {
  8531. this.addGroup( 0, indices.length );
  8532. }
  8533. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  8534. var group = groups[ j ];
  8535. var start = group.start;
  8536. var count = group.count;
  8537. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8538. vA = indices[ i + 0 ] * 3;
  8539. vB = indices[ i + 1 ] * 3;
  8540. vC = indices[ i + 2 ] * 3;
  8541. pA.fromArray( positions, vA );
  8542. pB.fromArray( positions, vB );
  8543. pC.fromArray( positions, vC );
  8544. cb.subVectors( pC, pB );
  8545. ab.subVectors( pA, pB );
  8546. cb.cross( ab );
  8547. normals[ vA ] += cb.x;
  8548. normals[ vA + 1 ] += cb.y;
  8549. normals[ vA + 2 ] += cb.z;
  8550. normals[ vB ] += cb.x;
  8551. normals[ vB + 1 ] += cb.y;
  8552. normals[ vB + 2 ] += cb.z;
  8553. normals[ vC ] += cb.x;
  8554. normals[ vC + 1 ] += cb.y;
  8555. normals[ vC + 2 ] += cb.z;
  8556. }
  8557. }
  8558. } else {
  8559. // non-indexed elements (unconnected triangle soup)
  8560. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  8561. pA.fromArray( positions, i );
  8562. pB.fromArray( positions, i + 3 );
  8563. pC.fromArray( positions, i + 6 );
  8564. cb.subVectors( pC, pB );
  8565. ab.subVectors( pA, pB );
  8566. cb.cross( ab );
  8567. normals[ i ] = cb.x;
  8568. normals[ i + 1 ] = cb.y;
  8569. normals[ i + 2 ] = cb.z;
  8570. normals[ i + 3 ] = cb.x;
  8571. normals[ i + 4 ] = cb.y;
  8572. normals[ i + 5 ] = cb.z;
  8573. normals[ i + 6 ] = cb.x;
  8574. normals[ i + 7 ] = cb.y;
  8575. normals[ i + 8 ] = cb.z;
  8576. }
  8577. }
  8578. this.normalizeNormals();
  8579. attributes.normal.needsUpdate = true;
  8580. }
  8581. },
  8582. merge: function ( geometry, offset ) {
  8583. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  8584. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  8585. return;
  8586. }
  8587. if ( offset === undefined ) offset = 0;
  8588. var attributes = this.attributes;
  8589. for ( var key in attributes ) {
  8590. if ( geometry.attributes[ key ] === undefined ) continue;
  8591. var attribute1 = attributes[ key ];
  8592. var attributeArray1 = attribute1.array;
  8593. var attribute2 = geometry.attributes[ key ];
  8594. var attributeArray2 = attribute2.array;
  8595. var attributeSize = attribute2.itemSize;
  8596. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  8597. attributeArray1[ j ] = attributeArray2[ i ];
  8598. }
  8599. }
  8600. return this;
  8601. },
  8602. normalizeNormals: function () {
  8603. var normals = this.attributes.normal.array;
  8604. var x, y, z, n;
  8605. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  8606. x = normals[ i ];
  8607. y = normals[ i + 1 ];
  8608. z = normals[ i + 2 ];
  8609. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  8610. normals[ i ] *= n;
  8611. normals[ i + 1 ] *= n;
  8612. normals[ i + 2 ] *= n;
  8613. }
  8614. },
  8615. toNonIndexed: function () {
  8616. if ( this.index === null ) {
  8617. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  8618. return this;
  8619. }
  8620. var geometry2 = new BufferGeometry();
  8621. var indices = this.index.array;
  8622. var attributes = this.attributes;
  8623. for ( var name in attributes ) {
  8624. var attribute = attributes[ name ];
  8625. var array = attribute.array;
  8626. var itemSize = attribute.itemSize;
  8627. var array2 = new array.constructor( indices.length * itemSize );
  8628. var index = 0, index2 = 0;
  8629. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  8630. index = indices[ i ] * itemSize;
  8631. for ( var j = 0; j < itemSize; j ++ ) {
  8632. array2[ index2 ++ ] = array[ index ++ ];
  8633. }
  8634. }
  8635. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  8636. }
  8637. return geometry2;
  8638. },
  8639. toJSON: function () {
  8640. var data = {
  8641. metadata: {
  8642. version: 4.4,
  8643. type: 'BufferGeometry',
  8644. generator: 'BufferGeometry.toJSON'
  8645. }
  8646. };
  8647. // standard BufferGeometry serialization
  8648. data.uuid = this.uuid;
  8649. data.type = this.type;
  8650. if ( this.name !== '' ) data.name = this.name;
  8651. if ( this.parameters !== undefined ) {
  8652. var parameters = this.parameters;
  8653. for ( var key in parameters ) {
  8654. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8655. }
  8656. return data;
  8657. }
  8658. data.data = { attributes: {} };
  8659. var index = this.index;
  8660. if ( index !== null ) {
  8661. var array = Array.prototype.slice.call( index.array );
  8662. data.data.index = {
  8663. type: index.array.constructor.name,
  8664. array: array
  8665. };
  8666. }
  8667. var attributes = this.attributes;
  8668. for ( var key in attributes ) {
  8669. var attribute = attributes[ key ];
  8670. var array = Array.prototype.slice.call( attribute.array );
  8671. data.data.attributes[ key ] = {
  8672. itemSize: attribute.itemSize,
  8673. type: attribute.array.constructor.name,
  8674. array: array,
  8675. normalized: attribute.normalized
  8676. };
  8677. }
  8678. var groups = this.groups;
  8679. if ( groups.length > 0 ) {
  8680. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8681. }
  8682. var boundingSphere = this.boundingSphere;
  8683. if ( boundingSphere !== null ) {
  8684. data.data.boundingSphere = {
  8685. center: boundingSphere.center.toArray(),
  8686. radius: boundingSphere.radius
  8687. };
  8688. }
  8689. return data;
  8690. },
  8691. clone: function () {
  8692. /*
  8693. // Handle primitives
  8694. var parameters = this.parameters;
  8695. if ( parameters !== undefined ) {
  8696. var values = [];
  8697. for ( var key in parameters ) {
  8698. values.push( parameters[ key ] );
  8699. }
  8700. var geometry = Object.create( this.constructor.prototype );
  8701. this.constructor.apply( geometry, values );
  8702. return geometry;
  8703. }
  8704. return new this.constructor().copy( this );
  8705. */
  8706. return new BufferGeometry().copy( this );
  8707. },
  8708. copy: function ( source ) {
  8709. var name, i, l;
  8710. // reset
  8711. this.index = null;
  8712. this.attributes = {};
  8713. this.morphAttributes = {};
  8714. this.groups = [];
  8715. this.boundingBox = null;
  8716. this.boundingSphere = null;
  8717. // name
  8718. this.name = source.name;
  8719. // index
  8720. var index = source.index;
  8721. if ( index !== null ) {
  8722. this.setIndex( index.clone() );
  8723. }
  8724. // attributes
  8725. var attributes = source.attributes;
  8726. for ( name in attributes ) {
  8727. var attribute = attributes[ name ];
  8728. this.addAttribute( name, attribute.clone() );
  8729. }
  8730. // morph attributes
  8731. var morphAttributes = source.morphAttributes;
  8732. for ( name in morphAttributes ) {
  8733. var array = [];
  8734. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8735. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8736. array.push( morphAttribute[ i ].clone() );
  8737. }
  8738. this.morphAttributes[ name ] = array;
  8739. }
  8740. // groups
  8741. var groups = source.groups;
  8742. for ( i = 0, l = groups.length; i < l; i ++ ) {
  8743. var group = groups[ i ];
  8744. this.addGroup( group.start, group.count, group.materialIndex );
  8745. }
  8746. // bounding box
  8747. var boundingBox = source.boundingBox;
  8748. if ( boundingBox !== null ) {
  8749. this.boundingBox = boundingBox.clone();
  8750. }
  8751. // bounding sphere
  8752. var boundingSphere = source.boundingSphere;
  8753. if ( boundingSphere !== null ) {
  8754. this.boundingSphere = boundingSphere.clone();
  8755. }
  8756. // draw range
  8757. this.drawRange.start = source.drawRange.start;
  8758. this.drawRange.count = source.drawRange.count;
  8759. return this;
  8760. },
  8761. dispose: function () {
  8762. this.dispatchEvent( { type: 'dispose' } );
  8763. }
  8764. };
  8765. BufferGeometry.MaxIndex = 65535;
  8766. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype );
  8767. /**
  8768. * @author mrdoob / http://mrdoob.com/
  8769. * @author alteredq / http://alteredqualia.com/
  8770. * @author mikael emtinger / http://gomo.se/
  8771. * @author jonobr1 / http://jonobr1.com/
  8772. */
  8773. function Mesh( geometry, material ) {
  8774. Object3D.call( this );
  8775. this.type = 'Mesh';
  8776. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8777. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8778. this.drawMode = TrianglesDrawMode;
  8779. this.updateMorphTargets();
  8780. }
  8781. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8782. constructor: Mesh,
  8783. isMesh: true,
  8784. setDrawMode: function ( value ) {
  8785. this.drawMode = value;
  8786. },
  8787. copy: function ( source ) {
  8788. Object3D.prototype.copy.call( this, source );
  8789. this.drawMode = source.drawMode;
  8790. return this;
  8791. },
  8792. updateMorphTargets: function () {
  8793. var morphTargets = this.geometry.morphTargets;
  8794. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  8795. this.morphTargetInfluences = [];
  8796. this.morphTargetDictionary = {};
  8797. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  8798. this.morphTargetInfluences.push( 0 );
  8799. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  8800. }
  8801. }
  8802. },
  8803. raycast: ( function () {
  8804. var inverseMatrix = new Matrix4();
  8805. var ray = new Ray();
  8806. var sphere = new Sphere();
  8807. var vA = new Vector3();
  8808. var vB = new Vector3();
  8809. var vC = new Vector3();
  8810. var tempA = new Vector3();
  8811. var tempB = new Vector3();
  8812. var tempC = new Vector3();
  8813. var uvA = new Vector2();
  8814. var uvB = new Vector2();
  8815. var uvC = new Vector2();
  8816. var barycoord = new Vector3();
  8817. var intersectionPoint = new Vector3();
  8818. var intersectionPointWorld = new Vector3();
  8819. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  8820. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  8821. uv1.multiplyScalar( barycoord.x );
  8822. uv2.multiplyScalar( barycoord.y );
  8823. uv3.multiplyScalar( barycoord.z );
  8824. uv1.add( uv2 ).add( uv3 );
  8825. return uv1.clone();
  8826. }
  8827. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  8828. var intersect;
  8829. var material = object.material;
  8830. if ( material.side === BackSide ) {
  8831. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8832. } else {
  8833. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  8834. }
  8835. if ( intersect === null ) return null;
  8836. intersectionPointWorld.copy( point );
  8837. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8838. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  8839. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8840. return {
  8841. distance: distance,
  8842. point: intersectionPointWorld.clone(),
  8843. object: object
  8844. };
  8845. }
  8846. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  8847. vA.fromBufferAttribute( position, a );
  8848. vB.fromBufferAttribute( position, b );
  8849. vC.fromBufferAttribute( position, c );
  8850. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  8851. if ( intersection ) {
  8852. if ( uv ) {
  8853. uvA.fromBufferAttribute( uv, a );
  8854. uvB.fromBufferAttribute( uv, b );
  8855. uvC.fromBufferAttribute( uv, c );
  8856. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  8857. }
  8858. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  8859. intersection.faceIndex = a;
  8860. }
  8861. return intersection;
  8862. }
  8863. return function raycast( raycaster, intersects ) {
  8864. var geometry = this.geometry;
  8865. var material = this.material;
  8866. var matrixWorld = this.matrixWorld;
  8867. if ( material === undefined ) return;
  8868. // Checking boundingSphere distance to ray
  8869. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8870. sphere.copy( geometry.boundingSphere );
  8871. sphere.applyMatrix4( matrixWorld );
  8872. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  8873. //
  8874. inverseMatrix.getInverse( matrixWorld );
  8875. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8876. // Check boundingBox before continuing
  8877. if ( geometry.boundingBox !== null ) {
  8878. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  8879. }
  8880. var intersection;
  8881. if ( geometry.isBufferGeometry ) {
  8882. var a, b, c;
  8883. var index = geometry.index;
  8884. var position = geometry.attributes.position;
  8885. var uv = geometry.attributes.uv;
  8886. var i, l;
  8887. if ( index !== null ) {
  8888. // indexed buffer geometry
  8889. for ( i = 0, l = index.count; i < l; i += 3 ) {
  8890. a = index.getX( i );
  8891. b = index.getX( i + 1 );
  8892. c = index.getX( i + 2 );
  8893. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  8894. if ( intersection ) {
  8895. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  8896. intersects.push( intersection );
  8897. }
  8898. }
  8899. } else {
  8900. // non-indexed buffer geometry
  8901. for ( i = 0, l = position.count; i < l; i += 3 ) {
  8902. a = i;
  8903. b = i + 1;
  8904. c = i + 2;
  8905. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  8906. if ( intersection ) {
  8907. intersection.index = a; // triangle number in positions buffer semantics
  8908. intersects.push( intersection );
  8909. }
  8910. }
  8911. }
  8912. } else if ( geometry.isGeometry ) {
  8913. var fvA, fvB, fvC;
  8914. var isFaceMaterial = ( material && material.isMultiMaterial );
  8915. var materials = isFaceMaterial === true ? material.materials : null;
  8916. var vertices = geometry.vertices;
  8917. var faces = geometry.faces;
  8918. var uvs;
  8919. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  8920. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  8921. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  8922. var face = faces[ f ];
  8923. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  8924. if ( faceMaterial === undefined ) continue;
  8925. fvA = vertices[ face.a ];
  8926. fvB = vertices[ face.b ];
  8927. fvC = vertices[ face.c ];
  8928. if ( faceMaterial.morphTargets === true ) {
  8929. var morphTargets = geometry.morphTargets;
  8930. var morphInfluences = this.morphTargetInfluences;
  8931. vA.set( 0, 0, 0 );
  8932. vB.set( 0, 0, 0 );
  8933. vC.set( 0, 0, 0 );
  8934. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8935. var influence = morphInfluences[ t ];
  8936. if ( influence === 0 ) continue;
  8937. var targets = morphTargets[ t ].vertices;
  8938. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  8939. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  8940. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  8941. }
  8942. vA.add( fvA );
  8943. vB.add( fvB );
  8944. vC.add( fvC );
  8945. fvA = vA;
  8946. fvB = vB;
  8947. fvC = vC;
  8948. }
  8949. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  8950. if ( intersection ) {
  8951. if ( uvs ) {
  8952. var uvs_f = uvs[ f ];
  8953. uvA.copy( uvs_f[ 0 ] );
  8954. uvB.copy( uvs_f[ 1 ] );
  8955. uvC.copy( uvs_f[ 2 ] );
  8956. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  8957. }
  8958. intersection.face = face;
  8959. intersection.faceIndex = f;
  8960. intersects.push( intersection );
  8961. }
  8962. }
  8963. }
  8964. };
  8965. }() ),
  8966. clone: function () {
  8967. return new this.constructor( this.geometry, this.material ).copy( this );
  8968. }
  8969. } );
  8970. /**
  8971. * @author Mugen87 / https://github.com/Mugen87
  8972. */
  8973. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  8974. BufferGeometry.call( this );
  8975. this.type = 'BoxBufferGeometry';
  8976. this.parameters = {
  8977. width: width,
  8978. height: height,
  8979. depth: depth,
  8980. widthSegments: widthSegments,
  8981. heightSegments: heightSegments,
  8982. depthSegments: depthSegments
  8983. };
  8984. var scope = this;
  8985. // segments
  8986. widthSegments = Math.floor( widthSegments ) || 1;
  8987. heightSegments = Math.floor( heightSegments ) || 1;
  8988. depthSegments = Math.floor( depthSegments ) || 1;
  8989. // these are used to calculate buffer length
  8990. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  8991. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  8992. // buffers
  8993. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  8994. var vertices = new Float32Array( vertexCount * 3 );
  8995. var normals = new Float32Array( vertexCount * 3 );
  8996. var uvs = new Float32Array( vertexCount * 2 );
  8997. // offset variables
  8998. var vertexBufferOffset = 0;
  8999. var uvBufferOffset = 0;
  9000. var indexBufferOffset = 0;
  9001. var numberOfVertices = 0;
  9002. // group variables
  9003. var groupStart = 0;
  9004. // build each side of the box geometry
  9005. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  9006. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  9007. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  9008. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  9009. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  9010. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  9011. // build geometry
  9012. this.setIndex( new BufferAttribute( indices, 1 ) );
  9013. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9014. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9015. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9016. // helper functions
  9017. function calculateVertexCount( w, h, d ) {
  9018. var vertices = 0;
  9019. // calculate the amount of vertices for each side (plane)
  9020. vertices += (w + 1) * (h + 1) * 2; // xy
  9021. vertices += (w + 1) * (d + 1) * 2; // xz
  9022. vertices += (d + 1) * (h + 1) * 2; // zy
  9023. return vertices;
  9024. }
  9025. function calculateIndexCount( w, h, d ) {
  9026. var index = 0;
  9027. // calculate the amount of squares for each side
  9028. index += w * h * 2; // xy
  9029. index += w * d * 2; // xz
  9030. index += d * h * 2; // zy
  9031. return index * 6; // two triangles per square => six vertices per square
  9032. }
  9033. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  9034. var segmentWidth = width / gridX;
  9035. var segmentHeight = height / gridY;
  9036. var widthHalf = width / 2;
  9037. var heightHalf = height / 2;
  9038. var depthHalf = depth / 2;
  9039. var gridX1 = gridX + 1;
  9040. var gridY1 = gridY + 1;
  9041. var vertexCounter = 0;
  9042. var groupCount = 0;
  9043. var vector = new Vector3();
  9044. // generate vertices, normals and uvs
  9045. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9046. var y = iy * segmentHeight - heightHalf;
  9047. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9048. var x = ix * segmentWidth - widthHalf;
  9049. // set values to correct vector component
  9050. vector[ u ] = x * udir;
  9051. vector[ v ] = y * vdir;
  9052. vector[ w ] = depthHalf;
  9053. // now apply vector to vertex buffer
  9054. vertices[ vertexBufferOffset ] = vector.x;
  9055. vertices[ vertexBufferOffset + 1 ] = vector.y;
  9056. vertices[ vertexBufferOffset + 2 ] = vector.z;
  9057. // set values to correct vector component
  9058. vector[ u ] = 0;
  9059. vector[ v ] = 0;
  9060. vector[ w ] = depth > 0 ? 1 : - 1;
  9061. // now apply vector to normal buffer
  9062. normals[ vertexBufferOffset ] = vector.x;
  9063. normals[ vertexBufferOffset + 1 ] = vector.y;
  9064. normals[ vertexBufferOffset + 2 ] = vector.z;
  9065. // uvs
  9066. uvs[ uvBufferOffset ] = ix / gridX;
  9067. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  9068. // update offsets and counters
  9069. vertexBufferOffset += 3;
  9070. uvBufferOffset += 2;
  9071. vertexCounter += 1;
  9072. }
  9073. }
  9074. // 1. you need three indices to draw a single face
  9075. // 2. a single segment consists of two faces
  9076. // 3. so we need to generate six (2*3) indices per segment
  9077. for ( iy = 0; iy < gridY; iy ++ ) {
  9078. for ( ix = 0; ix < gridX; ix ++ ) {
  9079. // indices
  9080. var a = numberOfVertices + ix + gridX1 * iy;
  9081. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  9082. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  9083. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  9084. // face one
  9085. indices[ indexBufferOffset ] = a;
  9086. indices[ indexBufferOffset + 1 ] = b;
  9087. indices[ indexBufferOffset + 2 ] = d;
  9088. // face two
  9089. indices[ indexBufferOffset + 3 ] = b;
  9090. indices[ indexBufferOffset + 4 ] = c;
  9091. indices[ indexBufferOffset + 5 ] = d;
  9092. // update offsets and counters
  9093. indexBufferOffset += 6;
  9094. groupCount += 6;
  9095. }
  9096. }
  9097. // add a group to the geometry. this will ensure multi material support
  9098. scope.addGroup( groupStart, groupCount, materialIndex );
  9099. // calculate new start value for groups
  9100. groupStart += groupCount;
  9101. // update total number of vertices
  9102. numberOfVertices += vertexCounter;
  9103. }
  9104. }
  9105. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9106. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  9107. /**
  9108. * @author mrdoob / http://mrdoob.com/
  9109. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  9110. */
  9111. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  9112. BufferGeometry.call( this );
  9113. this.type = 'PlaneBufferGeometry';
  9114. this.parameters = {
  9115. width: width,
  9116. height: height,
  9117. widthSegments: widthSegments,
  9118. heightSegments: heightSegments
  9119. };
  9120. var width_half = width / 2;
  9121. var height_half = height / 2;
  9122. var gridX = Math.floor( widthSegments ) || 1;
  9123. var gridY = Math.floor( heightSegments ) || 1;
  9124. var gridX1 = gridX + 1;
  9125. var gridY1 = gridY + 1;
  9126. var segment_width = width / gridX;
  9127. var segment_height = height / gridY;
  9128. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  9129. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  9130. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  9131. var offset = 0;
  9132. var offset2 = 0;
  9133. for ( var iy = 0; iy < gridY1; iy ++ ) {
  9134. var y = iy * segment_height - height_half;
  9135. for ( var ix = 0; ix < gridX1; ix ++ ) {
  9136. var x = ix * segment_width - width_half;
  9137. vertices[ offset ] = x;
  9138. vertices[ offset + 1 ] = - y;
  9139. normals[ offset + 2 ] = 1;
  9140. uvs[ offset2 ] = ix / gridX;
  9141. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  9142. offset += 3;
  9143. offset2 += 2;
  9144. }
  9145. }
  9146. offset = 0;
  9147. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  9148. for ( var iy = 0; iy < gridY; iy ++ ) {
  9149. for ( var ix = 0; ix < gridX; ix ++ ) {
  9150. var a = ix + gridX1 * iy;
  9151. var b = ix + gridX1 * ( iy + 1 );
  9152. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  9153. var d = ( ix + 1 ) + gridX1 * iy;
  9154. indices[ offset ] = a;
  9155. indices[ offset + 1 ] = b;
  9156. indices[ offset + 2 ] = d;
  9157. indices[ offset + 3 ] = b;
  9158. indices[ offset + 4 ] = c;
  9159. indices[ offset + 5 ] = d;
  9160. offset += 6;
  9161. }
  9162. }
  9163. this.setIndex( new BufferAttribute( indices, 1 ) );
  9164. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  9165. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  9166. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  9167. }
  9168. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  9169. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9170. /**
  9171. * @author mrdoob / http://mrdoob.com/
  9172. * @author mikael emtinger / http://gomo.se/
  9173. * @author WestLangley / http://github.com/WestLangley
  9174. */
  9175. function Camera() {
  9176. Object3D.call( this );
  9177. this.type = 'Camera';
  9178. this.matrixWorldInverse = new Matrix4();
  9179. this.projectionMatrix = new Matrix4();
  9180. }
  9181. Camera.prototype = Object.create( Object3D.prototype );
  9182. Camera.prototype.constructor = Camera;
  9183. Camera.prototype.isCamera = true;
  9184. Camera.prototype.getWorldDirection = function () {
  9185. var quaternion = new Quaternion();
  9186. return function getWorldDirection( optionalTarget ) {
  9187. var result = optionalTarget || new Vector3();
  9188. this.getWorldQuaternion( quaternion );
  9189. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9190. };
  9191. }();
  9192. Camera.prototype.lookAt = function () {
  9193. // This routine does not support cameras with rotated and/or translated parent(s)
  9194. var m1 = new Matrix4();
  9195. return function lookAt( vector ) {
  9196. m1.lookAt( this.position, vector, this.up );
  9197. this.quaternion.setFromRotationMatrix( m1 );
  9198. };
  9199. }();
  9200. Camera.prototype.clone = function () {
  9201. return new this.constructor().copy( this );
  9202. };
  9203. Camera.prototype.copy = function ( source ) {
  9204. Object3D.prototype.copy.call( this, source );
  9205. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9206. this.projectionMatrix.copy( source.projectionMatrix );
  9207. return this;
  9208. };
  9209. /**
  9210. * @author mrdoob / http://mrdoob.com/
  9211. * @author greggman / http://games.greggman.com/
  9212. * @author zz85 / http://www.lab4games.net/zz85/blog
  9213. * @author tschw
  9214. */
  9215. function PerspectiveCamera( fov, aspect, near, far ) {
  9216. Camera.call( this );
  9217. this.type = 'PerspectiveCamera';
  9218. this.fov = fov !== undefined ? fov : 50;
  9219. this.zoom = 1;
  9220. this.near = near !== undefined ? near : 0.1;
  9221. this.far = far !== undefined ? far : 2000;
  9222. this.focus = 10;
  9223. this.aspect = aspect !== undefined ? aspect : 1;
  9224. this.view = null;
  9225. this.filmGauge = 35; // width of the film (default in millimeters)
  9226. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9227. this.updateProjectionMatrix();
  9228. }
  9229. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9230. constructor: PerspectiveCamera,
  9231. isPerspectiveCamera: true,
  9232. copy: function ( source ) {
  9233. Camera.prototype.copy.call( this, source );
  9234. this.fov = source.fov;
  9235. this.zoom = source.zoom;
  9236. this.near = source.near;
  9237. this.far = source.far;
  9238. this.focus = source.focus;
  9239. this.aspect = source.aspect;
  9240. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9241. this.filmGauge = source.filmGauge;
  9242. this.filmOffset = source.filmOffset;
  9243. return this;
  9244. },
  9245. /**
  9246. * Sets the FOV by focal length in respect to the current .filmGauge.
  9247. *
  9248. * The default film gauge is 35, so that the focal length can be specified for
  9249. * a 35mm (full frame) camera.
  9250. *
  9251. * Values for focal length and film gauge must have the same unit.
  9252. */
  9253. setFocalLength: function ( focalLength ) {
  9254. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9255. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9256. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  9257. this.updateProjectionMatrix();
  9258. },
  9259. /**
  9260. * Calculates the focal length from the current .fov and .filmGauge.
  9261. */
  9262. getFocalLength: function () {
  9263. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  9264. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9265. },
  9266. getEffectiveFOV: function () {
  9267. return _Math.RAD2DEG * 2 * Math.atan(
  9268. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9269. },
  9270. getFilmWidth: function () {
  9271. // film not completely covered in portrait format (aspect < 1)
  9272. return this.filmGauge * Math.min( this.aspect, 1 );
  9273. },
  9274. getFilmHeight: function () {
  9275. // film not completely covered in landscape format (aspect > 1)
  9276. return this.filmGauge / Math.max( this.aspect, 1 );
  9277. },
  9278. /**
  9279. * Sets an offset in a larger frustum. This is useful for multi-window or
  9280. * multi-monitor/multi-machine setups.
  9281. *
  9282. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9283. * the monitors are in grid like this
  9284. *
  9285. * +---+---+---+
  9286. * | A | B | C |
  9287. * +---+---+---+
  9288. * | D | E | F |
  9289. * +---+---+---+
  9290. *
  9291. * then for each monitor you would call it like this
  9292. *
  9293. * var w = 1920;
  9294. * var h = 1080;
  9295. * var fullWidth = w * 3;
  9296. * var fullHeight = h * 2;
  9297. *
  9298. * --A--
  9299. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9300. * --B--
  9301. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9302. * --C--
  9303. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9304. * --D--
  9305. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9306. * --E--
  9307. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9308. * --F--
  9309. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9310. *
  9311. * Note there is no reason monitors have to be the same size or in a grid.
  9312. */
  9313. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  9314. this.aspect = fullWidth / fullHeight;
  9315. this.view = {
  9316. fullWidth: fullWidth,
  9317. fullHeight: fullHeight,
  9318. offsetX: x,
  9319. offsetY: y,
  9320. width: width,
  9321. height: height
  9322. };
  9323. this.updateProjectionMatrix();
  9324. },
  9325. clearViewOffset: function() {
  9326. this.view = null;
  9327. this.updateProjectionMatrix();
  9328. },
  9329. updateProjectionMatrix: function () {
  9330. var near = this.near,
  9331. top = near * Math.tan(
  9332. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  9333. height = 2 * top,
  9334. width = this.aspect * height,
  9335. left = - 0.5 * width,
  9336. view = this.view;
  9337. if ( view !== null ) {
  9338. var fullWidth = view.fullWidth,
  9339. fullHeight = view.fullHeight;
  9340. left += view.offsetX * width / fullWidth;
  9341. top -= view.offsetY * height / fullHeight;
  9342. width *= view.width / fullWidth;
  9343. height *= view.height / fullHeight;
  9344. }
  9345. var skew = this.filmOffset;
  9346. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9347. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  9348. },
  9349. toJSON: function ( meta ) {
  9350. var data = Object3D.prototype.toJSON.call( this, meta );
  9351. data.object.fov = this.fov;
  9352. data.object.zoom = this.zoom;
  9353. data.object.near = this.near;
  9354. data.object.far = this.far;
  9355. data.object.focus = this.focus;
  9356. data.object.aspect = this.aspect;
  9357. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9358. data.object.filmGauge = this.filmGauge;
  9359. data.object.filmOffset = this.filmOffset;
  9360. return data;
  9361. }
  9362. } );
  9363. /**
  9364. * @author alteredq / http://alteredqualia.com/
  9365. * @author arose / http://github.com/arose
  9366. */
  9367. function OrthographicCamera( left, right, top, bottom, near, far ) {
  9368. Camera.call( this );
  9369. this.type = 'OrthographicCamera';
  9370. this.zoom = 1;
  9371. this.view = null;
  9372. this.left = left;
  9373. this.right = right;
  9374. this.top = top;
  9375. this.bottom = bottom;
  9376. this.near = ( near !== undefined ) ? near : 0.1;
  9377. this.far = ( far !== undefined ) ? far : 2000;
  9378. this.updateProjectionMatrix();
  9379. }
  9380. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  9381. constructor: OrthographicCamera,
  9382. isOrthographicCamera: true,
  9383. copy: function ( source ) {
  9384. Camera.prototype.copy.call( this, source );
  9385. this.left = source.left;
  9386. this.right = source.right;
  9387. this.top = source.top;
  9388. this.bottom = source.bottom;
  9389. this.near = source.near;
  9390. this.far = source.far;
  9391. this.zoom = source.zoom;
  9392. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9393. return this;
  9394. },
  9395. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  9396. this.view = {
  9397. fullWidth: fullWidth,
  9398. fullHeight: fullHeight,
  9399. offsetX: x,
  9400. offsetY: y,
  9401. width: width,
  9402. height: height
  9403. };
  9404. this.updateProjectionMatrix();
  9405. },
  9406. clearViewOffset: function() {
  9407. this.view = null;
  9408. this.updateProjectionMatrix();
  9409. },
  9410. updateProjectionMatrix: function () {
  9411. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9412. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9413. var cx = ( this.right + this.left ) / 2;
  9414. var cy = ( this.top + this.bottom ) / 2;
  9415. var left = cx - dx;
  9416. var right = cx + dx;
  9417. var top = cy + dy;
  9418. var bottom = cy - dy;
  9419. if ( this.view !== null ) {
  9420. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  9421. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  9422. var scaleW = ( this.right - this.left ) / this.view.width;
  9423. var scaleH = ( this.top - this.bottom ) / this.view.height;
  9424. left += scaleW * ( this.view.offsetX / zoomW );
  9425. right = left + scaleW * ( this.view.width / zoomW );
  9426. top -= scaleH * ( this.view.offsetY / zoomH );
  9427. bottom = top - scaleH * ( this.view.height / zoomH );
  9428. }
  9429. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9430. },
  9431. toJSON: function ( meta ) {
  9432. var data = Object3D.prototype.toJSON.call( this, meta );
  9433. data.object.zoom = this.zoom;
  9434. data.object.left = this.left;
  9435. data.object.right = this.right;
  9436. data.object.top = this.top;
  9437. data.object.bottom = this.bottom;
  9438. data.object.near = this.near;
  9439. data.object.far = this.far;
  9440. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9441. return data;
  9442. }
  9443. } );
  9444. /**
  9445. * @author mrdoob / http://mrdoob.com/
  9446. */
  9447. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  9448. var mode;
  9449. function setMode( value ) {
  9450. mode = value;
  9451. }
  9452. var type, size;
  9453. function setIndex( index ) {
  9454. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9455. type = gl.UNSIGNED_INT;
  9456. size = 4;
  9457. } else if ( index.array instanceof Uint16Array ) {
  9458. type = gl.UNSIGNED_SHORT;
  9459. size = 2;
  9460. } else {
  9461. type = gl.UNSIGNED_BYTE;
  9462. size = 1;
  9463. }
  9464. }
  9465. function render( start, count ) {
  9466. gl.drawElements( mode, count, type, start * size );
  9467. infoRender.calls ++;
  9468. infoRender.vertices += count;
  9469. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9470. }
  9471. function renderInstances( geometry, start, count ) {
  9472. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9473. if ( extension === null ) {
  9474. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9475. return;
  9476. }
  9477. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  9478. infoRender.calls ++;
  9479. infoRender.vertices += count * geometry.maxInstancedCount;
  9480. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9481. }
  9482. return {
  9483. setMode: setMode,
  9484. setIndex: setIndex,
  9485. render: render,
  9486. renderInstances: renderInstances
  9487. };
  9488. }
  9489. /**
  9490. * @author mrdoob / http://mrdoob.com/
  9491. */
  9492. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  9493. var mode;
  9494. function setMode( value ) {
  9495. mode = value;
  9496. }
  9497. function render( start, count ) {
  9498. gl.drawArrays( mode, start, count );
  9499. infoRender.calls ++;
  9500. infoRender.vertices += count;
  9501. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  9502. }
  9503. function renderInstances( geometry ) {
  9504. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  9505. if ( extension === null ) {
  9506. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9507. return;
  9508. }
  9509. var position = geometry.attributes.position;
  9510. var count = 0;
  9511. if ( position.isInterleavedBufferAttribute ) {
  9512. count = position.data.count;
  9513. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9514. } else {
  9515. count = position.count;
  9516. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  9517. }
  9518. infoRender.calls ++;
  9519. infoRender.vertices += count * geometry.maxInstancedCount;
  9520. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  9521. }
  9522. return {
  9523. setMode: setMode,
  9524. render: render,
  9525. renderInstances: renderInstances
  9526. };
  9527. }
  9528. /**
  9529. * @author mrdoob / http://mrdoob.com/
  9530. */
  9531. function WebGLLights() {
  9532. var lights = {};
  9533. return {
  9534. get: function ( light ) {
  9535. if ( lights[ light.id ] !== undefined ) {
  9536. return lights[ light.id ];
  9537. }
  9538. var uniforms;
  9539. switch ( light.type ) {
  9540. case 'DirectionalLight':
  9541. uniforms = {
  9542. direction: new Vector3(),
  9543. color: new Color(),
  9544. shadow: false,
  9545. shadowBias: 0,
  9546. shadowRadius: 1,
  9547. shadowMapSize: new Vector2()
  9548. };
  9549. break;
  9550. case 'SpotLight':
  9551. uniforms = {
  9552. position: new Vector3(),
  9553. direction: new Vector3(),
  9554. color: new Color(),
  9555. distance: 0,
  9556. coneCos: 0,
  9557. penumbraCos: 0,
  9558. decay: 0,
  9559. shadow: false,
  9560. shadowBias: 0,
  9561. shadowRadius: 1,
  9562. shadowMapSize: new Vector2()
  9563. };
  9564. break;
  9565. case 'PointLight':
  9566. uniforms = {
  9567. position: new Vector3(),
  9568. color: new Color(),
  9569. distance: 0,
  9570. decay: 0,
  9571. shadow: false,
  9572. shadowBias: 0,
  9573. shadowRadius: 1,
  9574. shadowMapSize: new Vector2()
  9575. };
  9576. break;
  9577. case 'HemisphereLight':
  9578. uniforms = {
  9579. direction: new Vector3(),
  9580. skyColor: new Color(),
  9581. groundColor: new Color()
  9582. };
  9583. break;
  9584. case 'RectAreaLight':
  9585. uniforms = {
  9586. color: new Color(),
  9587. position: new Vector3(),
  9588. halfWidth: new Vector3(),
  9589. halfHeight: new Vector3()
  9590. // TODO (abelnation): set RectAreaLight shadow uniforms
  9591. };
  9592. break;
  9593. }
  9594. lights[ light.id ] = uniforms;
  9595. return uniforms;
  9596. }
  9597. };
  9598. }
  9599. /**
  9600. * @author mrdoob / http://mrdoob.com/
  9601. */
  9602. function addLineNumbers( string ) {
  9603. var lines = string.split( '\n' );
  9604. for ( var i = 0; i < lines.length; i ++ ) {
  9605. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9606. }
  9607. return lines.join( '\n' );
  9608. }
  9609. function WebGLShader( gl, type, string ) {
  9610. var shader = gl.createShader( type );
  9611. gl.shaderSource( shader, string );
  9612. gl.compileShader( shader );
  9613. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  9614. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  9615. }
  9616. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  9617. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  9618. }
  9619. // --enable-privileged-webgl-extension
  9620. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9621. return shader;
  9622. }
  9623. /**
  9624. * @author mrdoob / http://mrdoob.com/
  9625. */
  9626. var programIdCount = 0;
  9627. function getEncodingComponents( encoding ) {
  9628. switch ( encoding ) {
  9629. case LinearEncoding:
  9630. return [ 'Linear','( value )' ];
  9631. case sRGBEncoding:
  9632. return [ 'sRGB','( value )' ];
  9633. case RGBEEncoding:
  9634. return [ 'RGBE','( value )' ];
  9635. case RGBM7Encoding:
  9636. return [ 'RGBM','( value, 7.0 )' ];
  9637. case RGBM16Encoding:
  9638. return [ 'RGBM','( value, 16.0 )' ];
  9639. case RGBDEncoding:
  9640. return [ 'RGBD','( value, 256.0 )' ];
  9641. case GammaEncoding:
  9642. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  9643. default:
  9644. throw new Error( 'unsupported encoding: ' + encoding );
  9645. }
  9646. }
  9647. function getTexelDecodingFunction( functionName, encoding ) {
  9648. var components = getEncodingComponents( encoding );
  9649. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  9650. }
  9651. function getTexelEncodingFunction( functionName, encoding ) {
  9652. var components = getEncodingComponents( encoding );
  9653. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  9654. }
  9655. function getToneMappingFunction( functionName, toneMapping ) {
  9656. var toneMappingName;
  9657. switch ( toneMapping ) {
  9658. case LinearToneMapping:
  9659. toneMappingName = "Linear";
  9660. break;
  9661. case ReinhardToneMapping:
  9662. toneMappingName = "Reinhard";
  9663. break;
  9664. case Uncharted2ToneMapping:
  9665. toneMappingName = "Uncharted2";
  9666. break;
  9667. case CineonToneMapping:
  9668. toneMappingName = "OptimizedCineon";
  9669. break;
  9670. default:
  9671. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  9672. }
  9673. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  9674. }
  9675. function generateExtensions( extensions, parameters, rendererExtensions ) {
  9676. extensions = extensions || {};
  9677. var chunks = [
  9678. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9679. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  9680. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9681. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  9682. ];
  9683. return chunks.filter( filterEmptyLine ).join( '\n' );
  9684. }
  9685. function generateDefines( defines ) {
  9686. var chunks = [];
  9687. for ( var name in defines ) {
  9688. var value = defines[ name ];
  9689. if ( value === false ) continue;
  9690. chunks.push( '#define ' + name + ' ' + value );
  9691. }
  9692. return chunks.join( '\n' );
  9693. }
  9694. function fetchAttributeLocations( gl, program, identifiers ) {
  9695. var attributes = {};
  9696. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  9697. for ( var i = 0; i < n; i ++ ) {
  9698. var info = gl.getActiveAttrib( program, i );
  9699. var name = info.name;
  9700. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  9701. attributes[ name ] = gl.getAttribLocation( program, name );
  9702. }
  9703. return attributes;
  9704. }
  9705. function filterEmptyLine( string ) {
  9706. return string !== '';
  9707. }
  9708. function replaceLightNums( string, parameters ) {
  9709. return string
  9710. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9711. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9712. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  9713. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9714. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  9715. }
  9716. function parseIncludes( string ) {
  9717. var pattern = /#include +<([\w\d.]+)>/g;
  9718. function replace( match, include ) {
  9719. var replace = ShaderChunk[ include ];
  9720. if ( replace === undefined ) {
  9721. throw new Error( 'Can not resolve #include <' + include + '>' );
  9722. }
  9723. return parseIncludes( replace );
  9724. }
  9725. return string.replace( pattern, replace );
  9726. }
  9727. function unrollLoops( string ) {
  9728. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9729. function replace( match, start, end, snippet ) {
  9730. var unroll = '';
  9731. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9732. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  9733. }
  9734. return unroll;
  9735. }
  9736. return string.replace( pattern, replace );
  9737. }
  9738. function WebGLProgram( renderer, code, material, parameters ) {
  9739. var gl = renderer.context;
  9740. var extensions = material.extensions;
  9741. var defines = material.defines;
  9742. var vertexShader = material.__webglShader.vertexShader;
  9743. var fragmentShader = material.__webglShader.fragmentShader;
  9744. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9745. if ( parameters.shadowMapType === PCFShadowMap ) {
  9746. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9747. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9748. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9749. }
  9750. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9751. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9752. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9753. if ( parameters.envMap ) {
  9754. switch ( material.envMap.mapping ) {
  9755. case CubeReflectionMapping:
  9756. case CubeRefractionMapping:
  9757. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9758. break;
  9759. case CubeUVReflectionMapping:
  9760. case CubeUVRefractionMapping:
  9761. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9762. break;
  9763. case EquirectangularReflectionMapping:
  9764. case EquirectangularRefractionMapping:
  9765. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  9766. break;
  9767. case SphericalReflectionMapping:
  9768. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  9769. break;
  9770. }
  9771. switch ( material.envMap.mapping ) {
  9772. case CubeRefractionMapping:
  9773. case EquirectangularRefractionMapping:
  9774. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9775. break;
  9776. }
  9777. switch ( material.combine ) {
  9778. case MultiplyOperation:
  9779. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9780. break;
  9781. case MixOperation:
  9782. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9783. break;
  9784. case AddOperation:
  9785. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9786. break;
  9787. }
  9788. }
  9789. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9790. // console.log( 'building new program ' );
  9791. //
  9792. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  9793. var customDefines = generateDefines( defines );
  9794. //
  9795. var program = gl.createProgram();
  9796. var prefixVertex, prefixFragment;
  9797. if ( material.isRawShaderMaterial ) {
  9798. prefixVertex = [
  9799. customDefines,
  9800. '\n'
  9801. ].filter( filterEmptyLine ).join( '\n' );
  9802. prefixFragment = [
  9803. customExtensions,
  9804. customDefines,
  9805. '\n'
  9806. ].filter( filterEmptyLine ).join( '\n' );
  9807. } else {
  9808. prefixVertex = [
  9809. 'precision ' + parameters.precision + ' float;',
  9810. 'precision ' + parameters.precision + ' int;',
  9811. '#define SHADER_NAME ' + material.__webglShader.name,
  9812. customDefines,
  9813. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  9814. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9815. '#define MAX_BONES ' + parameters.maxBones,
  9816. parameters.map ? '#define USE_MAP' : '',
  9817. parameters.envMap ? '#define USE_ENVMAP' : '',
  9818. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9819. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9820. parameters.aoMap ? '#define USE_AOMAP' : '',
  9821. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9822. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9823. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9824. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  9825. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9826. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9827. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9828. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9829. parameters.vertexColors ? '#define USE_COLOR' : '',
  9830. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9831. parameters.skinning ? '#define USE_SKINNING' : '',
  9832. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  9833. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  9834. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  9835. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9836. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9837. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9838. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9839. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9840. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  9841. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9842. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9843. 'uniform mat4 modelMatrix;',
  9844. 'uniform mat4 modelViewMatrix;',
  9845. 'uniform mat4 projectionMatrix;',
  9846. 'uniform mat4 viewMatrix;',
  9847. 'uniform mat3 normalMatrix;',
  9848. 'uniform vec3 cameraPosition;',
  9849. 'attribute vec3 position;',
  9850. 'attribute vec3 normal;',
  9851. 'attribute vec2 uv;',
  9852. '#ifdef USE_COLOR',
  9853. ' attribute vec3 color;',
  9854. '#endif',
  9855. '#ifdef USE_MORPHTARGETS',
  9856. ' attribute vec3 morphTarget0;',
  9857. ' attribute vec3 morphTarget1;',
  9858. ' attribute vec3 morphTarget2;',
  9859. ' attribute vec3 morphTarget3;',
  9860. ' #ifdef USE_MORPHNORMALS',
  9861. ' attribute vec3 morphNormal0;',
  9862. ' attribute vec3 morphNormal1;',
  9863. ' attribute vec3 morphNormal2;',
  9864. ' attribute vec3 morphNormal3;',
  9865. ' #else',
  9866. ' attribute vec3 morphTarget4;',
  9867. ' attribute vec3 morphTarget5;',
  9868. ' attribute vec3 morphTarget6;',
  9869. ' attribute vec3 morphTarget7;',
  9870. ' #endif',
  9871. '#endif',
  9872. '#ifdef USE_SKINNING',
  9873. ' attribute vec4 skinIndex;',
  9874. ' attribute vec4 skinWeight;',
  9875. '#endif',
  9876. '\n'
  9877. ].filter( filterEmptyLine ).join( '\n' );
  9878. prefixFragment = [
  9879. customExtensions,
  9880. 'precision ' + parameters.precision + ' float;',
  9881. 'precision ' + parameters.precision + ' int;',
  9882. '#define SHADER_NAME ' + material.__webglShader.name,
  9883. customDefines,
  9884. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  9885. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  9886. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  9887. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  9888. parameters.map ? '#define USE_MAP' : '',
  9889. parameters.envMap ? '#define USE_ENVMAP' : '',
  9890. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  9891. parameters.envMap ? '#define ' + envMapModeDefine : '',
  9892. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  9893. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  9894. parameters.aoMap ? '#define USE_AOMAP' : '',
  9895. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  9896. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  9897. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  9898. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  9899. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  9900. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  9901. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  9902. parameters.vertexColors ? '#define USE_COLOR' : '',
  9903. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  9904. parameters.flatShading ? '#define FLAT_SHADED' : '',
  9905. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  9906. parameters.flipSided ? '#define FLIP_SIDED' : '',
  9907. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  9908. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  9909. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  9910. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  9911. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  9912. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  9913. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  9914. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  9915. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  9916. 'uniform mat4 viewMatrix;',
  9917. 'uniform vec3 cameraPosition;',
  9918. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  9919. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  9920. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  9921. ( 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
  9922. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  9923. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  9924. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  9925. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  9926. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  9927. '\n'
  9928. ].filter( filterEmptyLine ).join( '\n' );
  9929. }
  9930. vertexShader = parseIncludes( vertexShader, parameters );
  9931. vertexShader = replaceLightNums( vertexShader, parameters );
  9932. fragmentShader = parseIncludes( fragmentShader, parameters );
  9933. fragmentShader = replaceLightNums( fragmentShader, parameters );
  9934. if ( ! material.isShaderMaterial ) {
  9935. vertexShader = unrollLoops( vertexShader );
  9936. fragmentShader = unrollLoops( fragmentShader );
  9937. }
  9938. var vertexGlsl = prefixVertex + vertexShader;
  9939. var fragmentGlsl = prefixFragment + fragmentShader;
  9940. // console.log( '*VERTEX*', vertexGlsl );
  9941. // console.log( '*FRAGMENT*', fragmentGlsl );
  9942. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  9943. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  9944. gl.attachShader( program, glVertexShader );
  9945. gl.attachShader( program, glFragmentShader );
  9946. // Force a particular attribute to index 0.
  9947. if ( material.index0AttributeName !== undefined ) {
  9948. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  9949. } else if ( parameters.morphTargets === true ) {
  9950. // programs with morphTargets displace position out of attribute 0
  9951. gl.bindAttribLocation( program, 0, 'position' );
  9952. }
  9953. gl.linkProgram( program );
  9954. var programLog = gl.getProgramInfoLog( program );
  9955. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  9956. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  9957. var runnable = true;
  9958. var haveDiagnostics = true;
  9959. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  9960. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  9961. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  9962. runnable = false;
  9963. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  9964. } else if ( programLog !== '' ) {
  9965. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  9966. } else if ( vertexLog === '' || fragmentLog === '' ) {
  9967. haveDiagnostics = false;
  9968. }
  9969. if ( haveDiagnostics ) {
  9970. this.diagnostics = {
  9971. runnable: runnable,
  9972. material: material,
  9973. programLog: programLog,
  9974. vertexShader: {
  9975. log: vertexLog,
  9976. prefix: prefixVertex
  9977. },
  9978. fragmentShader: {
  9979. log: fragmentLog,
  9980. prefix: prefixFragment
  9981. }
  9982. };
  9983. }
  9984. // clean up
  9985. gl.deleteShader( glVertexShader );
  9986. gl.deleteShader( glFragmentShader );
  9987. // set up caching for uniform locations
  9988. var cachedUniforms;
  9989. this.getUniforms = function() {
  9990. if ( cachedUniforms === undefined ) {
  9991. cachedUniforms =
  9992. new WebGLUniforms( gl, program, renderer );
  9993. }
  9994. return cachedUniforms;
  9995. };
  9996. // set up caching for attribute locations
  9997. var cachedAttributes;
  9998. this.getAttributes = function() {
  9999. if ( cachedAttributes === undefined ) {
  10000. cachedAttributes = fetchAttributeLocations( gl, program );
  10001. }
  10002. return cachedAttributes;
  10003. };
  10004. // free resource
  10005. this.destroy = function() {
  10006. gl.deleteProgram( program );
  10007. this.program = undefined;
  10008. };
  10009. // DEPRECATED
  10010. Object.defineProperties( this, {
  10011. uniforms: {
  10012. get: function() {
  10013. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  10014. return this.getUniforms();
  10015. }
  10016. },
  10017. attributes: {
  10018. get: function() {
  10019. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  10020. return this.getAttributes();
  10021. }
  10022. }
  10023. } );
  10024. //
  10025. this.id = programIdCount ++;
  10026. this.code = code;
  10027. this.usedTimes = 1;
  10028. this.program = program;
  10029. this.vertexShader = glVertexShader;
  10030. this.fragmentShader = glFragmentShader;
  10031. return this;
  10032. }
  10033. /**
  10034. * @author mrdoob / http://mrdoob.com/
  10035. */
  10036. function WebGLPrograms( renderer, capabilities ) {
  10037. var programs = [];
  10038. var shaderIDs = {
  10039. MeshDepthMaterial: 'depth',
  10040. MeshNormalMaterial: 'normal',
  10041. MeshBasicMaterial: 'basic',
  10042. MeshLambertMaterial: 'lambert',
  10043. MeshPhongMaterial: 'phong',
  10044. MeshToonMaterial: 'phong',
  10045. MeshStandardMaterial: 'physical',
  10046. MeshPhysicalMaterial: 'physical',
  10047. LineBasicMaterial: 'basic',
  10048. LineDashedMaterial: 'dashed',
  10049. PointsMaterial: 'points'
  10050. };
  10051. var parameterNames = [
  10052. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  10053. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  10054. "roughnessMap", "metalnessMap", "gradientMap",
  10055. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  10056. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  10057. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  10058. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  10059. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  10060. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  10061. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  10062. ];
  10063. function allocateBones( object ) {
  10064. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  10065. return 1024;
  10066. } else {
  10067. // default for when object is not specified
  10068. // ( for example when prebuilding shader to be used with multiple objects )
  10069. //
  10070. // - leave some extra space for other uniforms
  10071. // - limit here is ANGLE's 254 max uniform vectors
  10072. // (up to 54 should be safe)
  10073. var nVertexUniforms = capabilities.maxVertexUniforms;
  10074. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10075. var maxBones = nVertexMatrices;
  10076. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  10077. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  10078. if ( maxBones < object.skeleton.bones.length ) {
  10079. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  10080. }
  10081. }
  10082. return maxBones;
  10083. }
  10084. }
  10085. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  10086. var encoding;
  10087. if ( ! map ) {
  10088. encoding = LinearEncoding;
  10089. } else if ( map.isTexture ) {
  10090. encoding = map.encoding;
  10091. } else if ( map.isWebGLRenderTarget ) {
  10092. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  10093. encoding = map.texture.encoding;
  10094. }
  10095. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  10096. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  10097. encoding = GammaEncoding;
  10098. }
  10099. return encoding;
  10100. }
  10101. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  10102. var shaderID = shaderIDs[ material.type ];
  10103. // heuristics to create shader parameters according to lights in the scene
  10104. // (not to blow over maxLights budget)
  10105. var maxBones = allocateBones( object );
  10106. var precision = renderer.getPrecision();
  10107. if ( material.precision !== null ) {
  10108. precision = capabilities.getMaxPrecision( material.precision );
  10109. if ( precision !== material.precision ) {
  10110. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10111. }
  10112. }
  10113. var currentRenderTarget = renderer.getCurrentRenderTarget();
  10114. var parameters = {
  10115. shaderID: shaderID,
  10116. precision: precision,
  10117. supportsVertexTextures: capabilities.vertexTextures,
  10118. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  10119. map: !! material.map,
  10120. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  10121. envMap: !! material.envMap,
  10122. envMapMode: material.envMap && material.envMap.mapping,
  10123. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  10124. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  10125. lightMap: !! material.lightMap,
  10126. aoMap: !! material.aoMap,
  10127. emissiveMap: !! material.emissiveMap,
  10128. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  10129. bumpMap: !! material.bumpMap,
  10130. normalMap: !! material.normalMap,
  10131. displacementMap: !! material.displacementMap,
  10132. roughnessMap: !! material.roughnessMap,
  10133. metalnessMap: !! material.metalnessMap,
  10134. specularMap: !! material.specularMap,
  10135. alphaMap: !! material.alphaMap,
  10136. gradientMap: !! material.gradientMap,
  10137. combine: material.combine,
  10138. vertexColors: material.vertexColors,
  10139. fog: !! fog,
  10140. useFog: material.fog,
  10141. fogExp: (fog && fog.isFogExp2),
  10142. flatShading: material.shading === FlatShading,
  10143. sizeAttenuation: material.sizeAttenuation,
  10144. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  10145. skinning: material.skinning,
  10146. maxBones: maxBones,
  10147. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  10148. morphTargets: material.morphTargets,
  10149. morphNormals: material.morphNormals,
  10150. maxMorphTargets: renderer.maxMorphTargets,
  10151. maxMorphNormals: renderer.maxMorphNormals,
  10152. numDirLights: lights.directional.length,
  10153. numPointLights: lights.point.length,
  10154. numSpotLights: lights.spot.length,
  10155. numRectAreaLights: lights.rectArea.length,
  10156. numHemiLights: lights.hemi.length,
  10157. numClippingPlanes: nClipPlanes,
  10158. numClipIntersection: nClipIntersection,
  10159. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  10160. shadowMapType: renderer.shadowMap.type,
  10161. toneMapping: renderer.toneMapping,
  10162. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10163. premultipliedAlpha: material.premultipliedAlpha,
  10164. alphaTest: material.alphaTest,
  10165. doubleSided: material.side === DoubleSide,
  10166. flipSided: material.side === BackSide,
  10167. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  10168. };
  10169. return parameters;
  10170. };
  10171. this.getProgramCode = function ( material, parameters ) {
  10172. var array = [];
  10173. if ( parameters.shaderID ) {
  10174. array.push( parameters.shaderID );
  10175. } else {
  10176. array.push( material.fragmentShader );
  10177. array.push( material.vertexShader );
  10178. }
  10179. if ( material.defines !== undefined ) {
  10180. for ( var name in material.defines ) {
  10181. array.push( name );
  10182. array.push( material.defines[ name ] );
  10183. }
  10184. }
  10185. for ( var i = 0; i < parameterNames.length; i ++ ) {
  10186. array.push( parameters[ parameterNames[ i ] ] );
  10187. }
  10188. return array.join();
  10189. };
  10190. this.acquireProgram = function ( material, parameters, code ) {
  10191. var program;
  10192. // Check if code has been already compiled
  10193. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  10194. var programInfo = programs[ p ];
  10195. if ( programInfo.code === code ) {
  10196. program = programInfo;
  10197. ++ program.usedTimes;
  10198. break;
  10199. }
  10200. }
  10201. if ( program === undefined ) {
  10202. program = new WebGLProgram( renderer, code, material, parameters );
  10203. programs.push( program );
  10204. }
  10205. return program;
  10206. };
  10207. this.releaseProgram = function( program ) {
  10208. if ( -- program.usedTimes === 0 ) {
  10209. // Remove from unordered set
  10210. var i = programs.indexOf( program );
  10211. programs[ i ] = programs[ programs.length - 1 ];
  10212. programs.pop();
  10213. // Free WebGL resources
  10214. program.destroy();
  10215. }
  10216. };
  10217. // Exposed for resource monitoring & error feedback via renderer.info:
  10218. this.programs = programs;
  10219. }
  10220. /**
  10221. * @author mrdoob / http://mrdoob.com/
  10222. */
  10223. function WebGLGeometries( gl, properties, info ) {
  10224. var geometries = {};
  10225. function onGeometryDispose( event ) {
  10226. var geometry = event.target;
  10227. var buffergeometry = geometries[ geometry.id ];
  10228. if ( buffergeometry.index !== null ) {
  10229. deleteAttribute( buffergeometry.index );
  10230. }
  10231. deleteAttributes( buffergeometry.attributes );
  10232. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10233. delete geometries[ geometry.id ];
  10234. // TODO
  10235. var property = properties.get( geometry );
  10236. if ( property.wireframe ) {
  10237. deleteAttribute( property.wireframe );
  10238. }
  10239. properties.delete( geometry );
  10240. var bufferproperty = properties.get( buffergeometry );
  10241. if ( bufferproperty.wireframe ) {
  10242. deleteAttribute( bufferproperty.wireframe );
  10243. }
  10244. properties.delete( buffergeometry );
  10245. //
  10246. info.memory.geometries --;
  10247. }
  10248. function getAttributeBuffer( attribute ) {
  10249. if ( attribute.isInterleavedBufferAttribute ) {
  10250. return properties.get( attribute.data ).__webglBuffer;
  10251. }
  10252. return properties.get( attribute ).__webglBuffer;
  10253. }
  10254. function deleteAttribute( attribute ) {
  10255. var buffer = getAttributeBuffer( attribute );
  10256. if ( buffer !== undefined ) {
  10257. gl.deleteBuffer( buffer );
  10258. removeAttributeBuffer( attribute );
  10259. }
  10260. }
  10261. function deleteAttributes( attributes ) {
  10262. for ( var name in attributes ) {
  10263. deleteAttribute( attributes[ name ] );
  10264. }
  10265. }
  10266. function removeAttributeBuffer( attribute ) {
  10267. if ( attribute.isInterleavedBufferAttribute ) {
  10268. properties.delete( attribute.data );
  10269. } else {
  10270. properties.delete( attribute );
  10271. }
  10272. }
  10273. return {
  10274. get: function ( object ) {
  10275. var geometry = object.geometry;
  10276. if ( geometries[ geometry.id ] !== undefined ) {
  10277. return geometries[ geometry.id ];
  10278. }
  10279. geometry.addEventListener( 'dispose', onGeometryDispose );
  10280. var buffergeometry;
  10281. if ( geometry.isBufferGeometry ) {
  10282. buffergeometry = geometry;
  10283. } else if ( geometry.isGeometry ) {
  10284. if ( geometry._bufferGeometry === undefined ) {
  10285. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  10286. }
  10287. buffergeometry = geometry._bufferGeometry;
  10288. }
  10289. geometries[ geometry.id ] = buffergeometry;
  10290. info.memory.geometries ++;
  10291. return buffergeometry;
  10292. }
  10293. };
  10294. }
  10295. /**
  10296. * @author mrdoob / http://mrdoob.com/
  10297. */
  10298. function WebGLObjects( gl, properties, info ) {
  10299. var geometries = new WebGLGeometries( gl, properties, info );
  10300. //
  10301. function update( object ) {
  10302. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  10303. var geometry = geometries.get( object );
  10304. if ( object.geometry.isGeometry ) {
  10305. geometry.updateFromObject( object );
  10306. }
  10307. var index = geometry.index;
  10308. var attributes = geometry.attributes;
  10309. if ( index !== null ) {
  10310. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  10311. }
  10312. for ( var name in attributes ) {
  10313. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  10314. }
  10315. // morph targets
  10316. var morphAttributes = geometry.morphAttributes;
  10317. for ( var name in morphAttributes ) {
  10318. var array = morphAttributes[ name ];
  10319. for ( var i = 0, l = array.length; i < l; i ++ ) {
  10320. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  10321. }
  10322. }
  10323. return geometry;
  10324. }
  10325. function updateAttribute( attribute, bufferType ) {
  10326. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  10327. var attributeProperties = properties.get( data );
  10328. if ( attributeProperties.__webglBuffer === undefined ) {
  10329. createBuffer( attributeProperties, data, bufferType );
  10330. } else if ( attributeProperties.version !== data.version ) {
  10331. updateBuffer( attributeProperties, data, bufferType );
  10332. }
  10333. }
  10334. function createBuffer( attributeProperties, data, bufferType ) {
  10335. attributeProperties.__webglBuffer = gl.createBuffer();
  10336. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10337. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10338. gl.bufferData( bufferType, data.array, usage );
  10339. var type = gl.FLOAT;
  10340. var array = data.array;
  10341. if ( array instanceof Float32Array ) {
  10342. type = gl.FLOAT;
  10343. } else if ( array instanceof Float64Array ) {
  10344. console.warn( "Unsupported data buffer format: Float64Array" );
  10345. } else if ( array instanceof Uint16Array ) {
  10346. type = gl.UNSIGNED_SHORT;
  10347. } else if ( array instanceof Int16Array ) {
  10348. type = gl.SHORT;
  10349. } else if ( array instanceof Uint32Array ) {
  10350. type = gl.UNSIGNED_INT;
  10351. } else if ( array instanceof Int32Array ) {
  10352. type = gl.INT;
  10353. } else if ( array instanceof Int8Array ) {
  10354. type = gl.BYTE;
  10355. } else if ( array instanceof Uint8Array ) {
  10356. type = gl.UNSIGNED_BYTE;
  10357. }
  10358. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  10359. attributeProperties.type = type;
  10360. attributeProperties.version = data.version;
  10361. data.onUploadCallback();
  10362. }
  10363. function updateBuffer( attributeProperties, data, bufferType ) {
  10364. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  10365. if ( data.dynamic === false ) {
  10366. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  10367. } else if ( data.updateRange.count === - 1 ) {
  10368. // Not using update ranges
  10369. gl.bufferSubData( bufferType, 0, data.array );
  10370. } else if ( data.updateRange.count === 0 ) {
  10371. 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.' );
  10372. } else {
  10373. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  10374. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  10375. data.updateRange.count = 0; // reset range
  10376. }
  10377. attributeProperties.version = data.version;
  10378. }
  10379. function getAttributeBuffer( attribute ) {
  10380. if ( attribute.isInterleavedBufferAttribute ) {
  10381. return properties.get( attribute.data ).__webglBuffer;
  10382. }
  10383. return properties.get( attribute ).__webglBuffer;
  10384. }
  10385. function getAttributeProperties( attribute ) {
  10386. if ( attribute.isInterleavedBufferAttribute ) {
  10387. return properties.get( attribute.data );
  10388. }
  10389. return properties.get( attribute );
  10390. }
  10391. function getWireframeAttribute( geometry ) {
  10392. var property = properties.get( geometry );
  10393. if ( property.wireframe !== undefined ) {
  10394. return property.wireframe;
  10395. }
  10396. var indices = [];
  10397. var index = geometry.index;
  10398. var attributes = geometry.attributes;
  10399. var position = attributes.position;
  10400. // console.time( 'wireframe' );
  10401. if ( index !== null ) {
  10402. var edges = {};
  10403. var array = index.array;
  10404. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  10405. var a = array[ i + 0 ];
  10406. var b = array[ i + 1 ];
  10407. var c = array[ i + 2 ];
  10408. indices.push( a, b, b, c, c, a );
  10409. }
  10410. } else {
  10411. var array = attributes.position.array;
  10412. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10413. var a = i + 0;
  10414. var b = i + 1;
  10415. var c = i + 2;
  10416. indices.push( a, b, b, c, c, a );
  10417. }
  10418. }
  10419. // console.timeEnd( 'wireframe' );
  10420. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  10421. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  10422. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  10423. property.wireframe = attribute;
  10424. return attribute;
  10425. }
  10426. return {
  10427. getAttributeBuffer: getAttributeBuffer,
  10428. getAttributeProperties: getAttributeProperties,
  10429. getWireframeAttribute: getWireframeAttribute,
  10430. update: update
  10431. };
  10432. }
  10433. /**
  10434. * @author mrdoob / http://mrdoob.com/
  10435. */
  10436. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  10437. var _infoMemory = info.memory;
  10438. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  10439. //
  10440. function clampToMaxSize( image, maxSize ) {
  10441. if ( image.width > maxSize || image.height > maxSize ) {
  10442. // Warning: Scaling through the canvas will only work with images that use
  10443. // premultiplied alpha.
  10444. var scale = maxSize / Math.max( image.width, image.height );
  10445. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10446. canvas.width = Math.floor( image.width * scale );
  10447. canvas.height = Math.floor( image.height * scale );
  10448. var context = canvas.getContext( '2d' );
  10449. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  10450. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10451. return canvas;
  10452. }
  10453. return image;
  10454. }
  10455. function isPowerOfTwo( image ) {
  10456. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  10457. }
  10458. function makePowerOfTwo( image ) {
  10459. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  10460. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  10461. canvas.width = _Math.nearestPowerOfTwo( image.width );
  10462. canvas.height = _Math.nearestPowerOfTwo( image.height );
  10463. var context = canvas.getContext( '2d' );
  10464. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  10465. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  10466. return canvas;
  10467. }
  10468. return image;
  10469. }
  10470. function textureNeedsPowerOfTwo( texture ) {
  10471. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  10472. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  10473. }
  10474. // Fallback filters for non-power-of-2 textures
  10475. function filterFallback( f ) {
  10476. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  10477. return _gl.NEAREST;
  10478. }
  10479. return _gl.LINEAR;
  10480. }
  10481. //
  10482. function onTextureDispose( event ) {
  10483. var texture = event.target;
  10484. texture.removeEventListener( 'dispose', onTextureDispose );
  10485. deallocateTexture( texture );
  10486. _infoMemory.textures --;
  10487. }
  10488. function onRenderTargetDispose( event ) {
  10489. var renderTarget = event.target;
  10490. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10491. deallocateRenderTarget( renderTarget );
  10492. _infoMemory.textures --;
  10493. }
  10494. //
  10495. function deallocateTexture( texture ) {
  10496. var textureProperties = properties.get( texture );
  10497. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  10498. // cube texture
  10499. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  10500. } else {
  10501. // 2D texture
  10502. if ( textureProperties.__webglInit === undefined ) return;
  10503. _gl.deleteTexture( textureProperties.__webglTexture );
  10504. }
  10505. // remove all webgl properties
  10506. properties.delete( texture );
  10507. }
  10508. function deallocateRenderTarget( renderTarget ) {
  10509. var renderTargetProperties = properties.get( renderTarget );
  10510. var textureProperties = properties.get( renderTarget.texture );
  10511. if ( ! renderTarget ) return;
  10512. if ( textureProperties.__webglTexture !== undefined ) {
  10513. _gl.deleteTexture( textureProperties.__webglTexture );
  10514. }
  10515. if ( renderTarget.depthTexture ) {
  10516. renderTarget.depthTexture.dispose();
  10517. }
  10518. if ( renderTarget.isWebGLRenderTargetCube ) {
  10519. for ( var i = 0; i < 6; i ++ ) {
  10520. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  10521. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  10522. }
  10523. } else {
  10524. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  10525. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  10526. }
  10527. properties.delete( renderTarget.texture );
  10528. properties.delete( renderTarget );
  10529. }
  10530. //
  10531. function setTexture2D( texture, slot ) {
  10532. var textureProperties = properties.get( texture );
  10533. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10534. var image = texture.image;
  10535. if ( image === undefined ) {
  10536. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  10537. } else if ( image.complete === false ) {
  10538. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  10539. } else {
  10540. uploadTexture( textureProperties, texture, slot );
  10541. return;
  10542. }
  10543. }
  10544. state.activeTexture( _gl.TEXTURE0 + slot );
  10545. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10546. }
  10547. function setTextureCube( texture, slot ) {
  10548. var textureProperties = properties.get( texture );
  10549. if ( texture.image.length === 6 ) {
  10550. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  10551. if ( ! textureProperties.__image__webglTextureCube ) {
  10552. texture.addEventListener( 'dispose', onTextureDispose );
  10553. textureProperties.__image__webglTextureCube = _gl.createTexture();
  10554. _infoMemory.textures ++;
  10555. }
  10556. state.activeTexture( _gl.TEXTURE0 + slot );
  10557. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10558. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10559. var isCompressed = ( texture && texture.isCompressedTexture );
  10560. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  10561. var cubeImage = [];
  10562. for ( var i = 0; i < 6; i ++ ) {
  10563. if ( ! isCompressed && ! isDataTexture ) {
  10564. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  10565. } else {
  10566. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  10567. }
  10568. }
  10569. var image = cubeImage[ 0 ],
  10570. isPowerOfTwoImage = isPowerOfTwo( image ),
  10571. glFormat = paramThreeToGL( texture.format ),
  10572. glType = paramThreeToGL( texture.type );
  10573. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  10574. for ( var i = 0; i < 6; i ++ ) {
  10575. if ( ! isCompressed ) {
  10576. if ( isDataTexture ) {
  10577. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  10578. } else {
  10579. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  10580. }
  10581. } else {
  10582. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  10583. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  10584. mipmap = mipmaps[ j ];
  10585. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10586. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10587. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10588. } else {
  10589. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  10590. }
  10591. } else {
  10592. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10593. }
  10594. }
  10595. }
  10596. }
  10597. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  10598. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10599. }
  10600. textureProperties.__version = texture.version;
  10601. if ( texture.onUpdate ) texture.onUpdate( texture );
  10602. } else {
  10603. state.activeTexture( _gl.TEXTURE0 + slot );
  10604. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  10605. }
  10606. }
  10607. }
  10608. function setTextureCubeDynamic( texture, slot ) {
  10609. state.activeTexture( _gl.TEXTURE0 + slot );
  10610. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  10611. }
  10612. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  10613. var extension;
  10614. if ( isPowerOfTwoImage ) {
  10615. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  10616. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  10617. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  10618. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  10619. } else {
  10620. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  10621. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  10622. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  10623. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  10624. }
  10625. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  10626. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  10627. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  10628. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  10629. }
  10630. }
  10631. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10632. if ( extension ) {
  10633. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  10634. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  10635. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  10636. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  10637. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  10638. }
  10639. }
  10640. }
  10641. function uploadTexture( textureProperties, texture, slot ) {
  10642. if ( textureProperties.__webglInit === undefined ) {
  10643. textureProperties.__webglInit = true;
  10644. texture.addEventListener( 'dispose', onTextureDispose );
  10645. textureProperties.__webglTexture = _gl.createTexture();
  10646. _infoMemory.textures ++;
  10647. }
  10648. state.activeTexture( _gl.TEXTURE0 + slot );
  10649. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10650. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  10651. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  10652. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  10653. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  10654. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  10655. image = makePowerOfTwo( image );
  10656. }
  10657. var isPowerOfTwoImage = isPowerOfTwo( image ),
  10658. glFormat = paramThreeToGL( texture.format ),
  10659. glType = paramThreeToGL( texture.type );
  10660. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  10661. var mipmap, mipmaps = texture.mipmaps;
  10662. if ( texture.isDepthTexture ) {
  10663. // populate depth texture with dummy data
  10664. var internalFormat = _gl.DEPTH_COMPONENT;
  10665. if ( texture.type === FloatType ) {
  10666. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  10667. internalFormat = _gl.DEPTH_COMPONENT32F;
  10668. } else if ( _isWebGL2 ) {
  10669. // WebGL 2.0 requires signed internalformat for glTexImage2D
  10670. internalFormat = _gl.DEPTH_COMPONENT16;
  10671. }
  10672. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  10673. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10674. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  10675. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10676. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  10677. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  10678. texture.type = UnsignedShortType;
  10679. glType = paramThreeToGL( texture.type );
  10680. }
  10681. }
  10682. // Depth stencil textures need the DEPTH_STENCIL internal format
  10683. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10684. if ( texture.format === DepthStencilFormat ) {
  10685. internalFormat = _gl.DEPTH_STENCIL;
  10686. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  10687. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  10688. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  10689. if ( texture.type !== UnsignedInt248Type ) {
  10690. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  10691. texture.type = UnsignedInt248Type;
  10692. glType = paramThreeToGL( texture.type );
  10693. }
  10694. }
  10695. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  10696. } else if ( texture.isDataTexture ) {
  10697. // use manually created mipmaps if available
  10698. // if there are no manual mipmaps
  10699. // set 0 level mipmap and then use GL to generate other mipmap levels
  10700. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10701. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10702. mipmap = mipmaps[ i ];
  10703. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10704. }
  10705. texture.generateMipmaps = false;
  10706. } else {
  10707. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  10708. }
  10709. } else if ( texture.isCompressedTexture ) {
  10710. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10711. mipmap = mipmaps[ i ];
  10712. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  10713. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  10714. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  10715. } else {
  10716. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  10717. }
  10718. } else {
  10719. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  10720. }
  10721. }
  10722. } else {
  10723. // regular Texture (image, video, canvas)
  10724. // use manually created mipmaps if available
  10725. // if there are no manual mipmaps
  10726. // set 0 level mipmap and then use GL to generate other mipmap levels
  10727. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  10728. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  10729. mipmap = mipmaps[ i ];
  10730. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  10731. }
  10732. texture.generateMipmaps = false;
  10733. } else {
  10734. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  10735. }
  10736. }
  10737. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10738. textureProperties.__version = texture.version;
  10739. if ( texture.onUpdate ) texture.onUpdate( texture );
  10740. }
  10741. // Render targets
  10742. // Setup storage for target texture and bind it to correct framebuffer
  10743. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  10744. var glFormat = paramThreeToGL( renderTarget.texture.format );
  10745. var glType = paramThreeToGL( renderTarget.texture.type );
  10746. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  10747. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10748. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  10749. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10750. }
  10751. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  10752. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  10753. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  10754. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  10755. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  10756. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10757. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  10758. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  10759. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  10760. } else {
  10761. // FIXME: We don't support !depth !stencil
  10762. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  10763. }
  10764. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  10765. }
  10766. // Setup resources for a Depth Texture for a FBO (needs an extension)
  10767. function setupDepthTexture( framebuffer, renderTarget ) {
  10768. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  10769. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  10770. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  10771. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  10772. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  10773. }
  10774. // upload an empty depth texture with framebuffer size
  10775. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  10776. renderTarget.depthTexture.image.width !== renderTarget.width ||
  10777. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  10778. renderTarget.depthTexture.image.width = renderTarget.width;
  10779. renderTarget.depthTexture.image.height = renderTarget.height;
  10780. renderTarget.depthTexture.needsUpdate = true;
  10781. }
  10782. setTexture2D( renderTarget.depthTexture, 0 );
  10783. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  10784. if ( renderTarget.depthTexture.format === DepthFormat ) {
  10785. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10786. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  10787. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  10788. } else {
  10789. throw new Error('Unknown depthTexture format')
  10790. }
  10791. }
  10792. // Setup GL resources for a non-texture depth buffer
  10793. function setupDepthRenderbuffer( renderTarget ) {
  10794. var renderTargetProperties = properties.get( renderTarget );
  10795. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10796. if ( renderTarget.depthTexture ) {
  10797. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  10798. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  10799. } else {
  10800. if ( isCube ) {
  10801. renderTargetProperties.__webglDepthbuffer = [];
  10802. for ( var i = 0; i < 6; i ++ ) {
  10803. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  10804. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  10805. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  10806. }
  10807. } else {
  10808. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  10809. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  10810. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  10811. }
  10812. }
  10813. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  10814. }
  10815. // Set up GL resources for the render target
  10816. function setupRenderTarget( renderTarget ) {
  10817. var renderTargetProperties = properties.get( renderTarget );
  10818. var textureProperties = properties.get( renderTarget.texture );
  10819. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  10820. textureProperties.__webglTexture = _gl.createTexture();
  10821. _infoMemory.textures ++;
  10822. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  10823. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  10824. // Setup framebuffer
  10825. if ( isCube ) {
  10826. renderTargetProperties.__webglFramebuffer = [];
  10827. for ( var i = 0; i < 6; i ++ ) {
  10828. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  10829. }
  10830. } else {
  10831. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  10832. }
  10833. // Setup color buffer
  10834. if ( isCube ) {
  10835. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  10836. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  10837. for ( var i = 0; i < 6; i ++ ) {
  10838. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  10839. }
  10840. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  10841. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  10842. } else {
  10843. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  10844. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  10845. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  10846. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  10847. state.bindTexture( _gl.TEXTURE_2D, null );
  10848. }
  10849. // Setup depth and stencil buffers
  10850. if ( renderTarget.depthBuffer ) {
  10851. setupDepthRenderbuffer( renderTarget );
  10852. }
  10853. }
  10854. function updateRenderTargetMipmap( renderTarget ) {
  10855. var texture = renderTarget.texture;
  10856. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  10857. texture.minFilter !== NearestFilter &&
  10858. texture.minFilter !== LinearFilter ) {
  10859. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  10860. var webglTexture = properties.get( texture ).__webglTexture;
  10861. state.bindTexture( target, webglTexture );
  10862. _gl.generateMipmap( target );
  10863. state.bindTexture( target, null );
  10864. }
  10865. }
  10866. this.setTexture2D = setTexture2D;
  10867. this.setTextureCube = setTextureCube;
  10868. this.setTextureCubeDynamic = setTextureCubeDynamic;
  10869. this.setupRenderTarget = setupRenderTarget;
  10870. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  10871. }
  10872. /**
  10873. * @author fordacious / fordacious.github.io
  10874. */
  10875. function WebGLProperties() {
  10876. var properties = {};
  10877. return {
  10878. get: function ( object ) {
  10879. var uuid = object.uuid;
  10880. var map = properties[ uuid ];
  10881. if ( map === undefined ) {
  10882. map = {};
  10883. properties[ uuid ] = map;
  10884. }
  10885. return map;
  10886. },
  10887. delete: function ( object ) {
  10888. delete properties[ object.uuid ];
  10889. },
  10890. clear: function () {
  10891. properties = {};
  10892. }
  10893. };
  10894. }
  10895. /**
  10896. * @author mrdoob / http://mrdoob.com/
  10897. */
  10898. function WebGLState( gl, extensions, paramThreeToGL ) {
  10899. function ColorBuffer() {
  10900. var locked = false;
  10901. var color = new Vector4();
  10902. var currentColorMask = null;
  10903. var currentColorClear = new Vector4();
  10904. return {
  10905. setMask: function ( colorMask ) {
  10906. if ( currentColorMask !== colorMask && ! locked ) {
  10907. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  10908. currentColorMask = colorMask;
  10909. }
  10910. },
  10911. setLocked: function ( lock ) {
  10912. locked = lock;
  10913. },
  10914. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  10915. if ( premultipliedAlpha === true ) {
  10916. r *= a; g *= a; b *= a;
  10917. }
  10918. color.set( r, g, b, a );
  10919. if ( currentColorClear.equals( color ) === false ) {
  10920. gl.clearColor( r, g, b, a );
  10921. currentColorClear.copy( color );
  10922. }
  10923. },
  10924. reset: function () {
  10925. locked = false;
  10926. currentColorMask = null;
  10927. currentColorClear.set( 0, 0, 0, 1 );
  10928. }
  10929. };
  10930. }
  10931. function DepthBuffer() {
  10932. var locked = false;
  10933. var currentDepthMask = null;
  10934. var currentDepthFunc = null;
  10935. var currentDepthClear = null;
  10936. return {
  10937. setTest: function ( depthTest ) {
  10938. if ( depthTest ) {
  10939. enable( gl.DEPTH_TEST );
  10940. } else {
  10941. disable( gl.DEPTH_TEST );
  10942. }
  10943. },
  10944. setMask: function ( depthMask ) {
  10945. if ( currentDepthMask !== depthMask && ! locked ) {
  10946. gl.depthMask( depthMask );
  10947. currentDepthMask = depthMask;
  10948. }
  10949. },
  10950. setFunc: function ( depthFunc ) {
  10951. if ( currentDepthFunc !== depthFunc ) {
  10952. if ( depthFunc ) {
  10953. switch ( depthFunc ) {
  10954. case NeverDepth:
  10955. gl.depthFunc( gl.NEVER );
  10956. break;
  10957. case AlwaysDepth:
  10958. gl.depthFunc( gl.ALWAYS );
  10959. break;
  10960. case LessDepth:
  10961. gl.depthFunc( gl.LESS );
  10962. break;
  10963. case LessEqualDepth:
  10964. gl.depthFunc( gl.LEQUAL );
  10965. break;
  10966. case EqualDepth:
  10967. gl.depthFunc( gl.EQUAL );
  10968. break;
  10969. case GreaterEqualDepth:
  10970. gl.depthFunc( gl.GEQUAL );
  10971. break;
  10972. case GreaterDepth:
  10973. gl.depthFunc( gl.GREATER );
  10974. break;
  10975. case NotEqualDepth:
  10976. gl.depthFunc( gl.NOTEQUAL );
  10977. break;
  10978. default:
  10979. gl.depthFunc( gl.LEQUAL );
  10980. }
  10981. } else {
  10982. gl.depthFunc( gl.LEQUAL );
  10983. }
  10984. currentDepthFunc = depthFunc;
  10985. }
  10986. },
  10987. setLocked: function ( lock ) {
  10988. locked = lock;
  10989. },
  10990. setClear: function ( depth ) {
  10991. if ( currentDepthClear !== depth ) {
  10992. gl.clearDepth( depth );
  10993. currentDepthClear = depth;
  10994. }
  10995. },
  10996. reset: function () {
  10997. locked = false;
  10998. currentDepthMask = null;
  10999. currentDepthFunc = null;
  11000. currentDepthClear = null;
  11001. }
  11002. };
  11003. }
  11004. function StencilBuffer() {
  11005. var locked = false;
  11006. var currentStencilMask = null;
  11007. var currentStencilFunc = null;
  11008. var currentStencilRef = null;
  11009. var currentStencilFuncMask = null;
  11010. var currentStencilFail = null;
  11011. var currentStencilZFail = null;
  11012. var currentStencilZPass = null;
  11013. var currentStencilClear = null;
  11014. return {
  11015. setTest: function ( stencilTest ) {
  11016. if ( stencilTest ) {
  11017. enable( gl.STENCIL_TEST );
  11018. } else {
  11019. disable( gl.STENCIL_TEST );
  11020. }
  11021. },
  11022. setMask: function ( stencilMask ) {
  11023. if ( currentStencilMask !== stencilMask && ! locked ) {
  11024. gl.stencilMask( stencilMask );
  11025. currentStencilMask = stencilMask;
  11026. }
  11027. },
  11028. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11029. if ( currentStencilFunc !== stencilFunc ||
  11030. currentStencilRef !== stencilRef ||
  11031. currentStencilFuncMask !== stencilMask ) {
  11032. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11033. currentStencilFunc = stencilFunc;
  11034. currentStencilRef = stencilRef;
  11035. currentStencilFuncMask = stencilMask;
  11036. }
  11037. },
  11038. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11039. if ( currentStencilFail !== stencilFail ||
  11040. currentStencilZFail !== stencilZFail ||
  11041. currentStencilZPass !== stencilZPass ) {
  11042. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11043. currentStencilFail = stencilFail;
  11044. currentStencilZFail = stencilZFail;
  11045. currentStencilZPass = stencilZPass;
  11046. }
  11047. },
  11048. setLocked: function ( lock ) {
  11049. locked = lock;
  11050. },
  11051. setClear: function ( stencil ) {
  11052. if ( currentStencilClear !== stencil ) {
  11053. gl.clearStencil( stencil );
  11054. currentStencilClear = stencil;
  11055. }
  11056. },
  11057. reset: function () {
  11058. locked = false;
  11059. currentStencilMask = null;
  11060. currentStencilFunc = null;
  11061. currentStencilRef = null;
  11062. currentStencilFuncMask = null;
  11063. currentStencilFail = null;
  11064. currentStencilZFail = null;
  11065. currentStencilZPass = null;
  11066. currentStencilClear = null;
  11067. }
  11068. };
  11069. }
  11070. //
  11071. var colorBuffer = new ColorBuffer();
  11072. var depthBuffer = new DepthBuffer();
  11073. var stencilBuffer = new StencilBuffer();
  11074. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11075. var newAttributes = new Uint8Array( maxVertexAttributes );
  11076. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  11077. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  11078. var capabilities = {};
  11079. var compressedTextureFormats = null;
  11080. var currentBlending = null;
  11081. var currentBlendEquation = null;
  11082. var currentBlendSrc = null;
  11083. var currentBlendDst = null;
  11084. var currentBlendEquationAlpha = null;
  11085. var currentBlendSrcAlpha = null;
  11086. var currentBlendDstAlpha = null;
  11087. var currentPremultipledAlpha = false;
  11088. var currentFlipSided = null;
  11089. var currentCullFace = null;
  11090. var currentLineWidth = null;
  11091. var currentPolygonOffsetFactor = null;
  11092. var currentPolygonOffsetUnits = null;
  11093. var currentScissorTest = null;
  11094. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11095. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  11096. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  11097. var currentTextureSlot = null;
  11098. var currentBoundTextures = {};
  11099. var currentScissor = new Vector4();
  11100. var currentViewport = new Vector4();
  11101. function createTexture( type, target, count ) {
  11102. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11103. var texture = gl.createTexture();
  11104. gl.bindTexture( type, texture );
  11105. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  11106. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  11107. for ( var i = 0; i < count; i ++ ) {
  11108. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  11109. }
  11110. return texture;
  11111. }
  11112. var emptyTextures = {};
  11113. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  11114. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  11115. //
  11116. function init() {
  11117. colorBuffer.setClear( 0, 0, 0, 1 );
  11118. depthBuffer.setClear( 1 );
  11119. stencilBuffer.setClear( 0 );
  11120. enable( gl.DEPTH_TEST );
  11121. setDepthFunc( LessEqualDepth );
  11122. setFlipSided( false );
  11123. setCullFace( CullFaceBack );
  11124. enable( gl.CULL_FACE );
  11125. enable( gl.BLEND );
  11126. setBlending( NormalBlending );
  11127. }
  11128. function initAttributes() {
  11129. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  11130. newAttributes[ i ] = 0;
  11131. }
  11132. }
  11133. function enableAttribute( attribute ) {
  11134. newAttributes[ attribute ] = 1;
  11135. if ( enabledAttributes[ attribute ] === 0 ) {
  11136. gl.enableVertexAttribArray( attribute );
  11137. enabledAttributes[ attribute ] = 1;
  11138. }
  11139. if ( attributeDivisors[ attribute ] !== 0 ) {
  11140. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11141. extension.vertexAttribDivisorANGLE( attribute, 0 );
  11142. attributeDivisors[ attribute ] = 0;
  11143. }
  11144. }
  11145. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  11146. newAttributes[ attribute ] = 1;
  11147. if ( enabledAttributes[ attribute ] === 0 ) {
  11148. gl.enableVertexAttribArray( attribute );
  11149. enabledAttributes[ attribute ] = 1;
  11150. }
  11151. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  11152. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  11153. attributeDivisors[ attribute ] = meshPerAttribute;
  11154. }
  11155. }
  11156. function disableUnusedAttributes() {
  11157. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  11158. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  11159. gl.disableVertexAttribArray( i );
  11160. enabledAttributes[ i ] = 0;
  11161. }
  11162. }
  11163. }
  11164. function enable( id ) {
  11165. if ( capabilities[ id ] !== true ) {
  11166. gl.enable( id );
  11167. capabilities[ id ] = true;
  11168. }
  11169. }
  11170. function disable( id ) {
  11171. if ( capabilities[ id ] !== false ) {
  11172. gl.disable( id );
  11173. capabilities[ id ] = false;
  11174. }
  11175. }
  11176. function getCompressedTextureFormats() {
  11177. if ( compressedTextureFormats === null ) {
  11178. compressedTextureFormats = [];
  11179. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  11180. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  11181. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  11182. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  11183. for ( var i = 0; i < formats.length; i ++ ) {
  11184. compressedTextureFormats.push( formats[ i ] );
  11185. }
  11186. }
  11187. }
  11188. return compressedTextureFormats;
  11189. }
  11190. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11191. if ( blending !== NoBlending ) {
  11192. enable( gl.BLEND );
  11193. } else {
  11194. disable( gl.BLEND );
  11195. }
  11196. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11197. if ( blending === AdditiveBlending ) {
  11198. if ( premultipliedAlpha ) {
  11199. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11200. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  11201. } else {
  11202. gl.blendEquation( gl.FUNC_ADD );
  11203. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  11204. }
  11205. } else if ( blending === SubtractiveBlending ) {
  11206. if ( premultipliedAlpha ) {
  11207. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11208. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  11209. } else {
  11210. gl.blendEquation( gl.FUNC_ADD );
  11211. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  11212. }
  11213. } else if ( blending === MultiplyBlending ) {
  11214. if ( premultipliedAlpha ) {
  11215. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11216. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  11217. } else {
  11218. gl.blendEquation( gl.FUNC_ADD );
  11219. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  11220. }
  11221. } else {
  11222. if ( premultipliedAlpha ) {
  11223. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11224. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11225. } else {
  11226. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  11227. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  11228. }
  11229. }
  11230. currentBlending = blending;
  11231. currentPremultipledAlpha = premultipliedAlpha;
  11232. }
  11233. if ( blending === CustomBlending ) {
  11234. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11235. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11236. blendDstAlpha = blendDstAlpha || blendDst;
  11237. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11238. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  11239. currentBlendEquation = blendEquation;
  11240. currentBlendEquationAlpha = blendEquationAlpha;
  11241. }
  11242. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11243. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  11244. currentBlendSrc = blendSrc;
  11245. currentBlendDst = blendDst;
  11246. currentBlendSrcAlpha = blendSrcAlpha;
  11247. currentBlendDstAlpha = blendDstAlpha;
  11248. }
  11249. } else {
  11250. currentBlendEquation = null;
  11251. currentBlendSrc = null;
  11252. currentBlendDst = null;
  11253. currentBlendEquationAlpha = null;
  11254. currentBlendSrcAlpha = null;
  11255. currentBlendDstAlpha = null;
  11256. }
  11257. }
  11258. // TODO Deprecate
  11259. function setColorWrite( colorWrite ) {
  11260. colorBuffer.setMask( colorWrite );
  11261. }
  11262. function setDepthTest( depthTest ) {
  11263. depthBuffer.setTest( depthTest );
  11264. }
  11265. function setDepthWrite( depthWrite ) {
  11266. depthBuffer.setMask( depthWrite );
  11267. }
  11268. function setDepthFunc( depthFunc ) {
  11269. depthBuffer.setFunc( depthFunc );
  11270. }
  11271. function setStencilTest( stencilTest ) {
  11272. stencilBuffer.setTest( stencilTest );
  11273. }
  11274. function setStencilWrite( stencilWrite ) {
  11275. stencilBuffer.setMask( stencilWrite );
  11276. }
  11277. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  11278. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  11279. }
  11280. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  11281. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  11282. }
  11283. //
  11284. function setFlipSided( flipSided ) {
  11285. if ( currentFlipSided !== flipSided ) {
  11286. if ( flipSided ) {
  11287. gl.frontFace( gl.CW );
  11288. } else {
  11289. gl.frontFace( gl.CCW );
  11290. }
  11291. currentFlipSided = flipSided;
  11292. }
  11293. }
  11294. function setCullFace( cullFace ) {
  11295. if ( cullFace !== CullFaceNone ) {
  11296. enable( gl.CULL_FACE );
  11297. if ( cullFace !== currentCullFace ) {
  11298. if ( cullFace === CullFaceBack ) {
  11299. gl.cullFace( gl.BACK );
  11300. } else if ( cullFace === CullFaceFront ) {
  11301. gl.cullFace( gl.FRONT );
  11302. } else {
  11303. gl.cullFace( gl.FRONT_AND_BACK );
  11304. }
  11305. }
  11306. } else {
  11307. disable( gl.CULL_FACE );
  11308. }
  11309. currentCullFace = cullFace;
  11310. }
  11311. function setLineWidth( width ) {
  11312. if ( width !== currentLineWidth ) {
  11313. if ( lineWidthAvailable ) gl.lineWidth( width );
  11314. currentLineWidth = width;
  11315. }
  11316. }
  11317. function setPolygonOffset( polygonOffset, factor, units ) {
  11318. if ( polygonOffset ) {
  11319. enable( gl.POLYGON_OFFSET_FILL );
  11320. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11321. gl.polygonOffset( factor, units );
  11322. currentPolygonOffsetFactor = factor;
  11323. currentPolygonOffsetUnits = units;
  11324. }
  11325. } else {
  11326. disable( gl.POLYGON_OFFSET_FILL );
  11327. }
  11328. }
  11329. function getScissorTest() {
  11330. return currentScissorTest;
  11331. }
  11332. function setScissorTest( scissorTest ) {
  11333. currentScissorTest = scissorTest;
  11334. if ( scissorTest ) {
  11335. enable( gl.SCISSOR_TEST );
  11336. } else {
  11337. disable( gl.SCISSOR_TEST );
  11338. }
  11339. }
  11340. // texture
  11341. function activeTexture( webglSlot ) {
  11342. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  11343. if ( currentTextureSlot !== webglSlot ) {
  11344. gl.activeTexture( webglSlot );
  11345. currentTextureSlot = webglSlot;
  11346. }
  11347. }
  11348. function bindTexture( webglType, webglTexture ) {
  11349. if ( currentTextureSlot === null ) {
  11350. activeTexture();
  11351. }
  11352. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  11353. if ( boundTexture === undefined ) {
  11354. boundTexture = { type: undefined, texture: undefined };
  11355. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11356. }
  11357. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11358. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11359. boundTexture.type = webglType;
  11360. boundTexture.texture = webglTexture;
  11361. }
  11362. }
  11363. function compressedTexImage2D() {
  11364. try {
  11365. gl.compressedTexImage2D.apply( gl, arguments );
  11366. } catch ( error ) {
  11367. console.error( error );
  11368. }
  11369. }
  11370. function texImage2D() {
  11371. try {
  11372. gl.texImage2D.apply( gl, arguments );
  11373. } catch ( error ) {
  11374. console.error( error );
  11375. }
  11376. }
  11377. //
  11378. function scissor( scissor ) {
  11379. if ( currentScissor.equals( scissor ) === false ) {
  11380. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11381. currentScissor.copy( scissor );
  11382. }
  11383. }
  11384. function viewport( viewport ) {
  11385. if ( currentViewport.equals( viewport ) === false ) {
  11386. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  11387. currentViewport.copy( viewport );
  11388. }
  11389. }
  11390. //
  11391. function reset() {
  11392. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  11393. if ( enabledAttributes[ i ] === 1 ) {
  11394. gl.disableVertexAttribArray( i );
  11395. enabledAttributes[ i ] = 0;
  11396. }
  11397. }
  11398. capabilities = {};
  11399. compressedTextureFormats = null;
  11400. currentTextureSlot = null;
  11401. currentBoundTextures = {};
  11402. currentBlending = null;
  11403. currentFlipSided = null;
  11404. currentCullFace = null;
  11405. colorBuffer.reset();
  11406. depthBuffer.reset();
  11407. stencilBuffer.reset();
  11408. }
  11409. return {
  11410. buffers: {
  11411. color: colorBuffer,
  11412. depth: depthBuffer,
  11413. stencil: stencilBuffer
  11414. },
  11415. init: init,
  11416. initAttributes: initAttributes,
  11417. enableAttribute: enableAttribute,
  11418. enableAttributeAndDivisor: enableAttributeAndDivisor,
  11419. disableUnusedAttributes: disableUnusedAttributes,
  11420. enable: enable,
  11421. disable: disable,
  11422. getCompressedTextureFormats: getCompressedTextureFormats,
  11423. setBlending: setBlending,
  11424. setColorWrite: setColorWrite,
  11425. setDepthTest: setDepthTest,
  11426. setDepthWrite: setDepthWrite,
  11427. setDepthFunc: setDepthFunc,
  11428. setStencilTest: setStencilTest,
  11429. setStencilWrite: setStencilWrite,
  11430. setStencilFunc: setStencilFunc,
  11431. setStencilOp: setStencilOp,
  11432. setFlipSided: setFlipSided,
  11433. setCullFace: setCullFace,
  11434. setLineWidth: setLineWidth,
  11435. setPolygonOffset: setPolygonOffset,
  11436. getScissorTest: getScissorTest,
  11437. setScissorTest: setScissorTest,
  11438. activeTexture: activeTexture,
  11439. bindTexture: bindTexture,
  11440. compressedTexImage2D: compressedTexImage2D,
  11441. texImage2D: texImage2D,
  11442. scissor: scissor,
  11443. viewport: viewport,
  11444. reset: reset
  11445. };
  11446. }
  11447. /**
  11448. * @author mrdoob / http://mrdoob.com/
  11449. */
  11450. function WebGLCapabilities( gl, extensions, parameters ) {
  11451. var maxAnisotropy;
  11452. function getMaxAnisotropy() {
  11453. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  11454. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11455. if ( extension !== null ) {
  11456. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11457. } else {
  11458. maxAnisotropy = 0;
  11459. }
  11460. return maxAnisotropy;
  11461. }
  11462. function getMaxPrecision( precision ) {
  11463. if ( precision === 'highp' ) {
  11464. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  11465. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  11466. return 'highp';
  11467. }
  11468. precision = 'mediump';
  11469. }
  11470. if ( precision === 'mediump' ) {
  11471. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  11472. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  11473. return 'mediump';
  11474. }
  11475. }
  11476. return 'lowp';
  11477. }
  11478. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11479. var maxPrecision = getMaxPrecision( precision );
  11480. if ( maxPrecision !== precision ) {
  11481. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  11482. precision = maxPrecision;
  11483. }
  11484. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  11485. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  11486. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11487. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  11488. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11489. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  11490. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  11491. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  11492. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  11493. var vertexTextures = maxVertexTextures > 0;
  11494. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  11495. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11496. return {
  11497. getMaxAnisotropy: getMaxAnisotropy,
  11498. getMaxPrecision: getMaxPrecision,
  11499. precision: precision,
  11500. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11501. maxTextures: maxTextures,
  11502. maxVertexTextures: maxVertexTextures,
  11503. maxTextureSize: maxTextureSize,
  11504. maxCubemapSize: maxCubemapSize,
  11505. maxAttributes: maxAttributes,
  11506. maxVertexUniforms: maxVertexUniforms,
  11507. maxVaryings: maxVaryings,
  11508. maxFragmentUniforms: maxFragmentUniforms,
  11509. vertexTextures: vertexTextures,
  11510. floatFragmentTextures: floatFragmentTextures,
  11511. floatVertexTextures: floatVertexTextures
  11512. };
  11513. }
  11514. /**
  11515. * @author mrdoob / http://mrdoob.com/
  11516. */
  11517. function WebGLExtensions( gl ) {
  11518. var extensions = {};
  11519. return {
  11520. get: function ( name ) {
  11521. if ( extensions[ name ] !== undefined ) {
  11522. return extensions[ name ];
  11523. }
  11524. var extension;
  11525. switch ( name ) {
  11526. case 'WEBGL_depth_texture':
  11527. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  11528. break;
  11529. case 'EXT_texture_filter_anisotropic':
  11530. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  11531. break;
  11532. case 'WEBGL_compressed_texture_s3tc':
  11533. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  11534. break;
  11535. case 'WEBGL_compressed_texture_pvrtc':
  11536. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  11537. break;
  11538. case 'WEBGL_compressed_texture_etc1':
  11539. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  11540. break;
  11541. default:
  11542. extension = gl.getExtension( name );
  11543. }
  11544. if ( extension === null ) {
  11545. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  11546. }
  11547. extensions[ name ] = extension;
  11548. return extension;
  11549. }
  11550. };
  11551. }
  11552. /**
  11553. * @author tschw
  11554. */
  11555. function WebGLClipping() {
  11556. var scope = this,
  11557. globalState = null,
  11558. numGlobalPlanes = 0,
  11559. localClippingEnabled = false,
  11560. renderingShadows = false,
  11561. plane = new Plane(),
  11562. viewNormalMatrix = new Matrix3(),
  11563. uniform = { value: null, needsUpdate: false };
  11564. this.uniform = uniform;
  11565. this.numPlanes = 0;
  11566. this.numIntersection = 0;
  11567. this.init = function( planes, enableLocalClipping, camera ) {
  11568. var enabled =
  11569. planes.length !== 0 ||
  11570. enableLocalClipping ||
  11571. // enable state of previous frame - the clipping code has to
  11572. // run another frame in order to reset the state:
  11573. numGlobalPlanes !== 0 ||
  11574. localClippingEnabled;
  11575. localClippingEnabled = enableLocalClipping;
  11576. globalState = projectPlanes( planes, camera, 0 );
  11577. numGlobalPlanes = planes.length;
  11578. return enabled;
  11579. };
  11580. this.beginShadows = function() {
  11581. renderingShadows = true;
  11582. projectPlanes( null );
  11583. };
  11584. this.endShadows = function() {
  11585. renderingShadows = false;
  11586. resetGlobalState();
  11587. };
  11588. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  11589. if ( ! localClippingEnabled ||
  11590. planes === null || planes.length === 0 ||
  11591. renderingShadows && ! clipShadows ) {
  11592. // there's no local clipping
  11593. if ( renderingShadows ) {
  11594. // there's no global clipping
  11595. projectPlanes( null );
  11596. } else {
  11597. resetGlobalState();
  11598. }
  11599. } else {
  11600. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11601. lGlobal = nGlobal * 4,
  11602. dstArray = cache.clippingState || null;
  11603. uniform.value = dstArray; // ensure unique state
  11604. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  11605. for ( var i = 0; i !== lGlobal; ++ i ) {
  11606. dstArray[ i ] = globalState[ i ];
  11607. }
  11608. cache.clippingState = dstArray;
  11609. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11610. this.numPlanes += nGlobal;
  11611. }
  11612. };
  11613. function resetGlobalState() {
  11614. if ( uniform.value !== globalState ) {
  11615. uniform.value = globalState;
  11616. uniform.needsUpdate = numGlobalPlanes > 0;
  11617. }
  11618. scope.numPlanes = numGlobalPlanes;
  11619. scope.numIntersection = 0;
  11620. }
  11621. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  11622. var nPlanes = planes !== null ? planes.length : 0,
  11623. dstArray = null;
  11624. if ( nPlanes !== 0 ) {
  11625. dstArray = uniform.value;
  11626. if ( skipTransform !== true || dstArray === null ) {
  11627. var flatSize = dstOffset + nPlanes * 4,
  11628. viewMatrix = camera.matrixWorldInverse;
  11629. viewNormalMatrix.getNormalMatrix( viewMatrix );
  11630. if ( dstArray === null || dstArray.length < flatSize ) {
  11631. dstArray = new Float32Array( flatSize );
  11632. }
  11633. for ( var i = 0, i4 = dstOffset;
  11634. i !== nPlanes; ++ i, i4 += 4 ) {
  11635. plane.copy( planes[ i ] ).
  11636. applyMatrix4( viewMatrix, viewNormalMatrix );
  11637. plane.normal.toArray( dstArray, i4 );
  11638. dstArray[ i4 + 3 ] = plane.constant;
  11639. }
  11640. }
  11641. uniform.value = dstArray;
  11642. uniform.needsUpdate = true;
  11643. }
  11644. scope.numPlanes = nPlanes;
  11645. return dstArray;
  11646. }
  11647. }
  11648. /**
  11649. * @author supereggbert / http://www.paulbrunt.co.uk/
  11650. * @author mrdoob / http://mrdoob.com/
  11651. * @author alteredq / http://alteredqualia.com/
  11652. * @author szimek / https://github.com/szimek/
  11653. * @author tschw
  11654. */
  11655. function WebGLRenderer( parameters ) {
  11656. console.log( 'THREE.WebGLRenderer', REVISION );
  11657. parameters = parameters || {};
  11658. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11659. _context = parameters.context !== undefined ? parameters.context : null,
  11660. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11661. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11662. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11663. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11664. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11665. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11666. var lights = [];
  11667. var opaqueObjects = [];
  11668. var opaqueObjectsLastIndex = - 1;
  11669. var transparentObjects = [];
  11670. var transparentObjectsLastIndex = - 1;
  11671. var morphInfluences = new Float32Array( 8 );
  11672. var sprites = [];
  11673. var lensFlares = [];
  11674. // public properties
  11675. this.domElement = _canvas;
  11676. this.context = null;
  11677. // clearing
  11678. this.autoClear = true;
  11679. this.autoClearColor = true;
  11680. this.autoClearDepth = true;
  11681. this.autoClearStencil = true;
  11682. // scene graph
  11683. this.sortObjects = true;
  11684. // user-defined clipping
  11685. this.clippingPlanes = [];
  11686. this.localClippingEnabled = false;
  11687. // physically based shading
  11688. this.gammaFactor = 2.0; // for backwards compatibility
  11689. this.gammaInput = false;
  11690. this.gammaOutput = false;
  11691. // physical lights
  11692. this.physicallyCorrectLights = false;
  11693. // tone mapping
  11694. this.toneMapping = LinearToneMapping;
  11695. this.toneMappingExposure = 1.0;
  11696. this.toneMappingWhitePoint = 1.0;
  11697. // morphs
  11698. this.maxMorphTargets = 8;
  11699. this.maxMorphNormals = 4;
  11700. // internal properties
  11701. var _this = this,
  11702. // internal state cache
  11703. _currentProgram = null,
  11704. _currentRenderTarget = null,
  11705. _currentFramebuffer = null,
  11706. _currentMaterialId = - 1,
  11707. _currentGeometryProgram = '',
  11708. _currentCamera = null,
  11709. _currentScissor = new Vector4(),
  11710. _currentScissorTest = null,
  11711. _currentViewport = new Vector4(),
  11712. //
  11713. _usedTextureUnits = 0,
  11714. //
  11715. _clearColor = new Color( 0x000000 ),
  11716. _clearAlpha = 0,
  11717. _width = _canvas.width,
  11718. _height = _canvas.height,
  11719. _pixelRatio = 1,
  11720. _scissor = new Vector4( 0, 0, _width, _height ),
  11721. _scissorTest = false,
  11722. _viewport = new Vector4( 0, 0, _width, _height ),
  11723. // frustum
  11724. _frustum = new Frustum(),
  11725. // clipping
  11726. _clipping = new WebGLClipping(),
  11727. _clippingEnabled = false,
  11728. _localClippingEnabled = false,
  11729. _sphere = new Sphere(),
  11730. // camera matrices cache
  11731. _projScreenMatrix = new Matrix4(),
  11732. _vector3 = new Vector3(),
  11733. _matrix4 = new Matrix4(),
  11734. _matrix42 = new Matrix4(),
  11735. // light arrays cache
  11736. _lights = {
  11737. hash: '',
  11738. ambient: [ 0, 0, 0 ],
  11739. directional: [],
  11740. directionalShadowMap: [],
  11741. directionalShadowMatrix: [],
  11742. spot: [],
  11743. spotShadowMap: [],
  11744. spotShadowMatrix: [],
  11745. rectArea: [],
  11746. point: [],
  11747. pointShadowMap: [],
  11748. pointShadowMatrix: [],
  11749. hemi: [],
  11750. shadows: []
  11751. },
  11752. // info
  11753. _infoRender = {
  11754. calls: 0,
  11755. vertices: 0,
  11756. faces: 0,
  11757. points: 0
  11758. };
  11759. this.info = {
  11760. render: _infoRender,
  11761. memory: {
  11762. geometries: 0,
  11763. textures: 0
  11764. },
  11765. programs: null
  11766. };
  11767. // initialize
  11768. var _gl;
  11769. try {
  11770. var attributes = {
  11771. alpha: _alpha,
  11772. depth: _depth,
  11773. stencil: _stencil,
  11774. antialias: _antialias,
  11775. premultipliedAlpha: _premultipliedAlpha,
  11776. preserveDrawingBuffer: _preserveDrawingBuffer
  11777. };
  11778. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11779. if ( _gl === null ) {
  11780. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11781. throw 'Error creating WebGL context with your selected attributes.';
  11782. } else {
  11783. throw 'Error creating WebGL context.';
  11784. }
  11785. }
  11786. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11787. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11788. _gl.getShaderPrecisionFormat = function () {
  11789. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11790. };
  11791. }
  11792. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11793. } catch ( error ) {
  11794. console.error( 'THREE.WebGLRenderer: ' + error );
  11795. }
  11796. var extensions = new WebGLExtensions( _gl );
  11797. extensions.get( 'WEBGL_depth_texture' );
  11798. extensions.get( 'OES_texture_float' );
  11799. extensions.get( 'OES_texture_float_linear' );
  11800. extensions.get( 'OES_texture_half_float' );
  11801. extensions.get( 'OES_texture_half_float_linear' );
  11802. extensions.get( 'OES_standard_derivatives' );
  11803. extensions.get( 'ANGLE_instanced_arrays' );
  11804. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11805. BufferGeometry.MaxIndex = 4294967296;
  11806. }
  11807. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11808. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11809. var properties = new WebGLProperties();
  11810. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11811. var objects = new WebGLObjects( _gl, properties, this.info );
  11812. var programCache = new WebGLPrograms( this, capabilities );
  11813. var lightCache = new WebGLLights();
  11814. this.info.programs = programCache.programs;
  11815. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11816. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11817. //
  11818. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11819. var backgroundCamera2 = new PerspectiveCamera();
  11820. var backgroundPlaneMesh = new Mesh(
  11821. new PlaneBufferGeometry( 2, 2 ),
  11822. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11823. );
  11824. var backgroundBoxShader = ShaderLib[ 'cube' ];
  11825. var backgroundBoxMesh = new Mesh(
  11826. new BoxBufferGeometry( 5, 5, 5 ),
  11827. new ShaderMaterial( {
  11828. uniforms: backgroundBoxShader.uniforms,
  11829. vertexShader: backgroundBoxShader.vertexShader,
  11830. fragmentShader: backgroundBoxShader.fragmentShader,
  11831. side: BackSide,
  11832. depthTest: false,
  11833. depthWrite: false,
  11834. fog: false
  11835. } )
  11836. );
  11837. //
  11838. function getTargetPixelRatio() {
  11839. return _currentRenderTarget === null ? _pixelRatio : 1;
  11840. }
  11841. function setDefaultGLState() {
  11842. state.init();
  11843. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11844. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11845. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11846. }
  11847. function resetGLState() {
  11848. _currentProgram = null;
  11849. _currentCamera = null;
  11850. _currentGeometryProgram = '';
  11851. _currentMaterialId = - 1;
  11852. state.reset();
  11853. }
  11854. setDefaultGLState();
  11855. this.context = _gl;
  11856. this.capabilities = capabilities;
  11857. this.extensions = extensions;
  11858. this.properties = properties;
  11859. this.state = state;
  11860. // shadow map
  11861. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11862. this.shadowMap = shadowMap;
  11863. // Plugins
  11864. var spritePlugin = new SpritePlugin( this, sprites );
  11865. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11866. // API
  11867. this.getContext = function () {
  11868. return _gl;
  11869. };
  11870. this.getContextAttributes = function () {
  11871. return _gl.getContextAttributes();
  11872. };
  11873. this.forceContextLoss = function () {
  11874. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11875. };
  11876. this.getMaxAnisotropy = function () {
  11877. return capabilities.getMaxAnisotropy();
  11878. };
  11879. this.getPrecision = function () {
  11880. return capabilities.precision;
  11881. };
  11882. this.getPixelRatio = function () {
  11883. return _pixelRatio;
  11884. };
  11885. this.setPixelRatio = function ( value ) {
  11886. if ( value === undefined ) return;
  11887. _pixelRatio = value;
  11888. this.setSize( _viewport.z, _viewport.w, false );
  11889. };
  11890. this.getSize = function () {
  11891. return {
  11892. width: _width,
  11893. height: _height
  11894. };
  11895. };
  11896. this.setSize = function ( width, height, updateStyle ) {
  11897. _width = width;
  11898. _height = height;
  11899. _canvas.width = width * _pixelRatio;
  11900. _canvas.height = height * _pixelRatio;
  11901. if ( updateStyle !== false ) {
  11902. _canvas.style.width = width + 'px';
  11903. _canvas.style.height = height + 'px';
  11904. }
  11905. this.setViewport( 0, 0, width, height );
  11906. };
  11907. this.setViewport = function ( x, y, width, height ) {
  11908. state.viewport( _viewport.set( x, y, width, height ) );
  11909. };
  11910. this.setScissor = function ( x, y, width, height ) {
  11911. state.scissor( _scissor.set( x, y, width, height ) );
  11912. };
  11913. this.setScissorTest = function ( boolean ) {
  11914. state.setScissorTest( _scissorTest = boolean );
  11915. };
  11916. // Clearing
  11917. this.getClearColor = function () {
  11918. return _clearColor;
  11919. };
  11920. this.setClearColor = function ( color, alpha ) {
  11921. _clearColor.set( color );
  11922. _clearAlpha = alpha !== undefined ? alpha : 1;
  11923. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11924. };
  11925. this.getClearAlpha = function () {
  11926. return _clearAlpha;
  11927. };
  11928. this.setClearAlpha = function ( alpha ) {
  11929. _clearAlpha = alpha;
  11930. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  11931. };
  11932. this.clear = function ( color, depth, stencil ) {
  11933. var bits = 0;
  11934. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11935. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11936. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11937. _gl.clear( bits );
  11938. };
  11939. this.clearColor = function () {
  11940. this.clear( true, false, false );
  11941. };
  11942. this.clearDepth = function () {
  11943. this.clear( false, true, false );
  11944. };
  11945. this.clearStencil = function () {
  11946. this.clear( false, false, true );
  11947. };
  11948. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11949. this.setRenderTarget( renderTarget );
  11950. this.clear( color, depth, stencil );
  11951. };
  11952. // Reset
  11953. this.resetGLState = resetGLState;
  11954. this.dispose = function() {
  11955. transparentObjects = [];
  11956. transparentObjectsLastIndex = -1;
  11957. opaqueObjects = [];
  11958. opaqueObjectsLastIndex = -1;
  11959. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11960. };
  11961. // Events
  11962. function onContextLost( event ) {
  11963. event.preventDefault();
  11964. resetGLState();
  11965. setDefaultGLState();
  11966. properties.clear();
  11967. }
  11968. function onMaterialDispose( event ) {
  11969. var material = event.target;
  11970. material.removeEventListener( 'dispose', onMaterialDispose );
  11971. deallocateMaterial( material );
  11972. }
  11973. // Buffer deallocation
  11974. function deallocateMaterial( material ) {
  11975. releaseMaterialProgramReference( material );
  11976. properties.delete( material );
  11977. }
  11978. function releaseMaterialProgramReference( material ) {
  11979. var programInfo = properties.get( material ).program;
  11980. material.program = undefined;
  11981. if ( programInfo !== undefined ) {
  11982. programCache.releaseProgram( programInfo );
  11983. }
  11984. }
  11985. // Buffer rendering
  11986. this.renderBufferImmediate = function ( object, program, material ) {
  11987. state.initAttributes();
  11988. var buffers = properties.get( object );
  11989. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  11990. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  11991. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  11992. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  11993. var attributes = program.getAttributes();
  11994. if ( object.hasPositions ) {
  11995. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  11996. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11997. state.enableAttribute( attributes.position );
  11998. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11999. }
  12000. if ( object.hasNormals ) {
  12001. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  12002. if ( ! material.isMeshPhongMaterial &&
  12003. ! material.isMeshStandardMaterial &&
  12004. ! material.isMeshNormalMaterial &&
  12005. material.shading === FlatShading ) {
  12006. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  12007. var array = object.normalArray;
  12008. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  12009. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  12010. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  12011. array[ i + 0 ] = nx;
  12012. array[ i + 1 ] = ny;
  12013. array[ i + 2 ] = nz;
  12014. array[ i + 3 ] = nx;
  12015. array[ i + 4 ] = ny;
  12016. array[ i + 5 ] = nz;
  12017. array[ i + 6 ] = nx;
  12018. array[ i + 7 ] = ny;
  12019. array[ i + 8 ] = nz;
  12020. }
  12021. }
  12022. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12023. state.enableAttribute( attributes.normal );
  12024. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12025. }
  12026. if ( object.hasUvs && material.map ) {
  12027. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  12028. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12029. state.enableAttribute( attributes.uv );
  12030. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12031. }
  12032. if ( object.hasColors && material.vertexColors !== NoColors ) {
  12033. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  12034. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12035. state.enableAttribute( attributes.color );
  12036. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12037. }
  12038. state.disableUnusedAttributes();
  12039. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12040. object.count = 0;
  12041. };
  12042. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  12043. setMaterial( material );
  12044. var program = setProgram( camera, fog, material, object );
  12045. var updateBuffers = false;
  12046. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  12047. if ( geometryProgram !== _currentGeometryProgram ) {
  12048. _currentGeometryProgram = geometryProgram;
  12049. updateBuffers = true;
  12050. }
  12051. // morph targets
  12052. var morphTargetInfluences = object.morphTargetInfluences;
  12053. if ( morphTargetInfluences !== undefined ) {
  12054. var activeInfluences = [];
  12055. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  12056. var influence = morphTargetInfluences[ i ];
  12057. activeInfluences.push( [ influence, i ] );
  12058. }
  12059. activeInfluences.sort( absNumericalSort );
  12060. if ( activeInfluences.length > 8 ) {
  12061. activeInfluences.length = 8;
  12062. }
  12063. var morphAttributes = geometry.morphAttributes;
  12064. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  12065. var influence = activeInfluences[ i ];
  12066. morphInfluences[ i ] = influence[ 0 ];
  12067. if ( influence[ 0 ] !== 0 ) {
  12068. var index = influence[ 1 ];
  12069. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  12070. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  12071. } else {
  12072. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  12073. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  12074. }
  12075. }
  12076. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  12077. morphInfluences[ i ] = 0.0;
  12078. }
  12079. program.getUniforms().setValue(
  12080. _gl, 'morphTargetInfluences', morphInfluences );
  12081. updateBuffers = true;
  12082. }
  12083. //
  12084. var index = geometry.index;
  12085. var position = geometry.attributes.position;
  12086. var rangeFactor = 1;
  12087. if ( material.wireframe === true ) {
  12088. index = objects.getWireframeAttribute( geometry );
  12089. rangeFactor = 2;
  12090. }
  12091. var renderer;
  12092. if ( index !== null ) {
  12093. renderer = indexedBufferRenderer;
  12094. renderer.setIndex( index );
  12095. } else {
  12096. renderer = bufferRenderer;
  12097. }
  12098. if ( updateBuffers ) {
  12099. setupVertexAttributes( material, program, geometry );
  12100. if ( index !== null ) {
  12101. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  12102. }
  12103. }
  12104. //
  12105. var dataCount = 0;
  12106. if ( index !== null ) {
  12107. dataCount = index.count;
  12108. } else if ( position !== undefined ) {
  12109. dataCount = position.count;
  12110. }
  12111. var rangeStart = geometry.drawRange.start * rangeFactor;
  12112. var rangeCount = geometry.drawRange.count * rangeFactor;
  12113. var groupStart = group !== null ? group.start * rangeFactor : 0;
  12114. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  12115. var drawStart = Math.max( rangeStart, groupStart );
  12116. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  12117. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  12118. if ( drawCount === 0 ) return;
  12119. //
  12120. if ( object.isMesh ) {
  12121. if ( material.wireframe === true ) {
  12122. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  12123. renderer.setMode( _gl.LINES );
  12124. } else {
  12125. switch ( object.drawMode ) {
  12126. case TrianglesDrawMode:
  12127. renderer.setMode( _gl.TRIANGLES );
  12128. break;
  12129. case TriangleStripDrawMode:
  12130. renderer.setMode( _gl.TRIANGLE_STRIP );
  12131. break;
  12132. case TriangleFanDrawMode:
  12133. renderer.setMode( _gl.TRIANGLE_FAN );
  12134. break;
  12135. }
  12136. }
  12137. } else if ( object.isLine ) {
  12138. var lineWidth = material.linewidth;
  12139. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  12140. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  12141. if ( object.isLineSegments ) {
  12142. renderer.setMode( _gl.LINES );
  12143. } else {
  12144. renderer.setMode( _gl.LINE_STRIP );
  12145. }
  12146. } else if ( object.isPoints ) {
  12147. renderer.setMode( _gl.POINTS );
  12148. }
  12149. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12150. if ( geometry.maxInstancedCount > 0 ) {
  12151. renderer.renderInstances( geometry, drawStart, drawCount );
  12152. }
  12153. } else {
  12154. renderer.render( drawStart, drawCount );
  12155. }
  12156. };
  12157. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12158. var extension;
  12159. if ( geometry && geometry.isInstancedBufferGeometry ) {
  12160. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12161. if ( extension === null ) {
  12162. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12163. return;
  12164. }
  12165. }
  12166. if ( startIndex === undefined ) startIndex = 0;
  12167. state.initAttributes();
  12168. var geometryAttributes = geometry.attributes;
  12169. var programAttributes = program.getAttributes();
  12170. var materialDefaultAttributeValues = material.defaultAttributeValues;
  12171. for ( var name in programAttributes ) {
  12172. var programAttribute = programAttributes[ name ];
  12173. if ( programAttribute >= 0 ) {
  12174. var geometryAttribute = geometryAttributes[ name ];
  12175. if ( geometryAttribute !== undefined ) {
  12176. var normalized = geometryAttribute.normalized;
  12177. var size = geometryAttribute.itemSize;
  12178. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  12179. var buffer = attributeProperties.__webglBuffer;
  12180. var type = attributeProperties.type;
  12181. var bytesPerElement = attributeProperties.bytesPerElement;
  12182. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  12183. var data = geometryAttribute.data;
  12184. var stride = data.stride;
  12185. var offset = geometryAttribute.offset;
  12186. if ( data && data.isInstancedInterleavedBuffer ) {
  12187. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12188. if ( geometry.maxInstancedCount === undefined ) {
  12189. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12190. }
  12191. } else {
  12192. state.enableAttribute( programAttribute );
  12193. }
  12194. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12195. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  12196. } else {
  12197. if ( geometryAttribute.isInstancedBufferAttribute ) {
  12198. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12199. if ( geometry.maxInstancedCount === undefined ) {
  12200. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12201. }
  12202. } else {
  12203. state.enableAttribute( programAttribute );
  12204. }
  12205. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12206. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  12207. }
  12208. } else if ( materialDefaultAttributeValues !== undefined ) {
  12209. var value = materialDefaultAttributeValues[ name ];
  12210. if ( value !== undefined ) {
  12211. switch ( value.length ) {
  12212. case 2:
  12213. _gl.vertexAttrib2fv( programAttribute, value );
  12214. break;
  12215. case 3:
  12216. _gl.vertexAttrib3fv( programAttribute, value );
  12217. break;
  12218. case 4:
  12219. _gl.vertexAttrib4fv( programAttribute, value );
  12220. break;
  12221. default:
  12222. _gl.vertexAttrib1fv( programAttribute, value );
  12223. }
  12224. }
  12225. }
  12226. }
  12227. }
  12228. state.disableUnusedAttributes();
  12229. }
  12230. // Sorting
  12231. function absNumericalSort( a, b ) {
  12232. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12233. }
  12234. function painterSortStable( a, b ) {
  12235. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12236. return a.object.renderOrder - b.object.renderOrder;
  12237. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12238. return a.material.program.id - b.material.program.id;
  12239. } else if ( a.material.id !== b.material.id ) {
  12240. return a.material.id - b.material.id;
  12241. } else if ( a.z !== b.z ) {
  12242. return a.z - b.z;
  12243. } else {
  12244. return a.id - b.id;
  12245. }
  12246. }
  12247. function reversePainterSortStable( a, b ) {
  12248. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12249. return a.object.renderOrder - b.object.renderOrder;
  12250. } if ( a.z !== b.z ) {
  12251. return b.z - a.z;
  12252. } else {
  12253. return a.id - b.id;
  12254. }
  12255. }
  12256. // Rendering
  12257. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12258. if ( camera !== undefined && camera.isCamera !== true ) {
  12259. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12260. return;
  12261. }
  12262. // reset caching for this frame
  12263. _currentGeometryProgram = '';
  12264. _currentMaterialId = - 1;
  12265. _currentCamera = null;
  12266. // update scene graph
  12267. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12268. // update camera matrices and frustum
  12269. if ( camera.parent === null ) camera.updateMatrixWorld();
  12270. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12271. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12272. _frustum.setFromMatrix( _projScreenMatrix );
  12273. lights.length = 0;
  12274. opaqueObjectsLastIndex = - 1;
  12275. transparentObjectsLastIndex = - 1;
  12276. sprites.length = 0;
  12277. lensFlares.length = 0;
  12278. _localClippingEnabled = this.localClippingEnabled;
  12279. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12280. projectObject( scene, camera );
  12281. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12282. transparentObjects.length = transparentObjectsLastIndex + 1;
  12283. if ( _this.sortObjects === true ) {
  12284. opaqueObjects.sort( painterSortStable );
  12285. transparentObjects.sort( reversePainterSortStable );
  12286. }
  12287. //
  12288. if ( _clippingEnabled ) _clipping.beginShadows();
  12289. setupShadows( lights );
  12290. shadowMap.render( scene, camera );
  12291. setupLights( lights, camera );
  12292. if ( _clippingEnabled ) _clipping.endShadows();
  12293. //
  12294. _infoRender.calls = 0;
  12295. _infoRender.vertices = 0;
  12296. _infoRender.faces = 0;
  12297. _infoRender.points = 0;
  12298. if ( renderTarget === undefined ) {
  12299. renderTarget = null;
  12300. }
  12301. this.setRenderTarget( renderTarget );
  12302. //
  12303. var background = scene.background;
  12304. if ( background === null ) {
  12305. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  12306. } else if ( background && background.isColor ) {
  12307. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  12308. forceClear = true;
  12309. }
  12310. if ( this.autoClear || forceClear ) {
  12311. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12312. }
  12313. if ( background && background.isCubeTexture ) {
  12314. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12315. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12316. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12317. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12318. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12319. objects.update( backgroundBoxMesh );
  12320. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12321. } else if ( background && background.isTexture ) {
  12322. backgroundPlaneMesh.material.map = background;
  12323. objects.update( backgroundPlaneMesh );
  12324. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12325. }
  12326. //
  12327. if ( scene.overrideMaterial ) {
  12328. var overrideMaterial = scene.overrideMaterial;
  12329. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  12330. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  12331. } else {
  12332. // opaque pass (front-to-back order)
  12333. state.setBlending( NoBlending );
  12334. renderObjects( opaqueObjects, scene, camera );
  12335. // transparent pass (back-to-front order)
  12336. renderObjects( transparentObjects, scene, camera );
  12337. }
  12338. // custom render plugins (post pass)
  12339. spritePlugin.render( scene, camera );
  12340. lensFlarePlugin.render( scene, camera, _currentViewport );
  12341. // Generate mipmap if we're using any kind of mipmap filtering
  12342. if ( renderTarget ) {
  12343. textures.updateRenderTargetMipmap( renderTarget );
  12344. }
  12345. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12346. state.setDepthTest( true );
  12347. state.setDepthWrite( true );
  12348. state.setColorWrite( true );
  12349. // _gl.finish();
  12350. };
  12351. function pushRenderItem( object, geometry, material, z, group ) {
  12352. var array, index;
  12353. // allocate the next position in the appropriate array
  12354. if ( material.transparent ) {
  12355. array = transparentObjects;
  12356. index = ++ transparentObjectsLastIndex;
  12357. } else {
  12358. array = opaqueObjects;
  12359. index = ++ opaqueObjectsLastIndex;
  12360. }
  12361. // recycle existing render item or grow the array
  12362. var renderItem = array[ index ];
  12363. if ( renderItem !== undefined ) {
  12364. renderItem.id = object.id;
  12365. renderItem.object = object;
  12366. renderItem.geometry = geometry;
  12367. renderItem.material = material;
  12368. renderItem.z = _vector3.z;
  12369. renderItem.group = group;
  12370. } else {
  12371. renderItem = {
  12372. id: object.id,
  12373. object: object,
  12374. geometry: geometry,
  12375. material: material,
  12376. z: _vector3.z,
  12377. group: group
  12378. };
  12379. // assert( index === array.length );
  12380. array.push( renderItem );
  12381. }
  12382. }
  12383. // TODO Duplicated code (Frustum)
  12384. function isObjectViewable( object ) {
  12385. var geometry = object.geometry;
  12386. if ( geometry.boundingSphere === null )
  12387. geometry.computeBoundingSphere();
  12388. _sphere.copy( geometry.boundingSphere ).
  12389. applyMatrix4( object.matrixWorld );
  12390. return isSphereViewable( _sphere );
  12391. }
  12392. function isSpriteViewable( sprite ) {
  12393. _sphere.center.set( 0, 0, 0 );
  12394. _sphere.radius = 0.7071067811865476;
  12395. _sphere.applyMatrix4( sprite.matrixWorld );
  12396. return isSphereViewable( _sphere );
  12397. }
  12398. function isSphereViewable( sphere ) {
  12399. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12400. var numPlanes = _clipping.numPlanes;
  12401. if ( numPlanes === 0 ) return true;
  12402. var planes = _this.clippingPlanes,
  12403. center = sphere.center,
  12404. negRad = - sphere.radius,
  12405. i = 0;
  12406. do {
  12407. // out when deeper than radius in the negative halfspace
  12408. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12409. } while ( ++ i !== numPlanes );
  12410. return true;
  12411. }
  12412. function projectObject( object, camera ) {
  12413. if ( object.visible === false ) return;
  12414. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  12415. if ( visible ) {
  12416. if ( object.isLight ) {
  12417. lights.push( object );
  12418. } else if ( object.isSprite ) {
  12419. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12420. sprites.push( object );
  12421. }
  12422. } else if ( object.isLensFlare ) {
  12423. lensFlares.push( object );
  12424. } else if ( object.isImmediateRenderObject ) {
  12425. if ( _this.sortObjects === true ) {
  12426. _vector3.setFromMatrixPosition( object.matrixWorld );
  12427. _vector3.applyMatrix4( _projScreenMatrix );
  12428. }
  12429. pushRenderItem( object, null, object.material, _vector3.z, null );
  12430. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  12431. if ( object.isSkinnedMesh ) {
  12432. object.skeleton.update();
  12433. }
  12434. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12435. var material = object.material;
  12436. if ( material.visible === true ) {
  12437. if ( _this.sortObjects === true ) {
  12438. _vector3.setFromMatrixPosition( object.matrixWorld );
  12439. _vector3.applyMatrix4( _projScreenMatrix );
  12440. }
  12441. var geometry = objects.update( object );
  12442. if ( material.isMultiMaterial ) {
  12443. var groups = geometry.groups;
  12444. var materials = material.materials;
  12445. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12446. var group = groups[ i ];
  12447. var groupMaterial = materials[ group.materialIndex ];
  12448. if ( groupMaterial.visible === true ) {
  12449. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12450. }
  12451. }
  12452. } else {
  12453. pushRenderItem( object, geometry, material, _vector3.z, null );
  12454. }
  12455. }
  12456. }
  12457. }
  12458. }
  12459. var children = object.children;
  12460. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12461. projectObject( children[ i ], camera );
  12462. }
  12463. }
  12464. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  12465. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12466. var renderItem = renderList[ i ];
  12467. var object = renderItem.object;
  12468. var geometry = renderItem.geometry;
  12469. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12470. var group = renderItem.group;
  12471. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12472. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12473. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  12474. if ( object.isImmediateRenderObject ) {
  12475. setMaterial( material );
  12476. var program = setProgram( camera, scene.fog, material, object );
  12477. _currentGeometryProgram = '';
  12478. object.render( function ( object ) {
  12479. _this.renderBufferImmediate( object, program, material );
  12480. } );
  12481. } else {
  12482. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  12483. }
  12484. object.onAfterRender( _this, scene, camera, geometry, material, group );
  12485. }
  12486. }
  12487. function initMaterial( material, fog, object ) {
  12488. var materialProperties = properties.get( material );
  12489. var parameters = programCache.getParameters(
  12490. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  12491. var code = programCache.getProgramCode( material, parameters );
  12492. var program = materialProperties.program;
  12493. var programChange = true;
  12494. if ( program === undefined ) {
  12495. // new material
  12496. material.addEventListener( 'dispose', onMaterialDispose );
  12497. } else if ( program.code !== code ) {
  12498. // changed glsl or parameters
  12499. releaseMaterialProgramReference( material );
  12500. } else if ( parameters.shaderID !== undefined ) {
  12501. // same glsl and uniform list
  12502. return;
  12503. } else {
  12504. // only rebuild uniform list
  12505. programChange = false;
  12506. }
  12507. if ( programChange ) {
  12508. if ( parameters.shaderID ) {
  12509. var shader = ShaderLib[ parameters.shaderID ];
  12510. materialProperties.__webglShader = {
  12511. name: material.type,
  12512. uniforms: UniformsUtils.clone( shader.uniforms ),
  12513. vertexShader: shader.vertexShader,
  12514. fragmentShader: shader.fragmentShader
  12515. };
  12516. } else {
  12517. materialProperties.__webglShader = {
  12518. name: material.type,
  12519. uniforms: material.uniforms,
  12520. vertexShader: material.vertexShader,
  12521. fragmentShader: material.fragmentShader
  12522. };
  12523. }
  12524. material.__webglShader = materialProperties.__webglShader;
  12525. program = programCache.acquireProgram( material, parameters, code );
  12526. materialProperties.program = program;
  12527. material.program = program;
  12528. }
  12529. var attributes = program.getAttributes();
  12530. if ( material.morphTargets ) {
  12531. material.numSupportedMorphTargets = 0;
  12532. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12533. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12534. material.numSupportedMorphTargets ++;
  12535. }
  12536. }
  12537. }
  12538. if ( material.morphNormals ) {
  12539. material.numSupportedMorphNormals = 0;
  12540. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12541. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12542. material.numSupportedMorphNormals ++;
  12543. }
  12544. }
  12545. }
  12546. var uniforms = materialProperties.__webglShader.uniforms;
  12547. if ( ! material.isShaderMaterial &&
  12548. ! material.isRawShaderMaterial ||
  12549. material.clipping === true ) {
  12550. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12551. materialProperties.numIntersection = _clipping.numIntersection;
  12552. uniforms.clippingPlanes = _clipping.uniform;
  12553. }
  12554. materialProperties.fog = fog;
  12555. // store the light setup it was created for
  12556. materialProperties.lightsHash = _lights.hash;
  12557. if ( material.lights ) {
  12558. // wire up the material to this renderer's lighting state
  12559. uniforms.ambientLightColor.value = _lights.ambient;
  12560. uniforms.directionalLights.value = _lights.directional;
  12561. uniforms.spotLights.value = _lights.spot;
  12562. uniforms.rectAreaLights.value = _lights.rectArea;
  12563. uniforms.pointLights.value = _lights.point;
  12564. uniforms.hemisphereLights.value = _lights.hemi;
  12565. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12566. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12567. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12568. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12569. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12570. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12571. // TODO (abelnation): add area lights shadow info to uniforms
  12572. }
  12573. var progUniforms = materialProperties.program.getUniforms(),
  12574. uniformsList =
  12575. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12576. materialProperties.uniformsList = uniformsList;
  12577. }
  12578. function setMaterial( material ) {
  12579. material.side === DoubleSide
  12580. ? state.disable( _gl.CULL_FACE )
  12581. : state.enable( _gl.CULL_FACE );
  12582. state.setFlipSided( material.side === BackSide );
  12583. material.transparent === true
  12584. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  12585. : state.setBlending( NoBlending );
  12586. state.setDepthFunc( material.depthFunc );
  12587. state.setDepthTest( material.depthTest );
  12588. state.setDepthWrite( material.depthWrite );
  12589. state.setColorWrite( material.colorWrite );
  12590. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12591. }
  12592. function setProgram( camera, fog, material, object ) {
  12593. _usedTextureUnits = 0;
  12594. var materialProperties = properties.get( material );
  12595. if ( _clippingEnabled ) {
  12596. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12597. var useCache =
  12598. camera === _currentCamera &&
  12599. material.id === _currentMaterialId;
  12600. // we might want to call this function with some ClippingGroup
  12601. // object instead of the material, once it becomes feasible
  12602. // (#8465, #8379)
  12603. _clipping.setState(
  12604. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  12605. camera, materialProperties, useCache );
  12606. }
  12607. }
  12608. if ( material.needsUpdate === false ) {
  12609. if ( materialProperties.program === undefined ) {
  12610. material.needsUpdate = true;
  12611. } else if ( material.fog && materialProperties.fog !== fog ) {
  12612. material.needsUpdate = true;
  12613. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  12614. material.needsUpdate = true;
  12615. } else if ( materialProperties.numClippingPlanes !== undefined &&
  12616. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  12617. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  12618. material.needsUpdate = true;
  12619. }
  12620. }
  12621. if ( material.needsUpdate ) {
  12622. initMaterial( material, fog, object );
  12623. material.needsUpdate = false;
  12624. }
  12625. var refreshProgram = false;
  12626. var refreshMaterial = false;
  12627. var refreshLights = false;
  12628. var program = materialProperties.program,
  12629. p_uniforms = program.getUniforms(),
  12630. m_uniforms = materialProperties.__webglShader.uniforms;
  12631. if ( program.id !== _currentProgram ) {
  12632. _gl.useProgram( program.program );
  12633. _currentProgram = program.id;
  12634. refreshProgram = true;
  12635. refreshMaterial = true;
  12636. refreshLights = true;
  12637. }
  12638. if ( material.id !== _currentMaterialId ) {
  12639. _currentMaterialId = material.id;
  12640. refreshMaterial = true;
  12641. }
  12642. if ( refreshProgram || camera !== _currentCamera ) {
  12643. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12644. if ( capabilities.logarithmicDepthBuffer ) {
  12645. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12646. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12647. }
  12648. if ( camera !== _currentCamera ) {
  12649. _currentCamera = camera;
  12650. // lighting uniforms depend on the camera so enforce an update
  12651. // now, in case this material supports lights - or later, when
  12652. // the next material that does gets activated:
  12653. refreshMaterial = true; // set to true on material change
  12654. refreshLights = true; // remains set until update done
  12655. }
  12656. // load material specific uniforms
  12657. // (shader material also gets them for the sake of genericity)
  12658. if ( material.isShaderMaterial ||
  12659. material.isMeshPhongMaterial ||
  12660. material.isMeshStandardMaterial ||
  12661. material.envMap ) {
  12662. var uCamPos = p_uniforms.map.cameraPosition;
  12663. if ( uCamPos !== undefined ) {
  12664. uCamPos.setValue( _gl,
  12665. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12666. }
  12667. }
  12668. if ( material.isMeshPhongMaterial ||
  12669. material.isMeshLambertMaterial ||
  12670. material.isMeshBasicMaterial ||
  12671. material.isMeshStandardMaterial ||
  12672. material.isShaderMaterial ||
  12673. material.skinning ) {
  12674. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12675. }
  12676. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12677. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12678. }
  12679. // skinning uniforms must be set even if material didn't change
  12680. // auto-setting of texture unit for bone texture must go before other textures
  12681. // not sure why, but otherwise weird things happen
  12682. if ( material.skinning ) {
  12683. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12684. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12685. var skeleton = object.skeleton;
  12686. if ( skeleton ) {
  12687. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12688. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12689. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12690. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12691. } else {
  12692. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12693. }
  12694. }
  12695. }
  12696. if ( refreshMaterial ) {
  12697. if ( material.lights ) {
  12698. // the current material requires lighting info
  12699. // note: all lighting uniforms are always set correctly
  12700. // they simply reference the renderer's state for their
  12701. // values
  12702. //
  12703. // use the current material's .needsUpdate flags to set
  12704. // the GL state when required
  12705. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12706. }
  12707. // refresh uniforms common to several materials
  12708. if ( fog && material.fog ) {
  12709. refreshUniformsFog( m_uniforms, fog );
  12710. }
  12711. if ( material.isMeshBasicMaterial ||
  12712. material.isMeshLambertMaterial ||
  12713. material.isMeshPhongMaterial ||
  12714. material.isMeshStandardMaterial ||
  12715. material.isMeshNormalMaterial ||
  12716. material.isMeshDepthMaterial ) {
  12717. refreshUniformsCommon( m_uniforms, material );
  12718. }
  12719. // refresh single material specific uniforms
  12720. if ( material.isLineBasicMaterial ) {
  12721. refreshUniformsLine( m_uniforms, material );
  12722. } else if ( material.isLineDashedMaterial ) {
  12723. refreshUniformsLine( m_uniforms, material );
  12724. refreshUniformsDash( m_uniforms, material );
  12725. } else if ( material.isPointsMaterial ) {
  12726. refreshUniformsPoints( m_uniforms, material );
  12727. } else if ( material.isMeshLambertMaterial ) {
  12728. refreshUniformsLambert( m_uniforms, material );
  12729. } else if ( material.isMeshToonMaterial ) {
  12730. refreshUniformsToon( m_uniforms, material );
  12731. } else if ( material.isMeshPhongMaterial ) {
  12732. refreshUniformsPhong( m_uniforms, material );
  12733. } else if ( material.isMeshPhysicalMaterial ) {
  12734. refreshUniformsPhysical( m_uniforms, material );
  12735. } else if ( material.isMeshStandardMaterial ) {
  12736. refreshUniformsStandard( m_uniforms, material );
  12737. } else if ( material.isMeshDepthMaterial ) {
  12738. if ( material.displacementMap ) {
  12739. m_uniforms.displacementMap.value = material.displacementMap;
  12740. m_uniforms.displacementScale.value = material.displacementScale;
  12741. m_uniforms.displacementBias.value = material.displacementBias;
  12742. }
  12743. } else if ( material.isMeshNormalMaterial ) {
  12744. refreshUniformsNormal( m_uniforms, material );
  12745. }
  12746. // RectAreaLight Texture
  12747. // TODO (mrdoob): Find a nicer implementation
  12748. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  12749. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  12750. WebGLUniforms.upload(
  12751. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12752. }
  12753. // common matrices
  12754. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12755. p_uniforms.set( _gl, object, 'normalMatrix' );
  12756. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12757. return program;
  12758. }
  12759. // Uniforms (refresh uniforms objects)
  12760. function refreshUniformsCommon( uniforms, material ) {
  12761. uniforms.opacity.value = material.opacity;
  12762. uniforms.diffuse.value = material.color;
  12763. if ( material.emissive ) {
  12764. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12765. }
  12766. uniforms.map.value = material.map;
  12767. uniforms.specularMap.value = material.specularMap;
  12768. uniforms.alphaMap.value = material.alphaMap;
  12769. if ( material.lightMap ) {
  12770. uniforms.lightMap.value = material.lightMap;
  12771. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12772. }
  12773. if ( material.aoMap ) {
  12774. uniforms.aoMap.value = material.aoMap;
  12775. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12776. }
  12777. // uv repeat and offset setting priorities
  12778. // 1. color map
  12779. // 2. specular map
  12780. // 3. normal map
  12781. // 4. bump map
  12782. // 5. alpha map
  12783. // 6. emissive map
  12784. var uvScaleMap;
  12785. if ( material.map ) {
  12786. uvScaleMap = material.map;
  12787. } else if ( material.specularMap ) {
  12788. uvScaleMap = material.specularMap;
  12789. } else if ( material.displacementMap ) {
  12790. uvScaleMap = material.displacementMap;
  12791. } else if ( material.normalMap ) {
  12792. uvScaleMap = material.normalMap;
  12793. } else if ( material.bumpMap ) {
  12794. uvScaleMap = material.bumpMap;
  12795. } else if ( material.roughnessMap ) {
  12796. uvScaleMap = material.roughnessMap;
  12797. } else if ( material.metalnessMap ) {
  12798. uvScaleMap = material.metalnessMap;
  12799. } else if ( material.alphaMap ) {
  12800. uvScaleMap = material.alphaMap;
  12801. } else if ( material.emissiveMap ) {
  12802. uvScaleMap = material.emissiveMap;
  12803. }
  12804. if ( uvScaleMap !== undefined ) {
  12805. // backwards compatibility
  12806. if ( uvScaleMap.isWebGLRenderTarget ) {
  12807. uvScaleMap = uvScaleMap.texture;
  12808. }
  12809. var offset = uvScaleMap.offset;
  12810. var repeat = uvScaleMap.repeat;
  12811. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12812. }
  12813. uniforms.envMap.value = material.envMap;
  12814. // don't flip CubeTexture envMaps, flip everything else:
  12815. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12816. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12817. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12818. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12819. uniforms.reflectivity.value = material.reflectivity;
  12820. uniforms.refractionRatio.value = material.refractionRatio;
  12821. }
  12822. function refreshUniformsLine( uniforms, material ) {
  12823. uniforms.diffuse.value = material.color;
  12824. uniforms.opacity.value = material.opacity;
  12825. }
  12826. function refreshUniformsDash( uniforms, material ) {
  12827. uniforms.dashSize.value = material.dashSize;
  12828. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12829. uniforms.scale.value = material.scale;
  12830. }
  12831. function refreshUniformsPoints( uniforms, material ) {
  12832. uniforms.diffuse.value = material.color;
  12833. uniforms.opacity.value = material.opacity;
  12834. uniforms.size.value = material.size * _pixelRatio;
  12835. uniforms.scale.value = _height * 0.5;
  12836. uniforms.map.value = material.map;
  12837. if ( material.map !== null ) {
  12838. var offset = material.map.offset;
  12839. var repeat = material.map.repeat;
  12840. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12841. }
  12842. }
  12843. function refreshUniformsFog( uniforms, fog ) {
  12844. uniforms.fogColor.value = fog.color;
  12845. if ( fog.isFog ) {
  12846. uniforms.fogNear.value = fog.near;
  12847. uniforms.fogFar.value = fog.far;
  12848. } else if ( fog.isFogExp2 ) {
  12849. uniforms.fogDensity.value = fog.density;
  12850. }
  12851. }
  12852. function refreshUniformsLambert( uniforms, material ) {
  12853. if ( material.emissiveMap ) {
  12854. uniforms.emissiveMap.value = material.emissiveMap;
  12855. }
  12856. }
  12857. function refreshUniformsPhong( uniforms, material ) {
  12858. uniforms.specular.value = material.specular;
  12859. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12860. if ( material.emissiveMap ) {
  12861. uniforms.emissiveMap.value = material.emissiveMap;
  12862. }
  12863. if ( material.bumpMap ) {
  12864. uniforms.bumpMap.value = material.bumpMap;
  12865. uniforms.bumpScale.value = material.bumpScale;
  12866. }
  12867. if ( material.normalMap ) {
  12868. uniforms.normalMap.value = material.normalMap;
  12869. uniforms.normalScale.value.copy( material.normalScale );
  12870. }
  12871. if ( material.displacementMap ) {
  12872. uniforms.displacementMap.value = material.displacementMap;
  12873. uniforms.displacementScale.value = material.displacementScale;
  12874. uniforms.displacementBias.value = material.displacementBias;
  12875. }
  12876. }
  12877. function refreshUniformsToon( uniforms, material ) {
  12878. refreshUniformsPhong( uniforms, material );
  12879. if ( material.gradientMap ) {
  12880. uniforms.gradientMap.value = material.gradientMap;
  12881. }
  12882. }
  12883. function refreshUniformsStandard( uniforms, material ) {
  12884. uniforms.roughness.value = material.roughness;
  12885. uniforms.metalness.value = material.metalness;
  12886. if ( material.roughnessMap ) {
  12887. uniforms.roughnessMap.value = material.roughnessMap;
  12888. }
  12889. if ( material.metalnessMap ) {
  12890. uniforms.metalnessMap.value = material.metalnessMap;
  12891. }
  12892. if ( material.emissiveMap ) {
  12893. uniforms.emissiveMap.value = material.emissiveMap;
  12894. }
  12895. if ( material.bumpMap ) {
  12896. uniforms.bumpMap.value = material.bumpMap;
  12897. uniforms.bumpScale.value = material.bumpScale;
  12898. }
  12899. if ( material.normalMap ) {
  12900. uniforms.normalMap.value = material.normalMap;
  12901. uniforms.normalScale.value.copy( material.normalScale );
  12902. }
  12903. if ( material.displacementMap ) {
  12904. uniforms.displacementMap.value = material.displacementMap;
  12905. uniforms.displacementScale.value = material.displacementScale;
  12906. uniforms.displacementBias.value = material.displacementBias;
  12907. }
  12908. if ( material.envMap ) {
  12909. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12910. uniforms.envMapIntensity.value = material.envMapIntensity;
  12911. }
  12912. }
  12913. function refreshUniformsPhysical( uniforms, material ) {
  12914. uniforms.clearCoat.value = material.clearCoat;
  12915. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12916. refreshUniformsStandard( uniforms, material );
  12917. }
  12918. function refreshUniformsNormal( uniforms, material ) {
  12919. if ( material.bumpMap ) {
  12920. uniforms.bumpMap.value = material.bumpMap;
  12921. uniforms.bumpScale.value = material.bumpScale;
  12922. }
  12923. if ( material.normalMap ) {
  12924. uniforms.normalMap.value = material.normalMap;
  12925. uniforms.normalScale.value.copy( material.normalScale );
  12926. }
  12927. if ( material.displacementMap ) {
  12928. uniforms.displacementMap.value = material.displacementMap;
  12929. uniforms.displacementScale.value = material.displacementScale;
  12930. uniforms.displacementBias.value = material.displacementBias;
  12931. }
  12932. }
  12933. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12934. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12935. uniforms.ambientLightColor.needsUpdate = value;
  12936. uniforms.directionalLights.needsUpdate = value;
  12937. uniforms.pointLights.needsUpdate = value;
  12938. uniforms.spotLights.needsUpdate = value;
  12939. uniforms.rectAreaLights.needsUpdate = value;
  12940. uniforms.hemisphereLights.needsUpdate = value;
  12941. }
  12942. // Lighting
  12943. function setupShadows( lights ) {
  12944. var lightShadowsLength = 0;
  12945. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12946. var light = lights[ i ];
  12947. if ( light.castShadow ) {
  12948. _lights.shadows[ lightShadowsLength ++ ] = light;
  12949. }
  12950. }
  12951. _lights.shadows.length = lightShadowsLength;
  12952. }
  12953. function setupLights( lights, camera ) {
  12954. var l, ll, light,
  12955. r = 0, g = 0, b = 0,
  12956. color,
  12957. intensity,
  12958. distance,
  12959. shadowMap,
  12960. viewMatrix = camera.matrixWorldInverse,
  12961. directionalLength = 0,
  12962. pointLength = 0,
  12963. spotLength = 0,
  12964. rectAreaLength = 0,
  12965. hemiLength = 0;
  12966. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12967. light = lights[ l ];
  12968. color = light.color;
  12969. intensity = light.intensity;
  12970. distance = light.distance;
  12971. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12972. if ( light.isAmbientLight ) {
  12973. r += color.r * intensity;
  12974. g += color.g * intensity;
  12975. b += color.b * intensity;
  12976. } else if ( light.isDirectionalLight ) {
  12977. var uniforms = lightCache.get( light );
  12978. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12979. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12980. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12981. uniforms.direction.sub( _vector3 );
  12982. uniforms.direction.transformDirection( viewMatrix );
  12983. uniforms.shadow = light.castShadow;
  12984. if ( light.castShadow ) {
  12985. uniforms.shadowBias = light.shadow.bias;
  12986. uniforms.shadowRadius = light.shadow.radius;
  12987. uniforms.shadowMapSize = light.shadow.mapSize;
  12988. }
  12989. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12990. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12991. _lights.directional[ directionalLength ++ ] = uniforms;
  12992. } else if ( light.isSpotLight ) {
  12993. var uniforms = lightCache.get( light );
  12994. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12995. uniforms.position.applyMatrix4( viewMatrix );
  12996. uniforms.color.copy( color ).multiplyScalar( intensity );
  12997. uniforms.distance = distance;
  12998. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12999. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13000. uniforms.direction.sub( _vector3 );
  13001. uniforms.direction.transformDirection( viewMatrix );
  13002. uniforms.coneCos = Math.cos( light.angle );
  13003. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13004. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13005. uniforms.shadow = light.castShadow;
  13006. if ( light.castShadow ) {
  13007. uniforms.shadowBias = light.shadow.bias;
  13008. uniforms.shadowRadius = light.shadow.radius;
  13009. uniforms.shadowMapSize = light.shadow.mapSize;
  13010. }
  13011. _lights.spotShadowMap[ spotLength ] = shadowMap;
  13012. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  13013. _lights.spot[ spotLength ++ ] = uniforms;
  13014. } else if ( light.isRectAreaLight ) {
  13015. var uniforms = lightCache.get( light );
  13016. // (a) intensity controls irradiance of entire light
  13017. uniforms.color
  13018. .copy( color )
  13019. .multiplyScalar( intensity / ( light.width * light.height ) );
  13020. // (b) intensity controls the radiance per light area
  13021. // uniforms.color.copy( color ).multiplyScalar( intensity );
  13022. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13023. uniforms.position.applyMatrix4( viewMatrix );
  13024. // extract local rotation of light to derive width/height half vectors
  13025. _matrix42.identity();
  13026. _matrix4.copy( light.matrixWorld );
  13027. _matrix4.premultiply( viewMatrix );
  13028. _matrix42.extractRotation( _matrix4 );
  13029. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13030. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13031. uniforms.halfWidth.applyMatrix4( _matrix42 );
  13032. uniforms.halfHeight.applyMatrix4( _matrix42 );
  13033. // TODO (abelnation): RectAreaLight distance?
  13034. // uniforms.distance = distance;
  13035. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  13036. } else if ( light.isPointLight ) {
  13037. var uniforms = lightCache.get( light );
  13038. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13039. uniforms.position.applyMatrix4( viewMatrix );
  13040. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13041. uniforms.distance = light.distance;
  13042. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  13043. uniforms.shadow = light.castShadow;
  13044. if ( light.castShadow ) {
  13045. uniforms.shadowBias = light.shadow.bias;
  13046. uniforms.shadowRadius = light.shadow.radius;
  13047. uniforms.shadowMapSize = light.shadow.mapSize;
  13048. }
  13049. _lights.pointShadowMap[ pointLength ] = shadowMap;
  13050. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  13051. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  13052. }
  13053. // for point lights we set the shadow matrix to be a translation-only matrix
  13054. // equal to inverse of the light's position
  13055. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  13056. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  13057. _lights.point[ pointLength ++ ] = uniforms;
  13058. } else if ( light.isHemisphereLight ) {
  13059. var uniforms = lightCache.get( light );
  13060. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13061. uniforms.direction.transformDirection( viewMatrix );
  13062. uniforms.direction.normalize();
  13063. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13064. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13065. _lights.hemi[ hemiLength ++ ] = uniforms;
  13066. }
  13067. }
  13068. _lights.ambient[ 0 ] = r;
  13069. _lights.ambient[ 1 ] = g;
  13070. _lights.ambient[ 2 ] = b;
  13071. _lights.directional.length = directionalLength;
  13072. _lights.spot.length = spotLength;
  13073. _lights.rectArea.length = rectAreaLength;
  13074. _lights.point.length = pointLength;
  13075. _lights.hemi.length = hemiLength;
  13076. // TODO (sam-g-steel) why aren't we using join
  13077. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  13078. }
  13079. // GL state setting
  13080. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13081. state.setCullFace( cullFace );
  13082. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  13083. };
  13084. // Textures
  13085. function allocTextureUnit() {
  13086. var textureUnit = _usedTextureUnits;
  13087. if ( textureUnit >= capabilities.maxTextures ) {
  13088. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13089. }
  13090. _usedTextureUnits += 1;
  13091. return textureUnit;
  13092. }
  13093. this.allocTextureUnit = allocTextureUnit;
  13094. // this.setTexture2D = setTexture2D;
  13095. this.setTexture2D = ( function() {
  13096. var warned = false;
  13097. // backwards compatibility: peel texture.texture
  13098. return function setTexture2D( texture, slot ) {
  13099. if ( texture && texture.isWebGLRenderTarget ) {
  13100. if ( ! warned ) {
  13101. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  13102. warned = true;
  13103. }
  13104. texture = texture.texture;
  13105. }
  13106. textures.setTexture2D( texture, slot );
  13107. };
  13108. }() );
  13109. this.setTexture = ( function() {
  13110. var warned = false;
  13111. return function setTexture( texture, slot ) {
  13112. if ( ! warned ) {
  13113. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  13114. warned = true;
  13115. }
  13116. textures.setTexture2D( texture, slot );
  13117. };
  13118. }() );
  13119. this.setTextureCube = ( function() {
  13120. var warned = false;
  13121. return function setTextureCube( texture, slot ) {
  13122. // backwards compatibility: peel texture.texture
  13123. if ( texture && texture.isWebGLRenderTargetCube ) {
  13124. if ( ! warned ) {
  13125. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  13126. warned = true;
  13127. }
  13128. texture = texture.texture;
  13129. }
  13130. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  13131. // TODO: unify these code paths
  13132. if ( ( texture && texture.isCubeTexture ) ||
  13133. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  13134. // CompressedTexture can have Array in image :/
  13135. // this function alone should take care of cube textures
  13136. textures.setTextureCube( texture, slot );
  13137. } else {
  13138. // assumed: texture property of THREE.WebGLRenderTargetCube
  13139. textures.setTextureCubeDynamic( texture, slot );
  13140. }
  13141. };
  13142. }() );
  13143. this.getCurrentRenderTarget = function() {
  13144. return _currentRenderTarget;
  13145. };
  13146. this.setRenderTarget = function ( renderTarget ) {
  13147. _currentRenderTarget = renderTarget;
  13148. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  13149. textures.setupRenderTarget( renderTarget );
  13150. }
  13151. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13152. var framebuffer;
  13153. if ( renderTarget ) {
  13154. var renderTargetProperties = properties.get( renderTarget );
  13155. if ( isCube ) {
  13156. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13157. } else {
  13158. framebuffer = renderTargetProperties.__webglFramebuffer;
  13159. }
  13160. _currentScissor.copy( renderTarget.scissor );
  13161. _currentScissorTest = renderTarget.scissorTest;
  13162. _currentViewport.copy( renderTarget.viewport );
  13163. } else {
  13164. framebuffer = null;
  13165. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  13166. _currentScissorTest = _scissorTest;
  13167. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  13168. }
  13169. if ( _currentFramebuffer !== framebuffer ) {
  13170. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13171. _currentFramebuffer = framebuffer;
  13172. }
  13173. state.scissor( _currentScissor );
  13174. state.setScissorTest( _currentScissorTest );
  13175. state.viewport( _currentViewport );
  13176. if ( isCube ) {
  13177. var textureProperties = properties.get( renderTarget.texture );
  13178. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  13179. }
  13180. };
  13181. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  13182. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  13183. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13184. return;
  13185. }
  13186. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  13187. if ( framebuffer ) {
  13188. var restore = false;
  13189. if ( framebuffer !== _currentFramebuffer ) {
  13190. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13191. restore = true;
  13192. }
  13193. try {
  13194. var texture = renderTarget.texture;
  13195. var textureFormat = texture.format;
  13196. var textureType = texture.type;
  13197. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  13198. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  13199. return;
  13200. }
  13201. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  13202. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  13203. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  13204. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  13205. return;
  13206. }
  13207. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13208. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  13209. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  13210. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  13211. }
  13212. } else {
  13213. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13214. }
  13215. } finally {
  13216. if ( restore ) {
  13217. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13218. }
  13219. }
  13220. }
  13221. };
  13222. // Map three.js constants to WebGL constants
  13223. function paramThreeToGL( p ) {
  13224. var extension;
  13225. if ( p === RepeatWrapping ) return _gl.REPEAT;
  13226. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13227. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13228. if ( p === NearestFilter ) return _gl.NEAREST;
  13229. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13230. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13231. if ( p === LinearFilter ) return _gl.LINEAR;
  13232. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13233. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13234. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13235. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13236. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13237. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13238. if ( p === ByteType ) return _gl.BYTE;
  13239. if ( p === ShortType ) return _gl.SHORT;
  13240. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13241. if ( p === IntType ) return _gl.INT;
  13242. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13243. if ( p === FloatType ) return _gl.FLOAT;
  13244. if ( p === HalfFloatType ) {
  13245. extension = extensions.get( 'OES_texture_half_float' );
  13246. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  13247. }
  13248. if ( p === AlphaFormat ) return _gl.ALPHA;
  13249. if ( p === RGBFormat ) return _gl.RGB;
  13250. if ( p === RGBAFormat ) return _gl.RGBA;
  13251. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13252. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13253. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13254. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  13255. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13256. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13257. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13258. if ( p === ZeroFactor ) return _gl.ZERO;
  13259. if ( p === OneFactor ) return _gl.ONE;
  13260. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13261. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13262. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13263. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13264. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13265. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13266. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13267. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13268. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13269. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13270. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13271. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13272. if ( extension !== null ) {
  13273. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13274. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13275. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13276. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13277. }
  13278. }
  13279. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13280. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13281. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13282. if ( extension !== null ) {
  13283. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13284. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13285. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13286. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13287. }
  13288. }
  13289. if ( p === RGB_ETC1_Format ) {
  13290. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13291. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13292. }
  13293. if ( p === MinEquation || p === MaxEquation ) {
  13294. extension = extensions.get( 'EXT_blend_minmax' );
  13295. if ( extension !== null ) {
  13296. if ( p === MinEquation ) return extension.MIN_EXT;
  13297. if ( p === MaxEquation ) return extension.MAX_EXT;
  13298. }
  13299. }
  13300. if ( p === UnsignedInt248Type ) {
  13301. extension = extensions.get( 'WEBGL_depth_texture' );
  13302. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  13303. }
  13304. return 0;
  13305. }
  13306. }
  13307. /**
  13308. * @author mrdoob / http://mrdoob.com/
  13309. * @author alteredq / http://alteredqualia.com/
  13310. */
  13311. function FogExp2 ( color, density ) {
  13312. this.name = '';
  13313. this.color = new Color( color );
  13314. this.density = ( density !== undefined ) ? density : 0.00025;
  13315. }
  13316. FogExp2.prototype.isFogExp2 = true;
  13317. FogExp2.prototype.clone = function () {
  13318. return new FogExp2( this.color.getHex(), this.density );
  13319. };
  13320. FogExp2.prototype.toJSON = function ( meta ) {
  13321. return {
  13322. type: 'FogExp2',
  13323. color: this.color.getHex(),
  13324. density: this.density
  13325. };
  13326. };
  13327. /**
  13328. * @author mrdoob / http://mrdoob.com/
  13329. * @author alteredq / http://alteredqualia.com/
  13330. */
  13331. function Fog ( color, near, far ) {
  13332. this.name = '';
  13333. this.color = new Color( color );
  13334. this.near = ( near !== undefined ) ? near : 1;
  13335. this.far = ( far !== undefined ) ? far : 1000;
  13336. }
  13337. Fog.prototype.isFog = true;
  13338. Fog.prototype.clone = function () {
  13339. return new Fog( this.color.getHex(), this.near, this.far );
  13340. };
  13341. Fog.prototype.toJSON = function ( meta ) {
  13342. return {
  13343. type: 'Fog',
  13344. color: this.color.getHex(),
  13345. near: this.near,
  13346. far: this.far
  13347. };
  13348. };
  13349. /**
  13350. * @author mrdoob / http://mrdoob.com/
  13351. */
  13352. function Scene () {
  13353. Object3D.call( this );
  13354. this.type = 'Scene';
  13355. this.background = null;
  13356. this.fog = null;
  13357. this.overrideMaterial = null;
  13358. this.autoUpdate = true; // checked by the renderer
  13359. }
  13360. Scene.prototype = Object.create( Object3D.prototype );
  13361. Scene.prototype.constructor = Scene;
  13362. Scene.prototype.copy = function ( source, recursive ) {
  13363. Object3D.prototype.copy.call( this, source, recursive );
  13364. if ( source.background !== null ) this.background = source.background.clone();
  13365. if ( source.fog !== null ) this.fog = source.fog.clone();
  13366. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13367. this.autoUpdate = source.autoUpdate;
  13368. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13369. return this;
  13370. };
  13371. Scene.prototype.toJSON = function ( meta ) {
  13372. var data = Object3D.prototype.toJSON.call( this, meta );
  13373. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  13374. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13375. return data;
  13376. };
  13377. /**
  13378. * @author mikael emtinger / http://gomo.se/
  13379. * @author alteredq / http://alteredqualia.com/
  13380. */
  13381. function LensFlare( texture, size, distance, blending, color ) {
  13382. Object3D.call( this );
  13383. this.lensFlares = [];
  13384. this.positionScreen = new Vector3();
  13385. this.customUpdateCallback = undefined;
  13386. if ( texture !== undefined ) {
  13387. this.add( texture, size, distance, blending, color );
  13388. }
  13389. }
  13390. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13391. constructor: LensFlare,
  13392. isLensFlare: true,
  13393. copy: function ( source ) {
  13394. Object3D.prototype.copy.call( this, source );
  13395. this.positionScreen.copy( source.positionScreen );
  13396. this.customUpdateCallback = source.customUpdateCallback;
  13397. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13398. this.lensFlares.push( source.lensFlares[ i ] );
  13399. }
  13400. return this;
  13401. },
  13402. add: function ( texture, size, distance, blending, color, opacity ) {
  13403. if ( size === undefined ) size = - 1;
  13404. if ( distance === undefined ) distance = 0;
  13405. if ( opacity === undefined ) opacity = 1;
  13406. if ( color === undefined ) color = new Color( 0xffffff );
  13407. if ( blending === undefined ) blending = NormalBlending;
  13408. distance = Math.min( distance, Math.max( 0, distance ) );
  13409. this.lensFlares.push( {
  13410. texture: texture, // THREE.Texture
  13411. size: size, // size in pixels (-1 = use texture.width)
  13412. distance: distance, // distance (0-1) from light source (0=at light source)
  13413. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13414. scale: 1, // scale
  13415. rotation: 0, // rotation
  13416. opacity: opacity, // opacity
  13417. color: color, // color
  13418. blending: blending // blending
  13419. } );
  13420. },
  13421. /*
  13422. * Update lens flares update positions on all flares based on the screen position
  13423. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13424. */
  13425. updateLensFlares: function () {
  13426. var f, fl = this.lensFlares.length;
  13427. var flare;
  13428. var vecX = - this.positionScreen.x * 2;
  13429. var vecY = - this.positionScreen.y * 2;
  13430. for ( f = 0; f < fl; f ++ ) {
  13431. flare = this.lensFlares[ f ];
  13432. flare.x = this.positionScreen.x + vecX * flare.distance;
  13433. flare.y = this.positionScreen.y + vecY * flare.distance;
  13434. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13435. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13436. }
  13437. }
  13438. } );
  13439. /**
  13440. * @author alteredq / http://alteredqualia.com/
  13441. *
  13442. * parameters = {
  13443. * color: <hex>,
  13444. * opacity: <float>,
  13445. * map: new THREE.Texture( <Image> ),
  13446. *
  13447. * uvOffset: new THREE.Vector2(),
  13448. * uvScale: new THREE.Vector2()
  13449. * }
  13450. */
  13451. function SpriteMaterial( parameters ) {
  13452. Material.call( this );
  13453. this.type = 'SpriteMaterial';
  13454. this.color = new Color( 0xffffff );
  13455. this.map = null;
  13456. this.rotation = 0;
  13457. this.fog = false;
  13458. this.lights = false;
  13459. this.setValues( parameters );
  13460. }
  13461. SpriteMaterial.prototype = Object.create( Material.prototype );
  13462. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13463. SpriteMaterial.prototype.copy = function ( source ) {
  13464. Material.prototype.copy.call( this, source );
  13465. this.color.copy( source.color );
  13466. this.map = source.map;
  13467. this.rotation = source.rotation;
  13468. return this;
  13469. };
  13470. /**
  13471. * @author mikael emtinger / http://gomo.se/
  13472. * @author alteredq / http://alteredqualia.com/
  13473. */
  13474. function Sprite( material ) {
  13475. Object3D.call( this );
  13476. this.type = 'Sprite';
  13477. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13478. }
  13479. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13480. constructor: Sprite,
  13481. isSprite: true,
  13482. raycast: ( function () {
  13483. var matrixPosition = new Vector3();
  13484. return function raycast( raycaster, intersects ) {
  13485. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13486. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13487. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13488. if ( distanceSq > guessSizeSq ) {
  13489. return;
  13490. }
  13491. intersects.push( {
  13492. distance: Math.sqrt( distanceSq ),
  13493. point: this.position,
  13494. face: null,
  13495. object: this
  13496. } );
  13497. };
  13498. }() ),
  13499. clone: function () {
  13500. return new this.constructor( this.material ).copy( this );
  13501. }
  13502. } );
  13503. /**
  13504. * @author mikael emtinger / http://gomo.se/
  13505. * @author alteredq / http://alteredqualia.com/
  13506. * @author mrdoob / http://mrdoob.com/
  13507. */
  13508. function LOD() {
  13509. Object3D.call( this );
  13510. this.type = 'LOD';
  13511. Object.defineProperties( this, {
  13512. levels: {
  13513. enumerable: true,
  13514. value: []
  13515. }
  13516. } );
  13517. }
  13518. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13519. constructor: LOD,
  13520. copy: function ( source ) {
  13521. Object3D.prototype.copy.call( this, source, false );
  13522. var levels = source.levels;
  13523. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13524. var level = levels[ i ];
  13525. this.addLevel( level.object.clone(), level.distance );
  13526. }
  13527. return this;
  13528. },
  13529. addLevel: function ( object, distance ) {
  13530. if ( distance === undefined ) distance = 0;
  13531. distance = Math.abs( distance );
  13532. var levels = this.levels;
  13533. for ( var l = 0; l < levels.length; l ++ ) {
  13534. if ( distance < levels[ l ].distance ) {
  13535. break;
  13536. }
  13537. }
  13538. levels.splice( l, 0, { distance: distance, object: object } );
  13539. this.add( object );
  13540. },
  13541. getObjectForDistance: function ( distance ) {
  13542. var levels = this.levels;
  13543. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13544. if ( distance < levels[ i ].distance ) {
  13545. break;
  13546. }
  13547. }
  13548. return levels[ i - 1 ].object;
  13549. },
  13550. raycast: ( function () {
  13551. var matrixPosition = new Vector3();
  13552. return function raycast( raycaster, intersects ) {
  13553. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13554. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13555. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13556. };
  13557. }() ),
  13558. update: function () {
  13559. var v1 = new Vector3();
  13560. var v2 = new Vector3();
  13561. return function update( camera ) {
  13562. var levels = this.levels;
  13563. if ( levels.length > 1 ) {
  13564. v1.setFromMatrixPosition( camera.matrixWorld );
  13565. v2.setFromMatrixPosition( this.matrixWorld );
  13566. var distance = v1.distanceTo( v2 );
  13567. levels[ 0 ].object.visible = true;
  13568. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13569. if ( distance >= levels[ i ].distance ) {
  13570. levels[ i - 1 ].object.visible = false;
  13571. levels[ i ].object.visible = true;
  13572. } else {
  13573. break;
  13574. }
  13575. }
  13576. for ( ; i < l; i ++ ) {
  13577. levels[ i ].object.visible = false;
  13578. }
  13579. }
  13580. };
  13581. }(),
  13582. toJSON: function ( meta ) {
  13583. var data = Object3D.prototype.toJSON.call( this, meta );
  13584. data.object.levels = [];
  13585. var levels = this.levels;
  13586. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13587. var level = levels[ i ];
  13588. data.object.levels.push( {
  13589. object: level.object.uuid,
  13590. distance: level.distance
  13591. } );
  13592. }
  13593. return data;
  13594. }
  13595. } );
  13596. /**
  13597. * @author mikael emtinger / http://gomo.se/
  13598. * @author alteredq / http://alteredqualia.com/
  13599. * @author michael guerrero / http://realitymeltdown.com
  13600. * @author ikerr / http://verold.com
  13601. */
  13602. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13603. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13604. this.identityMatrix = new Matrix4();
  13605. // copy the bone array
  13606. bones = bones || [];
  13607. this.bones = bones.slice( 0 );
  13608. // create a bone texture or an array of floats
  13609. if ( this.useVertexTexture ) {
  13610. // layout (1 matrix = 4 pixels)
  13611. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13612. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13613. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13614. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13615. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13616. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13617. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  13618. size = Math.max( size, 4 );
  13619. this.boneTextureWidth = size;
  13620. this.boneTextureHeight = size;
  13621. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13622. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13623. } else {
  13624. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13625. }
  13626. // use the supplied bone inverses or calculate the inverses
  13627. if ( boneInverses === undefined ) {
  13628. this.calculateInverses();
  13629. } else {
  13630. if ( this.bones.length === boneInverses.length ) {
  13631. this.boneInverses = boneInverses.slice( 0 );
  13632. } else {
  13633. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13634. this.boneInverses = [];
  13635. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13636. this.boneInverses.push( new Matrix4() );
  13637. }
  13638. }
  13639. }
  13640. }
  13641. Object.assign( Skeleton.prototype, {
  13642. calculateInverses: function () {
  13643. this.boneInverses = [];
  13644. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13645. var inverse = new Matrix4();
  13646. if ( this.bones[ b ] ) {
  13647. inverse.getInverse( this.bones[ b ].matrixWorld );
  13648. }
  13649. this.boneInverses.push( inverse );
  13650. }
  13651. },
  13652. pose: function () {
  13653. var bone;
  13654. // recover the bind-time world matrices
  13655. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13656. bone = this.bones[ b ];
  13657. if ( bone ) {
  13658. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13659. }
  13660. }
  13661. // compute the local matrices, positions, rotations and scales
  13662. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13663. bone = this.bones[ b ];
  13664. if ( bone ) {
  13665. if ( bone.parent && bone.parent.isBone ) {
  13666. bone.matrix.getInverse( bone.parent.matrixWorld );
  13667. bone.matrix.multiply( bone.matrixWorld );
  13668. } else {
  13669. bone.matrix.copy( bone.matrixWorld );
  13670. }
  13671. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13672. }
  13673. }
  13674. },
  13675. update: ( function () {
  13676. var offsetMatrix = new Matrix4();
  13677. return function update() {
  13678. // flatten bone matrices to array
  13679. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13680. // compute the offset between the current and the original transform
  13681. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13682. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13683. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13684. }
  13685. if ( this.useVertexTexture ) {
  13686. this.boneTexture.needsUpdate = true;
  13687. }
  13688. };
  13689. } )(),
  13690. clone: function () {
  13691. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13692. }
  13693. } );
  13694. /**
  13695. * @author mikael emtinger / http://gomo.se/
  13696. * @author alteredq / http://alteredqualia.com/
  13697. * @author ikerr / http://verold.com
  13698. */
  13699. function Bone() {
  13700. Object3D.call( this );
  13701. this.type = 'Bone';
  13702. }
  13703. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13704. constructor: Bone,
  13705. isBone: true
  13706. } );
  13707. /**
  13708. * @author mikael emtinger / http://gomo.se/
  13709. * @author alteredq / http://alteredqualia.com/
  13710. * @author ikerr / http://verold.com
  13711. */
  13712. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13713. Mesh.call( this, geometry, material );
  13714. this.type = 'SkinnedMesh';
  13715. this.bindMode = "attached";
  13716. this.bindMatrix = new Matrix4();
  13717. this.bindMatrixInverse = new Matrix4();
  13718. // init bones
  13719. // TODO: remove bone creation as there is no reason (other than
  13720. // convenience) for THREE.SkinnedMesh to do this.
  13721. var bones = [];
  13722. if ( this.geometry && this.geometry.bones !== undefined ) {
  13723. var bone, gbone;
  13724. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13725. gbone = this.geometry.bones[ b ];
  13726. bone = new Bone();
  13727. bones.push( bone );
  13728. bone.name = gbone.name;
  13729. bone.position.fromArray( gbone.pos );
  13730. bone.quaternion.fromArray( gbone.rotq );
  13731. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13732. }
  13733. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13734. gbone = this.geometry.bones[ b ];
  13735. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13736. bones[ gbone.parent ] !== undefined ) {
  13737. bones[ gbone.parent ].add( bones[ b ] );
  13738. } else {
  13739. this.add( bones[ b ] );
  13740. }
  13741. }
  13742. }
  13743. this.normalizeSkinWeights();
  13744. this.updateMatrixWorld( true );
  13745. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13746. }
  13747. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13748. constructor: SkinnedMesh,
  13749. isSkinnedMesh: true,
  13750. bind: function( skeleton, bindMatrix ) {
  13751. this.skeleton = skeleton;
  13752. if ( bindMatrix === undefined ) {
  13753. this.updateMatrixWorld( true );
  13754. this.skeleton.calculateInverses();
  13755. bindMatrix = this.matrixWorld;
  13756. }
  13757. this.bindMatrix.copy( bindMatrix );
  13758. this.bindMatrixInverse.getInverse( bindMatrix );
  13759. },
  13760. pose: function () {
  13761. this.skeleton.pose();
  13762. },
  13763. normalizeSkinWeights: function () {
  13764. if ( this.geometry && this.geometry.isGeometry ) {
  13765. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13766. var sw = this.geometry.skinWeights[ i ];
  13767. var scale = 1.0 / sw.lengthManhattan();
  13768. if ( scale !== Infinity ) {
  13769. sw.multiplyScalar( scale );
  13770. } else {
  13771. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13772. }
  13773. }
  13774. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  13775. var vec = new Vector4();
  13776. var skinWeight = this.geometry.attributes.skinWeight;
  13777. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13778. vec.x = skinWeight.getX( i );
  13779. vec.y = skinWeight.getY( i );
  13780. vec.z = skinWeight.getZ( i );
  13781. vec.w = skinWeight.getW( i );
  13782. var scale = 1.0 / vec.lengthManhattan();
  13783. if ( scale !== Infinity ) {
  13784. vec.multiplyScalar( scale );
  13785. } else {
  13786. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13787. }
  13788. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13789. }
  13790. }
  13791. },
  13792. updateMatrixWorld: function( force ) {
  13793. Mesh.prototype.updateMatrixWorld.call( this, true );
  13794. if ( this.bindMode === "attached" ) {
  13795. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13796. } else if ( this.bindMode === "detached" ) {
  13797. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13798. } else {
  13799. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13800. }
  13801. },
  13802. clone: function() {
  13803. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13804. }
  13805. } );
  13806. /**
  13807. * @author mrdoob / http://mrdoob.com/
  13808. * @author alteredq / http://alteredqualia.com/
  13809. *
  13810. * parameters = {
  13811. * color: <hex>,
  13812. * opacity: <float>,
  13813. *
  13814. * linewidth: <float>,
  13815. * linecap: "round",
  13816. * linejoin: "round"
  13817. * }
  13818. */
  13819. function LineBasicMaterial( parameters ) {
  13820. Material.call( this );
  13821. this.type = 'LineBasicMaterial';
  13822. this.color = new Color( 0xffffff );
  13823. this.linewidth = 1;
  13824. this.linecap = 'round';
  13825. this.linejoin = 'round';
  13826. this.lights = false;
  13827. this.setValues( parameters );
  13828. }
  13829. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13830. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13831. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13832. LineBasicMaterial.prototype.copy = function ( source ) {
  13833. Material.prototype.copy.call( this, source );
  13834. this.color.copy( source.color );
  13835. this.linewidth = source.linewidth;
  13836. this.linecap = source.linecap;
  13837. this.linejoin = source.linejoin;
  13838. return this;
  13839. };
  13840. /**
  13841. * @author mrdoob / http://mrdoob.com/
  13842. */
  13843. function Line( geometry, material, mode ) {
  13844. if ( mode === 1 ) {
  13845. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13846. return new LineSegments( geometry, material );
  13847. }
  13848. Object3D.call( this );
  13849. this.type = 'Line';
  13850. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13851. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13852. }
  13853. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13854. constructor: Line,
  13855. isLine: true,
  13856. raycast: ( function () {
  13857. var inverseMatrix = new Matrix4();
  13858. var ray = new Ray();
  13859. var sphere = new Sphere();
  13860. return function raycast( raycaster, intersects ) {
  13861. var precision = raycaster.linePrecision;
  13862. var precisionSq = precision * precision;
  13863. var geometry = this.geometry;
  13864. var matrixWorld = this.matrixWorld;
  13865. // Checking boundingSphere distance to ray
  13866. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13867. sphere.copy( geometry.boundingSphere );
  13868. sphere.applyMatrix4( matrixWorld );
  13869. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13870. //
  13871. inverseMatrix.getInverse( matrixWorld );
  13872. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13873. var vStart = new Vector3();
  13874. var vEnd = new Vector3();
  13875. var interSegment = new Vector3();
  13876. var interRay = new Vector3();
  13877. var step = (this && this.isLineSegments) ? 2 : 1;
  13878. if ( geometry.isBufferGeometry ) {
  13879. var index = geometry.index;
  13880. var attributes = geometry.attributes;
  13881. var positions = attributes.position.array;
  13882. if ( index !== null ) {
  13883. var indices = index.array;
  13884. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13885. var a = indices[ i ];
  13886. var b = indices[ i + 1 ];
  13887. vStart.fromArray( positions, a * 3 );
  13888. vEnd.fromArray( positions, b * 3 );
  13889. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13890. if ( distSq > precisionSq ) continue;
  13891. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13892. var distance = raycaster.ray.origin.distanceTo( interRay );
  13893. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13894. intersects.push( {
  13895. distance: distance,
  13896. // What do we want? intersection point on the ray or on the segment??
  13897. // point: raycaster.ray.at( distance ),
  13898. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13899. index: i,
  13900. face: null,
  13901. faceIndex: null,
  13902. object: this
  13903. } );
  13904. }
  13905. } else {
  13906. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13907. vStart.fromArray( positions, 3 * i );
  13908. vEnd.fromArray( positions, 3 * i + 3 );
  13909. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13910. if ( distSq > precisionSq ) continue;
  13911. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13912. var distance = raycaster.ray.origin.distanceTo( interRay );
  13913. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13914. intersects.push( {
  13915. distance: distance,
  13916. // What do we want? intersection point on the ray or on the segment??
  13917. // point: raycaster.ray.at( distance ),
  13918. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13919. index: i,
  13920. face: null,
  13921. faceIndex: null,
  13922. object: this
  13923. } );
  13924. }
  13925. }
  13926. } else if ( geometry.isGeometry ) {
  13927. var vertices = geometry.vertices;
  13928. var nbVertices = vertices.length;
  13929. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13930. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13931. if ( distSq > precisionSq ) continue;
  13932. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13933. var distance = raycaster.ray.origin.distanceTo( interRay );
  13934. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13935. intersects.push( {
  13936. distance: distance,
  13937. // What do we want? intersection point on the ray or on the segment??
  13938. // point: raycaster.ray.at( distance ),
  13939. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13940. index: i,
  13941. face: null,
  13942. faceIndex: null,
  13943. object: this
  13944. } );
  13945. }
  13946. }
  13947. };
  13948. }() ),
  13949. clone: function () {
  13950. return new this.constructor( this.geometry, this.material ).copy( this );
  13951. }
  13952. } );
  13953. /**
  13954. * @author mrdoob / http://mrdoob.com/
  13955. */
  13956. function LineSegments( geometry, material ) {
  13957. Line.call( this, geometry, material );
  13958. this.type = 'LineSegments';
  13959. }
  13960. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13961. constructor: LineSegments,
  13962. isLineSegments: true
  13963. } );
  13964. /**
  13965. * @author mrdoob / http://mrdoob.com/
  13966. * @author alteredq / http://alteredqualia.com/
  13967. *
  13968. * parameters = {
  13969. * color: <hex>,
  13970. * opacity: <float>,
  13971. * map: new THREE.Texture( <Image> ),
  13972. *
  13973. * size: <float>,
  13974. * sizeAttenuation: <bool>
  13975. * }
  13976. */
  13977. function PointsMaterial( parameters ) {
  13978. Material.call( this );
  13979. this.type = 'PointsMaterial';
  13980. this.color = new Color( 0xffffff );
  13981. this.map = null;
  13982. this.size = 1;
  13983. this.sizeAttenuation = true;
  13984. this.lights = false;
  13985. this.setValues( parameters );
  13986. }
  13987. PointsMaterial.prototype = Object.create( Material.prototype );
  13988. PointsMaterial.prototype.constructor = PointsMaterial;
  13989. PointsMaterial.prototype.isPointsMaterial = true;
  13990. PointsMaterial.prototype.copy = function ( source ) {
  13991. Material.prototype.copy.call( this, source );
  13992. this.color.copy( source.color );
  13993. this.map = source.map;
  13994. this.size = source.size;
  13995. this.sizeAttenuation = source.sizeAttenuation;
  13996. return this;
  13997. };
  13998. /**
  13999. * @author alteredq / http://alteredqualia.com/
  14000. */
  14001. function Points( geometry, material ) {
  14002. Object3D.call( this );
  14003. this.type = 'Points';
  14004. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  14005. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  14006. }
  14007. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14008. constructor: Points,
  14009. isPoints: true,
  14010. raycast: ( function () {
  14011. var inverseMatrix = new Matrix4();
  14012. var ray = new Ray();
  14013. var sphere = new Sphere();
  14014. return function raycast( raycaster, intersects ) {
  14015. var object = this;
  14016. var geometry = this.geometry;
  14017. var matrixWorld = this.matrixWorld;
  14018. var threshold = raycaster.params.Points.threshold;
  14019. // Checking boundingSphere distance to ray
  14020. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14021. sphere.copy( geometry.boundingSphere );
  14022. sphere.applyMatrix4( matrixWorld );
  14023. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14024. //
  14025. inverseMatrix.getInverse( matrixWorld );
  14026. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14027. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  14028. var localThresholdSq = localThreshold * localThreshold;
  14029. var position = new Vector3();
  14030. function testPoint( point, index ) {
  14031. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  14032. if ( rayPointDistanceSq < localThresholdSq ) {
  14033. var intersectPoint = ray.closestPointToPoint( point );
  14034. intersectPoint.applyMatrix4( matrixWorld );
  14035. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  14036. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14037. intersects.push( {
  14038. distance: distance,
  14039. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  14040. point: intersectPoint.clone(),
  14041. index: index,
  14042. face: null,
  14043. object: object
  14044. } );
  14045. }
  14046. }
  14047. if ( geometry.isBufferGeometry ) {
  14048. var index = geometry.index;
  14049. var attributes = geometry.attributes;
  14050. var positions = attributes.position.array;
  14051. if ( index !== null ) {
  14052. var indices = index.array;
  14053. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  14054. var a = indices[ i ];
  14055. position.fromArray( positions, a * 3 );
  14056. testPoint( position, a );
  14057. }
  14058. } else {
  14059. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  14060. position.fromArray( positions, i * 3 );
  14061. testPoint( position, i );
  14062. }
  14063. }
  14064. } else {
  14065. var vertices = geometry.vertices;
  14066. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  14067. testPoint( vertices[ i ], i );
  14068. }
  14069. }
  14070. };
  14071. }() ),
  14072. clone: function () {
  14073. return new this.constructor( this.geometry, this.material ).copy( this );
  14074. }
  14075. } );
  14076. /**
  14077. * @author mrdoob / http://mrdoob.com/
  14078. */
  14079. function Group() {
  14080. Object3D.call( this );
  14081. this.type = 'Group';
  14082. }
  14083. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14084. constructor: Group
  14085. } );
  14086. /**
  14087. * @author mrdoob / http://mrdoob.com/
  14088. */
  14089. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14090. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14091. this.generateMipmaps = false;
  14092. var scope = this;
  14093. function update() {
  14094. requestAnimationFrame( update );
  14095. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  14096. scope.needsUpdate = true;
  14097. }
  14098. }
  14099. update();
  14100. }
  14101. VideoTexture.prototype = Object.create( Texture.prototype );
  14102. VideoTexture.prototype.constructor = VideoTexture;
  14103. /**
  14104. * @author alteredq / http://alteredqualia.com/
  14105. */
  14106. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  14107. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14108. this.image = { width: width, height: height };
  14109. this.mipmaps = mipmaps;
  14110. // no flipping for cube textures
  14111. // (also flipping doesn't work for compressed textures )
  14112. this.flipY = false;
  14113. // can't generate mipmaps for compressed textures
  14114. // mips must be embedded in DDS files
  14115. this.generateMipmaps = false;
  14116. }
  14117. CompressedTexture.prototype = Object.create( Texture.prototype );
  14118. CompressedTexture.prototype.constructor = CompressedTexture;
  14119. CompressedTexture.prototype.isCompressedTexture = true;
  14120. /**
  14121. * @author mrdoob / http://mrdoob.com/
  14122. */
  14123. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  14124. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14125. this.needsUpdate = true;
  14126. }
  14127. CanvasTexture.prototype = Object.create( Texture.prototype );
  14128. CanvasTexture.prototype.constructor = CanvasTexture;
  14129. /**
  14130. * @author Matt DesLauriers / @mattdesl
  14131. * @author atix / arthursilber.de
  14132. */
  14133. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14134. format = format !== undefined ? format : DepthFormat;
  14135. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14136. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  14137. }
  14138. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  14139. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14140. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14141. this.image = { width: width, height: height };
  14142. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14143. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14144. this.flipY = false;
  14145. this.generateMipmaps = false;
  14146. }
  14147. DepthTexture.prototype = Object.create( Texture.prototype );
  14148. DepthTexture.prototype.constructor = DepthTexture;
  14149. DepthTexture.prototype.isDepthTexture = true;
  14150. /**
  14151. * @author mrdoob / http://mrdoob.com/
  14152. */
  14153. function WireframeGeometry( geometry ) {
  14154. BufferGeometry.call( this );
  14155. var edge = [ 0, 0 ], hash = {};
  14156. function sortFunction( a, b ) {
  14157. return a - b;
  14158. }
  14159. var keys = [ 'a', 'b', 'c' ];
  14160. if ( geometry && geometry.isGeometry ) {
  14161. var vertices = geometry.vertices;
  14162. var faces = geometry.faces;
  14163. var numEdges = 0;
  14164. // allocate maximal size
  14165. var edges = new Uint32Array( 6 * faces.length );
  14166. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  14167. var face = faces[ i ];
  14168. for ( var j = 0; j < 3; j ++ ) {
  14169. edge[ 0 ] = face[ keys[ j ] ];
  14170. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  14171. edge.sort( sortFunction );
  14172. var key = edge.toString();
  14173. if ( hash[ key ] === undefined ) {
  14174. edges[ 2 * numEdges ] = edge[ 0 ];
  14175. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14176. hash[ key ] = true;
  14177. numEdges ++;
  14178. }
  14179. }
  14180. }
  14181. var coords = new Float32Array( numEdges * 2 * 3 );
  14182. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14183. for ( var j = 0; j < 2; j ++ ) {
  14184. var vertex = vertices[ edges [ 2 * i + j ] ];
  14185. var index = 6 * i + 3 * j;
  14186. coords[ index + 0 ] = vertex.x;
  14187. coords[ index + 1 ] = vertex.y;
  14188. coords[ index + 2 ] = vertex.z;
  14189. }
  14190. }
  14191. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14192. } else if ( geometry && geometry.isBufferGeometry ) {
  14193. if ( geometry.index !== null ) {
  14194. // Indexed BufferGeometry
  14195. var indices = geometry.index.array;
  14196. var vertices = geometry.attributes.position;
  14197. var groups = geometry.groups;
  14198. var numEdges = 0;
  14199. if ( groups.length === 0 ) {
  14200. geometry.addGroup( 0, indices.length );
  14201. }
  14202. // allocate maximal size
  14203. var edges = new Uint32Array( 2 * indices.length );
  14204. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  14205. var group = groups[ o ];
  14206. var start = group.start;
  14207. var count = group.count;
  14208. for ( var i = start, il = start + count; i < il; i += 3 ) {
  14209. for ( var j = 0; j < 3; j ++ ) {
  14210. edge[ 0 ] = indices[ i + j ];
  14211. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  14212. edge.sort( sortFunction );
  14213. var key = edge.toString();
  14214. if ( hash[ key ] === undefined ) {
  14215. edges[ 2 * numEdges ] = edge[ 0 ];
  14216. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  14217. hash[ key ] = true;
  14218. numEdges ++;
  14219. }
  14220. }
  14221. }
  14222. }
  14223. var coords = new Float32Array( numEdges * 2 * 3 );
  14224. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  14225. for ( var j = 0; j < 2; j ++ ) {
  14226. var index = 6 * i + 3 * j;
  14227. var index2 = edges[ 2 * i + j ];
  14228. coords[ index + 0 ] = vertices.getX( index2 );
  14229. coords[ index + 1 ] = vertices.getY( index2 );
  14230. coords[ index + 2 ] = vertices.getZ( index2 );
  14231. }
  14232. }
  14233. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14234. } else {
  14235. // non-indexed BufferGeometry
  14236. var vertices = geometry.attributes.position.array;
  14237. var numEdges = vertices.length / 3;
  14238. var numTris = numEdges / 3;
  14239. var coords = new Float32Array( numEdges * 2 * 3 );
  14240. for ( var i = 0, l = numTris; i < l; i ++ ) {
  14241. for ( var j = 0; j < 3; j ++ ) {
  14242. var index = 18 * i + 6 * j;
  14243. var index1 = 9 * i + 3 * j;
  14244. coords[ index + 0 ] = vertices[ index1 ];
  14245. coords[ index + 1 ] = vertices[ index1 + 1 ];
  14246. coords[ index + 2 ] = vertices[ index1 + 2 ];
  14247. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  14248. coords[ index + 3 ] = vertices[ index2 ];
  14249. coords[ index + 4 ] = vertices[ index2 + 1 ];
  14250. coords[ index + 5 ] = vertices[ index2 + 2 ];
  14251. }
  14252. }
  14253. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  14254. }
  14255. }
  14256. }
  14257. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  14258. WireframeGeometry.prototype.constructor = WireframeGeometry;
  14259. /**
  14260. * @author Mugen87 / https://github.com/Mugen87
  14261. *
  14262. * Parametric Surfaces Geometry
  14263. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14264. */
  14265. function ParametricBufferGeometry( func, slices, stacks ) {
  14266. BufferGeometry.call( this );
  14267. this.type = 'ParametricBufferGeometry';
  14268. this.parameters = {
  14269. func: func,
  14270. slices: slices,
  14271. stacks: stacks
  14272. };
  14273. // generate vertices and uvs
  14274. var vertices = [];
  14275. var uvs = [];
  14276. var i, j, p;
  14277. var u, v;
  14278. var sliceCount = slices + 1;
  14279. for ( i = 0; i <= stacks; i ++ ) {
  14280. v = i / stacks;
  14281. for ( j = 0; j <= slices; j ++ ) {
  14282. u = j / slices;
  14283. p = func( u, v );
  14284. vertices.push( p.x, p.y, p.z );
  14285. uvs.push( u, v );
  14286. }
  14287. }
  14288. // generate indices
  14289. var indices = [];
  14290. var a, b, c, d;
  14291. for ( i = 0; i < stacks; i ++ ) {
  14292. for ( j = 0; j < slices; j ++ ) {
  14293. a = i * sliceCount + j;
  14294. b = i * sliceCount + j + 1;
  14295. c = ( i + 1 ) * sliceCount + j + 1;
  14296. d = ( i + 1 ) * sliceCount + j;
  14297. // faces one and two
  14298. indices.push( a, b, d );
  14299. indices.push( b, c, d );
  14300. }
  14301. }
  14302. // build geometry
  14303. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14304. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14305. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14306. // generate normals
  14307. this.computeVertexNormals();
  14308. }
  14309. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14310. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  14311. /**
  14312. * @author zz85 / https://github.com/zz85
  14313. *
  14314. * Parametric Surfaces Geometry
  14315. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  14316. */
  14317. function ParametricGeometry( func, slices, stacks ) {
  14318. Geometry.call( this );
  14319. this.type = 'ParametricGeometry';
  14320. this.parameters = {
  14321. func: func,
  14322. slices: slices,
  14323. stacks: stacks
  14324. };
  14325. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  14326. this.mergeVertices();
  14327. }
  14328. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  14329. ParametricGeometry.prototype.constructor = ParametricGeometry;
  14330. /**
  14331. * @author Mugen87 / https://github.com/Mugen87
  14332. */
  14333. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  14334. BufferGeometry.call( this );
  14335. this.type = 'PolyhedronBufferGeometry';
  14336. this.parameters = {
  14337. vertices: vertices,
  14338. indices: indices,
  14339. radius: radius,
  14340. detail: detail
  14341. };
  14342. radius = radius || 1;
  14343. detail = detail || 0;
  14344. // default buffer data
  14345. var vertexBuffer = [];
  14346. var uvBuffer = [];
  14347. // the subdivision creates the vertex buffer data
  14348. subdivide( detail );
  14349. // all vertices should lie on a conceptual sphere with a given radius
  14350. appplyRadius( radius );
  14351. // finally, create the uv data
  14352. generateUVs();
  14353. // build non-indexed geometry
  14354. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  14355. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  14356. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  14357. this.normalizeNormals();
  14358. this.boundingSphere = new Sphere( new Vector3(), radius );
  14359. // helper functions
  14360. function subdivide( detail ) {
  14361. var a = new Vector3();
  14362. var b = new Vector3();
  14363. var c = new Vector3();
  14364. // iterate over all faces and apply a subdivison with the given detail value
  14365. for ( var i = 0; i < indices.length; i += 3 ) {
  14366. // get the vertices of the face
  14367. getVertexByIndex( indices[ i + 0 ], a );
  14368. getVertexByIndex( indices[ i + 1 ], b );
  14369. getVertexByIndex( indices[ i + 2 ], c );
  14370. // perform subdivision
  14371. subdivideFace( a, b, c, detail );
  14372. }
  14373. }
  14374. function subdivideFace( a, b, c, detail ) {
  14375. var cols = Math.pow( 2, detail );
  14376. // we use this multidimensional array as a data structure for creating the subdivision
  14377. var v = [];
  14378. var i, j;
  14379. // construct all of the vertices for this subdivision
  14380. for ( i = 0 ; i <= cols; i ++ ) {
  14381. v[ i ] = [];
  14382. var aj = a.clone().lerp( c, i / cols );
  14383. var bj = b.clone().lerp( c, i / cols );
  14384. var rows = cols - i;
  14385. for ( j = 0; j <= rows; j ++ ) {
  14386. if ( j === 0 && i === cols ) {
  14387. v[ i ][ j ] = aj;
  14388. } else {
  14389. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  14390. }
  14391. }
  14392. }
  14393. // construct all of the faces
  14394. for ( i = 0; i < cols ; i ++ ) {
  14395. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  14396. var k = Math.floor( j / 2 );
  14397. if ( j % 2 === 0 ) {
  14398. pushVertex( v[ i ][ k + 1 ] );
  14399. pushVertex( v[ i + 1 ][ k ] );
  14400. pushVertex( v[ i ][ k ] );
  14401. } else {
  14402. pushVertex( v[ i ][ k + 1 ] );
  14403. pushVertex( v[ i + 1 ][ k + 1 ] );
  14404. pushVertex( v[ i + 1 ][ k ] );
  14405. }
  14406. }
  14407. }
  14408. }
  14409. function appplyRadius( radius ) {
  14410. var vertex = new Vector3();
  14411. // iterate over the entire buffer and apply the radius to each vertex
  14412. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14413. vertex.x = vertexBuffer[ i + 0 ];
  14414. vertex.y = vertexBuffer[ i + 1 ];
  14415. vertex.z = vertexBuffer[ i + 2 ];
  14416. vertex.normalize().multiplyScalar( radius );
  14417. vertexBuffer[ i + 0 ] = vertex.x;
  14418. vertexBuffer[ i + 1 ] = vertex.y;
  14419. vertexBuffer[ i + 2 ] = vertex.z;
  14420. }
  14421. }
  14422. function generateUVs() {
  14423. var vertex = new Vector3();
  14424. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  14425. vertex.x = vertexBuffer[ i + 0 ];
  14426. vertex.y = vertexBuffer[ i + 1 ];
  14427. vertex.z = vertexBuffer[ i + 2 ];
  14428. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  14429. var v = inclination( vertex ) / Math.PI + 0.5;
  14430. uvBuffer.push( u, 1 - v );
  14431. }
  14432. correctUVs();
  14433. correctSeam();
  14434. }
  14435. function correctSeam() {
  14436. // handle case when face straddles the seam, see #3269
  14437. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  14438. // uv data of a single face
  14439. var x0 = uvBuffer[ i + 0 ];
  14440. var x1 = uvBuffer[ i + 2 ];
  14441. var x2 = uvBuffer[ i + 4 ];
  14442. var max = Math.max( x0, x1, x2 );
  14443. var min = Math.min( x0, x1, x2 );
  14444. // 0.9 is somewhat arbitrary
  14445. if ( max > 0.9 && min < 0.1 ) {
  14446. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  14447. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  14448. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  14449. }
  14450. }
  14451. }
  14452. function pushVertex( vertex ) {
  14453. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  14454. }
  14455. function getVertexByIndex( index, vertex ) {
  14456. var stride = index * 3;
  14457. vertex.x = vertices[ stride + 0 ];
  14458. vertex.y = vertices[ stride + 1 ];
  14459. vertex.z = vertices[ stride + 2 ];
  14460. }
  14461. function correctUVs() {
  14462. var a = new Vector3();
  14463. var b = new Vector3();
  14464. var c = new Vector3();
  14465. var centroid = new Vector3();
  14466. var uvA = new Vector2();
  14467. var uvB = new Vector2();
  14468. var uvC = new Vector2();
  14469. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  14470. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  14471. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  14472. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  14473. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  14474. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  14475. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  14476. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  14477. var azi = azimuth( centroid );
  14478. correctUV( uvA, j + 0, a, azi );
  14479. correctUV( uvB, j + 2, b, azi );
  14480. correctUV( uvC, j + 4, c, azi );
  14481. }
  14482. }
  14483. function correctUV( uv, stride, vector, azimuth ) {
  14484. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  14485. uvBuffer[ stride ] = uv.x - 1;
  14486. }
  14487. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  14488. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  14489. }
  14490. }
  14491. // Angle around the Y axis, counter-clockwise when looking from above.
  14492. function azimuth( vector ) {
  14493. return Math.atan2( vector.z, - vector.x );
  14494. }
  14495. // Angle above the XZ plane.
  14496. function inclination( vector ) {
  14497. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  14498. }
  14499. }
  14500. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14501. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  14502. /**
  14503. * @author Mugen87 / https://github.com/Mugen87
  14504. */
  14505. function TetrahedronBufferGeometry( radius, detail ) {
  14506. var vertices = [
  14507. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  14508. ];
  14509. var indices = [
  14510. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  14511. ];
  14512. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14513. this.type = 'TetrahedronBufferGeometry';
  14514. this.parameters = {
  14515. radius: radius,
  14516. detail: detail
  14517. };
  14518. }
  14519. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14520. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  14521. /**
  14522. * @author timothypratley / https://github.com/timothypratley
  14523. */
  14524. function TetrahedronGeometry( radius, detail ) {
  14525. Geometry.call( this );
  14526. this.type = 'TetrahedronGeometry';
  14527. this.parameters = {
  14528. radius: radius,
  14529. detail: detail
  14530. };
  14531. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  14532. this.mergeVertices();
  14533. }
  14534. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  14535. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  14536. /**
  14537. * @author Mugen87 / https://github.com/Mugen87
  14538. */
  14539. function OctahedronBufferGeometry( radius,detail ) {
  14540. var vertices = [
  14541. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  14542. ];
  14543. var indices = [
  14544. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  14545. ];
  14546. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14547. this.type = 'OctahedronBufferGeometry';
  14548. this.parameters = {
  14549. radius: radius,
  14550. detail: detail
  14551. };
  14552. }
  14553. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14554. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  14555. /**
  14556. * @author timothypratley / https://github.com/timothypratley
  14557. */
  14558. function OctahedronGeometry( radius, detail ) {
  14559. Geometry.call( this );
  14560. this.type = 'OctahedronGeometry';
  14561. this.parameters = {
  14562. radius: radius,
  14563. detail: detail
  14564. };
  14565. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  14566. this.mergeVertices();
  14567. }
  14568. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  14569. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  14570. /**
  14571. * @author Mugen87 / https://github.com/Mugen87
  14572. */
  14573. function IcosahedronBufferGeometry( radius, detail ) {
  14574. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14575. var vertices = [
  14576. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  14577. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  14578. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  14579. ];
  14580. var indices = [
  14581. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  14582. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  14583. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  14584. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  14585. ];
  14586. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14587. this.type = 'IcosahedronBufferGeometry';
  14588. this.parameters = {
  14589. radius: radius,
  14590. detail: detail
  14591. };
  14592. }
  14593. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14594. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  14595. /**
  14596. * @author timothypratley / https://github.com/timothypratley
  14597. */
  14598. function IcosahedronGeometry( radius, detail ) {
  14599. Geometry.call( this );
  14600. this.type = 'IcosahedronGeometry';
  14601. this.parameters = {
  14602. radius: radius,
  14603. detail: detail
  14604. };
  14605. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  14606. this.mergeVertices();
  14607. }
  14608. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  14609. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  14610. /**
  14611. * @author Mugen87 / https://github.com/Mugen87
  14612. */
  14613. function DodecahedronBufferGeometry( radius, detail ) {
  14614. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  14615. var r = 1 / t;
  14616. var vertices = [
  14617. // (±1, ±1, ±1)
  14618. - 1, - 1, - 1, - 1, - 1, 1,
  14619. - 1, 1, - 1, - 1, 1, 1,
  14620. 1, - 1, - 1, 1, - 1, 1,
  14621. 1, 1, - 1, 1, 1, 1,
  14622. // (0, ±1/φ, ±φ)
  14623. 0, - r, - t, 0, - r, t,
  14624. 0, r, - t, 0, r, t,
  14625. // (±1/φ, ±φ, 0)
  14626. - r, - t, 0, - r, t, 0,
  14627. r, - t, 0, r, t, 0,
  14628. // (±φ, 0, ±1/φ)
  14629. - t, 0, - r, t, 0, - r,
  14630. - t, 0, r, t, 0, r
  14631. ];
  14632. var indices = [
  14633. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  14634. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  14635. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  14636. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  14637. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  14638. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  14639. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  14640. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  14641. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  14642. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  14643. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  14644. 1, 12, 14, 1, 14, 5, 1, 5, 9
  14645. ];
  14646. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  14647. this.type = 'DodecahedronBufferGeometry';
  14648. this.parameters = {
  14649. radius: radius,
  14650. detail: detail
  14651. };
  14652. }
  14653. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  14654. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  14655. /**
  14656. * @author Abe Pazos / https://hamoid.com
  14657. */
  14658. function DodecahedronGeometry( radius, detail ) {
  14659. Geometry.call( this );
  14660. this.type = 'DodecahedronGeometry';
  14661. this.parameters = {
  14662. radius: radius,
  14663. detail: detail
  14664. };
  14665. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  14666. this.mergeVertices();
  14667. }
  14668. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  14669. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  14670. /**
  14671. * @author clockworkgeek / https://github.com/clockworkgeek
  14672. * @author timothypratley / https://github.com/timothypratley
  14673. * @author WestLangley / http://github.com/WestLangley
  14674. */
  14675. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  14676. Geometry.call( this );
  14677. this.type = 'PolyhedronGeometry';
  14678. this.parameters = {
  14679. vertices: vertices,
  14680. indices: indices,
  14681. radius: radius,
  14682. detail: detail
  14683. };
  14684. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  14685. this.mergeVertices();
  14686. }
  14687. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  14688. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  14689. /**
  14690. * @author Mugen87 / https://github.com/Mugen87
  14691. *
  14692. * Creates a tube which extrudes along a 3d spline.
  14693. *
  14694. */
  14695. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  14696. BufferGeometry.call( this );
  14697. this.type = 'TubeBufferGeometry';
  14698. this.parameters = {
  14699. path: path,
  14700. tubularSegments: tubularSegments,
  14701. radius: radius,
  14702. radialSegments: radialSegments,
  14703. closed: closed
  14704. };
  14705. tubularSegments = tubularSegments || 64;
  14706. radius = radius || 1;
  14707. radialSegments = radialSegments || 8;
  14708. closed = closed || false;
  14709. var frames = path.computeFrenetFrames( tubularSegments, closed );
  14710. // expose internals
  14711. this.tangents = frames.tangents;
  14712. this.normals = frames.normals;
  14713. this.binormals = frames.binormals;
  14714. // helper variables
  14715. var vertex = new Vector3();
  14716. var normal = new Vector3();
  14717. var uv = new Vector2();
  14718. var i, j;
  14719. // buffer
  14720. var vertices = [];
  14721. var normals = [];
  14722. var uvs = [];
  14723. var indices = [];
  14724. // create buffer data
  14725. generateBufferData();
  14726. // build geometry
  14727. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  14728. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14729. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14730. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14731. // functions
  14732. function generateBufferData() {
  14733. for ( i = 0; i < tubularSegments; i ++ ) {
  14734. generateSegment( i );
  14735. }
  14736. // if the geometry is not closed, generate the last row of vertices and normals
  14737. // at the regular position on the given path
  14738. //
  14739. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  14740. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  14741. // uvs are generated in a separate function.
  14742. // this makes it easy compute correct values for closed geometries
  14743. generateUVs();
  14744. // finally create faces
  14745. generateIndices();
  14746. }
  14747. function generateSegment( i ) {
  14748. // we use getPointAt to sample evenly distributed points from the given path
  14749. var P = path.getPointAt( i / tubularSegments );
  14750. // retrieve corresponding normal and binormal
  14751. var N = frames.normals[ i ];
  14752. var B = frames.binormals[ i ];
  14753. // generate normals and vertices for the current segment
  14754. for ( j = 0; j <= radialSegments; j ++ ) {
  14755. var v = j / radialSegments * Math.PI * 2;
  14756. var sin = Math.sin( v );
  14757. var cos = - Math.cos( v );
  14758. // normal
  14759. normal.x = ( cos * N.x + sin * B.x );
  14760. normal.y = ( cos * N.y + sin * B.y );
  14761. normal.z = ( cos * N.z + sin * B.z );
  14762. normal.normalize();
  14763. normals.push( normal.x, normal.y, normal.z );
  14764. // vertex
  14765. vertex.x = P.x + radius * normal.x;
  14766. vertex.y = P.y + radius * normal.y;
  14767. vertex.z = P.z + radius * normal.z;
  14768. vertices.push( vertex.x, vertex.y, vertex.z );
  14769. }
  14770. }
  14771. function generateIndices() {
  14772. for ( j = 1; j <= tubularSegments; j ++ ) {
  14773. for ( i = 1; i <= radialSegments; i ++ ) {
  14774. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14775. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14776. var c = ( radialSegments + 1 ) * j + i;
  14777. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14778. // faces
  14779. indices.push( a, b, d );
  14780. indices.push( b, c, d );
  14781. }
  14782. }
  14783. }
  14784. function generateUVs() {
  14785. for ( i = 0; i <= tubularSegments; i ++ ) {
  14786. for ( j = 0; j <= radialSegments; j ++ ) {
  14787. uv.x = i / tubularSegments;
  14788. uv.y = j / radialSegments;
  14789. uvs.push( uv.x, uv.y );
  14790. }
  14791. }
  14792. }
  14793. }
  14794. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14795. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  14796. /**
  14797. * @author oosmoxiecode / https://github.com/oosmoxiecode
  14798. * @author WestLangley / https://github.com/WestLangley
  14799. * @author zz85 / https://github.com/zz85
  14800. * @author miningold / https://github.com/miningold
  14801. * @author jonobr1 / https://github.com/jonobr1
  14802. *
  14803. * Creates a tube which extrudes along a 3d spline.
  14804. */
  14805. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  14806. Geometry.call( this );
  14807. this.type = 'TubeGeometry';
  14808. this.parameters = {
  14809. path: path,
  14810. tubularSegments: tubularSegments,
  14811. radius: radius,
  14812. radialSegments: radialSegments,
  14813. closed: closed
  14814. };
  14815. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  14816. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  14817. // expose internals
  14818. this.tangents = bufferGeometry.tangents;
  14819. this.normals = bufferGeometry.normals;
  14820. this.binormals = bufferGeometry.binormals;
  14821. // create geometry
  14822. this.fromBufferGeometry( bufferGeometry );
  14823. this.mergeVertices();
  14824. }
  14825. TubeGeometry.prototype = Object.create( Geometry.prototype );
  14826. TubeGeometry.prototype.constructor = TubeGeometry;
  14827. /**
  14828. * @author Mugen87 / https://github.com/Mugen87
  14829. *
  14830. * see: http://www.blackpawn.com/texts/pqtorus/
  14831. */
  14832. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  14833. BufferGeometry.call( this );
  14834. this.type = 'TorusKnotBufferGeometry';
  14835. this.parameters = {
  14836. radius: radius,
  14837. tube: tube,
  14838. tubularSegments: tubularSegments,
  14839. radialSegments: radialSegments,
  14840. p: p,
  14841. q: q
  14842. };
  14843. radius = radius || 100;
  14844. tube = tube || 40;
  14845. tubularSegments = Math.floor( tubularSegments ) || 64;
  14846. radialSegments = Math.floor( radialSegments ) || 8;
  14847. p = p || 2;
  14848. q = q || 3;
  14849. // used to calculate buffer length
  14850. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14851. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14852. // buffers
  14853. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  14854. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14855. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  14856. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  14857. // helper variables
  14858. var i, j, index = 0, indexOffset = 0;
  14859. var vertex = new Vector3();
  14860. var normal = new Vector3();
  14861. var uv = new Vector2();
  14862. var P1 = new Vector3();
  14863. var P2 = new Vector3();
  14864. var B = new Vector3();
  14865. var T = new Vector3();
  14866. var N = new Vector3();
  14867. // generate vertices, normals and uvs
  14868. for ( i = 0; i <= tubularSegments; ++ i ) {
  14869. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  14870. var u = i / tubularSegments * p * Math.PI * 2;
  14871. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  14872. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  14873. calculatePositionOnCurve( u, p, q, radius, P1 );
  14874. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  14875. // calculate orthonormal basis
  14876. T.subVectors( P2, P1 );
  14877. N.addVectors( P2, P1 );
  14878. B.crossVectors( T, N );
  14879. N.crossVectors( B, T );
  14880. // normalize B, N. T can be ignored, we don't use it
  14881. B.normalize();
  14882. N.normalize();
  14883. for ( j = 0; j <= radialSegments; ++ j ) {
  14884. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  14885. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  14886. var v = j / radialSegments * Math.PI * 2;
  14887. var cx = - tube * Math.cos( v );
  14888. var cy = tube * Math.sin( v );
  14889. // now calculate the final vertex position.
  14890. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  14891. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  14892. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  14893. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  14894. // vertex
  14895. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  14896. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  14897. normal.subVectors( vertex, P1 ).normalize();
  14898. normals.setXYZ( index, normal.x, normal.y, normal.z );
  14899. // uv
  14900. uv.x = i / tubularSegments;
  14901. uv.y = j / radialSegments;
  14902. uvs.setXY( index, uv.x, uv.y );
  14903. // increase index
  14904. index ++;
  14905. }
  14906. }
  14907. // generate indices
  14908. for ( j = 1; j <= tubularSegments; j ++ ) {
  14909. for ( i = 1; i <= radialSegments; i ++ ) {
  14910. // indices
  14911. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  14912. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  14913. var c = ( radialSegments + 1 ) * j + i;
  14914. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  14915. // face one
  14916. indices.setX( indexOffset, a ); indexOffset++;
  14917. indices.setX( indexOffset, b ); indexOffset++;
  14918. indices.setX( indexOffset, d ); indexOffset++;
  14919. // face two
  14920. indices.setX( indexOffset, b ); indexOffset++;
  14921. indices.setX( indexOffset, c ); indexOffset++;
  14922. indices.setX( indexOffset, d ); indexOffset++;
  14923. }
  14924. }
  14925. // build geometry
  14926. this.setIndex( indices );
  14927. this.addAttribute( 'position', vertices );
  14928. this.addAttribute( 'normal', normals );
  14929. this.addAttribute( 'uv', uvs );
  14930. // this function calculates the current position on the torus curve
  14931. function calculatePositionOnCurve( u, p, q, radius, position ) {
  14932. var cu = Math.cos( u );
  14933. var su = Math.sin( u );
  14934. var quOverP = q / p * u;
  14935. var cs = Math.cos( quOverP );
  14936. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  14937. position.y = radius * ( 2 + cs ) * su * 0.5;
  14938. position.z = radius * Math.sin( quOverP ) * 0.5;
  14939. }
  14940. }
  14941. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14942. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  14943. /**
  14944. * @author oosmoxiecode
  14945. */
  14946. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  14947. Geometry.call( this );
  14948. this.type = 'TorusKnotGeometry';
  14949. this.parameters = {
  14950. radius: radius,
  14951. tube: tube,
  14952. tubularSegments: tubularSegments,
  14953. radialSegments: radialSegments,
  14954. p: p,
  14955. q: q
  14956. };
  14957. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  14958. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  14959. this.mergeVertices();
  14960. }
  14961. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  14962. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  14963. /**
  14964. * @author Mugen87 / https://github.com/Mugen87
  14965. */
  14966. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  14967. BufferGeometry.call( this );
  14968. this.type = 'TorusBufferGeometry';
  14969. this.parameters = {
  14970. radius: radius,
  14971. tube: tube,
  14972. radialSegments: radialSegments,
  14973. tubularSegments: tubularSegments,
  14974. arc: arc
  14975. };
  14976. radius = radius || 100;
  14977. tube = tube || 40;
  14978. radialSegments = Math.floor( radialSegments ) || 8;
  14979. tubularSegments = Math.floor( tubularSegments ) || 6;
  14980. arc = arc || Math.PI * 2;
  14981. // used to calculate buffer length
  14982. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  14983. var indexCount = radialSegments * tubularSegments * 2 * 3;
  14984. // buffers
  14985. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  14986. var vertices = new Float32Array( vertexCount * 3 );
  14987. var normals = new Float32Array( vertexCount * 3 );
  14988. var uvs = new Float32Array( vertexCount * 2 );
  14989. // offset variables
  14990. var vertexBufferOffset = 0;
  14991. var uvBufferOffset = 0;
  14992. var indexBufferOffset = 0;
  14993. // helper variables
  14994. var center = new Vector3();
  14995. var vertex = new Vector3();
  14996. var normal = new Vector3();
  14997. var j, i;
  14998. // generate vertices, normals and uvs
  14999. for ( j = 0; j <= radialSegments; j ++ ) {
  15000. for ( i = 0; i <= tubularSegments; i ++ ) {
  15001. var u = i / tubularSegments * arc;
  15002. var v = j / radialSegments * Math.PI * 2;
  15003. // vertex
  15004. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15005. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15006. vertex.z = tube * Math.sin( v );
  15007. vertices[ vertexBufferOffset ] = vertex.x;
  15008. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  15009. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  15010. // this vector is used to calculate the normal
  15011. center.x = radius * Math.cos( u );
  15012. center.y = radius * Math.sin( u );
  15013. // normal
  15014. normal.subVectors( vertex, center ).normalize();
  15015. normals[ vertexBufferOffset ] = normal.x;
  15016. normals[ vertexBufferOffset + 1 ] = normal.y;
  15017. normals[ vertexBufferOffset + 2 ] = normal.z;
  15018. // uv
  15019. uvs[ uvBufferOffset ] = i / tubularSegments;
  15020. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  15021. // update offsets
  15022. vertexBufferOffset += 3;
  15023. uvBufferOffset += 2;
  15024. }
  15025. }
  15026. // generate indices
  15027. for ( j = 1; j <= radialSegments; j ++ ) {
  15028. for ( i = 1; i <= tubularSegments; i ++ ) {
  15029. // indices
  15030. var a = ( tubularSegments + 1 ) * j + i - 1;
  15031. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15032. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15033. var d = ( tubularSegments + 1 ) * j + i;
  15034. // face one
  15035. indices[ indexBufferOffset ] = a;
  15036. indices[ indexBufferOffset + 1 ] = b;
  15037. indices[ indexBufferOffset + 2 ] = d;
  15038. // face two
  15039. indices[ indexBufferOffset + 3 ] = b;
  15040. indices[ indexBufferOffset + 4 ] = c;
  15041. indices[ indexBufferOffset + 5 ] = d;
  15042. // update offset
  15043. indexBufferOffset += 6;
  15044. }
  15045. }
  15046. // build geometry
  15047. this.setIndex( new BufferAttribute( indices, 1 ) );
  15048. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  15049. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  15050. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  15051. }
  15052. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  15053. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  15054. /**
  15055. * @author oosmoxiecode
  15056. * @author mrdoob / http://mrdoob.com/
  15057. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15058. */
  15059. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  15060. Geometry.call( this );
  15061. this.type = 'TorusGeometry';
  15062. this.parameters = {
  15063. radius: radius,
  15064. tube: tube,
  15065. radialSegments: radialSegments,
  15066. tubularSegments: tubularSegments,
  15067. arc: arc
  15068. };
  15069. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  15070. }
  15071. TorusGeometry.prototype = Object.create( Geometry.prototype );
  15072. TorusGeometry.prototype.constructor = TorusGeometry;
  15073. /**
  15074. * @author zz85 / http://www.lab4games.net/zz85/blog
  15075. */
  15076. var ShapeUtils = {
  15077. // calculate area of the contour polygon
  15078. area: function ( contour ) {
  15079. var n = contour.length;
  15080. var a = 0.0;
  15081. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15082. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15083. }
  15084. return a * 0.5;
  15085. },
  15086. triangulate: ( function () {
  15087. /**
  15088. * This code is a quick port of code written in C++ which was submitted to
  15089. * flipcode.com by John W. Ratcliff // July 22, 2000
  15090. * See original code and more information here:
  15091. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15092. *
  15093. * ported to actionscript by Zevan Rosser
  15094. * www.actionsnippet.com
  15095. *
  15096. * ported to javascript by Joshua Koo
  15097. * http://www.lab4games.net/zz85/blog
  15098. *
  15099. */
  15100. function snip( contour, u, v, w, n, verts ) {
  15101. var p;
  15102. var ax, ay, bx, by;
  15103. var cx, cy, px, py;
  15104. ax = contour[ verts[ u ] ].x;
  15105. ay = contour[ verts[ u ] ].y;
  15106. bx = contour[ verts[ v ] ].x;
  15107. by = contour[ verts[ v ] ].y;
  15108. cx = contour[ verts[ w ] ].x;
  15109. cy = contour[ verts[ w ] ].y;
  15110. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  15111. var aX, aY, bX, bY, cX, cY;
  15112. var apx, apy, bpx, bpy, cpx, cpy;
  15113. var cCROSSap, bCROSScp, aCROSSbp;
  15114. aX = cx - bx; aY = cy - by;
  15115. bX = ax - cx; bY = ay - cy;
  15116. cX = bx - ax; cY = by - ay;
  15117. for ( p = 0; p < n; p ++ ) {
  15118. px = contour[ verts[ p ] ].x;
  15119. py = contour[ verts[ p ] ].y;
  15120. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15121. ( ( px === bx ) && ( py === by ) ) ||
  15122. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15123. apx = px - ax; apy = py - ay;
  15124. bpx = px - bx; bpy = py - by;
  15125. cpx = px - cx; cpy = py - cy;
  15126. // see if p is inside triangle abc
  15127. aCROSSbp = aX * bpy - aY * bpx;
  15128. cCROSSap = cX * apy - cY * apx;
  15129. bCROSScp = bX * cpy - bY * cpx;
  15130. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  15131. }
  15132. return true;
  15133. }
  15134. // takes in an contour array and returns
  15135. return function triangulate( contour, indices ) {
  15136. var n = contour.length;
  15137. if ( n < 3 ) return null;
  15138. var result = [],
  15139. verts = [],
  15140. vertIndices = [];
  15141. /* we want a counter-clockwise polygon in verts */
  15142. var u, v, w;
  15143. if ( ShapeUtils.area( contour ) > 0.0 ) {
  15144. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15145. } else {
  15146. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15147. }
  15148. var nv = n;
  15149. /* remove nv - 2 vertices, creating 1 triangle every time */
  15150. var count = 2 * nv; /* error detection */
  15151. for ( v = nv - 1; nv > 2; ) {
  15152. /* if we loop, it is probably a non-simple polygon */
  15153. if ( ( count -- ) <= 0 ) {
  15154. //** Triangulate: ERROR - probable bad polygon!
  15155. //throw ( "Warning, unable to triangulate polygon!" );
  15156. //return null;
  15157. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15158. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  15159. if ( indices ) return vertIndices;
  15160. return result;
  15161. }
  15162. /* three consecutive vertices in current polygon, <u,v,w> */
  15163. u = v; if ( nv <= u ) u = 0; /* previous */
  15164. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15165. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15166. if ( snip( contour, u, v, w, nv, verts ) ) {
  15167. var a, b, c, s, t;
  15168. /* true names of the vertices */
  15169. a = verts[ u ];
  15170. b = verts[ v ];
  15171. c = verts[ w ];
  15172. /* output Triangle */
  15173. result.push( [ contour[ a ],
  15174. contour[ b ],
  15175. contour[ c ] ] );
  15176. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15177. /* remove v from the remaining polygon */
  15178. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15179. verts[ s ] = verts[ t ];
  15180. }
  15181. nv --;
  15182. /* reset error detection counter */
  15183. count = 2 * nv;
  15184. }
  15185. }
  15186. if ( indices ) return vertIndices;
  15187. return result;
  15188. }
  15189. } )(),
  15190. triangulateShape: function ( contour, holes ) {
  15191. function removeDupEndPts(points) {
  15192. var l = points.length;
  15193. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  15194. points.pop();
  15195. }
  15196. }
  15197. removeDupEndPts( contour );
  15198. holes.forEach( removeDupEndPts );
  15199. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  15200. // inOtherPt needs to be collinear to the inSegment
  15201. if ( inSegPt1.x !== inSegPt2.x ) {
  15202. if ( inSegPt1.x < inSegPt2.x ) {
  15203. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  15204. } else {
  15205. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  15206. }
  15207. } else {
  15208. if ( inSegPt1.y < inSegPt2.y ) {
  15209. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  15210. } else {
  15211. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  15212. }
  15213. }
  15214. }
  15215. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  15216. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  15217. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  15218. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  15219. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  15220. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  15221. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  15222. if ( Math.abs( limit ) > Number.EPSILON ) {
  15223. // not parallel
  15224. var perpSeg2;
  15225. if ( limit > 0 ) {
  15226. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  15227. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15228. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  15229. } else {
  15230. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  15231. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  15232. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  15233. }
  15234. // i.e. to reduce rounding errors
  15235. // intersection at endpoint of segment#1?
  15236. if ( perpSeg2 === 0 ) {
  15237. if ( ( inExcludeAdjacentSegs ) &&
  15238. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15239. return [ inSeg1Pt1 ];
  15240. }
  15241. if ( perpSeg2 === limit ) {
  15242. if ( ( inExcludeAdjacentSegs ) &&
  15243. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  15244. return [ inSeg1Pt2 ];
  15245. }
  15246. // intersection at endpoint of segment#2?
  15247. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  15248. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  15249. // return real intersection point
  15250. var factorSeg1 = perpSeg2 / limit;
  15251. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  15252. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  15253. } else {
  15254. // parallel or collinear
  15255. if ( ( perpSeg1 !== 0 ) ||
  15256. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  15257. // they are collinear or degenerate
  15258. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  15259. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  15260. // both segments are points
  15261. if ( seg1Pt && seg2Pt ) {
  15262. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  15263. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  15264. return [ inSeg1Pt1 ]; // they are the same point
  15265. }
  15266. // segment#1 is a single point
  15267. if ( seg1Pt ) {
  15268. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  15269. return [ inSeg1Pt1 ];
  15270. }
  15271. // segment#2 is a single point
  15272. if ( seg2Pt ) {
  15273. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  15274. return [ inSeg2Pt1 ];
  15275. }
  15276. // they are collinear segments, which might overlap
  15277. var seg1min, seg1max, seg1minVal, seg1maxVal;
  15278. var seg2min, seg2max, seg2minVal, seg2maxVal;
  15279. if ( seg1dx !== 0 ) {
  15280. // the segments are NOT on a vertical line
  15281. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  15282. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  15283. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  15284. } else {
  15285. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  15286. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  15287. }
  15288. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  15289. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  15290. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  15291. } else {
  15292. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  15293. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  15294. }
  15295. } else {
  15296. // the segments are on a vertical line
  15297. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  15298. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  15299. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  15300. } else {
  15301. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  15302. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  15303. }
  15304. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  15305. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  15306. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  15307. } else {
  15308. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  15309. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  15310. }
  15311. }
  15312. if ( seg1minVal <= seg2minVal ) {
  15313. if ( seg1maxVal < seg2minVal ) return [];
  15314. if ( seg1maxVal === seg2minVal ) {
  15315. if ( inExcludeAdjacentSegs ) return [];
  15316. return [ seg2min ];
  15317. }
  15318. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  15319. return [ seg2min, seg2max ];
  15320. } else {
  15321. if ( seg1minVal > seg2maxVal ) return [];
  15322. if ( seg1minVal === seg2maxVal ) {
  15323. if ( inExcludeAdjacentSegs ) return [];
  15324. return [ seg1min ];
  15325. }
  15326. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  15327. return [ seg1min, seg2max ];
  15328. }
  15329. }
  15330. }
  15331. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  15332. // The order of legs is important
  15333. // translation of all points, so that Vertex is at (0,0)
  15334. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  15335. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  15336. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  15337. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  15338. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  15339. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  15340. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  15341. // angle != 180 deg.
  15342. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  15343. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  15344. if ( from2toAngle > 0 ) {
  15345. // main angle < 180 deg.
  15346. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  15347. } else {
  15348. // main angle > 180 deg.
  15349. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  15350. }
  15351. } else {
  15352. // angle == 180 deg.
  15353. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  15354. return ( from2otherAngle > 0 );
  15355. }
  15356. }
  15357. function removeHoles( contour, holes ) {
  15358. var shape = contour.concat(); // work on this shape
  15359. var hole;
  15360. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  15361. // Check if hole point lies within angle around shape point
  15362. var lastShapeIdx = shape.length - 1;
  15363. var prevShapeIdx = inShapeIdx - 1;
  15364. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  15365. var nextShapeIdx = inShapeIdx + 1;
  15366. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  15367. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  15368. if ( ! insideAngle ) {
  15369. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  15370. return false;
  15371. }
  15372. // Check if shape point lies within angle around hole point
  15373. var lastHoleIdx = hole.length - 1;
  15374. var prevHoleIdx = inHoleIdx - 1;
  15375. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  15376. var nextHoleIdx = inHoleIdx + 1;
  15377. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  15378. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  15379. if ( ! insideAngle ) {
  15380. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  15381. return false;
  15382. }
  15383. return true;
  15384. }
  15385. function intersectsShapeEdge( inShapePt, inHolePt ) {
  15386. // checks for intersections with shape edges
  15387. var sIdx, nextIdx, intersection;
  15388. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  15389. nextIdx = sIdx + 1; nextIdx %= shape.length;
  15390. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  15391. if ( intersection.length > 0 ) return true;
  15392. }
  15393. return false;
  15394. }
  15395. var indepHoles = [];
  15396. function intersectsHoleEdge( inShapePt, inHolePt ) {
  15397. // checks for intersections with hole edges
  15398. var ihIdx, chkHole,
  15399. hIdx, nextIdx, intersection;
  15400. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  15401. chkHole = holes[ indepHoles[ ihIdx ]];
  15402. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  15403. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  15404. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  15405. if ( intersection.length > 0 ) return true;
  15406. }
  15407. }
  15408. return false;
  15409. }
  15410. var holeIndex, shapeIndex,
  15411. shapePt, holePt,
  15412. holeIdx, cutKey, failedCuts = [],
  15413. tmpShape1, tmpShape2,
  15414. tmpHole1, tmpHole2;
  15415. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15416. indepHoles.push( h );
  15417. }
  15418. var minShapeIndex = 0;
  15419. var counter = indepHoles.length * 2;
  15420. while ( indepHoles.length > 0 ) {
  15421. counter --;
  15422. if ( counter < 0 ) {
  15423. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  15424. break;
  15425. }
  15426. // search for shape-vertex and hole-vertex,
  15427. // which can be connected without intersections
  15428. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  15429. shapePt = shape[ shapeIndex ];
  15430. holeIndex = - 1;
  15431. // search for hole which can be reached without intersections
  15432. for ( var h = 0; h < indepHoles.length; h ++ ) {
  15433. holeIdx = indepHoles[ h ];
  15434. // prevent multiple checks
  15435. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  15436. if ( failedCuts[ cutKey ] !== undefined ) continue;
  15437. hole = holes[ holeIdx ];
  15438. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  15439. holePt = hole[ h2 ];
  15440. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  15441. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  15442. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  15443. holeIndex = h2;
  15444. indepHoles.splice( h, 1 );
  15445. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  15446. tmpShape2 = shape.slice( shapeIndex );
  15447. tmpHole1 = hole.slice( holeIndex );
  15448. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  15449. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15450. minShapeIndex = shapeIndex;
  15451. // Debug only, to show the selected cuts
  15452. // glob_CutLines.push( [ shapePt, holePt ] );
  15453. break;
  15454. }
  15455. if ( holeIndex >= 0 ) break; // hole-vertex found
  15456. failedCuts[ cutKey ] = true; // remember failure
  15457. }
  15458. if ( holeIndex >= 0 ) break; // hole-vertex found
  15459. }
  15460. }
  15461. return shape; /* shape with no holes */
  15462. }
  15463. var i, il, f, face,
  15464. key, index,
  15465. allPointsMap = {};
  15466. // 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.
  15467. var allpoints = contour.concat();
  15468. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  15469. Array.prototype.push.apply( allpoints, holes[ h ] );
  15470. }
  15471. //console.log( "allpoints",allpoints, allpoints.length );
  15472. // prepare all points map
  15473. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15474. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15475. if ( allPointsMap[ key ] !== undefined ) {
  15476. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  15477. }
  15478. allPointsMap[ key ] = i;
  15479. }
  15480. // remove holes by cutting paths to holes and adding them to the shape
  15481. var shapeWithoutHoles = removeHoles( contour, holes );
  15482. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  15483. //console.log( "triangles",triangles, triangles.length );
  15484. // check all face vertices against all points map
  15485. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15486. face = triangles[ i ];
  15487. for ( f = 0; f < 3; f ++ ) {
  15488. key = face[ f ].x + ":" + face[ f ].y;
  15489. index = allPointsMap[ key ];
  15490. if ( index !== undefined ) {
  15491. face[ f ] = index;
  15492. }
  15493. }
  15494. }
  15495. return triangles.concat();
  15496. },
  15497. isClockWise: function ( pts ) {
  15498. return ShapeUtils.area( pts ) < 0;
  15499. }
  15500. };
  15501. /**
  15502. * @author zz85 / http://www.lab4games.net/zz85/blog
  15503. *
  15504. * Creates extruded geometry from a path shape.
  15505. *
  15506. * parameters = {
  15507. *
  15508. * curveSegments: <int>, // number of points on the curves
  15509. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  15510. * amount: <int>, // Depth to extrude the shape
  15511. *
  15512. * bevelEnabled: <bool>, // turn on bevel
  15513. * bevelThickness: <float>, // how deep into the original shape bevel goes
  15514. * bevelSize: <float>, // how far from shape outline is bevel
  15515. * bevelSegments: <int>, // number of bevel layers
  15516. *
  15517. * extrudePath: <THREE.Curve> // curve to extrude shape along
  15518. * frames: <Object> // containing arrays of tangents, normals, binormals
  15519. *
  15520. * uvGenerator: <Object> // object that provides UV generator functions
  15521. *
  15522. * }
  15523. **/
  15524. function ExtrudeGeometry( shapes, options ) {
  15525. if ( typeof( shapes ) === "undefined" ) {
  15526. shapes = [];
  15527. return;
  15528. }
  15529. Geometry.call( this );
  15530. this.type = 'ExtrudeGeometry';
  15531. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  15532. this.addShapeList( shapes, options );
  15533. this.computeFaceNormals();
  15534. // can't really use automatic vertex normals
  15535. // as then front and back sides get smoothed too
  15536. // should do separate smoothing just for sides
  15537. //this.computeVertexNormals();
  15538. //console.log( "took", ( Date.now() - startTime ) );
  15539. }
  15540. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  15541. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  15542. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  15543. var sl = shapes.length;
  15544. for ( var s = 0; s < sl; s ++ ) {
  15545. var shape = shapes[ s ];
  15546. this.addShape( shape, options );
  15547. }
  15548. };
  15549. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  15550. var amount = options.amount !== undefined ? options.amount : 100;
  15551. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  15552. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  15553. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  15554. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  15555. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  15556. var steps = options.steps !== undefined ? options.steps : 1;
  15557. var extrudePath = options.extrudePath;
  15558. var extrudePts, extrudeByPath = false;
  15559. // Use default WorldUVGenerator if no UV generators are specified.
  15560. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  15561. var splineTube, binormal, normal, position2;
  15562. if ( extrudePath ) {
  15563. extrudePts = extrudePath.getSpacedPoints( steps );
  15564. extrudeByPath = true;
  15565. bevelEnabled = false; // bevels not supported for path extrusion
  15566. // SETUP TNB variables
  15567. // TODO1 - have a .isClosed in spline?
  15568. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  15569. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  15570. binormal = new Vector3();
  15571. normal = new Vector3();
  15572. position2 = new Vector3();
  15573. }
  15574. // Safeguards if bevels are not enabled
  15575. if ( ! bevelEnabled ) {
  15576. bevelSegments = 0;
  15577. bevelThickness = 0;
  15578. bevelSize = 0;
  15579. }
  15580. // Variables initialization
  15581. var ahole, h, hl; // looping of holes
  15582. var scope = this;
  15583. var shapesOffset = this.vertices.length;
  15584. var shapePoints = shape.extractPoints( curveSegments );
  15585. var vertices = shapePoints.shape;
  15586. var holes = shapePoints.holes;
  15587. var reverse = ! ShapeUtils.isClockWise( vertices );
  15588. if ( reverse ) {
  15589. vertices = vertices.reverse();
  15590. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  15591. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15592. ahole = holes[ h ];
  15593. if ( ShapeUtils.isClockWise( ahole ) ) {
  15594. holes[ h ] = ahole.reverse();
  15595. }
  15596. }
  15597. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  15598. }
  15599. var faces = ShapeUtils.triangulateShape( vertices, holes );
  15600. /* Vertices */
  15601. var contour = vertices; // vertices has all points but contour has only points of circumference
  15602. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15603. ahole = holes[ h ];
  15604. vertices = vertices.concat( ahole );
  15605. }
  15606. function scalePt2( pt, vec, size ) {
  15607. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  15608. return vec.clone().multiplyScalar( size ).add( pt );
  15609. }
  15610. var b, bs, t, z,
  15611. vert, vlen = vertices.length,
  15612. face, flen = faces.length;
  15613. // Find directions for point movement
  15614. function getBevelVec( inPt, inPrev, inNext ) {
  15615. // computes for inPt the corresponding point inPt' on a new contour
  15616. // shifted by 1 unit (length of normalized vector) to the left
  15617. // if we walk along contour clockwise, this new contour is outside the old one
  15618. //
  15619. // inPt' is the intersection of the two lines parallel to the two
  15620. // adjacent edges of inPt at a distance of 1 unit on the left side.
  15621. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  15622. // good reading for geometry algorithms (here: line-line intersection)
  15623. // http://geomalgorithms.com/a05-_intersect-1.html
  15624. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  15625. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  15626. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  15627. // check for collinear edges
  15628. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15629. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  15630. // not collinear
  15631. // length of vectors for normalizing
  15632. var v_prev_len = Math.sqrt( v_prev_lensq );
  15633. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  15634. // shift adjacent points by unit vectors to the left
  15635. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  15636. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  15637. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  15638. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  15639. // scaling factor for v_prev to intersection point
  15640. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  15641. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  15642. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  15643. // vector from inPt to intersection point
  15644. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  15645. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  15646. // Don't normalize!, otherwise sharp corners become ugly
  15647. // but prevent crazy spikes
  15648. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  15649. if ( v_trans_lensq <= 2 ) {
  15650. return new Vector2( v_trans_x, v_trans_y );
  15651. } else {
  15652. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  15653. }
  15654. } else {
  15655. // handle special case of collinear edges
  15656. var direction_eq = false; // assumes: opposite
  15657. if ( v_prev_x > Number.EPSILON ) {
  15658. if ( v_next_x > Number.EPSILON ) {
  15659. direction_eq = true;
  15660. }
  15661. } else {
  15662. if ( v_prev_x < - Number.EPSILON ) {
  15663. if ( v_next_x < - Number.EPSILON ) {
  15664. direction_eq = true;
  15665. }
  15666. } else {
  15667. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  15668. direction_eq = true;
  15669. }
  15670. }
  15671. }
  15672. if ( direction_eq ) {
  15673. // console.log("Warning: lines are a straight sequence");
  15674. v_trans_x = - v_prev_y;
  15675. v_trans_y = v_prev_x;
  15676. shrink_by = Math.sqrt( v_prev_lensq );
  15677. } else {
  15678. // console.log("Warning: lines are a straight spike");
  15679. v_trans_x = v_prev_x;
  15680. v_trans_y = v_prev_y;
  15681. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  15682. }
  15683. }
  15684. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  15685. }
  15686. var contourMovements = [];
  15687. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15688. if ( j === il ) j = 0;
  15689. if ( k === il ) k = 0;
  15690. // (j)---(i)---(k)
  15691. // console.log('i,j,k', i, j , k)
  15692. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  15693. }
  15694. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  15695. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15696. ahole = holes[ h ];
  15697. oneHoleMovements = [];
  15698. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  15699. if ( j === il ) j = 0;
  15700. if ( k === il ) k = 0;
  15701. // (j)---(i)---(k)
  15702. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  15703. }
  15704. holesMovements.push( oneHoleMovements );
  15705. verticesMovements = verticesMovements.concat( oneHoleMovements );
  15706. }
  15707. // Loop bevelSegments, 1 for the front, 1 for the back
  15708. for ( b = 0; b < bevelSegments; b ++ ) {
  15709. //for ( b = bevelSegments; b > 0; b -- ) {
  15710. t = b / bevelSegments;
  15711. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  15712. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15713. // contract shape
  15714. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15715. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15716. v( vert.x, vert.y, - z );
  15717. }
  15718. // expand holes
  15719. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15720. ahole = holes[ h ];
  15721. oneHoleMovements = holesMovements[ h ];
  15722. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15723. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15724. v( vert.x, vert.y, - z );
  15725. }
  15726. }
  15727. }
  15728. bs = bevelSize;
  15729. // Back facing vertices
  15730. for ( i = 0; i < vlen; i ++ ) {
  15731. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15732. if ( ! extrudeByPath ) {
  15733. v( vert.x, vert.y, 0 );
  15734. } else {
  15735. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  15736. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  15737. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  15738. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  15739. v( position2.x, position2.y, position2.z );
  15740. }
  15741. }
  15742. // Add stepped vertices...
  15743. // Including front facing vertices
  15744. var s;
  15745. for ( s = 1; s <= steps; s ++ ) {
  15746. for ( i = 0; i < vlen; i ++ ) {
  15747. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  15748. if ( ! extrudeByPath ) {
  15749. v( vert.x, vert.y, amount / steps * s );
  15750. } else {
  15751. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  15752. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  15753. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  15754. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  15755. v( position2.x, position2.y, position2.z );
  15756. }
  15757. }
  15758. }
  15759. // Add bevel segments planes
  15760. //for ( b = 1; b <= bevelSegments; b ++ ) {
  15761. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  15762. t = b / bevelSegments;
  15763. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  15764. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  15765. // contract shape
  15766. for ( i = 0, il = contour.length; i < il; i ++ ) {
  15767. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  15768. v( vert.x, vert.y, amount + z );
  15769. }
  15770. // expand holes
  15771. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15772. ahole = holes[ h ];
  15773. oneHoleMovements = holesMovements[ h ];
  15774. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  15775. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  15776. if ( ! extrudeByPath ) {
  15777. v( vert.x, vert.y, amount + z );
  15778. } else {
  15779. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  15780. }
  15781. }
  15782. }
  15783. }
  15784. /* Faces */
  15785. // Top and bottom faces
  15786. buildLidFaces();
  15787. // Sides faces
  15788. buildSideFaces();
  15789. ///// Internal functions
  15790. function buildLidFaces() {
  15791. if ( bevelEnabled ) {
  15792. var layer = 0; // steps + 1
  15793. var offset = vlen * layer;
  15794. // Bottom faces
  15795. for ( i = 0; i < flen; i ++ ) {
  15796. face = faces[ i ];
  15797. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  15798. }
  15799. layer = steps + bevelSegments * 2;
  15800. offset = vlen * layer;
  15801. // Top faces
  15802. for ( i = 0; i < flen; i ++ ) {
  15803. face = faces[ i ];
  15804. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  15805. }
  15806. } else {
  15807. // Bottom faces
  15808. for ( i = 0; i < flen; i ++ ) {
  15809. face = faces[ i ];
  15810. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  15811. }
  15812. // Top faces
  15813. for ( i = 0; i < flen; i ++ ) {
  15814. face = faces[ i ];
  15815. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  15816. }
  15817. }
  15818. }
  15819. // Create faces for the z-sides of the shape
  15820. function buildSideFaces() {
  15821. var layeroffset = 0;
  15822. sidewalls( contour, layeroffset );
  15823. layeroffset += contour.length;
  15824. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15825. ahole = holes[ h ];
  15826. sidewalls( ahole, layeroffset );
  15827. //, true
  15828. layeroffset += ahole.length;
  15829. }
  15830. }
  15831. function sidewalls( contour, layeroffset ) {
  15832. var j, k;
  15833. i = contour.length;
  15834. while ( -- i >= 0 ) {
  15835. j = i;
  15836. k = i - 1;
  15837. if ( k < 0 ) k = contour.length - 1;
  15838. //console.log('b', i,j, i-1, k,vertices.length);
  15839. var s = 0, sl = steps + bevelSegments * 2;
  15840. for ( s = 0; s < sl; s ++ ) {
  15841. var slen1 = vlen * s;
  15842. var slen2 = vlen * ( s + 1 );
  15843. var a = layeroffset + j + slen1,
  15844. b = layeroffset + k + slen1,
  15845. c = layeroffset + k + slen2,
  15846. d = layeroffset + j + slen2;
  15847. f4( a, b, c, d, contour, s, sl, j, k );
  15848. }
  15849. }
  15850. }
  15851. function v( x, y, z ) {
  15852. scope.vertices.push( new Vector3( x, y, z ) );
  15853. }
  15854. function f3( a, b, c ) {
  15855. a += shapesOffset;
  15856. b += shapesOffset;
  15857. c += shapesOffset;
  15858. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  15859. var uvs = uvgen.generateTopUV( scope, a, b, c );
  15860. scope.faceVertexUvs[ 0 ].push( uvs );
  15861. }
  15862. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  15863. a += shapesOffset;
  15864. b += shapesOffset;
  15865. c += shapesOffset;
  15866. d += shapesOffset;
  15867. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  15868. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  15869. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  15870. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  15871. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  15872. }
  15873. };
  15874. ExtrudeGeometry.WorldUVGenerator = {
  15875. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  15876. var vertices = geometry.vertices;
  15877. var a = vertices[ indexA ];
  15878. var b = vertices[ indexB ];
  15879. var c = vertices[ indexC ];
  15880. return [
  15881. new Vector2( a.x, a.y ),
  15882. new Vector2( b.x, b.y ),
  15883. new Vector2( c.x, c.y )
  15884. ];
  15885. },
  15886. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  15887. var vertices = geometry.vertices;
  15888. var a = vertices[ indexA ];
  15889. var b = vertices[ indexB ];
  15890. var c = vertices[ indexC ];
  15891. var d = vertices[ indexD ];
  15892. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  15893. return [
  15894. new Vector2( a.x, 1 - a.z ),
  15895. new Vector2( b.x, 1 - b.z ),
  15896. new Vector2( c.x, 1 - c.z ),
  15897. new Vector2( d.x, 1 - d.z )
  15898. ];
  15899. } else {
  15900. return [
  15901. new Vector2( a.y, 1 - a.z ),
  15902. new Vector2( b.y, 1 - b.z ),
  15903. new Vector2( c.y, 1 - c.z ),
  15904. new Vector2( d.y, 1 - d.z )
  15905. ];
  15906. }
  15907. }
  15908. };
  15909. /**
  15910. * @author zz85 / http://www.lab4games.net/zz85/blog
  15911. * @author alteredq / http://alteredqualia.com/
  15912. *
  15913. * Text = 3D Text
  15914. *
  15915. * parameters = {
  15916. * font: <THREE.Font>, // font
  15917. *
  15918. * size: <float>, // size of the text
  15919. * height: <float>, // thickness to extrude text
  15920. * curveSegments: <int>, // number of points on the curves
  15921. *
  15922. * bevelEnabled: <bool>, // turn on bevel
  15923. * bevelThickness: <float>, // how deep into text bevel goes
  15924. * bevelSize: <float> // how far from text outline is bevel
  15925. * }
  15926. */
  15927. function TextGeometry( text, parameters ) {
  15928. parameters = parameters || {};
  15929. var font = parameters.font;
  15930. if ( (font && font.isFont) === false ) {
  15931. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  15932. return new Geometry();
  15933. }
  15934. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  15935. // translate parameters to ExtrudeGeometry API
  15936. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15937. // defaults
  15938. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15939. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15940. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15941. ExtrudeGeometry.call( this, shapes, parameters );
  15942. this.type = 'TextGeometry';
  15943. }
  15944. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  15945. TextGeometry.prototype.constructor = TextGeometry;
  15946. /**
  15947. * @author benaadams / https://twitter.com/ben_a_adams
  15948. * based on THREE.SphereGeometry
  15949. */
  15950. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  15951. BufferGeometry.call( this );
  15952. this.type = 'SphereBufferGeometry';
  15953. this.parameters = {
  15954. radius: radius,
  15955. widthSegments: widthSegments,
  15956. heightSegments: heightSegments,
  15957. phiStart: phiStart,
  15958. phiLength: phiLength,
  15959. thetaStart: thetaStart,
  15960. thetaLength: thetaLength
  15961. };
  15962. radius = radius || 50;
  15963. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  15964. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  15965. phiStart = phiStart !== undefined ? phiStart : 0;
  15966. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  15967. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  15968. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  15969. var thetaEnd = thetaStart + thetaLength;
  15970. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  15971. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  15972. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  15973. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  15974. var index = 0, vertices = [], normal = new Vector3();
  15975. for ( var y = 0; y <= heightSegments; y ++ ) {
  15976. var verticesRow = [];
  15977. var v = y / heightSegments;
  15978. for ( var x = 0; x <= widthSegments; x ++ ) {
  15979. var u = x / widthSegments;
  15980. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15981. var py = radius * Math.cos( thetaStart + v * thetaLength );
  15982. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15983. normal.set( px, py, pz ).normalize();
  15984. positions.setXYZ( index, px, py, pz );
  15985. normals.setXYZ( index, normal.x, normal.y, normal.z );
  15986. uvs.setXY( index, u, 1 - v );
  15987. verticesRow.push( index );
  15988. index ++;
  15989. }
  15990. vertices.push( verticesRow );
  15991. }
  15992. var indices = [];
  15993. for ( var y = 0; y < heightSegments; y ++ ) {
  15994. for ( var x = 0; x < widthSegments; x ++ ) {
  15995. var v1 = vertices[ y ][ x + 1 ];
  15996. var v2 = vertices[ y ][ x ];
  15997. var v3 = vertices[ y + 1 ][ x ];
  15998. var v4 = vertices[ y + 1 ][ x + 1 ];
  15999. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  16000. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  16001. }
  16002. }
  16003. this.setIndex( new ( positions.count > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16004. this.addAttribute( 'position', positions );
  16005. this.addAttribute( 'normal', normals );
  16006. this.addAttribute( 'uv', uvs );
  16007. this.boundingSphere = new Sphere( new Vector3(), radius );
  16008. }
  16009. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16010. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  16011. /**
  16012. * @author mrdoob / http://mrdoob.com/
  16013. */
  16014. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  16015. Geometry.call( this );
  16016. this.type = 'SphereGeometry';
  16017. this.parameters = {
  16018. radius: radius,
  16019. widthSegments: widthSegments,
  16020. heightSegments: heightSegments,
  16021. phiStart: phiStart,
  16022. phiLength: phiLength,
  16023. thetaStart: thetaStart,
  16024. thetaLength: thetaLength
  16025. };
  16026. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  16027. }
  16028. SphereGeometry.prototype = Object.create( Geometry.prototype );
  16029. SphereGeometry.prototype.constructor = SphereGeometry;
  16030. /**
  16031. * @author Mugen87 / https://github.com/Mugen87
  16032. */
  16033. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16034. BufferGeometry.call( this );
  16035. this.type = 'RingBufferGeometry';
  16036. this.parameters = {
  16037. innerRadius: innerRadius,
  16038. outerRadius: outerRadius,
  16039. thetaSegments: thetaSegments,
  16040. phiSegments: phiSegments,
  16041. thetaStart: thetaStart,
  16042. thetaLength: thetaLength
  16043. };
  16044. innerRadius = innerRadius || 20;
  16045. outerRadius = outerRadius || 50;
  16046. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16047. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16048. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  16049. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  16050. // these are used to calculate buffer length
  16051. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  16052. var indexCount = thetaSegments * phiSegments * 2 * 3;
  16053. // buffers
  16054. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16055. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16056. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16057. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16058. // some helper variables
  16059. var index = 0, indexOffset = 0, segment;
  16060. var radius = innerRadius;
  16061. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  16062. var vertex = new Vector3();
  16063. var uv = new Vector2();
  16064. var j, i;
  16065. // generate vertices, normals and uvs
  16066. // values are generate from the inside of the ring to the outside
  16067. for ( j = 0; j <= phiSegments; j ++ ) {
  16068. for ( i = 0; i <= thetaSegments; i ++ ) {
  16069. segment = thetaStart + i / thetaSegments * thetaLength;
  16070. // vertex
  16071. vertex.x = radius * Math.cos( segment );
  16072. vertex.y = radius * Math.sin( segment );
  16073. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16074. // normal
  16075. normals.setXYZ( index, 0, 0, 1 );
  16076. // uv
  16077. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  16078. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  16079. uvs.setXY( index, uv.x, uv.y );
  16080. // increase index
  16081. index++;
  16082. }
  16083. // increase the radius for next row of vertices
  16084. radius += radiusStep;
  16085. }
  16086. // generate indices
  16087. for ( j = 0; j < phiSegments; j ++ ) {
  16088. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  16089. for ( i = 0; i < thetaSegments; i ++ ) {
  16090. segment = i + thetaSegmentLevel;
  16091. // indices
  16092. var a = segment;
  16093. var b = segment + thetaSegments + 1;
  16094. var c = segment + thetaSegments + 2;
  16095. var d = segment + 1;
  16096. // face one
  16097. indices.setX( indexOffset, a ); indexOffset++;
  16098. indices.setX( indexOffset, b ); indexOffset++;
  16099. indices.setX( indexOffset, c ); indexOffset++;
  16100. // face two
  16101. indices.setX( indexOffset, a ); indexOffset++;
  16102. indices.setX( indexOffset, c ); indexOffset++;
  16103. indices.setX( indexOffset, d ); indexOffset++;
  16104. }
  16105. }
  16106. // build geometry
  16107. this.setIndex( indices );
  16108. this.addAttribute( 'position', vertices );
  16109. this.addAttribute( 'normal', normals );
  16110. this.addAttribute( 'uv', uvs );
  16111. }
  16112. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16113. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  16114. /**
  16115. * @author Kaleb Murphy
  16116. */
  16117. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  16118. Geometry.call( this );
  16119. this.type = 'RingGeometry';
  16120. this.parameters = {
  16121. innerRadius: innerRadius,
  16122. outerRadius: outerRadius,
  16123. thetaSegments: thetaSegments,
  16124. phiSegments: phiSegments,
  16125. thetaStart: thetaStart,
  16126. thetaLength: thetaLength
  16127. };
  16128. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  16129. }
  16130. RingGeometry.prototype = Object.create( Geometry.prototype );
  16131. RingGeometry.prototype.constructor = RingGeometry;
  16132. /**
  16133. * @author mrdoob / http://mrdoob.com/
  16134. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  16135. */
  16136. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  16137. Geometry.call( this );
  16138. this.type = 'PlaneGeometry';
  16139. this.parameters = {
  16140. width: width,
  16141. height: height,
  16142. widthSegments: widthSegments,
  16143. heightSegments: heightSegments
  16144. };
  16145. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  16146. }
  16147. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  16148. PlaneGeometry.prototype.constructor = PlaneGeometry;
  16149. /**
  16150. * @author Mugen87 / https://github.com/Mugen87
  16151. */
  16152. // points - to create a closed torus, one must use a set of points
  16153. // like so: [ a, b, c, d, a ], see first is the same as last.
  16154. // segments - the number of circumference segments to create
  16155. // phiStart - the starting radian
  16156. // phiLength - the radian (0 to 2PI) range of the lathed section
  16157. // 2PI is a closed lathe, less than 2PI is a portion.
  16158. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  16159. BufferGeometry.call( this );
  16160. this.type = 'LatheBufferGeometry';
  16161. this.parameters = {
  16162. points: points,
  16163. segments: segments,
  16164. phiStart: phiStart,
  16165. phiLength: phiLength
  16166. };
  16167. segments = Math.floor( segments ) || 12;
  16168. phiStart = phiStart || 0;
  16169. phiLength = phiLength || Math.PI * 2;
  16170. // clamp phiLength so it's in range of [ 0, 2PI ]
  16171. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  16172. // these are used to calculate buffer length
  16173. var vertexCount = ( segments + 1 ) * points.length;
  16174. var indexCount = segments * points.length * 2 * 3;
  16175. // buffers
  16176. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  16177. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16178. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16179. // helper variables
  16180. var index = 0, indexOffset = 0, base;
  16181. var inverseSegments = 1.0 / segments;
  16182. var vertex = new Vector3();
  16183. var uv = new Vector2();
  16184. var i, j;
  16185. // generate vertices and uvs
  16186. for ( i = 0; i <= segments; i ++ ) {
  16187. var phi = phiStart + i * inverseSegments * phiLength;
  16188. var sin = Math.sin( phi );
  16189. var cos = Math.cos( phi );
  16190. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  16191. // vertex
  16192. vertex.x = points[ j ].x * sin;
  16193. vertex.y = points[ j ].y;
  16194. vertex.z = points[ j ].x * cos;
  16195. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16196. // uv
  16197. uv.x = i / segments;
  16198. uv.y = j / ( points.length - 1 );
  16199. uvs.setXY( index, uv.x, uv.y );
  16200. // increase index
  16201. index ++;
  16202. }
  16203. }
  16204. // generate indices
  16205. for ( i = 0; i < segments; i ++ ) {
  16206. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  16207. base = j + i * points.length;
  16208. // indices
  16209. var a = base;
  16210. var b = base + points.length;
  16211. var c = base + points.length + 1;
  16212. var d = base + 1;
  16213. // face one
  16214. indices.setX( indexOffset, a ); indexOffset++;
  16215. indices.setX( indexOffset, b ); indexOffset++;
  16216. indices.setX( indexOffset, d ); indexOffset++;
  16217. // face two
  16218. indices.setX( indexOffset, b ); indexOffset++;
  16219. indices.setX( indexOffset, c ); indexOffset++;
  16220. indices.setX( indexOffset, d ); indexOffset++;
  16221. }
  16222. }
  16223. // build geometry
  16224. this.setIndex( indices );
  16225. this.addAttribute( 'position', vertices );
  16226. this.addAttribute( 'uv', uvs );
  16227. // generate normals
  16228. this.computeVertexNormals();
  16229. // if the geometry is closed, we need to average the normals along the seam.
  16230. // because the corresponding vertices are identical (but still have different UVs).
  16231. if( phiLength === Math.PI * 2 ) {
  16232. var normals = this.attributes.normal.array;
  16233. var n1 = new Vector3();
  16234. var n2 = new Vector3();
  16235. var n = new Vector3();
  16236. // this is the buffer offset for the last line of vertices
  16237. base = segments * points.length * 3;
  16238. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  16239. // select the normal of the vertex in the first line
  16240. n1.x = normals[ j + 0 ];
  16241. n1.y = normals[ j + 1 ];
  16242. n1.z = normals[ j + 2 ];
  16243. // select the normal of the vertex in the last line
  16244. n2.x = normals[ base + j + 0 ];
  16245. n2.y = normals[ base + j + 1 ];
  16246. n2.z = normals[ base + j + 2 ];
  16247. // average normals
  16248. n.addVectors( n1, n2 ).normalize();
  16249. // assign the new values to both normals
  16250. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  16251. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  16252. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  16253. } // next row
  16254. }
  16255. }
  16256. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16257. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  16258. /**
  16259. * @author astrodud / http://astrodud.isgreat.org/
  16260. * @author zz85 / https://github.com/zz85
  16261. * @author bhouston / http://clara.io
  16262. */
  16263. // points - to create a closed torus, one must use a set of points
  16264. // like so: [ a, b, c, d, a ], see first is the same as last.
  16265. // segments - the number of circumference segments to create
  16266. // phiStart - the starting radian
  16267. // phiLength - the radian (0 to 2PI) range of the lathed section
  16268. // 2PI is a closed lathe, less than 2PI is a portion.
  16269. function LatheGeometry( points, segments, phiStart, phiLength ) {
  16270. Geometry.call( this );
  16271. this.type = 'LatheGeometry';
  16272. this.parameters = {
  16273. points: points,
  16274. segments: segments,
  16275. phiStart: phiStart,
  16276. phiLength: phiLength
  16277. };
  16278. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  16279. this.mergeVertices();
  16280. }
  16281. LatheGeometry.prototype = Object.create( Geometry.prototype );
  16282. LatheGeometry.prototype.constructor = LatheGeometry;
  16283. /**
  16284. * @author Mugen87 / https://github.com/Mugen87
  16285. *
  16286. * Creates a one-sided polygonal geometry from one or more shapes.
  16287. *
  16288. **/
  16289. function ShapeBufferGeometry( shapes, curveSegments ) {
  16290. BufferGeometry.call( this );
  16291. this.type = 'ShapeBufferGeometry';
  16292. this.parameters = {
  16293. shapes: shapes,
  16294. curveSegments: curveSegments
  16295. };
  16296. curveSegments = curveSegments || 12;
  16297. var vertices = [];
  16298. var normals = [];
  16299. var uvs = [];
  16300. var indices = [];
  16301. var groupStart = 0;
  16302. var groupCount = 0;
  16303. // allow single and array values for "shapes" parameter
  16304. if ( Array.isArray( shapes ) === false ) {
  16305. addShape( shapes );
  16306. } else {
  16307. for ( var i = 0; i < shapes.length; i++ ) {
  16308. addShape( shapes[ i ] );
  16309. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  16310. groupStart += groupCount;
  16311. groupCount = 0;
  16312. }
  16313. }
  16314. // build geometry
  16315. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  16316. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16317. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16318. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16319. // helper functions
  16320. function addShape( shape ) {
  16321. var i, l, shapeHole;
  16322. var indexOffset = vertices.length / 3;
  16323. var points = shape.extractPoints( curveSegments );
  16324. var shapeVertices = points.shape;
  16325. var shapeHoles = points.holes;
  16326. // check direction of vertices
  16327. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  16328. shapeVertices = shapeVertices.reverse();
  16329. // also check if holes are in the opposite direction
  16330. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16331. shapeHole = shapeHoles[ i ];
  16332. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  16333. shapeHoles[ i ] = shapeHole.reverse();
  16334. }
  16335. }
  16336. }
  16337. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  16338. // join vertices of inner and outer paths to a single array
  16339. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  16340. shapeHole = shapeHoles[ i ];
  16341. shapeVertices = shapeVertices.concat( shapeHole );
  16342. }
  16343. // vertices, normals, uvs
  16344. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  16345. var vertex = shapeVertices[ i ];
  16346. vertices.push( vertex.x, vertex.y, 0 );
  16347. normals.push( 0, 0, 1 );
  16348. uvs.push( vertex.x, vertex.y ); // world uvs
  16349. }
  16350. // incides
  16351. for ( i = 0, l = faces.length; i < l; i ++ ) {
  16352. var face = faces[ i ];
  16353. var a = face[ 0 ] + indexOffset;
  16354. var b = face[ 1 ] + indexOffset;
  16355. var c = face[ 2 ] + indexOffset;
  16356. indices.push( a, b, c );
  16357. groupCount += 3;
  16358. }
  16359. }
  16360. }
  16361. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16362. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  16363. /**
  16364. * @author jonobr1 / http://jonobr1.com
  16365. *
  16366. * Creates a one-sided polygonal geometry from a path shape.
  16367. *
  16368. **/
  16369. function ShapeGeometry( shapes, curveSegments ) {
  16370. Geometry.call( this );
  16371. this.type = 'ShapeGeometry';
  16372. if ( typeof curveSegments === 'object' ) {
  16373. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  16374. curveSegments = curveSegments.curveSegments;
  16375. }
  16376. this.parameters = {
  16377. shapes: shapes,
  16378. curveSegments: curveSegments
  16379. };
  16380. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  16381. this.mergeVertices();
  16382. }
  16383. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  16384. ShapeGeometry.prototype.constructor = ShapeGeometry;
  16385. /**
  16386. * @author WestLangley / http://github.com/WestLangley
  16387. */
  16388. function EdgesGeometry( geometry, thresholdAngle ) {
  16389. BufferGeometry.call( this );
  16390. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16391. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  16392. var edge = [ 0, 0 ], hash = {};
  16393. function sortFunction( a, b ) {
  16394. return a - b;
  16395. }
  16396. var keys = [ 'a', 'b', 'c' ];
  16397. var geometry2;
  16398. if ( geometry.isBufferGeometry ) {
  16399. geometry2 = new Geometry();
  16400. geometry2.fromBufferGeometry( geometry );
  16401. } else {
  16402. geometry2 = geometry.clone();
  16403. }
  16404. geometry2.mergeVertices();
  16405. geometry2.computeFaceNormals();
  16406. var vertices = geometry2.vertices;
  16407. var faces = geometry2.faces;
  16408. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16409. var face = faces[ i ];
  16410. for ( var j = 0; j < 3; j ++ ) {
  16411. edge[ 0 ] = face[ keys[ j ] ];
  16412. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  16413. edge.sort( sortFunction );
  16414. var key = edge.toString();
  16415. if ( hash[ key ] === undefined ) {
  16416. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  16417. } else {
  16418. hash[ key ].face2 = i;
  16419. }
  16420. }
  16421. }
  16422. var coords = [];
  16423. for ( var key in hash ) {
  16424. var h = hash[ key ];
  16425. // An edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  16426. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  16427. var vertex = vertices[ h.vert1 ];
  16428. coords.push( vertex.x );
  16429. coords.push( vertex.y );
  16430. coords.push( vertex.z );
  16431. vertex = vertices[ h.vert2 ];
  16432. coords.push( vertex.x );
  16433. coords.push( vertex.y );
  16434. coords.push( vertex.z );
  16435. }
  16436. }
  16437. this.addAttribute( 'position', new Float32BufferAttribute( coords, 3 ) );
  16438. }
  16439. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  16440. EdgesGeometry.prototype.constructor = EdgesGeometry;
  16441. /**
  16442. * @author Mugen87 / https://github.com/Mugen87
  16443. */
  16444. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16445. BufferGeometry.call( this );
  16446. this.type = 'CylinderBufferGeometry';
  16447. this.parameters = {
  16448. radiusTop: radiusTop,
  16449. radiusBottom: radiusBottom,
  16450. height: height,
  16451. radialSegments: radialSegments,
  16452. heightSegments: heightSegments,
  16453. openEnded: openEnded,
  16454. thetaStart: thetaStart,
  16455. thetaLength: thetaLength
  16456. };
  16457. var scope = this;
  16458. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  16459. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  16460. height = height !== undefined ? height : 100;
  16461. radialSegments = Math.floor( radialSegments ) || 8;
  16462. heightSegments = Math.floor( heightSegments ) || 1;
  16463. openEnded = openEnded !== undefined ? openEnded : false;
  16464. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  16465. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  16466. // used to calculate buffer length
  16467. var nbCap = 0;
  16468. if ( openEnded === false ) {
  16469. if ( radiusTop > 0 ) nbCap ++;
  16470. if ( radiusBottom > 0 ) nbCap ++;
  16471. }
  16472. var vertexCount = calculateVertexCount();
  16473. var indexCount = calculateIndexCount();
  16474. // buffers
  16475. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  16476. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16477. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  16478. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  16479. // helper variables
  16480. var index = 0,
  16481. indexOffset = 0,
  16482. indexArray = [],
  16483. halfHeight = height / 2;
  16484. // group variables
  16485. var groupStart = 0;
  16486. // generate geometry
  16487. generateTorso();
  16488. if ( openEnded === false ) {
  16489. if ( radiusTop > 0 ) generateCap( true );
  16490. if ( radiusBottom > 0 ) generateCap( false );
  16491. }
  16492. // build geometry
  16493. this.setIndex( indices );
  16494. this.addAttribute( 'position', vertices );
  16495. this.addAttribute( 'normal', normals );
  16496. this.addAttribute( 'uv', uvs );
  16497. // helper functions
  16498. function calculateVertexCount() {
  16499. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  16500. if ( openEnded === false ) {
  16501. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  16502. }
  16503. return count;
  16504. }
  16505. function calculateIndexCount() {
  16506. var count = radialSegments * heightSegments * 2 * 3;
  16507. if ( openEnded === false ) {
  16508. count += radialSegments * nbCap * 3;
  16509. }
  16510. return count;
  16511. }
  16512. function generateTorso() {
  16513. var x, y;
  16514. var normal = new Vector3();
  16515. var vertex = new Vector3();
  16516. var groupCount = 0;
  16517. // this will be used to calculate the normal
  16518. var slope = ( radiusBottom - radiusTop ) / height;
  16519. // generate vertices, normals and uvs
  16520. for ( y = 0; y <= heightSegments; y ++ ) {
  16521. var indexRow = [];
  16522. var v = y / heightSegments;
  16523. // calculate the radius of the current row
  16524. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16525. for ( x = 0; x <= radialSegments; x ++ ) {
  16526. var u = x / radialSegments;
  16527. var theta = u * thetaLength + thetaStart;
  16528. var sinTheta = Math.sin( theta );
  16529. var cosTheta = Math.cos( theta );
  16530. // vertex
  16531. vertex.x = radius * sinTheta;
  16532. vertex.y = - v * height + halfHeight;
  16533. vertex.z = radius * cosTheta;
  16534. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16535. // normal
  16536. normal.set( sinTheta, slope, cosTheta ).normalize();
  16537. normals.setXYZ( index, normal.x, normal.y, normal.z );
  16538. // uv
  16539. uvs.setXY( index, u, 1 - v );
  16540. // save index of vertex in respective row
  16541. indexRow.push( index );
  16542. // increase index
  16543. index ++;
  16544. }
  16545. // now save vertices of the row in our index array
  16546. indexArray.push( indexRow );
  16547. }
  16548. // generate indices
  16549. for ( x = 0; x < radialSegments; x ++ ) {
  16550. for ( y = 0; y < heightSegments; y ++ ) {
  16551. // we use the index array to access the correct indices
  16552. var i1 = indexArray[ y ][ x ];
  16553. var i2 = indexArray[ y + 1 ][ x ];
  16554. var i3 = indexArray[ y + 1 ][ x + 1 ];
  16555. var i4 = indexArray[ y ][ x + 1 ];
  16556. // face one
  16557. indices.setX( indexOffset, i1 ); indexOffset ++;
  16558. indices.setX( indexOffset, i2 ); indexOffset ++;
  16559. indices.setX( indexOffset, i4 ); indexOffset ++;
  16560. // face two
  16561. indices.setX( indexOffset, i2 ); indexOffset ++;
  16562. indices.setX( indexOffset, i3 ); indexOffset ++;
  16563. indices.setX( indexOffset, i4 ); indexOffset ++;
  16564. // update counters
  16565. groupCount += 6;
  16566. }
  16567. }
  16568. // add a group to the geometry. this will ensure multi material support
  16569. scope.addGroup( groupStart, groupCount, 0 );
  16570. // calculate new start value for groups
  16571. groupStart += groupCount;
  16572. }
  16573. function generateCap( top ) {
  16574. var x, centerIndexStart, centerIndexEnd;
  16575. var uv = new Vector2();
  16576. var vertex = new Vector3();
  16577. var groupCount = 0;
  16578. var radius = ( top === true ) ? radiusTop : radiusBottom;
  16579. var sign = ( top === true ) ? 1 : - 1;
  16580. // save the index of the first center vertex
  16581. centerIndexStart = index;
  16582. // first we generate the center vertex data of the cap.
  16583. // because the geometry needs one set of uvs per face,
  16584. // we must generate a center vertex per face/segment
  16585. for ( x = 1; x <= radialSegments; x ++ ) {
  16586. // vertex
  16587. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  16588. // normal
  16589. normals.setXYZ( index, 0, sign, 0 );
  16590. // uv
  16591. uv.x = 0.5;
  16592. uv.y = 0.5;
  16593. uvs.setXY( index, uv.x, uv.y );
  16594. // increase index
  16595. index ++;
  16596. }
  16597. // save the index of the last center vertex
  16598. centerIndexEnd = index;
  16599. // now we generate the surrounding vertices, normals and uvs
  16600. for ( x = 0; x <= radialSegments; x ++ ) {
  16601. var u = x / radialSegments;
  16602. var theta = u * thetaLength + thetaStart;
  16603. var cosTheta = Math.cos( theta );
  16604. var sinTheta = Math.sin( theta );
  16605. // vertex
  16606. vertex.x = radius * sinTheta;
  16607. vertex.y = halfHeight * sign;
  16608. vertex.z = radius * cosTheta;
  16609. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  16610. // normal
  16611. normals.setXYZ( index, 0, sign, 0 );
  16612. // uv
  16613. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16614. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16615. uvs.setXY( index, uv.x, uv.y );
  16616. // increase index
  16617. index ++;
  16618. }
  16619. // generate indices
  16620. for ( x = 0; x < radialSegments; x ++ ) {
  16621. var c = centerIndexStart + x;
  16622. var i = centerIndexEnd + x;
  16623. if ( top === true ) {
  16624. // face top
  16625. indices.setX( indexOffset, i ); indexOffset ++;
  16626. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16627. indices.setX( indexOffset, c ); indexOffset ++;
  16628. } else {
  16629. // face bottom
  16630. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  16631. indices.setX( indexOffset, i ); indexOffset ++;
  16632. indices.setX( indexOffset, c ); indexOffset ++;
  16633. }
  16634. // update counters
  16635. groupCount += 3;
  16636. }
  16637. // add a group to the geometry. this will ensure multi material support
  16638. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16639. // calculate new start value for groups
  16640. groupStart += groupCount;
  16641. }
  16642. }
  16643. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16644. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  16645. /**
  16646. * @author mrdoob / http://mrdoob.com/
  16647. */
  16648. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16649. Geometry.call( this );
  16650. this.type = 'CylinderGeometry';
  16651. this.parameters = {
  16652. radiusTop: radiusTop,
  16653. radiusBottom: radiusBottom,
  16654. height: height,
  16655. radialSegments: radialSegments,
  16656. heightSegments: heightSegments,
  16657. openEnded: openEnded,
  16658. thetaStart: thetaStart,
  16659. thetaLength: thetaLength
  16660. };
  16661. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  16662. this.mergeVertices();
  16663. }
  16664. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  16665. CylinderGeometry.prototype.constructor = CylinderGeometry;
  16666. /**
  16667. * @author abelnation / http://github.com/abelnation
  16668. */
  16669. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16670. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16671. this.type = 'ConeGeometry';
  16672. this.parameters = {
  16673. radius: radius,
  16674. height: height,
  16675. radialSegments: radialSegments,
  16676. heightSegments: heightSegments,
  16677. openEnded: openEnded,
  16678. thetaStart: thetaStart,
  16679. thetaLength: thetaLength
  16680. };
  16681. }
  16682. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  16683. ConeGeometry.prototype.constructor = ConeGeometry;
  16684. /**
  16685. * @author: abelnation / http://github.com/abelnation
  16686. */
  16687. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  16688. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16689. this.type = 'ConeBufferGeometry';
  16690. this.parameters = {
  16691. radius: radius,
  16692. height: height,
  16693. radialSegments: radialSegments,
  16694. heightSegments: heightSegments,
  16695. openEnded: openEnded,
  16696. thetaStart: thetaStart,
  16697. thetaLength: thetaLength
  16698. };
  16699. }
  16700. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  16701. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  16702. /**
  16703. * @author benaadams / https://twitter.com/ben_a_adams
  16704. */
  16705. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  16706. BufferGeometry.call( this );
  16707. this.type = 'CircleBufferGeometry';
  16708. this.parameters = {
  16709. radius: radius,
  16710. segments: segments,
  16711. thetaStart: thetaStart,
  16712. thetaLength: thetaLength
  16713. };
  16714. radius = radius || 50;
  16715. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  16716. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  16717. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  16718. var vertices = segments + 2;
  16719. var positions = new Float32Array( vertices * 3 );
  16720. var normals = new Float32Array( vertices * 3 );
  16721. var uvs = new Float32Array( vertices * 2 );
  16722. // center data is already zero, but need to set a few extras
  16723. normals[ 2 ] = 1.0;
  16724. uvs[ 0 ] = 0.5;
  16725. uvs[ 1 ] = 0.5;
  16726. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  16727. var segment = thetaStart + s / segments * thetaLength;
  16728. positions[ i ] = radius * Math.cos( segment );
  16729. positions[ i + 1 ] = radius * Math.sin( segment );
  16730. normals[ i + 2 ] = 1; // normal z
  16731. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  16732. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  16733. }
  16734. var indices = [];
  16735. for ( var i = 1; i <= segments; i ++ ) {
  16736. indices.push( i, i + 1, 0 );
  16737. }
  16738. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  16739. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  16740. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  16741. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  16742. this.boundingSphere = new Sphere( new Vector3(), radius );
  16743. }
  16744. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  16745. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  16746. /**
  16747. * @author hughes
  16748. */
  16749. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  16750. Geometry.call( this );
  16751. this.type = 'CircleGeometry';
  16752. this.parameters = {
  16753. radius: radius,
  16754. segments: segments,
  16755. thetaStart: thetaStart,
  16756. thetaLength: thetaLength
  16757. };
  16758. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  16759. }
  16760. CircleGeometry.prototype = Object.create( Geometry.prototype );
  16761. CircleGeometry.prototype.constructor = CircleGeometry;
  16762. /**
  16763. * @author mrdoob / http://mrdoob.com/
  16764. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  16765. */
  16766. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  16767. Geometry.call( this );
  16768. this.type = 'BoxGeometry';
  16769. this.parameters = {
  16770. width: width,
  16771. height: height,
  16772. depth: depth,
  16773. widthSegments: widthSegments,
  16774. heightSegments: heightSegments,
  16775. depthSegments: depthSegments
  16776. };
  16777. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  16778. this.mergeVertices();
  16779. }
  16780. BoxGeometry.prototype = Object.create( Geometry.prototype );
  16781. BoxGeometry.prototype.constructor = BoxGeometry;
  16782. var Geometries = Object.freeze({
  16783. WireframeGeometry: WireframeGeometry,
  16784. ParametricGeometry: ParametricGeometry,
  16785. ParametricBufferGeometry: ParametricBufferGeometry,
  16786. TetrahedronGeometry: TetrahedronGeometry,
  16787. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  16788. OctahedronGeometry: OctahedronGeometry,
  16789. OctahedronBufferGeometry: OctahedronBufferGeometry,
  16790. IcosahedronGeometry: IcosahedronGeometry,
  16791. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  16792. DodecahedronGeometry: DodecahedronGeometry,
  16793. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  16794. PolyhedronGeometry: PolyhedronGeometry,
  16795. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  16796. TubeGeometry: TubeGeometry,
  16797. TubeBufferGeometry: TubeBufferGeometry,
  16798. TorusKnotGeometry: TorusKnotGeometry,
  16799. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  16800. TorusGeometry: TorusGeometry,
  16801. TorusBufferGeometry: TorusBufferGeometry,
  16802. TextGeometry: TextGeometry,
  16803. SphereBufferGeometry: SphereBufferGeometry,
  16804. SphereGeometry: SphereGeometry,
  16805. RingGeometry: RingGeometry,
  16806. RingBufferGeometry: RingBufferGeometry,
  16807. PlaneBufferGeometry: PlaneBufferGeometry,
  16808. PlaneGeometry: PlaneGeometry,
  16809. LatheGeometry: LatheGeometry,
  16810. LatheBufferGeometry: LatheBufferGeometry,
  16811. ShapeGeometry: ShapeGeometry,
  16812. ShapeBufferGeometry: ShapeBufferGeometry,
  16813. ExtrudeGeometry: ExtrudeGeometry,
  16814. EdgesGeometry: EdgesGeometry,
  16815. ConeGeometry: ConeGeometry,
  16816. ConeBufferGeometry: ConeBufferGeometry,
  16817. CylinderGeometry: CylinderGeometry,
  16818. CylinderBufferGeometry: CylinderBufferGeometry,
  16819. CircleBufferGeometry: CircleBufferGeometry,
  16820. CircleGeometry: CircleGeometry,
  16821. BoxBufferGeometry: BoxBufferGeometry,
  16822. BoxGeometry: BoxGeometry
  16823. });
  16824. /**
  16825. * @author mrdoob / http://mrdoob.com/
  16826. */
  16827. function ShadowMaterial() {
  16828. ShaderMaterial.call( this, {
  16829. uniforms: UniformsUtils.merge( [
  16830. UniformsLib.lights,
  16831. {
  16832. opacity: { value: 1.0 }
  16833. }
  16834. ] ),
  16835. vertexShader: ShaderChunk[ 'shadow_vert' ],
  16836. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  16837. } );
  16838. this.lights = true;
  16839. this.transparent = true;
  16840. Object.defineProperties( this, {
  16841. opacity: {
  16842. enumerable: true,
  16843. get: function () {
  16844. return this.uniforms.opacity.value;
  16845. },
  16846. set: function ( value ) {
  16847. this.uniforms.opacity.value = value;
  16848. }
  16849. }
  16850. } );
  16851. }
  16852. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16853. ShadowMaterial.prototype.constructor = ShadowMaterial;
  16854. ShadowMaterial.prototype.isShadowMaterial = true;
  16855. /**
  16856. * @author mrdoob / http://mrdoob.com/
  16857. */
  16858. function RawShaderMaterial( parameters ) {
  16859. ShaderMaterial.call( this, parameters );
  16860. this.type = 'RawShaderMaterial';
  16861. }
  16862. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  16863. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  16864. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  16865. /**
  16866. * @author mrdoob / http://mrdoob.com/
  16867. */
  16868. function MultiMaterial( materials ) {
  16869. this.uuid = _Math.generateUUID();
  16870. this.type = 'MultiMaterial';
  16871. this.materials = Array.isArray( materials ) ? materials : [];
  16872. this.visible = true;
  16873. }
  16874. MultiMaterial.prototype = {
  16875. constructor: MultiMaterial,
  16876. isMultiMaterial: true,
  16877. toJSON: function ( meta ) {
  16878. var output = {
  16879. metadata: {
  16880. version: 4.2,
  16881. type: 'material',
  16882. generator: 'MaterialExporter'
  16883. },
  16884. uuid: this.uuid,
  16885. type: this.type,
  16886. materials: []
  16887. };
  16888. var materials = this.materials;
  16889. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16890. var material = materials[ i ].toJSON( meta );
  16891. delete material.metadata;
  16892. output.materials.push( material );
  16893. }
  16894. output.visible = this.visible;
  16895. return output;
  16896. },
  16897. clone: function () {
  16898. var material = new this.constructor();
  16899. for ( var i = 0; i < this.materials.length; i ++ ) {
  16900. material.materials.push( this.materials[ i ].clone() );
  16901. }
  16902. material.visible = this.visible;
  16903. return material;
  16904. }
  16905. };
  16906. /**
  16907. * @author WestLangley / http://github.com/WestLangley
  16908. *
  16909. * parameters = {
  16910. * color: <hex>,
  16911. * roughness: <float>,
  16912. * metalness: <float>,
  16913. * opacity: <float>,
  16914. *
  16915. * map: new THREE.Texture( <Image> ),
  16916. *
  16917. * lightMap: new THREE.Texture( <Image> ),
  16918. * lightMapIntensity: <float>
  16919. *
  16920. * aoMap: new THREE.Texture( <Image> ),
  16921. * aoMapIntensity: <float>
  16922. *
  16923. * emissive: <hex>,
  16924. * emissiveIntensity: <float>
  16925. * emissiveMap: new THREE.Texture( <Image> ),
  16926. *
  16927. * bumpMap: new THREE.Texture( <Image> ),
  16928. * bumpScale: <float>,
  16929. *
  16930. * normalMap: new THREE.Texture( <Image> ),
  16931. * normalScale: <Vector2>,
  16932. *
  16933. * displacementMap: new THREE.Texture( <Image> ),
  16934. * displacementScale: <float>,
  16935. * displacementBias: <float>,
  16936. *
  16937. * roughnessMap: new THREE.Texture( <Image> ),
  16938. *
  16939. * metalnessMap: new THREE.Texture( <Image> ),
  16940. *
  16941. * alphaMap: new THREE.Texture( <Image> ),
  16942. *
  16943. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  16944. * envMapIntensity: <float>
  16945. *
  16946. * refractionRatio: <float>,
  16947. *
  16948. * wireframe: <boolean>,
  16949. * wireframeLinewidth: <float>,
  16950. *
  16951. * skinning: <bool>,
  16952. * morphTargets: <bool>,
  16953. * morphNormals: <bool>
  16954. * }
  16955. */
  16956. function MeshStandardMaterial( parameters ) {
  16957. Material.call( this );
  16958. this.defines = { 'STANDARD': '' };
  16959. this.type = 'MeshStandardMaterial';
  16960. this.color = new Color( 0xffffff ); // diffuse
  16961. this.roughness = 0.5;
  16962. this.metalness = 0.5;
  16963. this.map = null;
  16964. this.lightMap = null;
  16965. this.lightMapIntensity = 1.0;
  16966. this.aoMap = null;
  16967. this.aoMapIntensity = 1.0;
  16968. this.emissive = new Color( 0x000000 );
  16969. this.emissiveIntensity = 1.0;
  16970. this.emissiveMap = null;
  16971. this.bumpMap = null;
  16972. this.bumpScale = 1;
  16973. this.normalMap = null;
  16974. this.normalScale = new Vector2( 1, 1 );
  16975. this.displacementMap = null;
  16976. this.displacementScale = 1;
  16977. this.displacementBias = 0;
  16978. this.roughnessMap = null;
  16979. this.metalnessMap = null;
  16980. this.alphaMap = null;
  16981. this.envMap = null;
  16982. this.envMapIntensity = 1.0;
  16983. this.refractionRatio = 0.98;
  16984. this.wireframe = false;
  16985. this.wireframeLinewidth = 1;
  16986. this.wireframeLinecap = 'round';
  16987. this.wireframeLinejoin = 'round';
  16988. this.skinning = false;
  16989. this.morphTargets = false;
  16990. this.morphNormals = false;
  16991. this.setValues( parameters );
  16992. }
  16993. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  16994. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  16995. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  16996. MeshStandardMaterial.prototype.copy = function ( source ) {
  16997. Material.prototype.copy.call( this, source );
  16998. this.defines = { 'STANDARD': '' };
  16999. this.color.copy( source.color );
  17000. this.roughness = source.roughness;
  17001. this.metalness = source.metalness;
  17002. this.map = source.map;
  17003. this.lightMap = source.lightMap;
  17004. this.lightMapIntensity = source.lightMapIntensity;
  17005. this.aoMap = source.aoMap;
  17006. this.aoMapIntensity = source.aoMapIntensity;
  17007. this.emissive.copy( source.emissive );
  17008. this.emissiveMap = source.emissiveMap;
  17009. this.emissiveIntensity = source.emissiveIntensity;
  17010. this.bumpMap = source.bumpMap;
  17011. this.bumpScale = source.bumpScale;
  17012. this.normalMap = source.normalMap;
  17013. this.normalScale.copy( source.normalScale );
  17014. this.displacementMap = source.displacementMap;
  17015. this.displacementScale = source.displacementScale;
  17016. this.displacementBias = source.displacementBias;
  17017. this.roughnessMap = source.roughnessMap;
  17018. this.metalnessMap = source.metalnessMap;
  17019. this.alphaMap = source.alphaMap;
  17020. this.envMap = source.envMap;
  17021. this.envMapIntensity = source.envMapIntensity;
  17022. this.refractionRatio = source.refractionRatio;
  17023. this.wireframe = source.wireframe;
  17024. this.wireframeLinewidth = source.wireframeLinewidth;
  17025. this.wireframeLinecap = source.wireframeLinecap;
  17026. this.wireframeLinejoin = source.wireframeLinejoin;
  17027. this.skinning = source.skinning;
  17028. this.morphTargets = source.morphTargets;
  17029. this.morphNormals = source.morphNormals;
  17030. return this;
  17031. };
  17032. /**
  17033. * @author WestLangley / http://github.com/WestLangley
  17034. *
  17035. * parameters = {
  17036. * reflectivity: <float>
  17037. * }
  17038. */
  17039. function MeshPhysicalMaterial( parameters ) {
  17040. MeshStandardMaterial.call( this );
  17041. this.defines = { 'PHYSICAL': '' };
  17042. this.type = 'MeshPhysicalMaterial';
  17043. this.reflectivity = 0.5; // maps to F0 = 0.04
  17044. this.clearCoat = 0.0;
  17045. this.clearCoatRoughness = 0.0;
  17046. this.setValues( parameters );
  17047. }
  17048. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  17049. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  17050. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  17051. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  17052. MeshStandardMaterial.prototype.copy.call( this, source );
  17053. this.defines = { 'PHYSICAL': '' };
  17054. this.reflectivity = source.reflectivity;
  17055. this.clearCoat = source.clearCoat;
  17056. this.clearCoatRoughness = source.clearCoatRoughness;
  17057. return this;
  17058. };
  17059. /**
  17060. * @author mrdoob / http://mrdoob.com/
  17061. * @author alteredq / http://alteredqualia.com/
  17062. *
  17063. * parameters = {
  17064. * color: <hex>,
  17065. * specular: <hex>,
  17066. * shininess: <float>,
  17067. * opacity: <float>,
  17068. *
  17069. * map: new THREE.Texture( <Image> ),
  17070. *
  17071. * lightMap: new THREE.Texture( <Image> ),
  17072. * lightMapIntensity: <float>
  17073. *
  17074. * aoMap: new THREE.Texture( <Image> ),
  17075. * aoMapIntensity: <float>
  17076. *
  17077. * emissive: <hex>,
  17078. * emissiveIntensity: <float>
  17079. * emissiveMap: new THREE.Texture( <Image> ),
  17080. *
  17081. * bumpMap: new THREE.Texture( <Image> ),
  17082. * bumpScale: <float>,
  17083. *
  17084. * normalMap: new THREE.Texture( <Image> ),
  17085. * normalScale: <Vector2>,
  17086. *
  17087. * displacementMap: new THREE.Texture( <Image> ),
  17088. * displacementScale: <float>,
  17089. * displacementBias: <float>,
  17090. *
  17091. * specularMap: new THREE.Texture( <Image> ),
  17092. *
  17093. * alphaMap: new THREE.Texture( <Image> ),
  17094. *
  17095. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17096. * combine: THREE.Multiply,
  17097. * reflectivity: <float>,
  17098. * refractionRatio: <float>,
  17099. *
  17100. * wireframe: <boolean>,
  17101. * wireframeLinewidth: <float>,
  17102. *
  17103. * skinning: <bool>,
  17104. * morphTargets: <bool>,
  17105. * morphNormals: <bool>
  17106. * }
  17107. */
  17108. function MeshPhongMaterial( parameters ) {
  17109. Material.call( this );
  17110. this.type = 'MeshPhongMaterial';
  17111. this.color = new Color( 0xffffff ); // diffuse
  17112. this.specular = new Color( 0x111111 );
  17113. this.shininess = 30;
  17114. this.map = null;
  17115. this.lightMap = null;
  17116. this.lightMapIntensity = 1.0;
  17117. this.aoMap = null;
  17118. this.aoMapIntensity = 1.0;
  17119. this.emissive = new Color( 0x000000 );
  17120. this.emissiveIntensity = 1.0;
  17121. this.emissiveMap = null;
  17122. this.bumpMap = null;
  17123. this.bumpScale = 1;
  17124. this.normalMap = null;
  17125. this.normalScale = new Vector2( 1, 1 );
  17126. this.displacementMap = null;
  17127. this.displacementScale = 1;
  17128. this.displacementBias = 0;
  17129. this.specularMap = null;
  17130. this.alphaMap = null;
  17131. this.envMap = null;
  17132. this.combine = MultiplyOperation;
  17133. this.reflectivity = 1;
  17134. this.refractionRatio = 0.98;
  17135. this.wireframe = false;
  17136. this.wireframeLinewidth = 1;
  17137. this.wireframeLinecap = 'round';
  17138. this.wireframeLinejoin = 'round';
  17139. this.skinning = false;
  17140. this.morphTargets = false;
  17141. this.morphNormals = false;
  17142. this.setValues( parameters );
  17143. }
  17144. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  17145. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  17146. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  17147. MeshPhongMaterial.prototype.copy = function ( source ) {
  17148. Material.prototype.copy.call( this, source );
  17149. this.color.copy( source.color );
  17150. this.specular.copy( source.specular );
  17151. this.shininess = source.shininess;
  17152. this.map = source.map;
  17153. this.lightMap = source.lightMap;
  17154. this.lightMapIntensity = source.lightMapIntensity;
  17155. this.aoMap = source.aoMap;
  17156. this.aoMapIntensity = source.aoMapIntensity;
  17157. this.emissive.copy( source.emissive );
  17158. this.emissiveMap = source.emissiveMap;
  17159. this.emissiveIntensity = source.emissiveIntensity;
  17160. this.bumpMap = source.bumpMap;
  17161. this.bumpScale = source.bumpScale;
  17162. this.normalMap = source.normalMap;
  17163. this.normalScale.copy( source.normalScale );
  17164. this.displacementMap = source.displacementMap;
  17165. this.displacementScale = source.displacementScale;
  17166. this.displacementBias = source.displacementBias;
  17167. this.specularMap = source.specularMap;
  17168. this.alphaMap = source.alphaMap;
  17169. this.envMap = source.envMap;
  17170. this.combine = source.combine;
  17171. this.reflectivity = source.reflectivity;
  17172. this.refractionRatio = source.refractionRatio;
  17173. this.wireframe = source.wireframe;
  17174. this.wireframeLinewidth = source.wireframeLinewidth;
  17175. this.wireframeLinecap = source.wireframeLinecap;
  17176. this.wireframeLinejoin = source.wireframeLinejoin;
  17177. this.skinning = source.skinning;
  17178. this.morphTargets = source.morphTargets;
  17179. this.morphNormals = source.morphNormals;
  17180. return this;
  17181. };
  17182. /**
  17183. * @author takahirox / http://github.com/takahirox
  17184. *
  17185. * parameters = {
  17186. * gradientMap: new THREE.Texture( <Image> )
  17187. * }
  17188. */
  17189. function MeshToonMaterial( parameters ) {
  17190. MeshPhongMaterial.call( this );
  17191. this.defines = { 'TOON': '' };
  17192. this.type = 'MeshToonMaterial';
  17193. this.gradientMap = null;
  17194. this.setValues( parameters );
  17195. }
  17196. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  17197. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  17198. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  17199. MeshToonMaterial.prototype.copy = function ( source ) {
  17200. MeshPhongMaterial.prototype.copy.call( this, source );
  17201. this.gradientMap = source.gradientMap;
  17202. return this;
  17203. };
  17204. /**
  17205. * @author mrdoob / http://mrdoob.com/
  17206. * @author WestLangley / http://github.com/WestLangley
  17207. *
  17208. * parameters = {
  17209. * opacity: <float>,
  17210. *
  17211. * bumpMap: new THREE.Texture( <Image> ),
  17212. * bumpScale: <float>,
  17213. *
  17214. * normalMap: new THREE.Texture( <Image> ),
  17215. * normalScale: <Vector2>,
  17216. *
  17217. * displacementMap: new THREE.Texture( <Image> ),
  17218. * displacementScale: <float>,
  17219. * displacementBias: <float>,
  17220. *
  17221. * wireframe: <boolean>,
  17222. * wireframeLinewidth: <float>
  17223. *
  17224. * skinning: <bool>,
  17225. * morphTargets: <bool>,
  17226. * morphNormals: <bool>
  17227. * }
  17228. */
  17229. function MeshNormalMaterial( parameters ) {
  17230. Material.call( this, parameters );
  17231. this.type = 'MeshNormalMaterial';
  17232. this.bumpMap = null;
  17233. this.bumpScale = 1;
  17234. this.normalMap = null;
  17235. this.normalScale = new Vector2( 1, 1 );
  17236. this.displacementMap = null;
  17237. this.displacementScale = 1;
  17238. this.displacementBias = 0;
  17239. this.wireframe = false;
  17240. this.wireframeLinewidth = 1;
  17241. this.fog = false;
  17242. this.lights = false;
  17243. this.skinning = false;
  17244. this.morphTargets = false;
  17245. this.morphNormals = false;
  17246. this.setValues( parameters );
  17247. }
  17248. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  17249. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  17250. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  17251. MeshNormalMaterial.prototype.copy = function ( source ) {
  17252. Material.prototype.copy.call( this, source );
  17253. this.bumpMap = source.bumpMap;
  17254. this.bumpScale = source.bumpScale;
  17255. this.normalMap = source.normalMap;
  17256. this.normalScale.copy( source.normalScale );
  17257. this.displacementMap = source.displacementMap;
  17258. this.displacementScale = source.displacementScale;
  17259. this.displacementBias = source.displacementBias;
  17260. this.wireframe = source.wireframe;
  17261. this.wireframeLinewidth = source.wireframeLinewidth;
  17262. this.skinning = source.skinning;
  17263. this.morphTargets = source.morphTargets;
  17264. this.morphNormals = source.morphNormals;
  17265. return this;
  17266. };
  17267. /**
  17268. * @author mrdoob / http://mrdoob.com/
  17269. * @author alteredq / http://alteredqualia.com/
  17270. *
  17271. * parameters = {
  17272. * color: <hex>,
  17273. * opacity: <float>,
  17274. *
  17275. * map: new THREE.Texture( <Image> ),
  17276. *
  17277. * lightMap: new THREE.Texture( <Image> ),
  17278. * lightMapIntensity: <float>
  17279. *
  17280. * aoMap: new THREE.Texture( <Image> ),
  17281. * aoMapIntensity: <float>
  17282. *
  17283. * emissive: <hex>,
  17284. * emissiveIntensity: <float>
  17285. * emissiveMap: new THREE.Texture( <Image> ),
  17286. *
  17287. * specularMap: new THREE.Texture( <Image> ),
  17288. *
  17289. * alphaMap: new THREE.Texture( <Image> ),
  17290. *
  17291. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  17292. * combine: THREE.Multiply,
  17293. * reflectivity: <float>,
  17294. * refractionRatio: <float>,
  17295. *
  17296. * wireframe: <boolean>,
  17297. * wireframeLinewidth: <float>,
  17298. *
  17299. * skinning: <bool>,
  17300. * morphTargets: <bool>,
  17301. * morphNormals: <bool>
  17302. * }
  17303. */
  17304. function MeshLambertMaterial( parameters ) {
  17305. Material.call( this );
  17306. this.type = 'MeshLambertMaterial';
  17307. this.color = new Color( 0xffffff ); // diffuse
  17308. this.map = null;
  17309. this.lightMap = null;
  17310. this.lightMapIntensity = 1.0;
  17311. this.aoMap = null;
  17312. this.aoMapIntensity = 1.0;
  17313. this.emissive = new Color( 0x000000 );
  17314. this.emissiveIntensity = 1.0;
  17315. this.emissiveMap = null;
  17316. this.specularMap = null;
  17317. this.alphaMap = null;
  17318. this.envMap = null;
  17319. this.combine = MultiplyOperation;
  17320. this.reflectivity = 1;
  17321. this.refractionRatio = 0.98;
  17322. this.wireframe = false;
  17323. this.wireframeLinewidth = 1;
  17324. this.wireframeLinecap = 'round';
  17325. this.wireframeLinejoin = 'round';
  17326. this.skinning = false;
  17327. this.morphTargets = false;
  17328. this.morphNormals = false;
  17329. this.setValues( parameters );
  17330. }
  17331. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  17332. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  17333. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  17334. MeshLambertMaterial.prototype.copy = function ( source ) {
  17335. Material.prototype.copy.call( this, source );
  17336. this.color.copy( source.color );
  17337. this.map = source.map;
  17338. this.lightMap = source.lightMap;
  17339. this.lightMapIntensity = source.lightMapIntensity;
  17340. this.aoMap = source.aoMap;
  17341. this.aoMapIntensity = source.aoMapIntensity;
  17342. this.emissive.copy( source.emissive );
  17343. this.emissiveMap = source.emissiveMap;
  17344. this.emissiveIntensity = source.emissiveIntensity;
  17345. this.specularMap = source.specularMap;
  17346. this.alphaMap = source.alphaMap;
  17347. this.envMap = source.envMap;
  17348. this.combine = source.combine;
  17349. this.reflectivity = source.reflectivity;
  17350. this.refractionRatio = source.refractionRatio;
  17351. this.wireframe = source.wireframe;
  17352. this.wireframeLinewidth = source.wireframeLinewidth;
  17353. this.wireframeLinecap = source.wireframeLinecap;
  17354. this.wireframeLinejoin = source.wireframeLinejoin;
  17355. this.skinning = source.skinning;
  17356. this.morphTargets = source.morphTargets;
  17357. this.morphNormals = source.morphNormals;
  17358. return this;
  17359. };
  17360. /**
  17361. * @author alteredq / http://alteredqualia.com/
  17362. *
  17363. * parameters = {
  17364. * color: <hex>,
  17365. * opacity: <float>,
  17366. *
  17367. * linewidth: <float>,
  17368. *
  17369. * scale: <float>,
  17370. * dashSize: <float>,
  17371. * gapSize: <float>
  17372. * }
  17373. */
  17374. function LineDashedMaterial( parameters ) {
  17375. Material.call( this );
  17376. this.type = 'LineDashedMaterial';
  17377. this.color = new Color( 0xffffff );
  17378. this.linewidth = 1;
  17379. this.scale = 1;
  17380. this.dashSize = 3;
  17381. this.gapSize = 1;
  17382. this.lights = false;
  17383. this.setValues( parameters );
  17384. }
  17385. LineDashedMaterial.prototype = Object.create( Material.prototype );
  17386. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  17387. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  17388. LineDashedMaterial.prototype.copy = function ( source ) {
  17389. Material.prototype.copy.call( this, source );
  17390. this.color.copy( source.color );
  17391. this.linewidth = source.linewidth;
  17392. this.scale = source.scale;
  17393. this.dashSize = source.dashSize;
  17394. this.gapSize = source.gapSize;
  17395. return this;
  17396. };
  17397. var Materials = Object.freeze({
  17398. ShadowMaterial: ShadowMaterial,
  17399. SpriteMaterial: SpriteMaterial,
  17400. RawShaderMaterial: RawShaderMaterial,
  17401. ShaderMaterial: ShaderMaterial,
  17402. PointsMaterial: PointsMaterial,
  17403. MultiMaterial: MultiMaterial,
  17404. MeshPhysicalMaterial: MeshPhysicalMaterial,
  17405. MeshStandardMaterial: MeshStandardMaterial,
  17406. MeshPhongMaterial: MeshPhongMaterial,
  17407. MeshToonMaterial: MeshToonMaterial,
  17408. MeshNormalMaterial: MeshNormalMaterial,
  17409. MeshLambertMaterial: MeshLambertMaterial,
  17410. MeshDepthMaterial: MeshDepthMaterial,
  17411. MeshBasicMaterial: MeshBasicMaterial,
  17412. LineDashedMaterial: LineDashedMaterial,
  17413. LineBasicMaterial: LineBasicMaterial,
  17414. Material: Material
  17415. });
  17416. /**
  17417. * @author mrdoob / http://mrdoob.com/
  17418. */
  17419. var Cache = {
  17420. enabled: false,
  17421. files: {},
  17422. add: function ( key, file ) {
  17423. if ( this.enabled === false ) return;
  17424. // console.log( 'THREE.Cache', 'Adding key:', key );
  17425. this.files[ key ] = file;
  17426. },
  17427. get: function ( key ) {
  17428. if ( this.enabled === false ) return;
  17429. // console.log( 'THREE.Cache', 'Checking key:', key );
  17430. return this.files[ key ];
  17431. },
  17432. remove: function ( key ) {
  17433. delete this.files[ key ];
  17434. },
  17435. clear: function () {
  17436. this.files = {};
  17437. }
  17438. };
  17439. /**
  17440. * @author mrdoob / http://mrdoob.com/
  17441. */
  17442. function LoadingManager( onLoad, onProgress, onError ) {
  17443. var scope = this;
  17444. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  17445. this.onStart = undefined;
  17446. this.onLoad = onLoad;
  17447. this.onProgress = onProgress;
  17448. this.onError = onError;
  17449. this.itemStart = function ( url ) {
  17450. itemsTotal ++;
  17451. if ( isLoading === false ) {
  17452. if ( scope.onStart !== undefined ) {
  17453. scope.onStart( url, itemsLoaded, itemsTotal );
  17454. }
  17455. }
  17456. isLoading = true;
  17457. };
  17458. this.itemEnd = function ( url ) {
  17459. itemsLoaded ++;
  17460. if ( scope.onProgress !== undefined ) {
  17461. scope.onProgress( url, itemsLoaded, itemsTotal );
  17462. }
  17463. if ( itemsLoaded === itemsTotal ) {
  17464. isLoading = false;
  17465. if ( scope.onLoad !== undefined ) {
  17466. scope.onLoad();
  17467. }
  17468. }
  17469. };
  17470. this.itemError = function ( url ) {
  17471. if ( scope.onError !== undefined ) {
  17472. scope.onError( url );
  17473. }
  17474. };
  17475. }
  17476. var DefaultLoadingManager = new LoadingManager();
  17477. /**
  17478. * @author mrdoob / http://mrdoob.com/
  17479. */
  17480. function FileLoader( manager ) {
  17481. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17482. }
  17483. Object.assign( FileLoader.prototype, {
  17484. load: function ( url, onLoad, onProgress, onError ) {
  17485. if ( url === undefined ) url = '';
  17486. if ( this.path !== undefined ) url = this.path + url;
  17487. var scope = this;
  17488. var cached = Cache.get( url );
  17489. if ( cached !== undefined ) {
  17490. scope.manager.itemStart( url );
  17491. setTimeout( function () {
  17492. if ( onLoad ) onLoad( cached );
  17493. scope.manager.itemEnd( url );
  17494. }, 0 );
  17495. return cached;
  17496. }
  17497. // Check for data: URI
  17498. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  17499. var dataUriRegexResult = url.match( dataUriRegex );
  17500. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  17501. if ( dataUriRegexResult ) {
  17502. var mimeType = dataUriRegexResult[ 1 ];
  17503. var isBase64 = !! dataUriRegexResult[ 2 ];
  17504. var data = dataUriRegexResult[ 3 ];
  17505. data = window.decodeURIComponent( data );
  17506. if ( isBase64 ) data = window.atob( data );
  17507. try {
  17508. var response;
  17509. var responseType = ( this.responseType || '' ).toLowerCase();
  17510. switch ( responseType ) {
  17511. case 'arraybuffer':
  17512. case 'blob':
  17513. response = new ArrayBuffer( data.length );
  17514. var view = new Uint8Array( response );
  17515. for ( var i = 0; i < data.length; i ++ ) {
  17516. view[ i ] = data.charCodeAt( i );
  17517. }
  17518. if ( responseType === 'blob' ) {
  17519. response = new Blob( [ response ], { type: mimeType } );
  17520. }
  17521. break;
  17522. case 'document':
  17523. var parser = new DOMParser();
  17524. response = parser.parseFromString( data, mimeType );
  17525. break;
  17526. case 'json':
  17527. response = JSON.parse( data );
  17528. break;
  17529. default: // 'text' or other
  17530. response = data;
  17531. break;
  17532. }
  17533. // Wait for next browser tick
  17534. window.setTimeout( function () {
  17535. if ( onLoad ) onLoad( response );
  17536. scope.manager.itemEnd( url );
  17537. }, 0 );
  17538. } catch ( error ) {
  17539. // Wait for next browser tick
  17540. window.setTimeout( function () {
  17541. if ( onError ) onError( error );
  17542. scope.manager.itemError( url );
  17543. }, 0 );
  17544. }
  17545. } else {
  17546. var request = new XMLHttpRequest();
  17547. request.open( 'GET', url, true );
  17548. request.addEventListener( 'load', function ( event ) {
  17549. var response = event.target.response;
  17550. Cache.add( url, response );
  17551. if ( this.status === 200 ) {
  17552. if ( onLoad ) onLoad( response );
  17553. scope.manager.itemEnd( url );
  17554. } else if ( this.status === 0 ) {
  17555. // Some browsers return HTTP Status 0 when using non-http protocol
  17556. // e.g. 'file://' or 'data://'. Handle as success.
  17557. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17558. if ( onLoad ) onLoad( response );
  17559. scope.manager.itemEnd( url );
  17560. } else {
  17561. if ( onError ) onError( event );
  17562. scope.manager.itemError( url );
  17563. }
  17564. }, false );
  17565. if ( onProgress !== undefined ) {
  17566. request.addEventListener( 'progress', function ( event ) {
  17567. onProgress( event );
  17568. }, false );
  17569. }
  17570. request.addEventListener( 'error', function ( event ) {
  17571. if ( onError ) onError( event );
  17572. scope.manager.itemError( url );
  17573. }, false );
  17574. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  17575. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  17576. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  17577. request.send( null );
  17578. }
  17579. scope.manager.itemStart( url );
  17580. return request;
  17581. },
  17582. setPath: function ( value ) {
  17583. this.path = value;
  17584. return this;
  17585. },
  17586. setResponseType: function ( value ) {
  17587. this.responseType = value;
  17588. return this;
  17589. },
  17590. setWithCredentials: function ( value ) {
  17591. this.withCredentials = value;
  17592. return this;
  17593. },
  17594. setMimeType: function ( value ) {
  17595. this.mimeType = value;
  17596. return this;
  17597. }
  17598. } );
  17599. /**
  17600. * @author mrdoob / http://mrdoob.com/
  17601. *
  17602. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17603. */
  17604. function CompressedTextureLoader( manager ) {
  17605. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17606. // override in sub classes
  17607. this._parser = null;
  17608. }
  17609. Object.assign( CompressedTextureLoader.prototype, {
  17610. load: function ( url, onLoad, onProgress, onError ) {
  17611. var scope = this;
  17612. var images = [];
  17613. var texture = new CompressedTexture();
  17614. texture.image = images;
  17615. var loader = new FileLoader( this.manager );
  17616. loader.setPath( this.path );
  17617. loader.setResponseType( 'arraybuffer' );
  17618. function loadTexture( i ) {
  17619. loader.load( url[ i ], function ( buffer ) {
  17620. var texDatas = scope._parser( buffer, true );
  17621. images[ i ] = {
  17622. width: texDatas.width,
  17623. height: texDatas.height,
  17624. format: texDatas.format,
  17625. mipmaps: texDatas.mipmaps
  17626. };
  17627. loaded += 1;
  17628. if ( loaded === 6 ) {
  17629. if ( texDatas.mipmapCount === 1 )
  17630. texture.minFilter = LinearFilter;
  17631. texture.format = texDatas.format;
  17632. texture.needsUpdate = true;
  17633. if ( onLoad ) onLoad( texture );
  17634. }
  17635. }, onProgress, onError );
  17636. }
  17637. if ( Array.isArray( url ) ) {
  17638. var loaded = 0;
  17639. for ( var i = 0, il = url.length; i < il; ++ i ) {
  17640. loadTexture( i );
  17641. }
  17642. } else {
  17643. // compressed cubemap texture stored in a single DDS file
  17644. loader.load( url, function ( buffer ) {
  17645. var texDatas = scope._parser( buffer, true );
  17646. if ( texDatas.isCubemap ) {
  17647. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17648. for ( var f = 0; f < faces; f ++ ) {
  17649. images[ f ] = { mipmaps : [] };
  17650. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  17651. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17652. images[ f ].format = texDatas.format;
  17653. images[ f ].width = texDatas.width;
  17654. images[ f ].height = texDatas.height;
  17655. }
  17656. }
  17657. } else {
  17658. texture.image.width = texDatas.width;
  17659. texture.image.height = texDatas.height;
  17660. texture.mipmaps = texDatas.mipmaps;
  17661. }
  17662. if ( texDatas.mipmapCount === 1 ) {
  17663. texture.minFilter = LinearFilter;
  17664. }
  17665. texture.format = texDatas.format;
  17666. texture.needsUpdate = true;
  17667. if ( onLoad ) onLoad( texture );
  17668. }, onProgress, onError );
  17669. }
  17670. return texture;
  17671. },
  17672. setPath: function ( value ) {
  17673. this.path = value;
  17674. return this;
  17675. }
  17676. } );
  17677. /**
  17678. * @author Nikos M. / https://github.com/foo123/
  17679. *
  17680. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  17681. */
  17682. function DataTextureLoader( manager ) {
  17683. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17684. // override in sub classes
  17685. this._parser = null;
  17686. }
  17687. Object.assign( DataTextureLoader.prototype, {
  17688. load: function ( url, onLoad, onProgress, onError ) {
  17689. var scope = this;
  17690. var texture = new DataTexture();
  17691. var loader = new FileLoader( this.manager );
  17692. loader.setResponseType( 'arraybuffer' );
  17693. loader.load( url, function ( buffer ) {
  17694. var texData = scope._parser( buffer );
  17695. if ( ! texData ) return;
  17696. if ( undefined !== texData.image ) {
  17697. texture.image = texData.image;
  17698. } else if ( undefined !== texData.data ) {
  17699. texture.image.width = texData.width;
  17700. texture.image.height = texData.height;
  17701. texture.image.data = texData.data;
  17702. }
  17703. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  17704. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  17705. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  17706. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  17707. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  17708. if ( undefined !== texData.format ) {
  17709. texture.format = texData.format;
  17710. }
  17711. if ( undefined !== texData.type ) {
  17712. texture.type = texData.type;
  17713. }
  17714. if ( undefined !== texData.mipmaps ) {
  17715. texture.mipmaps = texData.mipmaps;
  17716. }
  17717. if ( 1 === texData.mipmapCount ) {
  17718. texture.minFilter = LinearFilter;
  17719. }
  17720. texture.needsUpdate = true;
  17721. if ( onLoad ) onLoad( texture, texData );
  17722. }, onProgress, onError );
  17723. return texture;
  17724. }
  17725. } );
  17726. /**
  17727. * @author mrdoob / http://mrdoob.com/
  17728. */
  17729. function ImageLoader( manager ) {
  17730. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17731. }
  17732. Object.assign( ImageLoader.prototype, {
  17733. load: function ( url, onLoad, onProgress, onError ) {
  17734. if ( url === undefined ) url = '';
  17735. if ( this.path !== undefined ) url = this.path + url;
  17736. var scope = this;
  17737. var cached = Cache.get( url );
  17738. if ( cached !== undefined ) {
  17739. scope.manager.itemStart( url );
  17740. setTimeout( function () {
  17741. if ( onLoad ) onLoad( cached );
  17742. scope.manager.itemEnd( url );
  17743. }, 0 );
  17744. return cached;
  17745. }
  17746. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  17747. image.addEventListener( 'load', function () {
  17748. Cache.add( url, this );
  17749. if ( onLoad ) onLoad( this );
  17750. scope.manager.itemEnd( url );
  17751. }, false );
  17752. /*
  17753. image.addEventListener( 'progress', function ( event ) {
  17754. if ( onProgress ) onProgress( event );
  17755. }, false );
  17756. */
  17757. image.addEventListener( 'error', function ( event ) {
  17758. if ( onError ) onError( event );
  17759. scope.manager.itemError( url );
  17760. }, false );
  17761. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  17762. scope.manager.itemStart( url );
  17763. image.src = url;
  17764. return image;
  17765. },
  17766. setCrossOrigin: function ( value ) {
  17767. this.crossOrigin = value;
  17768. return this;
  17769. },
  17770. setPath: function ( value ) {
  17771. this.path = value;
  17772. return this;
  17773. }
  17774. } );
  17775. /**
  17776. * @author mrdoob / http://mrdoob.com/
  17777. */
  17778. function CubeTextureLoader( manager ) {
  17779. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17780. }
  17781. Object.assign( CubeTextureLoader.prototype, {
  17782. load: function ( urls, onLoad, onProgress, onError ) {
  17783. var texture = new CubeTexture();
  17784. var loader = new ImageLoader( this.manager );
  17785. loader.setCrossOrigin( this.crossOrigin );
  17786. loader.setPath( this.path );
  17787. var loaded = 0;
  17788. function loadTexture( i ) {
  17789. loader.load( urls[ i ], function ( image ) {
  17790. texture.images[ i ] = image;
  17791. loaded ++;
  17792. if ( loaded === 6 ) {
  17793. texture.needsUpdate = true;
  17794. if ( onLoad ) onLoad( texture );
  17795. }
  17796. }, undefined, onError );
  17797. }
  17798. for ( var i = 0; i < urls.length; ++ i ) {
  17799. loadTexture( i );
  17800. }
  17801. return texture;
  17802. },
  17803. setCrossOrigin: function ( value ) {
  17804. this.crossOrigin = value;
  17805. return this;
  17806. },
  17807. setPath: function ( value ) {
  17808. this.path = value;
  17809. return this;
  17810. }
  17811. } );
  17812. /**
  17813. * @author mrdoob / http://mrdoob.com/
  17814. */
  17815. function TextureLoader( manager ) {
  17816. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17817. }
  17818. Object.assign( TextureLoader.prototype, {
  17819. load: function ( url, onLoad, onProgress, onError ) {
  17820. var texture = new Texture();
  17821. var loader = new ImageLoader( this.manager );
  17822. loader.setCrossOrigin( this.crossOrigin );
  17823. loader.setPath( this.path );
  17824. loader.load( url, function ( image ) {
  17825. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  17826. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  17827. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  17828. texture.image = image;
  17829. texture.needsUpdate = true;
  17830. if ( onLoad !== undefined ) {
  17831. onLoad( texture );
  17832. }
  17833. }, onProgress, onError );
  17834. return texture;
  17835. },
  17836. setCrossOrigin: function ( value ) {
  17837. this.crossOrigin = value;
  17838. return this;
  17839. },
  17840. setPath: function ( value ) {
  17841. this.path = value;
  17842. return this;
  17843. }
  17844. } );
  17845. /**
  17846. * @author mrdoob / http://mrdoob.com/
  17847. * @author alteredq / http://alteredqualia.com/
  17848. */
  17849. function Light( color, intensity ) {
  17850. Object3D.call( this );
  17851. this.type = 'Light';
  17852. this.color = new Color( color );
  17853. this.intensity = intensity !== undefined ? intensity : 1;
  17854. this.receiveShadow = undefined;
  17855. }
  17856. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17857. constructor: Light,
  17858. isLight: true,
  17859. copy: function ( source ) {
  17860. Object3D.prototype.copy.call( this, source );
  17861. this.color.copy( source.color );
  17862. this.intensity = source.intensity;
  17863. return this;
  17864. },
  17865. toJSON: function ( meta ) {
  17866. var data = Object3D.prototype.toJSON.call( this, meta );
  17867. data.object.color = this.color.getHex();
  17868. data.object.intensity = this.intensity;
  17869. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  17870. if ( this.distance !== undefined ) data.object.distance = this.distance;
  17871. if ( this.angle !== undefined ) data.object.angle = this.angle;
  17872. if ( this.decay !== undefined ) data.object.decay = this.decay;
  17873. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  17874. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  17875. return data;
  17876. }
  17877. } );
  17878. /**
  17879. * @author alteredq / http://alteredqualia.com/
  17880. */
  17881. function HemisphereLight( skyColor, groundColor, intensity ) {
  17882. Light.call( this, skyColor, intensity );
  17883. this.type = 'HemisphereLight';
  17884. this.castShadow = undefined;
  17885. this.position.copy( Object3D.DefaultUp );
  17886. this.updateMatrix();
  17887. this.groundColor = new Color( groundColor );
  17888. }
  17889. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17890. constructor: HemisphereLight,
  17891. isHemisphereLight: true,
  17892. copy: function ( source ) {
  17893. Light.prototype.copy.call( this, source );
  17894. this.groundColor.copy( source.groundColor );
  17895. return this;
  17896. }
  17897. } );
  17898. /**
  17899. * @author mrdoob / http://mrdoob.com/
  17900. */
  17901. function LightShadow( camera ) {
  17902. this.camera = camera;
  17903. this.bias = 0;
  17904. this.radius = 1;
  17905. this.mapSize = new Vector2( 512, 512 );
  17906. this.map = null;
  17907. this.matrix = new Matrix4();
  17908. }
  17909. Object.assign( LightShadow.prototype, {
  17910. copy: function ( source ) {
  17911. this.camera = source.camera.clone();
  17912. this.bias = source.bias;
  17913. this.radius = source.radius;
  17914. this.mapSize.copy( source.mapSize );
  17915. return this;
  17916. },
  17917. clone: function () {
  17918. return new this.constructor().copy( this );
  17919. },
  17920. toJSON: function () {
  17921. var object = {};
  17922. if ( this.bias !== 0 ) object.bias = this.bias;
  17923. if ( this.radius !== 1 ) object.radius = this.radius;
  17924. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  17925. object.camera = this.camera.toJSON( false ).object;
  17926. delete object.camera.matrix;
  17927. return object;
  17928. }
  17929. } );
  17930. /**
  17931. * @author mrdoob / http://mrdoob.com/
  17932. */
  17933. function SpotLightShadow() {
  17934. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  17935. }
  17936. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  17937. constructor: SpotLightShadow,
  17938. isSpotLightShadow: true,
  17939. update: function ( light ) {
  17940. var fov = _Math.RAD2DEG * 2 * light.angle;
  17941. var aspect = this.mapSize.width / this.mapSize.height;
  17942. var far = light.distance || 500;
  17943. var camera = this.camera;
  17944. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  17945. camera.fov = fov;
  17946. camera.aspect = aspect;
  17947. camera.far = far;
  17948. camera.updateProjectionMatrix();
  17949. }
  17950. }
  17951. } );
  17952. /**
  17953. * @author alteredq / http://alteredqualia.com/
  17954. */
  17955. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  17956. Light.call( this, color, intensity );
  17957. this.type = 'SpotLight';
  17958. this.position.copy( Object3D.DefaultUp );
  17959. this.updateMatrix();
  17960. this.target = new Object3D();
  17961. Object.defineProperty( this, 'power', {
  17962. get: function () {
  17963. // intensity = power per solid angle.
  17964. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17965. return this.intensity * Math.PI;
  17966. },
  17967. set: function ( power ) {
  17968. // intensity = power per solid angle.
  17969. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  17970. this.intensity = power / Math.PI;
  17971. }
  17972. } );
  17973. this.distance = ( distance !== undefined ) ? distance : 0;
  17974. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  17975. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  17976. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  17977. this.shadow = new SpotLightShadow();
  17978. }
  17979. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  17980. constructor: SpotLight,
  17981. isSpotLight: true,
  17982. copy: function ( source ) {
  17983. Light.prototype.copy.call( this, source );
  17984. this.distance = source.distance;
  17985. this.angle = source.angle;
  17986. this.penumbra = source.penumbra;
  17987. this.decay = source.decay;
  17988. this.target = source.target.clone();
  17989. this.shadow = source.shadow.clone();
  17990. return this;
  17991. }
  17992. } );
  17993. /**
  17994. * @author mrdoob / http://mrdoob.com/
  17995. */
  17996. function PointLight( color, intensity, distance, decay ) {
  17997. Light.call( this, color, intensity );
  17998. this.type = 'PointLight';
  17999. Object.defineProperty( this, 'power', {
  18000. get: function () {
  18001. // intensity = power per solid angle.
  18002. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18003. return this.intensity * 4 * Math.PI;
  18004. },
  18005. set: function ( power ) {
  18006. // intensity = power per solid angle.
  18007. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  18008. this.intensity = power / ( 4 * Math.PI );
  18009. }
  18010. } );
  18011. this.distance = ( distance !== undefined ) ? distance : 0;
  18012. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  18013. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18014. }
  18015. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18016. constructor: PointLight,
  18017. isPointLight: true,
  18018. copy: function ( source ) {
  18019. Light.prototype.copy.call( this, source );
  18020. this.distance = source.distance;
  18021. this.decay = source.decay;
  18022. this.shadow = source.shadow.clone();
  18023. return this;
  18024. }
  18025. } );
  18026. /**
  18027. * @author mrdoob / http://mrdoob.com/
  18028. */
  18029. function DirectionalLightShadow( ) {
  18030. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  18031. }
  18032. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  18033. constructor: DirectionalLightShadow
  18034. } );
  18035. /**
  18036. * @author mrdoob / http://mrdoob.com/
  18037. * @author alteredq / http://alteredqualia.com/
  18038. */
  18039. function DirectionalLight( color, intensity ) {
  18040. Light.call( this, color, intensity );
  18041. this.type = 'DirectionalLight';
  18042. this.position.copy( Object3D.DefaultUp );
  18043. this.updateMatrix();
  18044. this.target = new Object3D();
  18045. this.shadow = new DirectionalLightShadow();
  18046. }
  18047. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18048. constructor: DirectionalLight,
  18049. isDirectionalLight: true,
  18050. copy: function ( source ) {
  18051. Light.prototype.copy.call( this, source );
  18052. this.target = source.target.clone();
  18053. this.shadow = source.shadow.clone();
  18054. return this;
  18055. }
  18056. } );
  18057. /**
  18058. * @author mrdoob / http://mrdoob.com/
  18059. */
  18060. function AmbientLight( color, intensity ) {
  18061. Light.call( this, color, intensity );
  18062. this.type = 'AmbientLight';
  18063. this.castShadow = undefined;
  18064. }
  18065. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  18066. constructor: AmbientLight,
  18067. isAmbientLight: true
  18068. } );
  18069. /**
  18070. * @author tschw
  18071. * @author Ben Houston / http://clara.io/
  18072. * @author David Sarno / http://lighthaus.us/
  18073. */
  18074. var AnimationUtils = {
  18075. // same as Array.prototype.slice, but also works on typed arrays
  18076. arraySlice: function( array, from, to ) {
  18077. if ( AnimationUtils.isTypedArray( array ) ) {
  18078. return new array.constructor( array.subarray( from, to ) );
  18079. }
  18080. return array.slice( from, to );
  18081. },
  18082. // converts an array to a specific type
  18083. convertArray: function( array, type, forceClone ) {
  18084. if ( ! array || // let 'undefined' and 'null' pass
  18085. ! forceClone && array.constructor === type ) return array;
  18086. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  18087. return new type( array ); // create typed array
  18088. }
  18089. return Array.prototype.slice.call( array ); // create Array
  18090. },
  18091. isTypedArray: function( object ) {
  18092. return ArrayBuffer.isView( object ) &&
  18093. ! ( object instanceof DataView );
  18094. },
  18095. // returns an array by which times and values can be sorted
  18096. getKeyframeOrder: function( times ) {
  18097. function compareTime( i, j ) {
  18098. return times[ i ] - times[ j ];
  18099. }
  18100. var n = times.length;
  18101. var result = new Array( n );
  18102. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  18103. result.sort( compareTime );
  18104. return result;
  18105. },
  18106. // uses the array previously returned by 'getKeyframeOrder' to sort data
  18107. sortedArray: function( values, stride, order ) {
  18108. var nValues = values.length;
  18109. var result = new values.constructor( nValues );
  18110. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  18111. var srcOffset = order[ i ] * stride;
  18112. for ( var j = 0; j !== stride; ++ j ) {
  18113. result[ dstOffset ++ ] = values[ srcOffset + j ];
  18114. }
  18115. }
  18116. return result;
  18117. },
  18118. // function for parsing AOS keyframe formats
  18119. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  18120. var i = 1, key = jsonKeys[ 0 ];
  18121. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  18122. key = jsonKeys[ i ++ ];
  18123. }
  18124. if ( key === undefined ) return; // no data
  18125. var value = key[ valuePropertyName ];
  18126. if ( value === undefined ) return; // no data
  18127. if ( Array.isArray( value ) ) {
  18128. do {
  18129. value = key[ valuePropertyName ];
  18130. if ( value !== undefined ) {
  18131. times.push( key.time );
  18132. values.push.apply( values, value ); // push all elements
  18133. }
  18134. key = jsonKeys[ i ++ ];
  18135. } while ( key !== undefined );
  18136. } else if ( value.toArray !== undefined ) {
  18137. // ...assume THREE.Math-ish
  18138. do {
  18139. value = key[ valuePropertyName ];
  18140. if ( value !== undefined ) {
  18141. times.push( key.time );
  18142. value.toArray( values, values.length );
  18143. }
  18144. key = jsonKeys[ i ++ ];
  18145. } while ( key !== undefined );
  18146. } else {
  18147. // otherwise push as-is
  18148. do {
  18149. value = key[ valuePropertyName ];
  18150. if ( value !== undefined ) {
  18151. times.push( key.time );
  18152. values.push( value );
  18153. }
  18154. key = jsonKeys[ i ++ ];
  18155. } while ( key !== undefined );
  18156. }
  18157. }
  18158. };
  18159. /**
  18160. * Abstract base class of interpolants over parametric samples.
  18161. *
  18162. * The parameter domain is one dimensional, typically the time or a path
  18163. * along a curve defined by the data.
  18164. *
  18165. * The sample values can have any dimensionality and derived classes may
  18166. * apply special interpretations to the data.
  18167. *
  18168. * This class provides the interval seek in a Template Method, deferring
  18169. * the actual interpolation to derived classes.
  18170. *
  18171. * Time complexity is O(1) for linear access crossing at most two points
  18172. * and O(log N) for random access, where N is the number of positions.
  18173. *
  18174. * References:
  18175. *
  18176. * http://www.oodesign.com/template-method-pattern.html
  18177. *
  18178. * @author tschw
  18179. */
  18180. function Interpolant(
  18181. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18182. this.parameterPositions = parameterPositions;
  18183. this._cachedIndex = 0;
  18184. this.resultBuffer = resultBuffer !== undefined ?
  18185. resultBuffer : new sampleValues.constructor( sampleSize );
  18186. this.sampleValues = sampleValues;
  18187. this.valueSize = sampleSize;
  18188. }
  18189. Interpolant.prototype = {
  18190. constructor: Interpolant,
  18191. evaluate: function( t ) {
  18192. var pp = this.parameterPositions,
  18193. i1 = this._cachedIndex,
  18194. t1 = pp[ i1 ],
  18195. t0 = pp[ i1 - 1 ];
  18196. validate_interval: {
  18197. seek: {
  18198. var right;
  18199. linear_scan: {
  18200. //- See http://jsperf.com/comparison-to-undefined/3
  18201. //- slower code:
  18202. //-
  18203. //- if ( t >= t1 || t1 === undefined ) {
  18204. forward_scan: if ( ! ( t < t1 ) ) {
  18205. for ( var giveUpAt = i1 + 2; ;) {
  18206. if ( t1 === undefined ) {
  18207. if ( t < t0 ) break forward_scan;
  18208. // after end
  18209. i1 = pp.length;
  18210. this._cachedIndex = i1;
  18211. return this.afterEnd_( i1 - 1, t, t0 );
  18212. }
  18213. if ( i1 === giveUpAt ) break; // this loop
  18214. t0 = t1;
  18215. t1 = pp[ ++ i1 ];
  18216. if ( t < t1 ) {
  18217. // we have arrived at the sought interval
  18218. break seek;
  18219. }
  18220. }
  18221. // prepare binary search on the right side of the index
  18222. right = pp.length;
  18223. break linear_scan;
  18224. }
  18225. //- slower code:
  18226. //- if ( t < t0 || t0 === undefined ) {
  18227. if ( ! ( t >= t0 ) ) {
  18228. // looping?
  18229. var t1global = pp[ 1 ];
  18230. if ( t < t1global ) {
  18231. i1 = 2; // + 1, using the scan for the details
  18232. t0 = t1global;
  18233. }
  18234. // linear reverse scan
  18235. for ( var giveUpAt = i1 - 2; ;) {
  18236. if ( t0 === undefined ) {
  18237. // before start
  18238. this._cachedIndex = 0;
  18239. return this.beforeStart_( 0, t, t1 );
  18240. }
  18241. if ( i1 === giveUpAt ) break; // this loop
  18242. t1 = t0;
  18243. t0 = pp[ -- i1 - 1 ];
  18244. if ( t >= t0 ) {
  18245. // we have arrived at the sought interval
  18246. break seek;
  18247. }
  18248. }
  18249. // prepare binary search on the left side of the index
  18250. right = i1;
  18251. i1 = 0;
  18252. break linear_scan;
  18253. }
  18254. // the interval is valid
  18255. break validate_interval;
  18256. } // linear scan
  18257. // binary search
  18258. while ( i1 < right ) {
  18259. var mid = ( i1 + right ) >>> 1;
  18260. if ( t < pp[ mid ] ) {
  18261. right = mid;
  18262. } else {
  18263. i1 = mid + 1;
  18264. }
  18265. }
  18266. t1 = pp[ i1 ];
  18267. t0 = pp[ i1 - 1 ];
  18268. // check boundary cases, again
  18269. if ( t0 === undefined ) {
  18270. this._cachedIndex = 0;
  18271. return this.beforeStart_( 0, t, t1 );
  18272. }
  18273. if ( t1 === undefined ) {
  18274. i1 = pp.length;
  18275. this._cachedIndex = i1;
  18276. return this.afterEnd_( i1 - 1, t0, t );
  18277. }
  18278. } // seek
  18279. this._cachedIndex = i1;
  18280. this.intervalChanged_( i1, t0, t1 );
  18281. } // validate_interval
  18282. return this.interpolate_( i1, t0, t, t1 );
  18283. },
  18284. settings: null, // optional, subclass-specific settings structure
  18285. // Note: The indirection allows central control of many interpolants.
  18286. // --- Protected interface
  18287. DefaultSettings_: {},
  18288. getSettings_: function() {
  18289. return this.settings || this.DefaultSettings_;
  18290. },
  18291. copySampleValue_: function( index ) {
  18292. // copies a sample value to the result buffer
  18293. var result = this.resultBuffer,
  18294. values = this.sampleValues,
  18295. stride = this.valueSize,
  18296. offset = index * stride;
  18297. for ( var i = 0; i !== stride; ++ i ) {
  18298. result[ i ] = values[ offset + i ];
  18299. }
  18300. return result;
  18301. },
  18302. // Template methods for derived classes:
  18303. interpolate_: function( i1, t0, t, t1 ) {
  18304. throw new Error( "call to abstract method" );
  18305. // implementations shall return this.resultBuffer
  18306. },
  18307. intervalChanged_: function( i1, t0, t1 ) {
  18308. // empty
  18309. }
  18310. };
  18311. Object.assign( Interpolant.prototype, {
  18312. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  18313. Interpolant.prototype.copySampleValue_,
  18314. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  18315. Interpolant.prototype.copySampleValue_
  18316. } );
  18317. /**
  18318. * Fast and simple cubic spline interpolant.
  18319. *
  18320. * It was derived from a Hermitian construction setting the first derivative
  18321. * at each sample position to the linear slope between neighboring positions
  18322. * over their parameter interval.
  18323. *
  18324. * @author tschw
  18325. */
  18326. function CubicInterpolant(
  18327. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18328. Interpolant.call(
  18329. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18330. this._weightPrev = -0;
  18331. this._offsetPrev = -0;
  18332. this._weightNext = -0;
  18333. this._offsetNext = -0;
  18334. }
  18335. CubicInterpolant.prototype =
  18336. Object.assign( Object.create( Interpolant.prototype ), {
  18337. constructor: CubicInterpolant,
  18338. DefaultSettings_: {
  18339. endingStart: ZeroCurvatureEnding,
  18340. endingEnd: ZeroCurvatureEnding
  18341. },
  18342. intervalChanged_: function( i1, t0, t1 ) {
  18343. var pp = this.parameterPositions,
  18344. iPrev = i1 - 2,
  18345. iNext = i1 + 1,
  18346. tPrev = pp[ iPrev ],
  18347. tNext = pp[ iNext ];
  18348. if ( tPrev === undefined ) {
  18349. switch ( this.getSettings_().endingStart ) {
  18350. case ZeroSlopeEnding:
  18351. // f'(t0) = 0
  18352. iPrev = i1;
  18353. tPrev = 2 * t0 - t1;
  18354. break;
  18355. case WrapAroundEnding:
  18356. // use the other end of the curve
  18357. iPrev = pp.length - 2;
  18358. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18359. break;
  18360. default: // ZeroCurvatureEnding
  18361. // f''(t0) = 0 a.k.a. Natural Spline
  18362. iPrev = i1;
  18363. tPrev = t1;
  18364. }
  18365. }
  18366. if ( tNext === undefined ) {
  18367. switch ( this.getSettings_().endingEnd ) {
  18368. case ZeroSlopeEnding:
  18369. // f'(tN) = 0
  18370. iNext = i1;
  18371. tNext = 2 * t1 - t0;
  18372. break;
  18373. case WrapAroundEnding:
  18374. // use the other end of the curve
  18375. iNext = 1;
  18376. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18377. break;
  18378. default: // ZeroCurvatureEnding
  18379. // f''(tN) = 0, a.k.a. Natural Spline
  18380. iNext = i1 - 1;
  18381. tNext = t0;
  18382. }
  18383. }
  18384. var halfDt = ( t1 - t0 ) * 0.5,
  18385. stride = this.valueSize;
  18386. this._weightPrev = halfDt / ( t0 - tPrev );
  18387. this._weightNext = halfDt / ( tNext - t1 );
  18388. this._offsetPrev = iPrev * stride;
  18389. this._offsetNext = iNext * stride;
  18390. },
  18391. interpolate_: function( i1, t0, t, t1 ) {
  18392. var result = this.resultBuffer,
  18393. values = this.sampleValues,
  18394. stride = this.valueSize,
  18395. o1 = i1 * stride, o0 = o1 - stride,
  18396. oP = this._offsetPrev, oN = this._offsetNext,
  18397. wP = this._weightPrev, wN = this._weightNext,
  18398. p = ( t - t0 ) / ( t1 - t0 ),
  18399. pp = p * p,
  18400. ppp = pp * p;
  18401. // evaluate polynomials
  18402. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18403. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18404. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18405. var sN = wN * ppp - wN * pp;
  18406. // combine data linearly
  18407. for ( var i = 0; i !== stride; ++ i ) {
  18408. result[ i ] =
  18409. sP * values[ oP + i ] +
  18410. s0 * values[ o0 + i ] +
  18411. s1 * values[ o1 + i ] +
  18412. sN * values[ oN + i ];
  18413. }
  18414. return result;
  18415. }
  18416. } );
  18417. /**
  18418. * @author tschw
  18419. */
  18420. function LinearInterpolant(
  18421. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18422. Interpolant.call(
  18423. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18424. }
  18425. LinearInterpolant.prototype =
  18426. Object.assign( Object.create( Interpolant.prototype ), {
  18427. constructor: LinearInterpolant,
  18428. interpolate_: function( i1, t0, t, t1 ) {
  18429. var result = this.resultBuffer,
  18430. values = this.sampleValues,
  18431. stride = this.valueSize,
  18432. offset1 = i1 * stride,
  18433. offset0 = offset1 - stride,
  18434. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18435. weight0 = 1 - weight1;
  18436. for ( var i = 0; i !== stride; ++ i ) {
  18437. result[ i ] =
  18438. values[ offset0 + i ] * weight0 +
  18439. values[ offset1 + i ] * weight1;
  18440. }
  18441. return result;
  18442. }
  18443. } );
  18444. /**
  18445. *
  18446. * Interpolant that evaluates to the sample value at the position preceeding
  18447. * the parameter.
  18448. *
  18449. * @author tschw
  18450. */
  18451. function DiscreteInterpolant(
  18452. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18453. Interpolant.call(
  18454. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18455. }
  18456. DiscreteInterpolant.prototype =
  18457. Object.assign( Object.create( Interpolant.prototype ), {
  18458. constructor: DiscreteInterpolant,
  18459. interpolate_: function( i1, t0, t, t1 ) {
  18460. return this.copySampleValue_( i1 - 1 );
  18461. }
  18462. } );
  18463. var KeyframeTrackPrototype;
  18464. KeyframeTrackPrototype = {
  18465. TimeBufferType: Float32Array,
  18466. ValueBufferType: Float32Array,
  18467. DefaultInterpolation: InterpolateLinear,
  18468. InterpolantFactoryMethodDiscrete: function ( result ) {
  18469. return new DiscreteInterpolant(
  18470. this.times, this.values, this.getValueSize(), result );
  18471. },
  18472. InterpolantFactoryMethodLinear: function ( result ) {
  18473. return new LinearInterpolant(
  18474. this.times, this.values, this.getValueSize(), result );
  18475. },
  18476. InterpolantFactoryMethodSmooth: function ( result ) {
  18477. return new CubicInterpolant(
  18478. this.times, this.values, this.getValueSize(), result );
  18479. },
  18480. setInterpolation: function ( interpolation ) {
  18481. var factoryMethod;
  18482. switch ( interpolation ) {
  18483. case InterpolateDiscrete:
  18484. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18485. break;
  18486. case InterpolateLinear:
  18487. factoryMethod = this.InterpolantFactoryMethodLinear;
  18488. break;
  18489. case InterpolateSmooth:
  18490. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18491. break;
  18492. }
  18493. if ( factoryMethod === undefined ) {
  18494. var message = "unsupported interpolation for " +
  18495. this.ValueTypeName + " keyframe track named " + this.name;
  18496. if ( this.createInterpolant === undefined ) {
  18497. // fall back to default, unless the default itself is messed up
  18498. if ( interpolation !== this.DefaultInterpolation ) {
  18499. this.setInterpolation( this.DefaultInterpolation );
  18500. } else {
  18501. throw new Error( message ); // fatal, in this case
  18502. }
  18503. }
  18504. console.warn( message );
  18505. return;
  18506. }
  18507. this.createInterpolant = factoryMethod;
  18508. },
  18509. getInterpolation: function () {
  18510. switch ( this.createInterpolant ) {
  18511. case this.InterpolantFactoryMethodDiscrete:
  18512. return InterpolateDiscrete;
  18513. case this.InterpolantFactoryMethodLinear:
  18514. return InterpolateLinear;
  18515. case this.InterpolantFactoryMethodSmooth:
  18516. return InterpolateSmooth;
  18517. }
  18518. },
  18519. getValueSize: function () {
  18520. return this.values.length / this.times.length;
  18521. },
  18522. // move all keyframes either forwards or backwards in time
  18523. shift: function ( timeOffset ) {
  18524. if ( timeOffset !== 0.0 ) {
  18525. var times = this.times;
  18526. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18527. times[ i ] += timeOffset;
  18528. }
  18529. }
  18530. return this;
  18531. },
  18532. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18533. scale: function ( timeScale ) {
  18534. if ( timeScale !== 1.0 ) {
  18535. var times = this.times;
  18536. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18537. times[ i ] *= timeScale;
  18538. }
  18539. }
  18540. return this;
  18541. },
  18542. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18543. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18544. trim: function ( startTime, endTime ) {
  18545. var times = this.times,
  18546. nKeys = times.length,
  18547. from = 0,
  18548. to = nKeys - 1;
  18549. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18550. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18551. ++ to; // inclusive -> exclusive bound
  18552. if ( from !== 0 || to !== nKeys ) {
  18553. // empty tracks are forbidden, so keep at least one keyframe
  18554. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18555. var stride = this.getValueSize();
  18556. this.times = AnimationUtils.arraySlice( times, from, to );
  18557. this.values = AnimationUtils.
  18558. arraySlice( this.values, from * stride, to * stride );
  18559. }
  18560. return this;
  18561. },
  18562. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18563. validate: function () {
  18564. var valid = true;
  18565. var valueSize = this.getValueSize();
  18566. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18567. console.error( "invalid value size in track", this );
  18568. valid = false;
  18569. }
  18570. var times = this.times,
  18571. values = this.values,
  18572. nKeys = times.length;
  18573. if ( nKeys === 0 ) {
  18574. console.error( "track is empty", this );
  18575. valid = false;
  18576. }
  18577. var prevTime = null;
  18578. for ( var i = 0; i !== nKeys; i ++ ) {
  18579. var currTime = times[ i ];
  18580. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18581. console.error( "time is not a valid number", this, i, currTime );
  18582. valid = false;
  18583. break;
  18584. }
  18585. if ( prevTime !== null && prevTime > currTime ) {
  18586. console.error( "out of order keys", this, i, currTime, prevTime );
  18587. valid = false;
  18588. break;
  18589. }
  18590. prevTime = currTime;
  18591. }
  18592. if ( values !== undefined ) {
  18593. if ( AnimationUtils.isTypedArray( values ) ) {
  18594. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18595. var value = values[ i ];
  18596. if ( isNaN( value ) ) {
  18597. console.error( "value is not a valid number", this, i, value );
  18598. valid = false;
  18599. break;
  18600. }
  18601. }
  18602. }
  18603. }
  18604. return valid;
  18605. },
  18606. // removes equivalent sequential keys as common in morph target sequences
  18607. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18608. optimize: function () {
  18609. var times = this.times,
  18610. values = this.values,
  18611. stride = this.getValueSize(),
  18612. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18613. writeIndex = 1,
  18614. lastIndex = times.length - 1;
  18615. for ( var i = 1; i < lastIndex; ++ i ) {
  18616. var keep = false;
  18617. var time = times[ i ];
  18618. var timeNext = times[ i + 1 ];
  18619. // remove adjacent keyframes scheduled at the same time
  18620. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18621. if ( ! smoothInterpolation ) {
  18622. // remove unnecessary keyframes same as their neighbors
  18623. var offset = i * stride,
  18624. offsetP = offset - stride,
  18625. offsetN = offset + stride;
  18626. for ( var j = 0; j !== stride; ++ j ) {
  18627. var value = values[ offset + j ];
  18628. if ( value !== values[ offsetP + j ] ||
  18629. value !== values[ offsetN + j ] ) {
  18630. keep = true;
  18631. break;
  18632. }
  18633. }
  18634. } else keep = true;
  18635. }
  18636. // in-place compaction
  18637. if ( keep ) {
  18638. if ( i !== writeIndex ) {
  18639. times[ writeIndex ] = times[ i ];
  18640. var readOffset = i * stride,
  18641. writeOffset = writeIndex * stride;
  18642. for ( var j = 0; j !== stride; ++ j )
  18643. values[ writeOffset + j ] = values[ readOffset + j ];
  18644. }
  18645. ++ writeIndex;
  18646. }
  18647. }
  18648. // flush last keyframe (compaction looks ahead)
  18649. if ( lastIndex > 0 ) {
  18650. times[ writeIndex ] = times[ lastIndex ];
  18651. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18652. values[ writeOffset + j ] = values[ readOffset + j ];
  18653. ++ writeIndex;
  18654. }
  18655. if ( writeIndex !== times.length ) {
  18656. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18657. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18658. }
  18659. return this;
  18660. }
  18661. };
  18662. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18663. if( name === undefined ) throw new Error( "track name is undefined" );
  18664. if( times === undefined || times.length === 0 ) {
  18665. throw new Error( "no keyframes in track named " + name );
  18666. }
  18667. this.name = name;
  18668. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18669. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18670. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18671. this.validate();
  18672. this.optimize();
  18673. }
  18674. /**
  18675. *
  18676. * A Track of vectored keyframe values.
  18677. *
  18678. *
  18679. * @author Ben Houston / http://clara.io/
  18680. * @author David Sarno / http://lighthaus.us/
  18681. * @author tschw
  18682. */
  18683. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18684. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18685. }
  18686. VectorKeyframeTrack.prototype =
  18687. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18688. constructor: VectorKeyframeTrack,
  18689. ValueTypeName: 'vector'
  18690. // ValueBufferType is inherited
  18691. // DefaultInterpolation is inherited
  18692. } );
  18693. /**
  18694. * Spherical linear unit quaternion interpolant.
  18695. *
  18696. * @author tschw
  18697. */
  18698. function QuaternionLinearInterpolant(
  18699. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18700. Interpolant.call(
  18701. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18702. }
  18703. QuaternionLinearInterpolant.prototype =
  18704. Object.assign( Object.create( Interpolant.prototype ), {
  18705. constructor: QuaternionLinearInterpolant,
  18706. interpolate_: function( i1, t0, t, t1 ) {
  18707. var result = this.resultBuffer,
  18708. values = this.sampleValues,
  18709. stride = this.valueSize,
  18710. offset = i1 * stride,
  18711. alpha = ( t - t0 ) / ( t1 - t0 );
  18712. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18713. Quaternion.slerpFlat( result, 0,
  18714. values, offset - stride, values, offset, alpha );
  18715. }
  18716. return result;
  18717. }
  18718. } );
  18719. /**
  18720. *
  18721. * A Track of quaternion keyframe values.
  18722. *
  18723. * @author Ben Houston / http://clara.io/
  18724. * @author David Sarno / http://lighthaus.us/
  18725. * @author tschw
  18726. */
  18727. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18728. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18729. }
  18730. QuaternionKeyframeTrack.prototype =
  18731. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18732. constructor: QuaternionKeyframeTrack,
  18733. ValueTypeName: 'quaternion',
  18734. // ValueBufferType is inherited
  18735. DefaultInterpolation: InterpolateLinear,
  18736. InterpolantFactoryMethodLinear: function( result ) {
  18737. return new QuaternionLinearInterpolant(
  18738. this.times, this.values, this.getValueSize(), result );
  18739. },
  18740. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18741. } );
  18742. /**
  18743. *
  18744. * A Track of numeric keyframe values.
  18745. *
  18746. * @author Ben Houston / http://clara.io/
  18747. * @author David Sarno / http://lighthaus.us/
  18748. * @author tschw
  18749. */
  18750. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18751. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18752. }
  18753. NumberKeyframeTrack.prototype =
  18754. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18755. constructor: NumberKeyframeTrack,
  18756. ValueTypeName: 'number'
  18757. // ValueBufferType is inherited
  18758. // DefaultInterpolation is inherited
  18759. } );
  18760. /**
  18761. *
  18762. * A Track that interpolates Strings
  18763. *
  18764. *
  18765. * @author Ben Houston / http://clara.io/
  18766. * @author David Sarno / http://lighthaus.us/
  18767. * @author tschw
  18768. */
  18769. function StringKeyframeTrack( name, times, values, interpolation ) {
  18770. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18771. }
  18772. StringKeyframeTrack.prototype =
  18773. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18774. constructor: StringKeyframeTrack,
  18775. ValueTypeName: 'string',
  18776. ValueBufferType: Array,
  18777. DefaultInterpolation: InterpolateDiscrete,
  18778. InterpolantFactoryMethodLinear: undefined,
  18779. InterpolantFactoryMethodSmooth: undefined
  18780. } );
  18781. /**
  18782. *
  18783. * A Track of Boolean keyframe values.
  18784. *
  18785. *
  18786. * @author Ben Houston / http://clara.io/
  18787. * @author David Sarno / http://lighthaus.us/
  18788. * @author tschw
  18789. */
  18790. function BooleanKeyframeTrack( name, times, values ) {
  18791. KeyframeTrackConstructor.call( this, name, times, values );
  18792. }
  18793. BooleanKeyframeTrack.prototype =
  18794. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18795. constructor: BooleanKeyframeTrack,
  18796. ValueTypeName: 'bool',
  18797. ValueBufferType: Array,
  18798. DefaultInterpolation: InterpolateDiscrete,
  18799. InterpolantFactoryMethodLinear: undefined,
  18800. InterpolantFactoryMethodSmooth: undefined
  18801. // Note: Actually this track could have a optimized / compressed
  18802. // representation of a single value and a custom interpolant that
  18803. // computes "firstValue ^ isOdd( index )".
  18804. } );
  18805. /**
  18806. *
  18807. * A Track of keyframe values that represent color.
  18808. *
  18809. *
  18810. * @author Ben Houston / http://clara.io/
  18811. * @author David Sarno / http://lighthaus.us/
  18812. * @author tschw
  18813. */
  18814. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18815. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18816. }
  18817. ColorKeyframeTrack.prototype =
  18818. Object.assign( Object.create( KeyframeTrackPrototype ), {
  18819. constructor: ColorKeyframeTrack,
  18820. ValueTypeName: 'color'
  18821. // ValueBufferType is inherited
  18822. // DefaultInterpolation is inherited
  18823. // Note: Very basic implementation and nothing special yet.
  18824. // However, this is the place for color space parameterization.
  18825. } );
  18826. /**
  18827. *
  18828. * A timed sequence of keyframes for a specific property.
  18829. *
  18830. *
  18831. * @author Ben Houston / http://clara.io/
  18832. * @author David Sarno / http://lighthaus.us/
  18833. * @author tschw
  18834. */
  18835. function KeyframeTrack( name, times, values, interpolation ) {
  18836. KeyframeTrackConstructor.apply( this, arguments );
  18837. }
  18838. KeyframeTrack.prototype = KeyframeTrackPrototype;
  18839. KeyframeTrackPrototype.constructor = KeyframeTrack;
  18840. // Static methods:
  18841. Object.assign( KeyframeTrack, {
  18842. // Serialization (in static context, because of constructor invocation
  18843. // and automatic invocation of .toJSON):
  18844. parse: function( json ) {
  18845. if( json.type === undefined ) {
  18846. throw new Error( "track type undefined, can not parse" );
  18847. }
  18848. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  18849. if ( json.times === undefined ) {
  18850. var times = [], values = [];
  18851. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  18852. json.times = times;
  18853. json.values = values;
  18854. }
  18855. // derived classes can define a static parse method
  18856. if ( trackType.parse !== undefined ) {
  18857. return trackType.parse( json );
  18858. } else {
  18859. // by default, we asssume a constructor compatible with the base
  18860. return new trackType(
  18861. json.name, json.times, json.values, json.interpolation );
  18862. }
  18863. },
  18864. toJSON: function( track ) {
  18865. var trackType = track.constructor;
  18866. var json;
  18867. // derived classes can define a static toJSON method
  18868. if ( trackType.toJSON !== undefined ) {
  18869. json = trackType.toJSON( track );
  18870. } else {
  18871. // by default, we assume the data can be serialized as-is
  18872. json = {
  18873. 'name': track.name,
  18874. 'times': AnimationUtils.convertArray( track.times, Array ),
  18875. 'values': AnimationUtils.convertArray( track.values, Array )
  18876. };
  18877. var interpolation = track.getInterpolation();
  18878. if ( interpolation !== track.DefaultInterpolation ) {
  18879. json.interpolation = interpolation;
  18880. }
  18881. }
  18882. json.type = track.ValueTypeName; // mandatory
  18883. return json;
  18884. },
  18885. _getTrackTypeForValueTypeName: function( typeName ) {
  18886. switch( typeName.toLowerCase() ) {
  18887. case "scalar":
  18888. case "double":
  18889. case "float":
  18890. case "number":
  18891. case "integer":
  18892. return NumberKeyframeTrack;
  18893. case "vector":
  18894. case "vector2":
  18895. case "vector3":
  18896. case "vector4":
  18897. return VectorKeyframeTrack;
  18898. case "color":
  18899. return ColorKeyframeTrack;
  18900. case "quaternion":
  18901. return QuaternionKeyframeTrack;
  18902. case "bool":
  18903. case "boolean":
  18904. return BooleanKeyframeTrack;
  18905. case "string":
  18906. return StringKeyframeTrack;
  18907. }
  18908. throw new Error( "Unsupported typeName: " + typeName );
  18909. }
  18910. } );
  18911. /**
  18912. *
  18913. * Reusable set of Tracks that represent an animation.
  18914. *
  18915. * @author Ben Houston / http://clara.io/
  18916. * @author David Sarno / http://lighthaus.us/
  18917. */
  18918. function AnimationClip( name, duration, tracks ) {
  18919. this.name = name;
  18920. this.tracks = tracks;
  18921. this.duration = ( duration !== undefined ) ? duration : -1;
  18922. this.uuid = _Math.generateUUID();
  18923. // this means it should figure out its duration by scanning the tracks
  18924. if ( this.duration < 0 ) {
  18925. this.resetDuration();
  18926. }
  18927. this.optimize();
  18928. }
  18929. AnimationClip.prototype = {
  18930. constructor: AnimationClip,
  18931. resetDuration: function() {
  18932. var tracks = this.tracks,
  18933. duration = 0;
  18934. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  18935. var track = this.tracks[ i ];
  18936. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  18937. }
  18938. this.duration = duration;
  18939. },
  18940. trim: function() {
  18941. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18942. this.tracks[ i ].trim( 0, this.duration );
  18943. }
  18944. return this;
  18945. },
  18946. optimize: function() {
  18947. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18948. this.tracks[ i ].optimize();
  18949. }
  18950. return this;
  18951. }
  18952. };
  18953. // Static methods:
  18954. Object.assign( AnimationClip, {
  18955. parse: function( json ) {
  18956. var tracks = [],
  18957. jsonTracks = json.tracks,
  18958. frameTime = 1.0 / ( json.fps || 1.0 );
  18959. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  18960. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  18961. }
  18962. return new AnimationClip( json.name, json.duration, tracks );
  18963. },
  18964. toJSON: function( clip ) {
  18965. var tracks = [],
  18966. clipTracks = clip.tracks;
  18967. var json = {
  18968. 'name': clip.name,
  18969. 'duration': clip.duration,
  18970. 'tracks': tracks
  18971. };
  18972. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  18973. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  18974. }
  18975. return json;
  18976. },
  18977. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  18978. var numMorphTargets = morphTargetSequence.length;
  18979. var tracks = [];
  18980. for ( var i = 0; i < numMorphTargets; i ++ ) {
  18981. var times = [];
  18982. var values = [];
  18983. times.push(
  18984. ( i + numMorphTargets - 1 ) % numMorphTargets,
  18985. i,
  18986. ( i + 1 ) % numMorphTargets );
  18987. values.push( 0, 1, 0 );
  18988. var order = AnimationUtils.getKeyframeOrder( times );
  18989. times = AnimationUtils.sortedArray( times, 1, order );
  18990. values = AnimationUtils.sortedArray( values, 1, order );
  18991. // if there is a key at the first frame, duplicate it as the
  18992. // last frame as well for perfect loop.
  18993. if ( ! noLoop && times[ 0 ] === 0 ) {
  18994. times.push( numMorphTargets );
  18995. values.push( values[ 0 ] );
  18996. }
  18997. tracks.push(
  18998. new NumberKeyframeTrack(
  18999. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  19000. times, values
  19001. ).scale( 1.0 / fps ) );
  19002. }
  19003. return new AnimationClip( name, -1, tracks );
  19004. },
  19005. findByName: function( objectOrClipArray, name ) {
  19006. var clipArray = objectOrClipArray;
  19007. if ( ! Array.isArray( objectOrClipArray ) ) {
  19008. var o = objectOrClipArray;
  19009. clipArray = o.geometry && o.geometry.animations || o.animations;
  19010. }
  19011. for ( var i = 0; i < clipArray.length; i ++ ) {
  19012. if ( clipArray[ i ].name === name ) {
  19013. return clipArray[ i ];
  19014. }
  19015. }
  19016. return null;
  19017. },
  19018. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  19019. var animationToMorphTargets = {};
  19020. // tested with https://regex101.com/ on trick sequences
  19021. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  19022. var pattern = /^([\w-]*?)([\d]+)$/;
  19023. // sort morph target names into animation groups based
  19024. // patterns like Walk_001, Walk_002, Run_001, Run_002
  19025. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  19026. var morphTarget = morphTargets[ i ];
  19027. var parts = morphTarget.name.match( pattern );
  19028. if ( parts && parts.length > 1 ) {
  19029. var name = parts[ 1 ];
  19030. var animationMorphTargets = animationToMorphTargets[ name ];
  19031. if ( ! animationMorphTargets ) {
  19032. animationToMorphTargets[ name ] = animationMorphTargets = [];
  19033. }
  19034. animationMorphTargets.push( morphTarget );
  19035. }
  19036. }
  19037. var clips = [];
  19038. for ( var name in animationToMorphTargets ) {
  19039. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  19040. }
  19041. return clips;
  19042. },
  19043. // parse the animation.hierarchy format
  19044. parseAnimation: function( animation, bones ) {
  19045. if ( ! animation ) {
  19046. console.error( " no animation in JSONLoader data" );
  19047. return null;
  19048. }
  19049. var addNonemptyTrack = function(
  19050. trackType, trackName, animationKeys, propertyName, destTracks ) {
  19051. // only return track if there are actually keys.
  19052. if ( animationKeys.length !== 0 ) {
  19053. var times = [];
  19054. var values = [];
  19055. AnimationUtils.flattenJSON(
  19056. animationKeys, times, values, propertyName );
  19057. // empty keys are filtered out, so check again
  19058. if ( times.length !== 0 ) {
  19059. destTracks.push( new trackType( trackName, times, values ) );
  19060. }
  19061. }
  19062. };
  19063. var tracks = [];
  19064. var clipName = animation.name || 'default';
  19065. // automatic length determination in AnimationClip.
  19066. var duration = animation.length || -1;
  19067. var fps = animation.fps || 30;
  19068. var hierarchyTracks = animation.hierarchy || [];
  19069. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  19070. var animationKeys = hierarchyTracks[ h ].keys;
  19071. // skip empty tracks
  19072. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  19073. // process morph targets in a way exactly compatible
  19074. // with AnimationHandler.init( animation )
  19075. if ( animationKeys[0].morphTargets ) {
  19076. // figure out all morph targets used in this track
  19077. var morphTargetNames = {};
  19078. for ( var k = 0; k < animationKeys.length; k ++ ) {
  19079. if ( animationKeys[k].morphTargets ) {
  19080. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  19081. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  19082. }
  19083. }
  19084. }
  19085. // create a track for each morph target with all zero
  19086. // morphTargetInfluences except for the keys in which
  19087. // the morphTarget is named.
  19088. for ( var morphTargetName in morphTargetNames ) {
  19089. var times = [];
  19090. var values = [];
  19091. for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) {
  19092. var animationKey = animationKeys[k];
  19093. times.push( animationKey.time );
  19094. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  19095. }
  19096. tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  19097. }
  19098. duration = morphTargetNames.length * ( fps || 1.0 );
  19099. } else {
  19100. // ...assume skeletal animation
  19101. var boneName = '.bones[' + bones[ h ].name + ']';
  19102. addNonemptyTrack(
  19103. VectorKeyframeTrack, boneName + '.position',
  19104. animationKeys, 'pos', tracks );
  19105. addNonemptyTrack(
  19106. QuaternionKeyframeTrack, boneName + '.quaternion',
  19107. animationKeys, 'rot', tracks );
  19108. addNonemptyTrack(
  19109. VectorKeyframeTrack, boneName + '.scale',
  19110. animationKeys, 'scl', tracks );
  19111. }
  19112. }
  19113. if ( tracks.length === 0 ) {
  19114. return null;
  19115. }
  19116. var clip = new AnimationClip( clipName, duration, tracks );
  19117. return clip;
  19118. }
  19119. } );
  19120. /**
  19121. * @author mrdoob / http://mrdoob.com/
  19122. */
  19123. function MaterialLoader( manager ) {
  19124. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19125. this.textures = {};
  19126. }
  19127. Object.assign( MaterialLoader.prototype, {
  19128. load: function ( url, onLoad, onProgress, onError ) {
  19129. var scope = this;
  19130. var loader = new FileLoader( scope.manager );
  19131. loader.load( url, function ( text ) {
  19132. onLoad( scope.parse( JSON.parse( text ) ) );
  19133. }, onProgress, onError );
  19134. },
  19135. setTextures: function ( value ) {
  19136. this.textures = value;
  19137. },
  19138. parse: function ( json ) {
  19139. var textures = this.textures;
  19140. function getTexture( name ) {
  19141. if ( textures[ name ] === undefined ) {
  19142. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  19143. }
  19144. return textures[ name ];
  19145. }
  19146. var material = new Materials[ json.type ]();
  19147. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  19148. if ( json.name !== undefined ) material.name = json.name;
  19149. if ( json.color !== undefined ) material.color.setHex( json.color );
  19150. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  19151. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  19152. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  19153. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  19154. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  19155. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  19156. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  19157. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  19158. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  19159. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  19160. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  19161. if ( json.fog !== undefined ) material.fog = json.fog;
  19162. if ( json.shading !== undefined ) material.shading = json.shading;
  19163. if ( json.blending !== undefined ) material.blending = json.blending;
  19164. if ( json.side !== undefined ) material.side = json.side;
  19165. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  19166. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  19167. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  19168. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  19169. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  19170. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  19171. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  19172. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  19173. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  19174. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  19175. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  19176. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  19177. // for PointsMaterial
  19178. if ( json.size !== undefined ) material.size = json.size;
  19179. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  19180. // maps
  19181. if ( json.map !== undefined ) material.map = getTexture( json.map );
  19182. if ( json.alphaMap !== undefined ) {
  19183. material.alphaMap = getTexture( json.alphaMap );
  19184. material.transparent = true;
  19185. }
  19186. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  19187. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  19188. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  19189. if ( json.normalScale !== undefined ) {
  19190. var normalScale = json.normalScale;
  19191. if ( Array.isArray( normalScale ) === false ) {
  19192. // Blender exporter used to export a scalar. See #7459
  19193. normalScale = [ normalScale, normalScale ];
  19194. }
  19195. material.normalScale = new Vector2().fromArray( normalScale );
  19196. }
  19197. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  19198. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  19199. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  19200. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  19201. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  19202. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  19203. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  19204. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  19205. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  19206. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  19207. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  19208. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  19209. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  19210. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  19211. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  19212. // MultiMaterial
  19213. if ( json.materials !== undefined ) {
  19214. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  19215. material.materials.push( this.parse( json.materials[ i ] ) );
  19216. }
  19217. }
  19218. return material;
  19219. }
  19220. } );
  19221. /**
  19222. * @author mrdoob / http://mrdoob.com/
  19223. */
  19224. function BufferGeometryLoader( manager ) {
  19225. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19226. }
  19227. Object.assign( BufferGeometryLoader.prototype, {
  19228. load: function ( url, onLoad, onProgress, onError ) {
  19229. var scope = this;
  19230. var loader = new FileLoader( scope.manager );
  19231. loader.load( url, function ( text ) {
  19232. onLoad( scope.parse( JSON.parse( text ) ) );
  19233. }, onProgress, onError );
  19234. },
  19235. parse: function ( json ) {
  19236. var geometry = new BufferGeometry();
  19237. var index = json.data.index;
  19238. var TYPED_ARRAYS = {
  19239. 'Int8Array': Int8Array,
  19240. 'Uint8Array': Uint8Array,
  19241. 'Uint8ClampedArray': Uint8ClampedArray,
  19242. 'Int16Array': Int16Array,
  19243. 'Uint16Array': Uint16Array,
  19244. 'Int32Array': Int32Array,
  19245. 'Uint32Array': Uint32Array,
  19246. 'Float32Array': Float32Array,
  19247. 'Float64Array': Float64Array
  19248. };
  19249. if ( index !== undefined ) {
  19250. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  19251. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19252. }
  19253. var attributes = json.data.attributes;
  19254. for ( var key in attributes ) {
  19255. var attribute = attributes[ key ];
  19256. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  19257. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  19258. }
  19259. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19260. if ( groups !== undefined ) {
  19261. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  19262. var group = groups[ i ];
  19263. geometry.addGroup( group.start, group.count, group.materialIndex );
  19264. }
  19265. }
  19266. var boundingSphere = json.data.boundingSphere;
  19267. if ( boundingSphere !== undefined ) {
  19268. var center = new Vector3();
  19269. if ( boundingSphere.center !== undefined ) {
  19270. center.fromArray( boundingSphere.center );
  19271. }
  19272. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19273. }
  19274. return geometry;
  19275. }
  19276. } );
  19277. /**
  19278. * @author alteredq / http://alteredqualia.com/
  19279. */
  19280. function Loader() {
  19281. this.onLoadStart = function () {};
  19282. this.onLoadProgress = function () {};
  19283. this.onLoadComplete = function () {};
  19284. }
  19285. Loader.prototype = {
  19286. constructor: Loader,
  19287. crossOrigin: undefined,
  19288. extractUrlBase: function ( url ) {
  19289. var parts = url.split( '/' );
  19290. if ( parts.length === 1 ) return './';
  19291. parts.pop();
  19292. return parts.join( '/' ) + '/';
  19293. },
  19294. initMaterials: function ( materials, texturePath, crossOrigin ) {
  19295. var array = [];
  19296. for ( var i = 0; i < materials.length; ++ i ) {
  19297. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  19298. }
  19299. return array;
  19300. },
  19301. createMaterial: ( function () {
  19302. var BlendingMode = {
  19303. NoBlending: NoBlending,
  19304. NormalBlending: NormalBlending,
  19305. AdditiveBlending: AdditiveBlending,
  19306. SubtractiveBlending: SubtractiveBlending,
  19307. MultiplyBlending: MultiplyBlending,
  19308. CustomBlending: CustomBlending
  19309. };
  19310. var color, textureLoader, materialLoader;
  19311. return function createMaterial( m, texturePath, crossOrigin ) {
  19312. if ( color === undefined ) color = new Color();
  19313. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  19314. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  19315. // convert from old material format
  19316. var textures = {};
  19317. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  19318. var fullPath = texturePath + path;
  19319. var loader = Loader.Handlers.get( fullPath );
  19320. var texture;
  19321. if ( loader !== null ) {
  19322. texture = loader.load( fullPath );
  19323. } else {
  19324. textureLoader.setCrossOrigin( crossOrigin );
  19325. texture = textureLoader.load( fullPath );
  19326. }
  19327. if ( repeat !== undefined ) {
  19328. texture.repeat.fromArray( repeat );
  19329. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  19330. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  19331. }
  19332. if ( offset !== undefined ) {
  19333. texture.offset.fromArray( offset );
  19334. }
  19335. if ( wrap !== undefined ) {
  19336. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  19337. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  19338. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  19339. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  19340. }
  19341. if ( anisotropy !== undefined ) {
  19342. texture.anisotropy = anisotropy;
  19343. }
  19344. var uuid = _Math.generateUUID();
  19345. textures[ uuid ] = texture;
  19346. return uuid;
  19347. }
  19348. //
  19349. var json = {
  19350. uuid: _Math.generateUUID(),
  19351. type: 'MeshLambertMaterial'
  19352. };
  19353. for ( var name in m ) {
  19354. var value = m[ name ];
  19355. switch ( name ) {
  19356. case 'DbgColor':
  19357. case 'DbgIndex':
  19358. case 'opticalDensity':
  19359. case 'illumination':
  19360. break;
  19361. case 'DbgName':
  19362. json.name = value;
  19363. break;
  19364. case 'blending':
  19365. json.blending = BlendingMode[ value ];
  19366. break;
  19367. case 'colorAmbient':
  19368. case 'mapAmbient':
  19369. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  19370. break;
  19371. case 'colorDiffuse':
  19372. json.color = color.fromArray( value ).getHex();
  19373. break;
  19374. case 'colorSpecular':
  19375. json.specular = color.fromArray( value ).getHex();
  19376. break;
  19377. case 'colorEmissive':
  19378. json.emissive = color.fromArray( value ).getHex();
  19379. break;
  19380. case 'specularCoef':
  19381. json.shininess = value;
  19382. break;
  19383. case 'shading':
  19384. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  19385. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  19386. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  19387. break;
  19388. case 'mapDiffuse':
  19389. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  19390. break;
  19391. case 'mapDiffuseRepeat':
  19392. case 'mapDiffuseOffset':
  19393. case 'mapDiffuseWrap':
  19394. case 'mapDiffuseAnisotropy':
  19395. break;
  19396. case 'mapEmissive':
  19397. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  19398. break;
  19399. case 'mapEmissiveRepeat':
  19400. case 'mapEmissiveOffset':
  19401. case 'mapEmissiveWrap':
  19402. case 'mapEmissiveAnisotropy':
  19403. break;
  19404. case 'mapLight':
  19405. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  19406. break;
  19407. case 'mapLightRepeat':
  19408. case 'mapLightOffset':
  19409. case 'mapLightWrap':
  19410. case 'mapLightAnisotropy':
  19411. break;
  19412. case 'mapAO':
  19413. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  19414. break;
  19415. case 'mapAORepeat':
  19416. case 'mapAOOffset':
  19417. case 'mapAOWrap':
  19418. case 'mapAOAnisotropy':
  19419. break;
  19420. case 'mapBump':
  19421. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  19422. break;
  19423. case 'mapBumpScale':
  19424. json.bumpScale = value;
  19425. break;
  19426. case 'mapBumpRepeat':
  19427. case 'mapBumpOffset':
  19428. case 'mapBumpWrap':
  19429. case 'mapBumpAnisotropy':
  19430. break;
  19431. case 'mapNormal':
  19432. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  19433. break;
  19434. case 'mapNormalFactor':
  19435. json.normalScale = [ value, value ];
  19436. break;
  19437. case 'mapNormalRepeat':
  19438. case 'mapNormalOffset':
  19439. case 'mapNormalWrap':
  19440. case 'mapNormalAnisotropy':
  19441. break;
  19442. case 'mapSpecular':
  19443. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  19444. break;
  19445. case 'mapSpecularRepeat':
  19446. case 'mapSpecularOffset':
  19447. case 'mapSpecularWrap':
  19448. case 'mapSpecularAnisotropy':
  19449. break;
  19450. case 'mapMetalness':
  19451. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  19452. break;
  19453. case 'mapMetalnessRepeat':
  19454. case 'mapMetalnessOffset':
  19455. case 'mapMetalnessWrap':
  19456. case 'mapMetalnessAnisotropy':
  19457. break;
  19458. case 'mapRoughness':
  19459. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  19460. break;
  19461. case 'mapRoughnessRepeat':
  19462. case 'mapRoughnessOffset':
  19463. case 'mapRoughnessWrap':
  19464. case 'mapRoughnessAnisotropy':
  19465. break;
  19466. case 'mapAlpha':
  19467. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  19468. break;
  19469. case 'mapAlphaRepeat':
  19470. case 'mapAlphaOffset':
  19471. case 'mapAlphaWrap':
  19472. case 'mapAlphaAnisotropy':
  19473. break;
  19474. case 'flipSided':
  19475. json.side = BackSide;
  19476. break;
  19477. case 'doubleSided':
  19478. json.side = DoubleSide;
  19479. break;
  19480. case 'transparency':
  19481. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  19482. json.opacity = value;
  19483. break;
  19484. case 'depthTest':
  19485. case 'depthWrite':
  19486. case 'colorWrite':
  19487. case 'opacity':
  19488. case 'reflectivity':
  19489. case 'transparent':
  19490. case 'visible':
  19491. case 'wireframe':
  19492. json[ name ] = value;
  19493. break;
  19494. case 'vertexColors':
  19495. if ( value === true ) json.vertexColors = VertexColors;
  19496. if ( value === 'face' ) json.vertexColors = FaceColors;
  19497. break;
  19498. default:
  19499. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  19500. break;
  19501. }
  19502. }
  19503. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  19504. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  19505. if ( json.opacity < 1 ) json.transparent = true;
  19506. materialLoader.setTextures( textures );
  19507. return materialLoader.parse( json );
  19508. };
  19509. } )()
  19510. };
  19511. Loader.Handlers = {
  19512. handlers: [],
  19513. add: function ( regex, loader ) {
  19514. this.handlers.push( regex, loader );
  19515. },
  19516. get: function ( file ) {
  19517. var handlers = this.handlers;
  19518. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  19519. var regex = handlers[ i ];
  19520. var loader = handlers[ i + 1 ];
  19521. if ( regex.test( file ) ) {
  19522. return loader;
  19523. }
  19524. }
  19525. return null;
  19526. }
  19527. };
  19528. /**
  19529. * @author mrdoob / http://mrdoob.com/
  19530. * @author alteredq / http://alteredqualia.com/
  19531. */
  19532. function JSONLoader( manager ) {
  19533. if ( typeof manager === 'boolean' ) {
  19534. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  19535. manager = undefined;
  19536. }
  19537. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19538. this.withCredentials = false;
  19539. }
  19540. Object.assign( JSONLoader.prototype, {
  19541. load: function( url, onLoad, onProgress, onError ) {
  19542. var scope = this;
  19543. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  19544. var loader = new FileLoader( this.manager );
  19545. loader.setWithCredentials( this.withCredentials );
  19546. loader.load( url, function ( text ) {
  19547. var json = JSON.parse( text );
  19548. var metadata = json.metadata;
  19549. if ( metadata !== undefined ) {
  19550. var type = metadata.type;
  19551. if ( type !== undefined ) {
  19552. if ( type.toLowerCase() === 'object' ) {
  19553. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  19554. return;
  19555. }
  19556. if ( type.toLowerCase() === 'scene' ) {
  19557. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  19558. return;
  19559. }
  19560. }
  19561. }
  19562. var object = scope.parse( json, texturePath );
  19563. onLoad( object.geometry, object.materials );
  19564. }, onProgress, onError );
  19565. },
  19566. setTexturePath: function ( value ) {
  19567. this.texturePath = value;
  19568. },
  19569. parse: function ( json, texturePath ) {
  19570. var geometry = new Geometry(),
  19571. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19572. parseModel( scale );
  19573. parseSkin();
  19574. parseMorphing( scale );
  19575. parseAnimations();
  19576. geometry.computeFaceNormals();
  19577. geometry.computeBoundingSphere();
  19578. function parseModel( scale ) {
  19579. function isBitSet( value, position ) {
  19580. return value & ( 1 << position );
  19581. }
  19582. var i, j, fi,
  19583. offset, zLength,
  19584. colorIndex, normalIndex, uvIndex, materialIndex,
  19585. type,
  19586. isQuad,
  19587. hasMaterial,
  19588. hasFaceVertexUv,
  19589. hasFaceNormal, hasFaceVertexNormal,
  19590. hasFaceColor, hasFaceVertexColor,
  19591. vertex, face, faceA, faceB, hex, normal,
  19592. uvLayer, uv, u, v,
  19593. faces = json.faces,
  19594. vertices = json.vertices,
  19595. normals = json.normals,
  19596. colors = json.colors,
  19597. nUvLayers = 0;
  19598. if ( json.uvs !== undefined ) {
  19599. // disregard empty arrays
  19600. for ( i = 0; i < json.uvs.length; i ++ ) {
  19601. if ( json.uvs[ i ].length ) nUvLayers ++;
  19602. }
  19603. for ( i = 0; i < nUvLayers; i ++ ) {
  19604. geometry.faceVertexUvs[ i ] = [];
  19605. }
  19606. }
  19607. offset = 0;
  19608. zLength = vertices.length;
  19609. while ( offset < zLength ) {
  19610. vertex = new Vector3();
  19611. vertex.x = vertices[ offset ++ ] * scale;
  19612. vertex.y = vertices[ offset ++ ] * scale;
  19613. vertex.z = vertices[ offset ++ ] * scale;
  19614. geometry.vertices.push( vertex );
  19615. }
  19616. offset = 0;
  19617. zLength = faces.length;
  19618. while ( offset < zLength ) {
  19619. type = faces[ offset ++ ];
  19620. isQuad = isBitSet( type, 0 );
  19621. hasMaterial = isBitSet( type, 1 );
  19622. hasFaceVertexUv = isBitSet( type, 3 );
  19623. hasFaceNormal = isBitSet( type, 4 );
  19624. hasFaceVertexNormal = isBitSet( type, 5 );
  19625. hasFaceColor = isBitSet( type, 6 );
  19626. hasFaceVertexColor = isBitSet( type, 7 );
  19627. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19628. if ( isQuad ) {
  19629. faceA = new Face3();
  19630. faceA.a = faces[ offset ];
  19631. faceA.b = faces[ offset + 1 ];
  19632. faceA.c = faces[ offset + 3 ];
  19633. faceB = new Face3();
  19634. faceB.a = faces[ offset + 1 ];
  19635. faceB.b = faces[ offset + 2 ];
  19636. faceB.c = faces[ offset + 3 ];
  19637. offset += 4;
  19638. if ( hasMaterial ) {
  19639. materialIndex = faces[ offset ++ ];
  19640. faceA.materialIndex = materialIndex;
  19641. faceB.materialIndex = materialIndex;
  19642. }
  19643. // to get face <=> uv index correspondence
  19644. fi = geometry.faces.length;
  19645. if ( hasFaceVertexUv ) {
  19646. for ( i = 0; i < nUvLayers; i ++ ) {
  19647. uvLayer = json.uvs[ i ];
  19648. geometry.faceVertexUvs[ i ][ fi ] = [];
  19649. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  19650. for ( j = 0; j < 4; j ++ ) {
  19651. uvIndex = faces[ offset ++ ];
  19652. u = uvLayer[ uvIndex * 2 ];
  19653. v = uvLayer[ uvIndex * 2 + 1 ];
  19654. uv = new Vector2( u, v );
  19655. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19656. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  19657. }
  19658. }
  19659. }
  19660. if ( hasFaceNormal ) {
  19661. normalIndex = faces[ offset ++ ] * 3;
  19662. faceA.normal.set(
  19663. normals[ normalIndex ++ ],
  19664. normals[ normalIndex ++ ],
  19665. normals[ normalIndex ]
  19666. );
  19667. faceB.normal.copy( faceA.normal );
  19668. }
  19669. if ( hasFaceVertexNormal ) {
  19670. for ( i = 0; i < 4; i ++ ) {
  19671. normalIndex = faces[ offset ++ ] * 3;
  19672. normal = new Vector3(
  19673. normals[ normalIndex ++ ],
  19674. normals[ normalIndex ++ ],
  19675. normals[ normalIndex ]
  19676. );
  19677. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  19678. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  19679. }
  19680. }
  19681. if ( hasFaceColor ) {
  19682. colorIndex = faces[ offset ++ ];
  19683. hex = colors[ colorIndex ];
  19684. faceA.color.setHex( hex );
  19685. faceB.color.setHex( hex );
  19686. }
  19687. if ( hasFaceVertexColor ) {
  19688. for ( i = 0; i < 4; i ++ ) {
  19689. colorIndex = faces[ offset ++ ];
  19690. hex = colors[ colorIndex ];
  19691. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  19692. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  19693. }
  19694. }
  19695. geometry.faces.push( faceA );
  19696. geometry.faces.push( faceB );
  19697. } else {
  19698. face = new Face3();
  19699. face.a = faces[ offset ++ ];
  19700. face.b = faces[ offset ++ ];
  19701. face.c = faces[ offset ++ ];
  19702. if ( hasMaterial ) {
  19703. materialIndex = faces[ offset ++ ];
  19704. face.materialIndex = materialIndex;
  19705. }
  19706. // to get face <=> uv index correspondence
  19707. fi = geometry.faces.length;
  19708. if ( hasFaceVertexUv ) {
  19709. for ( i = 0; i < nUvLayers; i ++ ) {
  19710. uvLayer = json.uvs[ i ];
  19711. geometry.faceVertexUvs[ i ][ fi ] = [];
  19712. for ( j = 0; j < 3; j ++ ) {
  19713. uvIndex = faces[ offset ++ ];
  19714. u = uvLayer[ uvIndex * 2 ];
  19715. v = uvLayer[ uvIndex * 2 + 1 ];
  19716. uv = new Vector2( u, v );
  19717. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  19718. }
  19719. }
  19720. }
  19721. if ( hasFaceNormal ) {
  19722. normalIndex = faces[ offset ++ ] * 3;
  19723. face.normal.set(
  19724. normals[ normalIndex ++ ],
  19725. normals[ normalIndex ++ ],
  19726. normals[ normalIndex ]
  19727. );
  19728. }
  19729. if ( hasFaceVertexNormal ) {
  19730. for ( i = 0; i < 3; i ++ ) {
  19731. normalIndex = faces[ offset ++ ] * 3;
  19732. normal = new Vector3(
  19733. normals[ normalIndex ++ ],
  19734. normals[ normalIndex ++ ],
  19735. normals[ normalIndex ]
  19736. );
  19737. face.vertexNormals.push( normal );
  19738. }
  19739. }
  19740. if ( hasFaceColor ) {
  19741. colorIndex = faces[ offset ++ ];
  19742. face.color.setHex( colors[ colorIndex ] );
  19743. }
  19744. if ( hasFaceVertexColor ) {
  19745. for ( i = 0; i < 3; i ++ ) {
  19746. colorIndex = faces[ offset ++ ];
  19747. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  19748. }
  19749. }
  19750. geometry.faces.push( face );
  19751. }
  19752. }
  19753. }
  19754. function parseSkin() {
  19755. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  19756. if ( json.skinWeights ) {
  19757. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  19758. var x = json.skinWeights[ i ];
  19759. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  19760. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  19761. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  19762. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  19763. }
  19764. }
  19765. if ( json.skinIndices ) {
  19766. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  19767. var a = json.skinIndices[ i ];
  19768. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  19769. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  19770. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  19771. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  19772. }
  19773. }
  19774. geometry.bones = json.bones;
  19775. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  19776. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  19777. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  19778. }
  19779. }
  19780. function parseMorphing( scale ) {
  19781. if ( json.morphTargets !== undefined ) {
  19782. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  19783. geometry.morphTargets[ i ] = {};
  19784. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  19785. geometry.morphTargets[ i ].vertices = [];
  19786. var dstVertices = geometry.morphTargets[ i ].vertices;
  19787. var srcVertices = json.morphTargets[ i ].vertices;
  19788. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  19789. var vertex = new Vector3();
  19790. vertex.x = srcVertices[ v ] * scale;
  19791. vertex.y = srcVertices[ v + 1 ] * scale;
  19792. vertex.z = srcVertices[ v + 2 ] * scale;
  19793. dstVertices.push( vertex );
  19794. }
  19795. }
  19796. }
  19797. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  19798. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  19799. var faces = geometry.faces;
  19800. var morphColors = json.morphColors[ 0 ].colors;
  19801. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19802. faces[ i ].color.fromArray( morphColors, i * 3 );
  19803. }
  19804. }
  19805. }
  19806. function parseAnimations() {
  19807. var outputAnimations = [];
  19808. // parse old style Bone/Hierarchy animations
  19809. var animations = [];
  19810. if ( json.animation !== undefined ) {
  19811. animations.push( json.animation );
  19812. }
  19813. if ( json.animations !== undefined ) {
  19814. if ( json.animations.length ) {
  19815. animations = animations.concat( json.animations );
  19816. } else {
  19817. animations.push( json.animations );
  19818. }
  19819. }
  19820. for ( var i = 0; i < animations.length; i ++ ) {
  19821. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  19822. if ( clip ) outputAnimations.push( clip );
  19823. }
  19824. // parse implicit morph animations
  19825. if ( geometry.morphTargets ) {
  19826. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  19827. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  19828. outputAnimations = outputAnimations.concat( morphAnimationClips );
  19829. }
  19830. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  19831. }
  19832. if ( json.materials === undefined || json.materials.length === 0 ) {
  19833. return { geometry: geometry };
  19834. } else {
  19835. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  19836. return { geometry: geometry, materials: materials };
  19837. }
  19838. }
  19839. } );
  19840. /**
  19841. * @author mrdoob / http://mrdoob.com/
  19842. */
  19843. function ObjectLoader( manager ) {
  19844. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  19845. this.texturePath = '';
  19846. }
  19847. Object.assign( ObjectLoader.prototype, {
  19848. load: function ( url, onLoad, onProgress, onError ) {
  19849. if ( this.texturePath === '' ) {
  19850. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  19851. }
  19852. var scope = this;
  19853. var loader = new FileLoader( scope.manager );
  19854. loader.load( url, function ( text ) {
  19855. var json = null;
  19856. try {
  19857. json = JSON.parse( text );
  19858. } catch ( error ) {
  19859. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  19860. return;
  19861. }
  19862. var metadata = json.metadata;
  19863. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19864. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  19865. return;
  19866. }
  19867. scope.parse( json, onLoad );
  19868. }, onProgress, onError );
  19869. },
  19870. setTexturePath: function ( value ) {
  19871. this.texturePath = value;
  19872. },
  19873. setCrossOrigin: function ( value ) {
  19874. this.crossOrigin = value;
  19875. },
  19876. parse: function ( json, onLoad ) {
  19877. var geometries = this.parseGeometries( json.geometries );
  19878. var images = this.parseImages( json.images, function () {
  19879. if ( onLoad !== undefined ) onLoad( object );
  19880. } );
  19881. var textures = this.parseTextures( json.textures, images );
  19882. var materials = this.parseMaterials( json.materials, textures );
  19883. var object = this.parseObject( json.object, geometries, materials );
  19884. if ( json.animations ) {
  19885. object.animations = this.parseAnimations( json.animations );
  19886. }
  19887. if ( json.images === undefined || json.images.length === 0 ) {
  19888. if ( onLoad !== undefined ) onLoad( object );
  19889. }
  19890. return object;
  19891. },
  19892. parseGeometries: function ( json ) {
  19893. var geometries = {};
  19894. if ( json !== undefined ) {
  19895. var geometryLoader = new JSONLoader();
  19896. var bufferGeometryLoader = new BufferGeometryLoader();
  19897. for ( var i = 0, l = json.length; i < l; i ++ ) {
  19898. var geometry;
  19899. var data = json[ i ];
  19900. switch ( data.type ) {
  19901. case 'PlaneGeometry':
  19902. case 'PlaneBufferGeometry':
  19903. geometry = new Geometries[ data.type ](
  19904. data.width,
  19905. data.height,
  19906. data.widthSegments,
  19907. data.heightSegments
  19908. );
  19909. break;
  19910. case 'BoxGeometry':
  19911. case 'BoxBufferGeometry':
  19912. case 'CubeGeometry': // backwards compatible
  19913. geometry = new Geometries[ data.type ](
  19914. data.width,
  19915. data.height,
  19916. data.depth,
  19917. data.widthSegments,
  19918. data.heightSegments,
  19919. data.depthSegments
  19920. );
  19921. break;
  19922. case 'CircleGeometry':
  19923. case 'CircleBufferGeometry':
  19924. geometry = new Geometries[ data.type ](
  19925. data.radius,
  19926. data.segments,
  19927. data.thetaStart,
  19928. data.thetaLength
  19929. );
  19930. break;
  19931. case 'CylinderGeometry':
  19932. case 'CylinderBufferGeometry':
  19933. geometry = new Geometries[ data.type ](
  19934. data.radiusTop,
  19935. data.radiusBottom,
  19936. data.height,
  19937. data.radialSegments,
  19938. data.heightSegments,
  19939. data.openEnded,
  19940. data.thetaStart,
  19941. data.thetaLength
  19942. );
  19943. break;
  19944. case 'ConeGeometry':
  19945. case 'ConeBufferGeometry':
  19946. geometry = new Geometries[ data.type ](
  19947. data.radius,
  19948. data.height,
  19949. data.radialSegments,
  19950. data.heightSegments,
  19951. data.openEnded,
  19952. data.thetaStart,
  19953. data.thetaLength
  19954. );
  19955. break;
  19956. case 'SphereGeometry':
  19957. case 'SphereBufferGeometry':
  19958. geometry = new Geometries[ data.type ](
  19959. data.radius,
  19960. data.widthSegments,
  19961. data.heightSegments,
  19962. data.phiStart,
  19963. data.phiLength,
  19964. data.thetaStart,
  19965. data.thetaLength
  19966. );
  19967. break;
  19968. case 'DodecahedronGeometry':
  19969. case 'IcosahedronGeometry':
  19970. case 'OctahedronGeometry':
  19971. case 'TetrahedronGeometry':
  19972. geometry = new Geometries[ data.type ](
  19973. data.radius,
  19974. data.detail
  19975. );
  19976. break;
  19977. case 'RingGeometry':
  19978. case 'RingBufferGeometry':
  19979. geometry = new Geometries[ data.type ](
  19980. data.innerRadius,
  19981. data.outerRadius,
  19982. data.thetaSegments,
  19983. data.phiSegments,
  19984. data.thetaStart,
  19985. data.thetaLength
  19986. );
  19987. break;
  19988. case 'TorusGeometry':
  19989. case 'TorusBufferGeometry':
  19990. geometry = new Geometries[ data.type ](
  19991. data.radius,
  19992. data.tube,
  19993. data.radialSegments,
  19994. data.tubularSegments,
  19995. data.arc
  19996. );
  19997. break;
  19998. case 'TorusKnotGeometry':
  19999. case 'TorusKnotBufferGeometry':
  20000. geometry = new Geometries[ data.type ](
  20001. data.radius,
  20002. data.tube,
  20003. data.tubularSegments,
  20004. data.radialSegments,
  20005. data.p,
  20006. data.q
  20007. );
  20008. break;
  20009. case 'LatheGeometry':
  20010. case 'LatheBufferGeometry':
  20011. geometry = new Geometries[ data.type ](
  20012. data.points,
  20013. data.segments,
  20014. data.phiStart,
  20015. data.phiLength
  20016. );
  20017. break;
  20018. case 'BufferGeometry':
  20019. geometry = bufferGeometryLoader.parse( data );
  20020. break;
  20021. case 'Geometry':
  20022. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  20023. break;
  20024. default:
  20025. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  20026. continue;
  20027. }
  20028. geometry.uuid = data.uuid;
  20029. if ( data.name !== undefined ) geometry.name = data.name;
  20030. geometries[ data.uuid ] = geometry;
  20031. }
  20032. }
  20033. return geometries;
  20034. },
  20035. parseMaterials: function ( json, textures ) {
  20036. var materials = {};
  20037. if ( json !== undefined ) {
  20038. var loader = new MaterialLoader();
  20039. loader.setTextures( textures );
  20040. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20041. var material = loader.parse( json[ i ] );
  20042. materials[ material.uuid ] = material;
  20043. }
  20044. }
  20045. return materials;
  20046. },
  20047. parseAnimations: function ( json ) {
  20048. var animations = [];
  20049. for ( var i = 0; i < json.length; i ++ ) {
  20050. var clip = AnimationClip.parse( json[ i ] );
  20051. animations.push( clip );
  20052. }
  20053. return animations;
  20054. },
  20055. parseImages: function ( json, onLoad ) {
  20056. var scope = this;
  20057. var images = {};
  20058. function loadImage( url ) {
  20059. scope.manager.itemStart( url );
  20060. return loader.load( url, function () {
  20061. scope.manager.itemEnd( url );
  20062. }, undefined, function () {
  20063. scope.manager.itemError( url );
  20064. } );
  20065. }
  20066. if ( json !== undefined && json.length > 0 ) {
  20067. var manager = new LoadingManager( onLoad );
  20068. var loader = new ImageLoader( manager );
  20069. loader.setCrossOrigin( this.crossOrigin );
  20070. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20071. var image = json[ i ];
  20072. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  20073. images[ image.uuid ] = loadImage( path );
  20074. }
  20075. }
  20076. return images;
  20077. },
  20078. parseTextures: function ( json, images ) {
  20079. var TextureMapping = {
  20080. UVMapping: UVMapping,
  20081. CubeReflectionMapping: CubeReflectionMapping,
  20082. CubeRefractionMapping: CubeRefractionMapping,
  20083. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  20084. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  20085. SphericalReflectionMapping: SphericalReflectionMapping,
  20086. CubeUVReflectionMapping: CubeUVReflectionMapping,
  20087. CubeUVRefractionMapping: CubeUVRefractionMapping
  20088. };
  20089. var TextureWrapping = {
  20090. RepeatWrapping: RepeatWrapping,
  20091. ClampToEdgeWrapping: ClampToEdgeWrapping,
  20092. MirroredRepeatWrapping: MirroredRepeatWrapping
  20093. };
  20094. var TextureFilter = {
  20095. NearestFilter: NearestFilter,
  20096. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  20097. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  20098. LinearFilter: LinearFilter,
  20099. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  20100. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  20101. };
  20102. function parseConstant( value, type ) {
  20103. if ( typeof( value ) === 'number' ) return value;
  20104. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  20105. return type[ value ];
  20106. }
  20107. var textures = {};
  20108. if ( json !== undefined ) {
  20109. for ( var i = 0, l = json.length; i < l; i ++ ) {
  20110. var data = json[ i ];
  20111. if ( data.image === undefined ) {
  20112. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  20113. }
  20114. if ( images[ data.image ] === undefined ) {
  20115. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  20116. }
  20117. var texture = new Texture( images[ data.image ] );
  20118. texture.needsUpdate = true;
  20119. texture.uuid = data.uuid;
  20120. if ( data.name !== undefined ) texture.name = data.name;
  20121. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  20122. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  20123. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  20124. if ( data.wrap !== undefined ) {
  20125. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  20126. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  20127. }
  20128. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  20129. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  20130. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  20131. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  20132. textures[ data.uuid ] = texture;
  20133. }
  20134. }
  20135. return textures;
  20136. },
  20137. parseObject: function () {
  20138. var matrix = new Matrix4();
  20139. return function parseObject( data, geometries, materials ) {
  20140. var object;
  20141. function getGeometry( name ) {
  20142. if ( geometries[ name ] === undefined ) {
  20143. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  20144. }
  20145. return geometries[ name ];
  20146. }
  20147. function getMaterial( name ) {
  20148. if ( name === undefined ) return undefined;
  20149. if ( materials[ name ] === undefined ) {
  20150. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  20151. }
  20152. return materials[ name ];
  20153. }
  20154. switch ( data.type ) {
  20155. case 'Scene':
  20156. object = new Scene();
  20157. if ( data.background !== undefined ) {
  20158. if ( Number.isInteger( data.background ) ) {
  20159. object.background = new Color( data.background );
  20160. }
  20161. }
  20162. if ( data.fog !== undefined ) {
  20163. if ( data.fog.type === 'Fog' ) {
  20164. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  20165. } else if ( data.fog.type === 'FogExp2' ) {
  20166. object.fog = new FogExp2( data.fog.color, data.fog.density );
  20167. }
  20168. }
  20169. break;
  20170. case 'PerspectiveCamera':
  20171. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  20172. if ( data.focus !== undefined ) object.focus = data.focus;
  20173. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  20174. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  20175. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  20176. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  20177. break;
  20178. case 'OrthographicCamera':
  20179. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  20180. break;
  20181. case 'AmbientLight':
  20182. object = new AmbientLight( data.color, data.intensity );
  20183. break;
  20184. case 'DirectionalLight':
  20185. object = new DirectionalLight( data.color, data.intensity );
  20186. break;
  20187. case 'PointLight':
  20188. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  20189. break;
  20190. case 'SpotLight':
  20191. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  20192. break;
  20193. case 'HemisphereLight':
  20194. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  20195. break;
  20196. case 'Mesh':
  20197. var geometry = getGeometry( data.geometry );
  20198. var material = getMaterial( data.material );
  20199. if ( geometry.bones && geometry.bones.length > 0 ) {
  20200. object = new SkinnedMesh( geometry, material );
  20201. } else {
  20202. object = new Mesh( geometry, material );
  20203. }
  20204. break;
  20205. case 'LOD':
  20206. object = new LOD();
  20207. break;
  20208. case 'Line':
  20209. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  20210. break;
  20211. case 'LineSegments':
  20212. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  20213. break;
  20214. case 'PointCloud':
  20215. case 'Points':
  20216. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  20217. break;
  20218. case 'Sprite':
  20219. object = new Sprite( getMaterial( data.material ) );
  20220. break;
  20221. case 'Group':
  20222. object = new Group();
  20223. break;
  20224. case 'SkinnedMesh':
  20225. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.' );
  20226. default:
  20227. object = new Object3D();
  20228. }
  20229. object.uuid = data.uuid;
  20230. if ( data.name !== undefined ) object.name = data.name;
  20231. if ( data.matrix !== undefined ) {
  20232. matrix.fromArray( data.matrix );
  20233. matrix.decompose( object.position, object.quaternion, object.scale );
  20234. } else {
  20235. if ( data.position !== undefined ) object.position.fromArray( data.position );
  20236. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  20237. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  20238. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  20239. }
  20240. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  20241. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  20242. if ( data.shadow ) {
  20243. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  20244. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  20245. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  20246. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  20247. }
  20248. if ( data.visible !== undefined ) object.visible = data.visible;
  20249. if ( data.userData !== undefined ) object.userData = data.userData;
  20250. if ( data.children !== undefined ) {
  20251. for ( var child in data.children ) {
  20252. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  20253. }
  20254. }
  20255. if ( data.type === 'LOD' ) {
  20256. var levels = data.levels;
  20257. for ( var l = 0; l < levels.length; l ++ ) {
  20258. var level = levels[ l ];
  20259. var child = object.getObjectByProperty( 'uuid', level.object );
  20260. if ( child !== undefined ) {
  20261. object.addLevel( child, level.distance );
  20262. }
  20263. }
  20264. }
  20265. return object;
  20266. };
  20267. }()
  20268. } );
  20269. /**
  20270. * @author zz85 / http://www.lab4games.net/zz85/blog
  20271. *
  20272. * Bezier Curves formulas obtained from
  20273. * http://en.wikipedia.org/wiki/Bézier_curve
  20274. */
  20275. function CatmullRom( t, p0, p1, p2, p3 ) {
  20276. var v0 = ( p2 - p0 ) * 0.5;
  20277. var v1 = ( p3 - p1 ) * 0.5;
  20278. var t2 = t * t;
  20279. var t3 = t * t2;
  20280. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20281. }
  20282. //
  20283. function QuadraticBezierP0( t, p ) {
  20284. var k = 1 - t;
  20285. return k * k * p;
  20286. }
  20287. function QuadraticBezierP1( t, p ) {
  20288. return 2 * ( 1 - t ) * t * p;
  20289. }
  20290. function QuadraticBezierP2( t, p ) {
  20291. return t * t * p;
  20292. }
  20293. function QuadraticBezier( t, p0, p1, p2 ) {
  20294. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20295. QuadraticBezierP2( t, p2 );
  20296. }
  20297. //
  20298. function CubicBezierP0( t, p ) {
  20299. var k = 1 - t;
  20300. return k * k * k * p;
  20301. }
  20302. function CubicBezierP1( t, p ) {
  20303. var k = 1 - t;
  20304. return 3 * k * k * t * p;
  20305. }
  20306. function CubicBezierP2( t, p ) {
  20307. return 3 * ( 1 - t ) * t * t * p;
  20308. }
  20309. function CubicBezierP3( t, p ) {
  20310. return t * t * t * p;
  20311. }
  20312. function CubicBezier( t, p0, p1, p2, p3 ) {
  20313. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20314. CubicBezierP3( t, p3 );
  20315. }
  20316. /**
  20317. * @author zz85 / http://www.lab4games.net/zz85/blog
  20318. * Extensible curve object
  20319. *
  20320. * Some common of Curve methods
  20321. * .getPoint(t), getTangent(t)
  20322. * .getPointAt(u), getTangentAt(u)
  20323. * .getPoints(), .getSpacedPoints()
  20324. * .getLength()
  20325. * .updateArcLengths()
  20326. *
  20327. * This following classes subclasses THREE.Curve:
  20328. *
  20329. * -- 2d classes --
  20330. * THREE.LineCurve
  20331. * THREE.QuadraticBezierCurve
  20332. * THREE.CubicBezierCurve
  20333. * THREE.SplineCurve
  20334. * THREE.ArcCurve
  20335. * THREE.EllipseCurve
  20336. *
  20337. * -- 3d classes --
  20338. * THREE.LineCurve3
  20339. * THREE.QuadraticBezierCurve3
  20340. * THREE.CubicBezierCurve3
  20341. * THREE.CatmullRomCurve3
  20342. *
  20343. * A series of curves can be represented as a THREE.CurvePath
  20344. *
  20345. **/
  20346. /**************************************************************
  20347. * Abstract Curve base class
  20348. **************************************************************/
  20349. function Curve() {}
  20350. Curve.prototype = {
  20351. constructor: Curve,
  20352. // Virtual base class method to overwrite and implement in subclasses
  20353. // - t [0 .. 1]
  20354. getPoint: function ( t ) {
  20355. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20356. return null;
  20357. },
  20358. // Get point at relative position in curve according to arc length
  20359. // - u [0 .. 1]
  20360. getPointAt: function ( u ) {
  20361. var t = this.getUtoTmapping( u );
  20362. return this.getPoint( t );
  20363. },
  20364. // Get sequence of points using getPoint( t )
  20365. getPoints: function ( divisions ) {
  20366. if ( ! divisions ) divisions = 5;
  20367. var points = [];
  20368. for ( var d = 0; d <= divisions; d ++ ) {
  20369. points.push( this.getPoint( d / divisions ) );
  20370. }
  20371. return points;
  20372. },
  20373. // Get sequence of points using getPointAt( u )
  20374. getSpacedPoints: function ( divisions ) {
  20375. if ( ! divisions ) divisions = 5;
  20376. var points = [];
  20377. for ( var d = 0; d <= divisions; d ++ ) {
  20378. points.push( this.getPointAt( d / divisions ) );
  20379. }
  20380. return points;
  20381. },
  20382. // Get total curve arc length
  20383. getLength: function () {
  20384. var lengths = this.getLengths();
  20385. return lengths[ lengths.length - 1 ];
  20386. },
  20387. // Get list of cumulative segment lengths
  20388. getLengths: function ( divisions ) {
  20389. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20390. if ( this.cacheArcLengths
  20391. && ( this.cacheArcLengths.length === divisions + 1 )
  20392. && ! this.needsUpdate ) {
  20393. //console.log( "cached", this.cacheArcLengths );
  20394. return this.cacheArcLengths;
  20395. }
  20396. this.needsUpdate = false;
  20397. var cache = [];
  20398. var current, last = this.getPoint( 0 );
  20399. var p, sum = 0;
  20400. cache.push( 0 );
  20401. for ( p = 1; p <= divisions; p ++ ) {
  20402. current = this.getPoint ( p / divisions );
  20403. sum += current.distanceTo( last );
  20404. cache.push( sum );
  20405. last = current;
  20406. }
  20407. this.cacheArcLengths = cache;
  20408. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20409. },
  20410. updateArcLengths: function() {
  20411. this.needsUpdate = true;
  20412. this.getLengths();
  20413. },
  20414. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20415. getUtoTmapping: function ( u, distance ) {
  20416. var arcLengths = this.getLengths();
  20417. var i = 0, il = arcLengths.length;
  20418. var targetArcLength; // The targeted u distance value to get
  20419. if ( distance ) {
  20420. targetArcLength = distance;
  20421. } else {
  20422. targetArcLength = u * arcLengths[ il - 1 ];
  20423. }
  20424. //var time = Date.now();
  20425. // binary search for the index with largest value smaller than target u distance
  20426. var low = 0, high = il - 1, comparison;
  20427. while ( low <= high ) {
  20428. 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
  20429. comparison = arcLengths[ i ] - targetArcLength;
  20430. if ( comparison < 0 ) {
  20431. low = i + 1;
  20432. } else if ( comparison > 0 ) {
  20433. high = i - 1;
  20434. } else {
  20435. high = i;
  20436. break;
  20437. // DONE
  20438. }
  20439. }
  20440. i = high;
  20441. //console.log('b' , i, low, high, Date.now()- time);
  20442. if ( arcLengths[ i ] === targetArcLength ) {
  20443. var t = i / ( il - 1 );
  20444. return t;
  20445. }
  20446. // we could get finer grain at lengths, or use simple interpolation between two points
  20447. var lengthBefore = arcLengths[ i ];
  20448. var lengthAfter = arcLengths[ i + 1 ];
  20449. var segmentLength = lengthAfter - lengthBefore;
  20450. // determine where we are between the 'before' and 'after' points
  20451. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20452. // add that fractional amount to t
  20453. var t = ( i + segmentFraction ) / ( il - 1 );
  20454. return t;
  20455. },
  20456. // Returns a unit vector tangent at t
  20457. // In case any sub curve does not implement its tangent derivation,
  20458. // 2 points a small delta apart will be used to find its gradient
  20459. // which seems to give a reasonable approximation
  20460. getTangent: function( t ) {
  20461. var delta = 0.0001;
  20462. var t1 = t - delta;
  20463. var t2 = t + delta;
  20464. // Capping in case of danger
  20465. if ( t1 < 0 ) t1 = 0;
  20466. if ( t2 > 1 ) t2 = 1;
  20467. var pt1 = this.getPoint( t1 );
  20468. var pt2 = this.getPoint( t2 );
  20469. var vec = pt2.clone().sub( pt1 );
  20470. return vec.normalize();
  20471. },
  20472. getTangentAt: function ( u ) {
  20473. var t = this.getUtoTmapping( u );
  20474. return this.getTangent( t );
  20475. },
  20476. computeFrenetFrames: function ( segments, closed ) {
  20477. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20478. var normal = new Vector3();
  20479. var tangents = [];
  20480. var normals = [];
  20481. var binormals = [];
  20482. var vec = new Vector3();
  20483. var mat = new Matrix4();
  20484. var i, u, theta;
  20485. // compute the tangent vectors for each segment on the curve
  20486. for ( i = 0; i <= segments; i ++ ) {
  20487. u = i / segments;
  20488. tangents[ i ] = this.getTangentAt( u );
  20489. tangents[ i ].normalize();
  20490. }
  20491. // select an initial normal vector perpendicular to the first tangent vector,
  20492. // and in the direction of the minimum tangent xyz component
  20493. normals[ 0 ] = new Vector3();
  20494. binormals[ 0 ] = new Vector3();
  20495. var min = Number.MAX_VALUE;
  20496. var tx = Math.abs( tangents[ 0 ].x );
  20497. var ty = Math.abs( tangents[ 0 ].y );
  20498. var tz = Math.abs( tangents[ 0 ].z );
  20499. if ( tx <= min ) {
  20500. min = tx;
  20501. normal.set( 1, 0, 0 );
  20502. }
  20503. if ( ty <= min ) {
  20504. min = ty;
  20505. normal.set( 0, 1, 0 );
  20506. }
  20507. if ( tz <= min ) {
  20508. normal.set( 0, 0, 1 );
  20509. }
  20510. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20511. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20512. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20513. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20514. for ( i = 1; i <= segments; i ++ ) {
  20515. normals[ i ] = normals[ i - 1 ].clone();
  20516. binormals[ i ] = binormals[ i - 1 ].clone();
  20517. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20518. if ( vec.length() > Number.EPSILON ) {
  20519. vec.normalize();
  20520. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20521. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20522. }
  20523. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20524. }
  20525. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20526. if ( closed === true ) {
  20527. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20528. theta /= segments;
  20529. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20530. theta = - theta;
  20531. }
  20532. for ( i = 1; i <= segments; i ++ ) {
  20533. // twist a little...
  20534. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20535. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20536. }
  20537. }
  20538. return {
  20539. tangents: tangents,
  20540. normals: normals,
  20541. binormals: binormals
  20542. };
  20543. }
  20544. };
  20545. function LineCurve( v1, v2 ) {
  20546. this.v1 = v1;
  20547. this.v2 = v2;
  20548. }
  20549. LineCurve.prototype = Object.create( Curve.prototype );
  20550. LineCurve.prototype.constructor = LineCurve;
  20551. LineCurve.prototype.isLineCurve = true;
  20552. LineCurve.prototype.getPoint = function ( t ) {
  20553. if ( t === 1 ) {
  20554. return this.v2.clone();
  20555. }
  20556. var point = this.v2.clone().sub( this.v1 );
  20557. point.multiplyScalar( t ).add( this.v1 );
  20558. return point;
  20559. };
  20560. // Line curve is linear, so we can overwrite default getPointAt
  20561. LineCurve.prototype.getPointAt = function ( u ) {
  20562. return this.getPoint( u );
  20563. };
  20564. LineCurve.prototype.getTangent = function ( t ) {
  20565. var tangent = this.v2.clone().sub( this.v1 );
  20566. return tangent.normalize();
  20567. };
  20568. /**
  20569. * @author zz85 / http://www.lab4games.net/zz85/blog
  20570. *
  20571. **/
  20572. /**************************************************************
  20573. * Curved Path - a curve path is simply a array of connected
  20574. * curves, but retains the api of a curve
  20575. **************************************************************/
  20576. function CurvePath() {
  20577. this.curves = [];
  20578. this.autoClose = false; // Automatically closes the path
  20579. }
  20580. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  20581. constructor: CurvePath,
  20582. add: function ( curve ) {
  20583. this.curves.push( curve );
  20584. },
  20585. closePath: function () {
  20586. // Add a line curve if start and end of lines are not connected
  20587. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20588. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20589. if ( ! startPoint.equals( endPoint ) ) {
  20590. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20591. }
  20592. },
  20593. // To get accurate point with reference to
  20594. // entire path distance at time t,
  20595. // following has to be done:
  20596. // 1. Length of each sub path have to be known
  20597. // 2. Locate and identify type of curve
  20598. // 3. Get t for the curve
  20599. // 4. Return curve.getPointAt(t')
  20600. getPoint: function ( t ) {
  20601. var d = t * this.getLength();
  20602. var curveLengths = this.getCurveLengths();
  20603. var i = 0;
  20604. // To think about boundaries points.
  20605. while ( i < curveLengths.length ) {
  20606. if ( curveLengths[ i ] >= d ) {
  20607. var diff = curveLengths[ i ] - d;
  20608. var curve = this.curves[ i ];
  20609. var segmentLength = curve.getLength();
  20610. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20611. return curve.getPointAt( u );
  20612. }
  20613. i ++;
  20614. }
  20615. return null;
  20616. // loop where sum != 0, sum > d , sum+1 <d
  20617. },
  20618. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20619. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20620. // getPoint() depends on getLength
  20621. getLength: function () {
  20622. var lens = this.getCurveLengths();
  20623. return lens[ lens.length - 1 ];
  20624. },
  20625. // cacheLengths must be recalculated.
  20626. updateArcLengths: function () {
  20627. this.needsUpdate = true;
  20628. this.cacheLengths = null;
  20629. this.getLengths();
  20630. },
  20631. // Compute lengths and cache them
  20632. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20633. getCurveLengths: function () {
  20634. // We use cache values if curves and cache array are same length
  20635. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20636. return this.cacheLengths;
  20637. }
  20638. // Get length of sub-curve
  20639. // Push sums into cached array
  20640. var lengths = [], sums = 0;
  20641. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20642. sums += this.curves[ i ].getLength();
  20643. lengths.push( sums );
  20644. }
  20645. this.cacheLengths = lengths;
  20646. return lengths;
  20647. },
  20648. getSpacedPoints: function ( divisions ) {
  20649. if ( ! divisions ) divisions = 40;
  20650. var points = [];
  20651. for ( var i = 0; i <= divisions; i ++ ) {
  20652. points.push( this.getPoint( i / divisions ) );
  20653. }
  20654. if ( this.autoClose ) {
  20655. points.push( points[ 0 ] );
  20656. }
  20657. return points;
  20658. },
  20659. getPoints: function ( divisions ) {
  20660. divisions = divisions || 12;
  20661. var points = [], last;
  20662. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20663. var curve = curves[ i ];
  20664. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  20665. : (curve && curve.isLineCurve) ? 1
  20666. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  20667. : divisions;
  20668. var pts = curve.getPoints( resolution );
  20669. for ( var j = 0; j < pts.length; j++ ) {
  20670. var point = pts[ j ];
  20671. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20672. points.push( point );
  20673. last = point;
  20674. }
  20675. }
  20676. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20677. points.push( points[ 0 ] );
  20678. }
  20679. return points;
  20680. },
  20681. /**************************************************************
  20682. * Create Geometries Helpers
  20683. **************************************************************/
  20684. /// Generate geometry from path points (for Line or Points objects)
  20685. createPointsGeometry: function ( divisions ) {
  20686. var pts = this.getPoints( divisions );
  20687. return this.createGeometry( pts );
  20688. },
  20689. // Generate geometry from equidistant sampling along the path
  20690. createSpacedPointsGeometry: function ( divisions ) {
  20691. var pts = this.getSpacedPoints( divisions );
  20692. return this.createGeometry( pts );
  20693. },
  20694. createGeometry: function ( points ) {
  20695. var geometry = new Geometry();
  20696. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20697. var point = points[ i ];
  20698. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  20699. }
  20700. return geometry;
  20701. }
  20702. } );
  20703. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20704. this.aX = aX;
  20705. this.aY = aY;
  20706. this.xRadius = xRadius;
  20707. this.yRadius = yRadius;
  20708. this.aStartAngle = aStartAngle;
  20709. this.aEndAngle = aEndAngle;
  20710. this.aClockwise = aClockwise;
  20711. this.aRotation = aRotation || 0;
  20712. }
  20713. EllipseCurve.prototype = Object.create( Curve.prototype );
  20714. EllipseCurve.prototype.constructor = EllipseCurve;
  20715. EllipseCurve.prototype.isEllipseCurve = true;
  20716. EllipseCurve.prototype.getPoint = function ( t ) {
  20717. var twoPi = Math.PI * 2;
  20718. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20719. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20720. // ensures that deltaAngle is 0 .. 2 PI
  20721. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20722. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20723. if ( deltaAngle < Number.EPSILON ) {
  20724. if ( samePoints ) {
  20725. deltaAngle = 0;
  20726. } else {
  20727. deltaAngle = twoPi;
  20728. }
  20729. }
  20730. if ( this.aClockwise === true && ! samePoints ) {
  20731. if ( deltaAngle === twoPi ) {
  20732. deltaAngle = - twoPi;
  20733. } else {
  20734. deltaAngle = deltaAngle - twoPi;
  20735. }
  20736. }
  20737. var angle = this.aStartAngle + t * deltaAngle;
  20738. var x = this.aX + this.xRadius * Math.cos( angle );
  20739. var y = this.aY + this.yRadius * Math.sin( angle );
  20740. if ( this.aRotation !== 0 ) {
  20741. var cos = Math.cos( this.aRotation );
  20742. var sin = Math.sin( this.aRotation );
  20743. var tx = x - this.aX;
  20744. var ty = y - this.aY;
  20745. // Rotate the point about the center of the ellipse.
  20746. x = tx * cos - ty * sin + this.aX;
  20747. y = tx * sin + ty * cos + this.aY;
  20748. }
  20749. return new Vector2( x, y );
  20750. };
  20751. function SplineCurve( points /* array of Vector2 */ ) {
  20752. this.points = ( points === undefined ) ? [] : points;
  20753. }
  20754. SplineCurve.prototype = Object.create( Curve.prototype );
  20755. SplineCurve.prototype.constructor = SplineCurve;
  20756. SplineCurve.prototype.isSplineCurve = true;
  20757. SplineCurve.prototype.getPoint = function ( t ) {
  20758. var points = this.points;
  20759. var point = ( points.length - 1 ) * t;
  20760. var intPoint = Math.floor( point );
  20761. var weight = point - intPoint;
  20762. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20763. var point1 = points[ intPoint ];
  20764. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20765. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20766. return new Vector2(
  20767. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  20768. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  20769. );
  20770. };
  20771. function CubicBezierCurve( v0, v1, v2, v3 ) {
  20772. this.v0 = v0;
  20773. this.v1 = v1;
  20774. this.v2 = v2;
  20775. this.v3 = v3;
  20776. }
  20777. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  20778. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  20779. CubicBezierCurve.prototype.getPoint = function ( t ) {
  20780. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20781. return new Vector2(
  20782. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20783. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  20784. );
  20785. };
  20786. function QuadraticBezierCurve( v0, v1, v2 ) {
  20787. this.v0 = v0;
  20788. this.v1 = v1;
  20789. this.v2 = v2;
  20790. }
  20791. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  20792. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  20793. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20794. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20795. return new Vector2(
  20796. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20797. QuadraticBezier( t, v0.y, v1.y, v2.y )
  20798. );
  20799. };
  20800. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  20801. fromPoints: function ( vectors ) {
  20802. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20803. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20804. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20805. }
  20806. },
  20807. moveTo: function ( x, y ) {
  20808. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20809. },
  20810. lineTo: function ( x, y ) {
  20811. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20812. this.curves.push( curve );
  20813. this.currentPoint.set( x, y );
  20814. },
  20815. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20816. var curve = new QuadraticBezierCurve(
  20817. this.currentPoint.clone(),
  20818. new Vector2( aCPx, aCPy ),
  20819. new Vector2( aX, aY )
  20820. );
  20821. this.curves.push( curve );
  20822. this.currentPoint.set( aX, aY );
  20823. },
  20824. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20825. var curve = new CubicBezierCurve(
  20826. this.currentPoint.clone(),
  20827. new Vector2( aCP1x, aCP1y ),
  20828. new Vector2( aCP2x, aCP2y ),
  20829. new Vector2( aX, aY )
  20830. );
  20831. this.curves.push( curve );
  20832. this.currentPoint.set( aX, aY );
  20833. },
  20834. splineThru: function ( pts /*Array of Vector*/ ) {
  20835. var npts = [ this.currentPoint.clone() ].concat( pts );
  20836. var curve = new SplineCurve( npts );
  20837. this.curves.push( curve );
  20838. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20839. },
  20840. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20841. var x0 = this.currentPoint.x;
  20842. var y0 = this.currentPoint.y;
  20843. this.absarc( aX + x0, aY + y0, aRadius,
  20844. aStartAngle, aEndAngle, aClockwise );
  20845. },
  20846. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20847. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20848. },
  20849. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20850. var x0 = this.currentPoint.x;
  20851. var y0 = this.currentPoint.y;
  20852. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20853. },
  20854. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20855. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20856. if ( this.curves.length > 0 ) {
  20857. // if a previous curve is present, attempt to join
  20858. var firstPoint = curve.getPoint( 0 );
  20859. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20860. this.lineTo( firstPoint.x, firstPoint.y );
  20861. }
  20862. }
  20863. this.curves.push( curve );
  20864. var lastPoint = curve.getPoint( 1 );
  20865. this.currentPoint.copy( lastPoint );
  20866. }
  20867. } );
  20868. /**
  20869. * @author zz85 / http://www.lab4games.net/zz85/blog
  20870. * Creates free form 2d path using series of points, lines or curves.
  20871. **/
  20872. function Path( points ) {
  20873. CurvePath.call( this );
  20874. this.currentPoint = new Vector2();
  20875. if ( points ) {
  20876. this.fromPoints( points );
  20877. }
  20878. }
  20879. Path.prototype = PathPrototype;
  20880. PathPrototype.constructor = Path;
  20881. /**
  20882. * @author zz85 / http://www.lab4games.net/zz85/blog
  20883. * Defines a 2d shape plane using paths.
  20884. **/
  20885. // STEP 1 Create a path.
  20886. // STEP 2 Turn path into shape.
  20887. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20888. // STEP 3a - Extract points from each shape, turn to vertices
  20889. // STEP 3b - Triangulate each shape, add faces.
  20890. function Shape() {
  20891. Path.apply( this, arguments );
  20892. this.holes = [];
  20893. }
  20894. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  20895. constructor: Shape,
  20896. getPointsHoles: function ( divisions ) {
  20897. var holesPts = [];
  20898. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20899. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20900. }
  20901. return holesPts;
  20902. },
  20903. // Get points of shape and holes (keypoints based on segments parameter)
  20904. extractAllPoints: function ( divisions ) {
  20905. return {
  20906. shape: this.getPoints( divisions ),
  20907. holes: this.getPointsHoles( divisions )
  20908. };
  20909. },
  20910. extractPoints: function ( divisions ) {
  20911. return this.extractAllPoints( divisions );
  20912. }
  20913. } );
  20914. /**
  20915. * @author zz85 / http://www.lab4games.net/zz85/blog
  20916. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  20917. **/
  20918. function ShapePath() {
  20919. this.subPaths = [];
  20920. this.currentPath = null;
  20921. }
  20922. ShapePath.prototype = {
  20923. moveTo: function ( x, y ) {
  20924. this.currentPath = new Path();
  20925. this.subPaths.push( this.currentPath );
  20926. this.currentPath.moveTo( x, y );
  20927. },
  20928. lineTo: function ( x, y ) {
  20929. this.currentPath.lineTo( x, y );
  20930. },
  20931. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20932. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  20933. },
  20934. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20935. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  20936. },
  20937. splineThru: function ( pts ) {
  20938. this.currentPath.splineThru( pts );
  20939. },
  20940. toShapes: function ( isCCW, noHoles ) {
  20941. function toShapesNoHoles( inSubpaths ) {
  20942. var shapes = [];
  20943. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20944. var tmpPath = inSubpaths[ i ];
  20945. var tmpShape = new Shape();
  20946. tmpShape.curves = tmpPath.curves;
  20947. shapes.push( tmpShape );
  20948. }
  20949. return shapes;
  20950. }
  20951. function isPointInsidePolygon( inPt, inPolygon ) {
  20952. var polyLen = inPolygon.length;
  20953. // inPt on polygon contour => immediate success or
  20954. // toggling of inside/outside at every single! intersection point of an edge
  20955. // with the horizontal line through inPt, left of inPt
  20956. // not counting lowerY endpoints of edges and whole edges on that line
  20957. var inside = false;
  20958. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20959. var edgeLowPt = inPolygon[ p ];
  20960. var edgeHighPt = inPolygon[ q ];
  20961. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20962. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20963. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20964. // not parallel
  20965. if ( edgeDy < 0 ) {
  20966. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20967. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20968. }
  20969. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20970. if ( inPt.y === edgeLowPt.y ) {
  20971. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20972. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20973. } else {
  20974. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20975. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20976. if ( perpEdge < 0 ) continue;
  20977. inside = ! inside; // true intersection left of inPt
  20978. }
  20979. } else {
  20980. // parallel or collinear
  20981. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20982. // edge lies on the same horizontal line as inPt
  20983. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20984. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20985. // continue;
  20986. }
  20987. }
  20988. return inside;
  20989. }
  20990. var isClockWise = ShapeUtils.isClockWise;
  20991. var subPaths = this.subPaths;
  20992. if ( subPaths.length === 0 ) return [];
  20993. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20994. var solid, tmpPath, tmpShape, shapes = [];
  20995. if ( subPaths.length === 1 ) {
  20996. tmpPath = subPaths[ 0 ];
  20997. tmpShape = new Shape();
  20998. tmpShape.curves = tmpPath.curves;
  20999. shapes.push( tmpShape );
  21000. return shapes;
  21001. }
  21002. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21003. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21004. // console.log("Holes first", holesFirst);
  21005. var betterShapeHoles = [];
  21006. var newShapes = [];
  21007. var newShapeHoles = [];
  21008. var mainIdx = 0;
  21009. var tmpPoints;
  21010. newShapes[ mainIdx ] = undefined;
  21011. newShapeHoles[ mainIdx ] = [];
  21012. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21013. tmpPath = subPaths[ i ];
  21014. tmpPoints = tmpPath.getPoints();
  21015. solid = isClockWise( tmpPoints );
  21016. solid = isCCW ? ! solid : solid;
  21017. if ( solid ) {
  21018. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21019. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21020. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21021. if ( holesFirst ) mainIdx ++;
  21022. newShapeHoles[ mainIdx ] = [];
  21023. //console.log('cw', i);
  21024. } else {
  21025. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21026. //console.log('ccw', i);
  21027. }
  21028. }
  21029. // only Holes? -> probably all Shapes with wrong orientation
  21030. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21031. if ( newShapes.length > 1 ) {
  21032. var ambiguous = false;
  21033. var toChange = [];
  21034. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21035. betterShapeHoles[ sIdx ] = [];
  21036. }
  21037. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21038. var sho = newShapeHoles[ sIdx ];
  21039. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21040. var ho = sho[ hIdx ];
  21041. var hole_unassigned = true;
  21042. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21043. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21044. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21045. if ( hole_unassigned ) {
  21046. hole_unassigned = false;
  21047. betterShapeHoles[ s2Idx ].push( ho );
  21048. } else {
  21049. ambiguous = true;
  21050. }
  21051. }
  21052. }
  21053. if ( hole_unassigned ) {
  21054. betterShapeHoles[ sIdx ].push( ho );
  21055. }
  21056. }
  21057. }
  21058. // console.log("ambiguous: ", ambiguous);
  21059. if ( toChange.length > 0 ) {
  21060. // console.log("to change: ", toChange);
  21061. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21062. }
  21063. }
  21064. var tmpHoles;
  21065. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21066. tmpShape = newShapes[ i ].s;
  21067. shapes.push( tmpShape );
  21068. tmpHoles = newShapeHoles[ i ];
  21069. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21070. tmpShape.holes.push( tmpHoles[ j ].h );
  21071. }
  21072. }
  21073. //console.log("shape", shapes);
  21074. return shapes;
  21075. }
  21076. };
  21077. /**
  21078. * @author zz85 / http://www.lab4games.net/zz85/blog
  21079. * @author mrdoob / http://mrdoob.com/
  21080. */
  21081. function Font( data ) {
  21082. this.data = data;
  21083. }
  21084. Object.assign( Font.prototype, {
  21085. isFont: true,
  21086. generateShapes: function ( text, size, divisions ) {
  21087. function createPaths( text ) {
  21088. var chars = String( text ).split( '' );
  21089. var scale = size / data.resolution;
  21090. var offset = 0;
  21091. var paths = [];
  21092. for ( var i = 0; i < chars.length; i ++ ) {
  21093. var ret = createPath( chars[ i ], scale, offset );
  21094. offset += ret.offset;
  21095. paths.push( ret.path );
  21096. }
  21097. return paths;
  21098. }
  21099. function createPath( c, scale, offset ) {
  21100. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  21101. if ( ! glyph ) return;
  21102. var path = new ShapePath();
  21103. var pts = [];
  21104. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  21105. if ( glyph.o ) {
  21106. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  21107. for ( var i = 0, l = outline.length; i < l; ) {
  21108. var action = outline[ i ++ ];
  21109. switch ( action ) {
  21110. case 'm': // moveTo
  21111. x = outline[ i ++ ] * scale + offset;
  21112. y = outline[ i ++ ] * scale;
  21113. path.moveTo( x, y );
  21114. break;
  21115. case 'l': // lineTo
  21116. x = outline[ i ++ ] * scale + offset;
  21117. y = outline[ i ++ ] * scale;
  21118. path.lineTo( x, y );
  21119. break;
  21120. case 'q': // quadraticCurveTo
  21121. cpx = outline[ i ++ ] * scale + offset;
  21122. cpy = outline[ i ++ ] * scale;
  21123. cpx1 = outline[ i ++ ] * scale + offset;
  21124. cpy1 = outline[ i ++ ] * scale;
  21125. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  21126. laste = pts[ pts.length - 1 ];
  21127. if ( laste ) {
  21128. cpx0 = laste.x;
  21129. cpy0 = laste.y;
  21130. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21131. var t = i2 / divisions;
  21132. QuadraticBezier( t, cpx0, cpx1, cpx );
  21133. QuadraticBezier( t, cpy0, cpy1, cpy );
  21134. }
  21135. }
  21136. break;
  21137. case 'b': // bezierCurveTo
  21138. cpx = outline[ i ++ ] * scale + offset;
  21139. cpy = outline[ i ++ ] * scale;
  21140. cpx1 = outline[ i ++ ] * scale + offset;
  21141. cpy1 = outline[ i ++ ] * scale;
  21142. cpx2 = outline[ i ++ ] * scale + offset;
  21143. cpy2 = outline[ i ++ ] * scale;
  21144. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  21145. laste = pts[ pts.length - 1 ];
  21146. if ( laste ) {
  21147. cpx0 = laste.x;
  21148. cpy0 = laste.y;
  21149. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  21150. var t = i2 / divisions;
  21151. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  21152. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  21153. }
  21154. }
  21155. break;
  21156. }
  21157. }
  21158. }
  21159. return { offset: glyph.ha * scale, path: path };
  21160. }
  21161. //
  21162. if ( size === undefined ) size = 100;
  21163. if ( divisions === undefined ) divisions = 4;
  21164. var data = this.data;
  21165. var paths = createPaths( text );
  21166. var shapes = [];
  21167. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  21168. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  21169. }
  21170. return shapes;
  21171. }
  21172. } );
  21173. /**
  21174. * @author mrdoob / http://mrdoob.com/
  21175. */
  21176. function FontLoader( manager ) {
  21177. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21178. }
  21179. Object.assign( FontLoader.prototype, {
  21180. load: function ( url, onLoad, onProgress, onError ) {
  21181. var scope = this;
  21182. var loader = new FileLoader( this.manager );
  21183. loader.load( url, function ( text ) {
  21184. var json;
  21185. try {
  21186. json = JSON.parse( text );
  21187. } catch ( e ) {
  21188. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  21189. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  21190. }
  21191. var font = scope.parse( json );
  21192. if ( onLoad ) onLoad( font );
  21193. }, onProgress, onError );
  21194. },
  21195. parse: function ( json ) {
  21196. return new Font( json );
  21197. }
  21198. } );
  21199. var context;
  21200. var AudioContext = {
  21201. getContext: function () {
  21202. if ( context === undefined ) {
  21203. context = new ( window.AudioContext || window.webkitAudioContext )();
  21204. }
  21205. return context;
  21206. },
  21207. setContext: function ( value ) {
  21208. context = value;
  21209. }
  21210. };
  21211. /**
  21212. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21213. */
  21214. function AudioLoader( manager ) {
  21215. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21216. }
  21217. Object.assign( AudioLoader.prototype, {
  21218. load: function ( url, onLoad, onProgress, onError ) {
  21219. var loader = new FileLoader( this.manager );
  21220. loader.setResponseType( 'arraybuffer' );
  21221. loader.load( url, function ( buffer ) {
  21222. var context = AudioContext.getContext();
  21223. context.decodeAudioData( buffer, function ( audioBuffer ) {
  21224. onLoad( audioBuffer );
  21225. } );
  21226. }, onProgress, onError );
  21227. }
  21228. } );
  21229. /**
  21230. * @author abelnation / http://github.com/abelnation
  21231. */
  21232. function RectAreaLight ( color, intensity, width, height ) {
  21233. Light.call( this, color, intensity );
  21234. this.type = 'RectAreaLight';
  21235. this.position.set( 0, 1, 0 );
  21236. this.updateMatrix();
  21237. this.width = ( width !== undefined ) ? width : 10;
  21238. this.height = ( height !== undefined ) ? height : 10;
  21239. // TODO (abelnation): distance/decay
  21240. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  21241. // TODO (abelnation): shadows
  21242. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  21243. }
  21244. // TODO (abelnation): RectAreaLight update when light shape is changed
  21245. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  21246. constructor: RectAreaLight,
  21247. isRectAreaLight: true,
  21248. copy: function ( source ) {
  21249. Light.prototype.copy.call( this, source );
  21250. this.width = source.width;
  21251. this.height = source.height;
  21252. // this.shadow = source.shadow.clone();
  21253. return this;
  21254. }
  21255. } );
  21256. /**
  21257. * @author mrdoob / http://mrdoob.com/
  21258. */
  21259. function StereoCamera() {
  21260. this.type = 'StereoCamera';
  21261. this.aspect = 1;
  21262. this.eyeSep = 0.064;
  21263. this.cameraL = new PerspectiveCamera();
  21264. this.cameraL.layers.enable( 1 );
  21265. this.cameraL.matrixAutoUpdate = false;
  21266. this.cameraR = new PerspectiveCamera();
  21267. this.cameraR.layers.enable( 2 );
  21268. this.cameraR.matrixAutoUpdate = false;
  21269. }
  21270. Object.assign( StereoCamera.prototype, {
  21271. update: ( function () {
  21272. var instance, focus, fov, aspect, near, far, zoom;
  21273. var eyeRight = new Matrix4();
  21274. var eyeLeft = new Matrix4();
  21275. return function update( camera ) {
  21276. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  21277. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  21278. far !== camera.far || zoom !== camera.zoom;
  21279. if ( needsUpdate ) {
  21280. instance = this;
  21281. focus = camera.focus;
  21282. fov = camera.fov;
  21283. aspect = camera.aspect * this.aspect;
  21284. near = camera.near;
  21285. far = camera.far;
  21286. zoom = camera.zoom;
  21287. // Off-axis stereoscopic effect based on
  21288. // http://paulbourke.net/stereographics/stereorender/
  21289. var projectionMatrix = camera.projectionMatrix.clone();
  21290. var eyeSep = this.eyeSep / 2;
  21291. var eyeSepOnProjection = eyeSep * near / focus;
  21292. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  21293. var xmin, xmax;
  21294. // translate xOffset
  21295. eyeLeft.elements[ 12 ] = - eyeSep;
  21296. eyeRight.elements[ 12 ] = eyeSep;
  21297. // for left eye
  21298. xmin = - ymax * aspect + eyeSepOnProjection;
  21299. xmax = ymax * aspect + eyeSepOnProjection;
  21300. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21301. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21302. this.cameraL.projectionMatrix.copy( projectionMatrix );
  21303. // for right eye
  21304. xmin = - ymax * aspect - eyeSepOnProjection;
  21305. xmax = ymax * aspect - eyeSepOnProjection;
  21306. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  21307. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  21308. this.cameraR.projectionMatrix.copy( projectionMatrix );
  21309. }
  21310. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  21311. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  21312. };
  21313. } )()
  21314. } );
  21315. /**
  21316. * Camera for rendering cube maps
  21317. * - renders scene into axis-aligned cube
  21318. *
  21319. * @author alteredq / http://alteredqualia.com/
  21320. */
  21321. function CubeCamera( near, far, cubeResolution ) {
  21322. Object3D.call( this );
  21323. this.type = 'CubeCamera';
  21324. var fov = 90, aspect = 1;
  21325. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  21326. cameraPX.up.set( 0, - 1, 0 );
  21327. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  21328. this.add( cameraPX );
  21329. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  21330. cameraNX.up.set( 0, - 1, 0 );
  21331. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  21332. this.add( cameraNX );
  21333. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  21334. cameraPY.up.set( 0, 0, 1 );
  21335. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  21336. this.add( cameraPY );
  21337. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  21338. cameraNY.up.set( 0, 0, - 1 );
  21339. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  21340. this.add( cameraNY );
  21341. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  21342. cameraPZ.up.set( 0, - 1, 0 );
  21343. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  21344. this.add( cameraPZ );
  21345. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  21346. cameraNZ.up.set( 0, - 1, 0 );
  21347. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  21348. this.add( cameraNZ );
  21349. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  21350. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  21351. this.updateCubeMap = function ( renderer, scene ) {
  21352. if ( this.parent === null ) this.updateMatrixWorld();
  21353. var renderTarget = this.renderTarget;
  21354. var generateMipmaps = renderTarget.texture.generateMipmaps;
  21355. renderTarget.texture.generateMipmaps = false;
  21356. renderTarget.activeCubeFace = 0;
  21357. renderer.render( scene, cameraPX, renderTarget );
  21358. renderTarget.activeCubeFace = 1;
  21359. renderer.render( scene, cameraNX, renderTarget );
  21360. renderTarget.activeCubeFace = 2;
  21361. renderer.render( scene, cameraPY, renderTarget );
  21362. renderTarget.activeCubeFace = 3;
  21363. renderer.render( scene, cameraNY, renderTarget );
  21364. renderTarget.activeCubeFace = 4;
  21365. renderer.render( scene, cameraPZ, renderTarget );
  21366. renderTarget.texture.generateMipmaps = generateMipmaps;
  21367. renderTarget.activeCubeFace = 5;
  21368. renderer.render( scene, cameraNZ, renderTarget );
  21369. renderer.setRenderTarget( null );
  21370. };
  21371. }
  21372. CubeCamera.prototype = Object.create( Object3D.prototype );
  21373. CubeCamera.prototype.constructor = CubeCamera;
  21374. /**
  21375. * @author mrdoob / http://mrdoob.com/
  21376. */
  21377. function AudioListener() {
  21378. Object3D.call( this );
  21379. this.type = 'AudioListener';
  21380. this.context = AudioContext.getContext();
  21381. this.gain = this.context.createGain();
  21382. this.gain.connect( this.context.destination );
  21383. this.filter = null;
  21384. }
  21385. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21386. constructor: AudioListener,
  21387. getInput: function () {
  21388. return this.gain;
  21389. },
  21390. removeFilter: function ( ) {
  21391. if ( this.filter !== null ) {
  21392. this.gain.disconnect( this.filter );
  21393. this.filter.disconnect( this.context.destination );
  21394. this.gain.connect( this.context.destination );
  21395. this.filter = null;
  21396. }
  21397. },
  21398. getFilter: function () {
  21399. return this.filter;
  21400. },
  21401. setFilter: function ( value ) {
  21402. if ( this.filter !== null ) {
  21403. this.gain.disconnect( this.filter );
  21404. this.filter.disconnect( this.context.destination );
  21405. } else {
  21406. this.gain.disconnect( this.context.destination );
  21407. }
  21408. this.filter = value;
  21409. this.gain.connect( this.filter );
  21410. this.filter.connect( this.context.destination );
  21411. },
  21412. getMasterVolume: function () {
  21413. return this.gain.gain.value;
  21414. },
  21415. setMasterVolume: function ( value ) {
  21416. this.gain.gain.value = value;
  21417. },
  21418. updateMatrixWorld: ( function () {
  21419. var position = new Vector3();
  21420. var quaternion = new Quaternion();
  21421. var scale = new Vector3();
  21422. var orientation = new Vector3();
  21423. return function updateMatrixWorld( force ) {
  21424. Object3D.prototype.updateMatrixWorld.call( this, force );
  21425. var listener = this.context.listener;
  21426. var up = this.up;
  21427. this.matrixWorld.decompose( position, quaternion, scale );
  21428. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  21429. if ( listener.positionX ) {
  21430. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  21431. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  21432. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  21433. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  21434. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  21435. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  21436. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  21437. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  21438. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  21439. } else {
  21440. listener.setPosition( position.x, position.y, position.z );
  21441. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  21442. }
  21443. };
  21444. } )()
  21445. } );
  21446. /**
  21447. * @author mrdoob / http://mrdoob.com/
  21448. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  21449. */
  21450. function Audio( listener ) {
  21451. Object3D.call( this );
  21452. this.type = 'Audio';
  21453. this.context = listener.context;
  21454. this.gain = this.context.createGain();
  21455. this.gain.connect( listener.getInput() );
  21456. this.autoplay = false;
  21457. this.buffer = null;
  21458. this.loop = false;
  21459. this.startTime = 0;
  21460. this.playbackRate = 1;
  21461. this.isPlaying = false;
  21462. this.hasPlaybackControl = true;
  21463. this.sourceType = 'empty';
  21464. this.filters = [];
  21465. }
  21466. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21467. constructor: Audio,
  21468. getOutput: function () {
  21469. return this.gain;
  21470. },
  21471. setNodeSource: function ( audioNode ) {
  21472. this.hasPlaybackControl = false;
  21473. this.sourceType = 'audioNode';
  21474. this.source = audioNode;
  21475. this.connect();
  21476. return this;
  21477. },
  21478. setBuffer: function ( audioBuffer ) {
  21479. this.buffer = audioBuffer;
  21480. this.sourceType = 'buffer';
  21481. if ( this.autoplay ) this.play();
  21482. return this;
  21483. },
  21484. play: function () {
  21485. if ( this.isPlaying === true ) {
  21486. console.warn( 'THREE.Audio: Audio is already playing.' );
  21487. return;
  21488. }
  21489. if ( this.hasPlaybackControl === false ) {
  21490. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21491. return;
  21492. }
  21493. var source = this.context.createBufferSource();
  21494. source.buffer = this.buffer;
  21495. source.loop = this.loop;
  21496. source.onended = this.onEnded.bind( this );
  21497. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  21498. source.start( 0, this.startTime );
  21499. this.isPlaying = true;
  21500. this.source = source;
  21501. return this.connect();
  21502. },
  21503. pause: function () {
  21504. if ( this.hasPlaybackControl === false ) {
  21505. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21506. return;
  21507. }
  21508. this.source.stop();
  21509. this.startTime = this.context.currentTime;
  21510. this.isPlaying = false;
  21511. return this;
  21512. },
  21513. stop: function () {
  21514. if ( this.hasPlaybackControl === false ) {
  21515. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21516. return;
  21517. }
  21518. this.source.stop();
  21519. this.startTime = 0;
  21520. this.isPlaying = false;
  21521. return this;
  21522. },
  21523. connect: function () {
  21524. if ( this.filters.length > 0 ) {
  21525. this.source.connect( this.filters[ 0 ] );
  21526. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21527. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21528. }
  21529. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21530. } else {
  21531. this.source.connect( this.getOutput() );
  21532. }
  21533. return this;
  21534. },
  21535. disconnect: function () {
  21536. if ( this.filters.length > 0 ) {
  21537. this.source.disconnect( this.filters[ 0 ] );
  21538. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  21539. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21540. }
  21541. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21542. } else {
  21543. this.source.disconnect( this.getOutput() );
  21544. }
  21545. return this;
  21546. },
  21547. getFilters: function () {
  21548. return this.filters;
  21549. },
  21550. setFilters: function ( value ) {
  21551. if ( ! value ) value = [];
  21552. if ( this.isPlaying === true ) {
  21553. this.disconnect();
  21554. this.filters = value;
  21555. this.connect();
  21556. } else {
  21557. this.filters = value;
  21558. }
  21559. return this;
  21560. },
  21561. getFilter: function () {
  21562. return this.getFilters()[ 0 ];
  21563. },
  21564. setFilter: function ( filter ) {
  21565. return this.setFilters( filter ? [ filter ] : [] );
  21566. },
  21567. setPlaybackRate: function ( value ) {
  21568. if ( this.hasPlaybackControl === false ) {
  21569. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21570. return;
  21571. }
  21572. this.playbackRate = value;
  21573. if ( this.isPlaying === true ) {
  21574. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  21575. }
  21576. return this;
  21577. },
  21578. getPlaybackRate: function () {
  21579. return this.playbackRate;
  21580. },
  21581. onEnded: function () {
  21582. this.isPlaying = false;
  21583. },
  21584. getLoop: function () {
  21585. if ( this.hasPlaybackControl === false ) {
  21586. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21587. return false;
  21588. }
  21589. return this.loop;
  21590. },
  21591. setLoop: function ( value ) {
  21592. if ( this.hasPlaybackControl === false ) {
  21593. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21594. return;
  21595. }
  21596. this.loop = value;
  21597. if ( this.isPlaying === true ) {
  21598. this.source.loop = this.loop;
  21599. }
  21600. return this;
  21601. },
  21602. getVolume: function () {
  21603. return this.gain.gain.value;
  21604. },
  21605. setVolume: function ( value ) {
  21606. this.gain.gain.value = value;
  21607. return this;
  21608. }
  21609. } );
  21610. /**
  21611. * @author mrdoob / http://mrdoob.com/
  21612. */
  21613. function PositionalAudio( listener ) {
  21614. Audio.call( this, listener );
  21615. this.panner = this.context.createPanner();
  21616. this.panner.connect( this.gain );
  21617. }
  21618. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  21619. constructor: PositionalAudio,
  21620. getOutput: function () {
  21621. return this.panner;
  21622. },
  21623. getRefDistance: function () {
  21624. return this.panner.refDistance;
  21625. },
  21626. setRefDistance: function ( value ) {
  21627. this.panner.refDistance = value;
  21628. },
  21629. getRolloffFactor: function () {
  21630. return this.panner.rolloffFactor;
  21631. },
  21632. setRolloffFactor: function ( value ) {
  21633. this.panner.rolloffFactor = value;
  21634. },
  21635. getDistanceModel: function () {
  21636. return this.panner.distanceModel;
  21637. },
  21638. setDistanceModel: function ( value ) {
  21639. this.panner.distanceModel = value;
  21640. },
  21641. getMaxDistance: function () {
  21642. return this.panner.maxDistance;
  21643. },
  21644. setMaxDistance: function ( value ) {
  21645. this.panner.maxDistance = value;
  21646. },
  21647. updateMatrixWorld: ( function () {
  21648. var position = new Vector3();
  21649. return function updateMatrixWorld( force ) {
  21650. Object3D.prototype.updateMatrixWorld.call( this, force );
  21651. position.setFromMatrixPosition( this.matrixWorld );
  21652. this.panner.setPosition( position.x, position.y, position.z );
  21653. };
  21654. } )()
  21655. } );
  21656. /**
  21657. * @author mrdoob / http://mrdoob.com/
  21658. */
  21659. function AudioAnalyser( audio, fftSize ) {
  21660. this.analyser = audio.context.createAnalyser();
  21661. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  21662. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  21663. audio.getOutput().connect( this.analyser );
  21664. }
  21665. Object.assign( AudioAnalyser.prototype, {
  21666. getFrequencyData: function () {
  21667. this.analyser.getByteFrequencyData( this.data );
  21668. return this.data;
  21669. },
  21670. getAverageFrequency: function () {
  21671. var value = 0, data = this.getFrequencyData();
  21672. for ( var i = 0; i < data.length; i ++ ) {
  21673. value += data[ i ];
  21674. }
  21675. return value / data.length;
  21676. }
  21677. } );
  21678. /**
  21679. *
  21680. * Buffered scene graph property that allows weighted accumulation.
  21681. *
  21682. *
  21683. * @author Ben Houston / http://clara.io/
  21684. * @author David Sarno / http://lighthaus.us/
  21685. * @author tschw
  21686. */
  21687. function PropertyMixer( binding, typeName, valueSize ) {
  21688. this.binding = binding;
  21689. this.valueSize = valueSize;
  21690. var bufferType = Float64Array,
  21691. mixFunction;
  21692. switch ( typeName ) {
  21693. case 'quaternion':
  21694. mixFunction = this._slerp;
  21695. break;
  21696. case 'string':
  21697. case 'bool':
  21698. bufferType = Array;
  21699. mixFunction = this._select;
  21700. break;
  21701. default:
  21702. mixFunction = this._lerp;
  21703. }
  21704. this.buffer = new bufferType( valueSize * 4 );
  21705. // layout: [ incoming | accu0 | accu1 | orig ]
  21706. //
  21707. // interpolators can use .buffer as their .result
  21708. // the data then goes to 'incoming'
  21709. //
  21710. // 'accu0' and 'accu1' are used frame-interleaved for
  21711. // the cumulative result and are compared to detect
  21712. // changes
  21713. //
  21714. // 'orig' stores the original state of the property
  21715. this._mixBufferRegion = mixFunction;
  21716. this.cumulativeWeight = 0;
  21717. this.useCount = 0;
  21718. this.referenceCount = 0;
  21719. }
  21720. PropertyMixer.prototype = {
  21721. constructor: PropertyMixer,
  21722. // accumulate data in the 'incoming' region into 'accu<i>'
  21723. accumulate: function( accuIndex, weight ) {
  21724. // note: happily accumulating nothing when weight = 0, the caller knows
  21725. // the weight and shouldn't have made the call in the first place
  21726. var buffer = this.buffer,
  21727. stride = this.valueSize,
  21728. offset = accuIndex * stride + stride,
  21729. currentWeight = this.cumulativeWeight;
  21730. if ( currentWeight === 0 ) {
  21731. // accuN := incoming * weight
  21732. for ( var i = 0; i !== stride; ++ i ) {
  21733. buffer[ offset + i ] = buffer[ i ];
  21734. }
  21735. currentWeight = weight;
  21736. } else {
  21737. // accuN := accuN + incoming * weight
  21738. currentWeight += weight;
  21739. var mix = weight / currentWeight;
  21740. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  21741. }
  21742. this.cumulativeWeight = currentWeight;
  21743. },
  21744. // apply the state of 'accu<i>' to the binding when accus differ
  21745. apply: function( accuIndex ) {
  21746. var stride = this.valueSize,
  21747. buffer = this.buffer,
  21748. offset = accuIndex * stride + stride,
  21749. weight = this.cumulativeWeight,
  21750. binding = this.binding;
  21751. this.cumulativeWeight = 0;
  21752. if ( weight < 1 ) {
  21753. // accuN := accuN + original * ( 1 - cumulativeWeight )
  21754. var originalValueOffset = stride * 3;
  21755. this._mixBufferRegion(
  21756. buffer, offset, originalValueOffset, 1 - weight, stride );
  21757. }
  21758. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  21759. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  21760. // value has changed -> update scene graph
  21761. binding.setValue( buffer, offset );
  21762. break;
  21763. }
  21764. }
  21765. },
  21766. // remember the state of the bound property and copy it to both accus
  21767. saveOriginalState: function() {
  21768. var binding = this.binding;
  21769. var buffer = this.buffer,
  21770. stride = this.valueSize,
  21771. originalValueOffset = stride * 3;
  21772. binding.getValue( buffer, originalValueOffset );
  21773. // accu[0..1] := orig -- initially detect changes against the original
  21774. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  21775. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  21776. }
  21777. this.cumulativeWeight = 0;
  21778. },
  21779. // apply the state previously taken via 'saveOriginalState' to the binding
  21780. restoreOriginalState: function() {
  21781. var originalValueOffset = this.valueSize * 3;
  21782. this.binding.setValue( this.buffer, originalValueOffset );
  21783. },
  21784. // mix functions
  21785. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  21786. if ( t >= 0.5 ) {
  21787. for ( var i = 0; i !== stride; ++ i ) {
  21788. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  21789. }
  21790. }
  21791. },
  21792. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21793. Quaternion.slerpFlat( buffer, dstOffset,
  21794. buffer, dstOffset, buffer, srcOffset, t );
  21795. },
  21796. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  21797. var s = 1 - t;
  21798. for ( var i = 0; i !== stride; ++ i ) {
  21799. var j = dstOffset + i;
  21800. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  21801. }
  21802. }
  21803. };
  21804. /**
  21805. *
  21806. * A reference to a real property in the scene graph.
  21807. *
  21808. *
  21809. * @author Ben Houston / http://clara.io/
  21810. * @author David Sarno / http://lighthaus.us/
  21811. * @author tschw
  21812. */
  21813. function PropertyBinding( rootNode, path, parsedPath ) {
  21814. this.path = path;
  21815. this.parsedPath = parsedPath ||
  21816. PropertyBinding.parseTrackName( path );
  21817. this.node = PropertyBinding.findNode(
  21818. rootNode, this.parsedPath.nodeName ) || rootNode;
  21819. this.rootNode = rootNode;
  21820. }
  21821. PropertyBinding.prototype = {
  21822. constructor: PropertyBinding,
  21823. getValue: function getValue_unbound( targetArray, offset ) {
  21824. this.bind();
  21825. this.getValue( targetArray, offset );
  21826. // Note: This class uses a State pattern on a per-method basis:
  21827. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  21828. // prototype version of these methods with one that represents
  21829. // the bound state. When the property is not found, the methods
  21830. // become no-ops.
  21831. },
  21832. setValue: function getValue_unbound( sourceArray, offset ) {
  21833. this.bind();
  21834. this.setValue( sourceArray, offset );
  21835. },
  21836. // create getter / setter pair for a property in the scene graph
  21837. bind: function() {
  21838. var targetObject = this.node,
  21839. parsedPath = this.parsedPath,
  21840. objectName = parsedPath.objectName,
  21841. propertyName = parsedPath.propertyName,
  21842. propertyIndex = parsedPath.propertyIndex;
  21843. if ( ! targetObject ) {
  21844. targetObject = PropertyBinding.findNode(
  21845. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  21846. this.node = targetObject;
  21847. }
  21848. // set fail state so we can just 'return' on error
  21849. this.getValue = this._getValue_unavailable;
  21850. this.setValue = this._setValue_unavailable;
  21851. // ensure there is a value node
  21852. if ( ! targetObject ) {
  21853. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  21854. return;
  21855. }
  21856. if ( objectName ) {
  21857. var objectIndex = parsedPath.objectIndex;
  21858. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  21859. switch ( objectName ) {
  21860. case 'materials':
  21861. if ( ! targetObject.material ) {
  21862. console.error( ' can not bind to material as node does not have a material', this );
  21863. return;
  21864. }
  21865. if ( ! targetObject.material.materials ) {
  21866. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  21867. return;
  21868. }
  21869. targetObject = targetObject.material.materials;
  21870. break;
  21871. case 'bones':
  21872. if ( ! targetObject.skeleton ) {
  21873. console.error( ' can not bind to bones as node does not have a skeleton', this );
  21874. return;
  21875. }
  21876. // potential future optimization: skip this if propertyIndex is already an integer
  21877. // and convert the integer string to a true integer.
  21878. targetObject = targetObject.skeleton.bones;
  21879. // support resolving morphTarget names into indices.
  21880. for ( var i = 0; i < targetObject.length; i ++ ) {
  21881. if ( targetObject[ i ].name === objectIndex ) {
  21882. objectIndex = i;
  21883. break;
  21884. }
  21885. }
  21886. break;
  21887. default:
  21888. if ( targetObject[ objectName ] === undefined ) {
  21889. console.error( ' can not bind to objectName of node, undefined', this );
  21890. return;
  21891. }
  21892. targetObject = targetObject[ objectName ];
  21893. }
  21894. if ( objectIndex !== undefined ) {
  21895. if ( targetObject[ objectIndex ] === undefined ) {
  21896. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  21897. return;
  21898. }
  21899. targetObject = targetObject[ objectIndex ];
  21900. }
  21901. }
  21902. // resolve property
  21903. var nodeProperty = targetObject[ propertyName ];
  21904. if ( nodeProperty === undefined ) {
  21905. var nodeName = parsedPath.nodeName;
  21906. console.error( " trying to update property for track: " + nodeName +
  21907. '.' + propertyName + " but it wasn't found.", targetObject );
  21908. return;
  21909. }
  21910. // determine versioning scheme
  21911. var versioning = this.Versioning.None;
  21912. if ( targetObject.needsUpdate !== undefined ) { // material
  21913. versioning = this.Versioning.NeedsUpdate;
  21914. this.targetObject = targetObject;
  21915. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  21916. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  21917. this.targetObject = targetObject;
  21918. }
  21919. // determine how the property gets bound
  21920. var bindingType = this.BindingType.Direct;
  21921. if ( propertyIndex !== undefined ) {
  21922. // access a sub element of the property array (only primitives are supported right now)
  21923. if ( propertyName === "morphTargetInfluences" ) {
  21924. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  21925. // support resolving morphTarget names into indices.
  21926. if ( ! targetObject.geometry ) {
  21927. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  21928. return;
  21929. }
  21930. if ( ! targetObject.geometry.morphTargets ) {
  21931. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  21932. return;
  21933. }
  21934. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  21935. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  21936. propertyIndex = i;
  21937. break;
  21938. }
  21939. }
  21940. }
  21941. bindingType = this.BindingType.ArrayElement;
  21942. this.resolvedProperty = nodeProperty;
  21943. this.propertyIndex = propertyIndex;
  21944. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  21945. // must use copy for Object3D.Euler/Quaternion
  21946. bindingType = this.BindingType.HasFromToArray;
  21947. this.resolvedProperty = nodeProperty;
  21948. } else if ( nodeProperty.length !== undefined ) {
  21949. bindingType = this.BindingType.EntireArray;
  21950. this.resolvedProperty = nodeProperty;
  21951. } else {
  21952. this.propertyName = propertyName;
  21953. }
  21954. // select getter / setter
  21955. this.getValue = this.GetterByBindingType[ bindingType ];
  21956. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  21957. },
  21958. unbind: function() {
  21959. this.node = null;
  21960. // back to the prototype version of getValue / setValue
  21961. // note: avoiding to mutate the shape of 'this' via 'delete'
  21962. this.getValue = this._getValue_unbound;
  21963. this.setValue = this._setValue_unbound;
  21964. }
  21965. };
  21966. Object.assign( PropertyBinding.prototype, { // prototype, continued
  21967. // these are used to "bind" a nonexistent property
  21968. _getValue_unavailable: function() {},
  21969. _setValue_unavailable: function() {},
  21970. // initial state of these methods that calls 'bind'
  21971. _getValue_unbound: PropertyBinding.prototype.getValue,
  21972. _setValue_unbound: PropertyBinding.prototype.setValue,
  21973. BindingType: {
  21974. Direct: 0,
  21975. EntireArray: 1,
  21976. ArrayElement: 2,
  21977. HasFromToArray: 3
  21978. },
  21979. Versioning: {
  21980. None: 0,
  21981. NeedsUpdate: 1,
  21982. MatrixWorldNeedsUpdate: 2
  21983. },
  21984. GetterByBindingType: [
  21985. function getValue_direct( buffer, offset ) {
  21986. buffer[ offset ] = this.node[ this.propertyName ];
  21987. },
  21988. function getValue_array( buffer, offset ) {
  21989. var source = this.resolvedProperty;
  21990. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  21991. buffer[ offset ++ ] = source[ i ];
  21992. }
  21993. },
  21994. function getValue_arrayElement( buffer, offset ) {
  21995. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  21996. },
  21997. function getValue_toArray( buffer, offset ) {
  21998. this.resolvedProperty.toArray( buffer, offset );
  21999. }
  22000. ],
  22001. SetterByBindingTypeAndVersioning: [
  22002. [
  22003. // Direct
  22004. function setValue_direct( buffer, offset ) {
  22005. this.node[ this.propertyName ] = buffer[ offset ];
  22006. },
  22007. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  22008. this.node[ this.propertyName ] = buffer[ offset ];
  22009. this.targetObject.needsUpdate = true;
  22010. },
  22011. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22012. this.node[ this.propertyName ] = buffer[ offset ];
  22013. this.targetObject.matrixWorldNeedsUpdate = true;
  22014. }
  22015. ], [
  22016. // EntireArray
  22017. function setValue_array( buffer, offset ) {
  22018. var dest = this.resolvedProperty;
  22019. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22020. dest[ i ] = buffer[ offset ++ ];
  22021. }
  22022. },
  22023. function setValue_array_setNeedsUpdate( buffer, offset ) {
  22024. var dest = this.resolvedProperty;
  22025. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22026. dest[ i ] = buffer[ offset ++ ];
  22027. }
  22028. this.targetObject.needsUpdate = true;
  22029. },
  22030. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22031. var dest = this.resolvedProperty;
  22032. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  22033. dest[ i ] = buffer[ offset ++ ];
  22034. }
  22035. this.targetObject.matrixWorldNeedsUpdate = true;
  22036. }
  22037. ], [
  22038. // ArrayElement
  22039. function setValue_arrayElement( buffer, offset ) {
  22040. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22041. },
  22042. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22043. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22044. this.targetObject.needsUpdate = true;
  22045. },
  22046. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22047. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22048. this.targetObject.matrixWorldNeedsUpdate = true;
  22049. }
  22050. ], [
  22051. // HasToFromArray
  22052. function setValue_fromArray( buffer, offset ) {
  22053. this.resolvedProperty.fromArray( buffer, offset );
  22054. },
  22055. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22056. this.resolvedProperty.fromArray( buffer, offset );
  22057. this.targetObject.needsUpdate = true;
  22058. },
  22059. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22060. this.resolvedProperty.fromArray( buffer, offset );
  22061. this.targetObject.matrixWorldNeedsUpdate = true;
  22062. }
  22063. ]
  22064. ]
  22065. } );
  22066. PropertyBinding.Composite =
  22067. function( targetGroup, path, optionalParsedPath ) {
  22068. var parsedPath = optionalParsedPath ||
  22069. PropertyBinding.parseTrackName( path );
  22070. this._targetGroup = targetGroup;
  22071. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22072. };
  22073. PropertyBinding.Composite.prototype = {
  22074. constructor: PropertyBinding.Composite,
  22075. getValue: function( array, offset ) {
  22076. this.bind(); // bind all binding
  22077. var firstValidIndex = this._targetGroup.nCachedObjects_,
  22078. binding = this._bindings[ firstValidIndex ];
  22079. // and only call .getValue on the first
  22080. if ( binding !== undefined ) binding.getValue( array, offset );
  22081. },
  22082. setValue: function( array, offset ) {
  22083. var bindings = this._bindings;
  22084. for ( var i = this._targetGroup.nCachedObjects_,
  22085. n = bindings.length; i !== n; ++ i ) {
  22086. bindings[ i ].setValue( array, offset );
  22087. }
  22088. },
  22089. bind: function() {
  22090. var bindings = this._bindings;
  22091. for ( var i = this._targetGroup.nCachedObjects_,
  22092. n = bindings.length; i !== n; ++ i ) {
  22093. bindings[ i ].bind();
  22094. }
  22095. },
  22096. unbind: function() {
  22097. var bindings = this._bindings;
  22098. for ( var i = this._targetGroup.nCachedObjects_,
  22099. n = bindings.length; i !== n; ++ i ) {
  22100. bindings[ i ].unbind();
  22101. }
  22102. }
  22103. };
  22104. PropertyBinding.create = function( root, path, parsedPath ) {
  22105. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22106. return new PropertyBinding( root, path, parsedPath );
  22107. } else {
  22108. return new PropertyBinding.Composite( root, path, parsedPath );
  22109. }
  22110. };
  22111. PropertyBinding.parseTrackName = function( trackName ) {
  22112. // matches strings in the form of:
  22113. // nodeName.property
  22114. // nodeName.property[accessor]
  22115. // nodeName.material.property[accessor]
  22116. // uuid.property[accessor]
  22117. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  22118. // parentName/nodeName.property
  22119. // parentName/parentName/nodeName.property[index]
  22120. // .bone[Armature.DEF_cog].position
  22121. // scene:helium_balloon_model:helium_balloon_model.position
  22122. // created and tested via https://regex101.com/#javascript
  22123. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  22124. var matches = re.exec( trackName );
  22125. if ( ! matches ) {
  22126. throw new Error( "cannot parse trackName at all: " + trackName );
  22127. }
  22128. var results = {
  22129. // directoryName: matches[ 1 ], // (tschw) currently unused
  22130. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  22131. objectName: matches[ 3 ],
  22132. objectIndex: matches[ 4 ],
  22133. propertyName: matches[ 5 ],
  22134. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  22135. };
  22136. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22137. throw new Error( "can not parse propertyName from trackName: " + trackName );
  22138. }
  22139. return results;
  22140. };
  22141. PropertyBinding.findNode = function( root, nodeName ) {
  22142. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  22143. return root;
  22144. }
  22145. // search into skeleton bones.
  22146. if ( root.skeleton ) {
  22147. var searchSkeleton = function( skeleton ) {
  22148. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  22149. var bone = skeleton.bones[ i ];
  22150. if ( bone.name === nodeName ) {
  22151. return bone;
  22152. }
  22153. }
  22154. return null;
  22155. };
  22156. var bone = searchSkeleton( root.skeleton );
  22157. if ( bone ) {
  22158. return bone;
  22159. }
  22160. }
  22161. // search into node subtree.
  22162. if ( root.children ) {
  22163. var searchNodeSubtree = function( children ) {
  22164. for( var i = 0; i < children.length; i ++ ) {
  22165. var childNode = children[ i ];
  22166. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22167. return childNode;
  22168. }
  22169. var result = searchNodeSubtree( childNode.children );
  22170. if ( result ) return result;
  22171. }
  22172. return null;
  22173. };
  22174. var subTreeNode = searchNodeSubtree( root.children );
  22175. if ( subTreeNode ) {
  22176. return subTreeNode;
  22177. }
  22178. }
  22179. return null;
  22180. };
  22181. /**
  22182. *
  22183. * A group of objects that receives a shared animation state.
  22184. *
  22185. * Usage:
  22186. *
  22187. * - Add objects you would otherwise pass as 'root' to the
  22188. * constructor or the .clipAction method of AnimationMixer.
  22189. *
  22190. * - Instead pass this object as 'root'.
  22191. *
  22192. * - You can also add and remove objects later when the mixer
  22193. * is running.
  22194. *
  22195. * Note:
  22196. *
  22197. * Objects of this class appear as one object to the mixer,
  22198. * so cache control of the individual objects must be done
  22199. * on the group.
  22200. *
  22201. * Limitation:
  22202. *
  22203. * - The animated properties must be compatible among the
  22204. * all objects in the group.
  22205. *
  22206. * - A single property can either be controlled through a
  22207. * target group or directly, but not both.
  22208. *
  22209. * @author tschw
  22210. */
  22211. function AnimationObjectGroup( var_args ) {
  22212. this.uuid = _Math.generateUUID();
  22213. // cached objects followed by the active ones
  22214. this._objects = Array.prototype.slice.call( arguments );
  22215. this.nCachedObjects_ = 0; // threshold
  22216. // note: read by PropertyBinding.Composite
  22217. var indices = {};
  22218. this._indicesByUUID = indices; // for bookkeeping
  22219. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22220. indices[ arguments[ i ].uuid ] = i;
  22221. }
  22222. this._paths = []; // inside: string
  22223. this._parsedPaths = []; // inside: { we don't care, here }
  22224. this._bindings = []; // inside: Array< PropertyBinding >
  22225. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  22226. var scope = this;
  22227. this.stats = {
  22228. objects: {
  22229. get total() { return scope._objects.length; },
  22230. get inUse() { return this.total - scope.nCachedObjects_; }
  22231. },
  22232. get bindingsPerObject() { return scope._bindings.length; }
  22233. };
  22234. }
  22235. AnimationObjectGroup.prototype = {
  22236. constructor: AnimationObjectGroup,
  22237. isAnimationObjectGroup: true,
  22238. add: function( var_args ) {
  22239. var objects = this._objects,
  22240. nObjects = objects.length,
  22241. nCachedObjects = this.nCachedObjects_,
  22242. indicesByUUID = this._indicesByUUID,
  22243. paths = this._paths,
  22244. parsedPaths = this._parsedPaths,
  22245. bindings = this._bindings,
  22246. nBindings = bindings.length;
  22247. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22248. var object = arguments[ i ],
  22249. uuid = object.uuid,
  22250. index = indicesByUUID[ uuid ],
  22251. knownObject = undefined;
  22252. if ( index === undefined ) {
  22253. // unknown object -> add it to the ACTIVE region
  22254. index = nObjects ++;
  22255. indicesByUUID[ uuid ] = index;
  22256. objects.push( object );
  22257. // accounting is done, now do the same for all bindings
  22258. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22259. bindings[ j ].push(
  22260. new PropertyBinding(
  22261. object, paths[ j ], parsedPaths[ j ] ) );
  22262. }
  22263. } else if ( index < nCachedObjects ) {
  22264. knownObject = objects[ index ];
  22265. // move existing object to the ACTIVE region
  22266. var firstActiveIndex = -- nCachedObjects,
  22267. lastCachedObject = objects[ firstActiveIndex ];
  22268. indicesByUUID[ lastCachedObject.uuid ] = index;
  22269. objects[ index ] = lastCachedObject;
  22270. indicesByUUID[ uuid ] = firstActiveIndex;
  22271. objects[ firstActiveIndex ] = object;
  22272. // accounting is done, now do the same for all bindings
  22273. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22274. var bindingsForPath = bindings[ j ],
  22275. lastCached = bindingsForPath[ firstActiveIndex ],
  22276. binding = bindingsForPath[ index ];
  22277. bindingsForPath[ index ] = lastCached;
  22278. if ( binding === undefined ) {
  22279. // since we do not bother to create new bindings
  22280. // for objects that are cached, the binding may
  22281. // or may not exist
  22282. binding = new PropertyBinding(
  22283. object, paths[ j ], parsedPaths[ j ] );
  22284. }
  22285. bindingsForPath[ firstActiveIndex ] = binding;
  22286. }
  22287. } else if ( objects[ index ] !== knownObject) {
  22288. console.error( "Different objects with the same UUID " +
  22289. "detected. Clean the caches or recreate your " +
  22290. "infrastructure when reloading scenes..." );
  22291. } // else the object is already where we want it to be
  22292. } // for arguments
  22293. this.nCachedObjects_ = nCachedObjects;
  22294. },
  22295. remove: function( var_args ) {
  22296. var objects = this._objects,
  22297. nCachedObjects = this.nCachedObjects_,
  22298. indicesByUUID = this._indicesByUUID,
  22299. bindings = this._bindings,
  22300. nBindings = bindings.length;
  22301. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22302. var object = arguments[ i ],
  22303. uuid = object.uuid,
  22304. index = indicesByUUID[ uuid ];
  22305. if ( index !== undefined && index >= nCachedObjects ) {
  22306. // move existing object into the CACHED region
  22307. var lastCachedIndex = nCachedObjects ++,
  22308. firstActiveObject = objects[ lastCachedIndex ];
  22309. indicesByUUID[ firstActiveObject.uuid ] = index;
  22310. objects[ index ] = firstActiveObject;
  22311. indicesByUUID[ uuid ] = lastCachedIndex;
  22312. objects[ lastCachedIndex ] = object;
  22313. // accounting is done, now do the same for all bindings
  22314. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22315. var bindingsForPath = bindings[ j ],
  22316. firstActive = bindingsForPath[ lastCachedIndex ],
  22317. binding = bindingsForPath[ index ];
  22318. bindingsForPath[ index ] = firstActive;
  22319. bindingsForPath[ lastCachedIndex ] = binding;
  22320. }
  22321. }
  22322. } // for arguments
  22323. this.nCachedObjects_ = nCachedObjects;
  22324. },
  22325. // remove & forget
  22326. uncache: function( var_args ) {
  22327. var objects = this._objects,
  22328. nObjects = objects.length,
  22329. nCachedObjects = this.nCachedObjects_,
  22330. indicesByUUID = this._indicesByUUID,
  22331. bindings = this._bindings,
  22332. nBindings = bindings.length;
  22333. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  22334. var object = arguments[ i ],
  22335. uuid = object.uuid,
  22336. index = indicesByUUID[ uuid ];
  22337. if ( index !== undefined ) {
  22338. delete indicesByUUID[ uuid ];
  22339. if ( index < nCachedObjects ) {
  22340. // object is cached, shrink the CACHED region
  22341. var firstActiveIndex = -- nCachedObjects,
  22342. lastCachedObject = objects[ firstActiveIndex ],
  22343. lastIndex = -- nObjects,
  22344. lastObject = objects[ lastIndex ];
  22345. // last cached object takes this object's place
  22346. indicesByUUID[ lastCachedObject.uuid ] = index;
  22347. objects[ index ] = lastCachedObject;
  22348. // last object goes to the activated slot and pop
  22349. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  22350. objects[ firstActiveIndex ] = lastObject;
  22351. objects.pop();
  22352. // accounting is done, now do the same for all bindings
  22353. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22354. var bindingsForPath = bindings[ j ],
  22355. lastCached = bindingsForPath[ firstActiveIndex ],
  22356. last = bindingsForPath[ lastIndex ];
  22357. bindingsForPath[ index ] = lastCached;
  22358. bindingsForPath[ firstActiveIndex ] = last;
  22359. bindingsForPath.pop();
  22360. }
  22361. } else {
  22362. // object is active, just swap with the last and pop
  22363. var lastIndex = -- nObjects,
  22364. lastObject = objects[ lastIndex ];
  22365. indicesByUUID[ lastObject.uuid ] = index;
  22366. objects[ index ] = lastObject;
  22367. objects.pop();
  22368. // accounting is done, now do the same for all bindings
  22369. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  22370. var bindingsForPath = bindings[ j ];
  22371. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  22372. bindingsForPath.pop();
  22373. }
  22374. } // cached or active
  22375. } // if object is known
  22376. } // for arguments
  22377. this.nCachedObjects_ = nCachedObjects;
  22378. },
  22379. // Internal interface used by befriended PropertyBinding.Composite:
  22380. subscribe_: function( path, parsedPath ) {
  22381. // returns an array of bindings for the given path that is changed
  22382. // according to the contained objects in the group
  22383. var indicesByPath = this._bindingsIndicesByPath,
  22384. index = indicesByPath[ path ],
  22385. bindings = this._bindings;
  22386. if ( index !== undefined ) return bindings[ index ];
  22387. var paths = this._paths,
  22388. parsedPaths = this._parsedPaths,
  22389. objects = this._objects,
  22390. nObjects = objects.length,
  22391. nCachedObjects = this.nCachedObjects_,
  22392. bindingsForPath = new Array( nObjects );
  22393. index = bindings.length;
  22394. indicesByPath[ path ] = index;
  22395. paths.push( path );
  22396. parsedPaths.push( parsedPath );
  22397. bindings.push( bindingsForPath );
  22398. for ( var i = nCachedObjects,
  22399. n = objects.length; i !== n; ++ i ) {
  22400. var object = objects[ i ];
  22401. bindingsForPath[ i ] =
  22402. new PropertyBinding( object, path, parsedPath );
  22403. }
  22404. return bindingsForPath;
  22405. },
  22406. unsubscribe_: function( path ) {
  22407. // tells the group to forget about a property path and no longer
  22408. // update the array previously obtained with 'subscribe_'
  22409. var indicesByPath = this._bindingsIndicesByPath,
  22410. index = indicesByPath[ path ];
  22411. if ( index !== undefined ) {
  22412. var paths = this._paths,
  22413. parsedPaths = this._parsedPaths,
  22414. bindings = this._bindings,
  22415. lastBindingsIndex = bindings.length - 1,
  22416. lastBindings = bindings[ lastBindingsIndex ],
  22417. lastBindingsPath = path[ lastBindingsIndex ];
  22418. indicesByPath[ lastBindingsPath ] = index;
  22419. bindings[ index ] = lastBindings;
  22420. bindings.pop();
  22421. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  22422. parsedPaths.pop();
  22423. paths[ index ] = paths[ lastBindingsIndex ];
  22424. paths.pop();
  22425. }
  22426. }
  22427. };
  22428. /**
  22429. *
  22430. * Action provided by AnimationMixer for scheduling clip playback on specific
  22431. * objects.
  22432. *
  22433. * @author Ben Houston / http://clara.io/
  22434. * @author David Sarno / http://lighthaus.us/
  22435. * @author tschw
  22436. *
  22437. */
  22438. function AnimationAction( mixer, clip, localRoot ) {
  22439. this._mixer = mixer;
  22440. this._clip = clip;
  22441. this._localRoot = localRoot || null;
  22442. var tracks = clip.tracks,
  22443. nTracks = tracks.length,
  22444. interpolants = new Array( nTracks );
  22445. var interpolantSettings = {
  22446. endingStart: ZeroCurvatureEnding,
  22447. endingEnd: ZeroCurvatureEnding
  22448. };
  22449. for ( var i = 0; i !== nTracks; ++ i ) {
  22450. var interpolant = tracks[ i ].createInterpolant( null );
  22451. interpolants[ i ] = interpolant;
  22452. interpolant.settings = interpolantSettings;
  22453. }
  22454. this._interpolantSettings = interpolantSettings;
  22455. this._interpolants = interpolants; // bound by the mixer
  22456. // inside: PropertyMixer (managed by the mixer)
  22457. this._propertyBindings = new Array( nTracks );
  22458. this._cacheIndex = null; // for the memory manager
  22459. this._byClipCacheIndex = null; // for the memory manager
  22460. this._timeScaleInterpolant = null;
  22461. this._weightInterpolant = null;
  22462. this.loop = LoopRepeat;
  22463. this._loopCount = -1;
  22464. // global mixer time when the action is to be started
  22465. // it's set back to 'null' upon start of the action
  22466. this._startTime = null;
  22467. // scaled local time of the action
  22468. // gets clamped or wrapped to 0..clip.duration according to loop
  22469. this.time = 0;
  22470. this.timeScale = 1;
  22471. this._effectiveTimeScale = 1;
  22472. this.weight = 1;
  22473. this._effectiveWeight = 1;
  22474. this.repetitions = Infinity; // no. of repetitions when looping
  22475. this.paused = false; // false -> zero effective time scale
  22476. this.enabled = true; // true -> zero effective weight
  22477. this.clampWhenFinished = false; // keep feeding the last frame?
  22478. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  22479. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  22480. }
  22481. AnimationAction.prototype = {
  22482. constructor: AnimationAction,
  22483. // State & Scheduling
  22484. play: function() {
  22485. this._mixer._activateAction( this );
  22486. return this;
  22487. },
  22488. stop: function() {
  22489. this._mixer._deactivateAction( this );
  22490. return this.reset();
  22491. },
  22492. reset: function() {
  22493. this.paused = false;
  22494. this.enabled = true;
  22495. this.time = 0; // restart clip
  22496. this._loopCount = -1; // forget previous loops
  22497. this._startTime = null; // forget scheduling
  22498. return this.stopFading().stopWarping();
  22499. },
  22500. isRunning: function() {
  22501. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22502. this._startTime === null && this._mixer._isActiveAction( this );
  22503. },
  22504. // return true when play has been called
  22505. isScheduled: function() {
  22506. return this._mixer._isActiveAction( this );
  22507. },
  22508. startAt: function( time ) {
  22509. this._startTime = time;
  22510. return this;
  22511. },
  22512. setLoop: function( mode, repetitions ) {
  22513. this.loop = mode;
  22514. this.repetitions = repetitions;
  22515. return this;
  22516. },
  22517. // Weight
  22518. // set the weight stopping any scheduled fading
  22519. // although .enabled = false yields an effective weight of zero, this
  22520. // method does *not* change .enabled, because it would be confusing
  22521. setEffectiveWeight: function( weight ) {
  22522. this.weight = weight;
  22523. // note: same logic as when updated at runtime
  22524. this._effectiveWeight = this.enabled ? weight : 0;
  22525. return this.stopFading();
  22526. },
  22527. // return the weight considering fading and .enabled
  22528. getEffectiveWeight: function() {
  22529. return this._effectiveWeight;
  22530. },
  22531. fadeIn: function( duration ) {
  22532. return this._scheduleFading( duration, 0, 1 );
  22533. },
  22534. fadeOut: function( duration ) {
  22535. return this._scheduleFading( duration, 1, 0 );
  22536. },
  22537. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  22538. fadeOutAction.fadeOut( duration );
  22539. this.fadeIn( duration );
  22540. if( warp ) {
  22541. var fadeInDuration = this._clip.duration,
  22542. fadeOutDuration = fadeOutAction._clip.duration,
  22543. startEndRatio = fadeOutDuration / fadeInDuration,
  22544. endStartRatio = fadeInDuration / fadeOutDuration;
  22545. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22546. this.warp( endStartRatio, 1.0, duration );
  22547. }
  22548. return this;
  22549. },
  22550. crossFadeTo: function( fadeInAction, duration, warp ) {
  22551. return fadeInAction.crossFadeFrom( this, duration, warp );
  22552. },
  22553. stopFading: function() {
  22554. var weightInterpolant = this._weightInterpolant;
  22555. if ( weightInterpolant !== null ) {
  22556. this._weightInterpolant = null;
  22557. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22558. }
  22559. return this;
  22560. },
  22561. // Time Scale Control
  22562. // set the weight stopping any scheduled warping
  22563. // although .paused = true yields an effective time scale of zero, this
  22564. // method does *not* change .paused, because it would be confusing
  22565. setEffectiveTimeScale: function( timeScale ) {
  22566. this.timeScale = timeScale;
  22567. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  22568. return this.stopWarping();
  22569. },
  22570. // return the time scale considering warping and .paused
  22571. getEffectiveTimeScale: function() {
  22572. return this._effectiveTimeScale;
  22573. },
  22574. setDuration: function( duration ) {
  22575. this.timeScale = this._clip.duration / duration;
  22576. return this.stopWarping();
  22577. },
  22578. syncWith: function( action ) {
  22579. this.time = action.time;
  22580. this.timeScale = action.timeScale;
  22581. return this.stopWarping();
  22582. },
  22583. halt: function( duration ) {
  22584. return this.warp( this._effectiveTimeScale, 0, duration );
  22585. },
  22586. warp: function( startTimeScale, endTimeScale, duration ) {
  22587. var mixer = this._mixer, now = mixer.time,
  22588. interpolant = this._timeScaleInterpolant,
  22589. timeScale = this.timeScale;
  22590. if ( interpolant === null ) {
  22591. interpolant = mixer._lendControlInterpolant();
  22592. this._timeScaleInterpolant = interpolant;
  22593. }
  22594. var times = interpolant.parameterPositions,
  22595. values = interpolant.sampleValues;
  22596. times[ 0 ] = now;
  22597. times[ 1 ] = now + duration;
  22598. values[ 0 ] = startTimeScale / timeScale;
  22599. values[ 1 ] = endTimeScale / timeScale;
  22600. return this;
  22601. },
  22602. stopWarping: function() {
  22603. var timeScaleInterpolant = this._timeScaleInterpolant;
  22604. if ( timeScaleInterpolant !== null ) {
  22605. this._timeScaleInterpolant = null;
  22606. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22607. }
  22608. return this;
  22609. },
  22610. // Object Accessors
  22611. getMixer: function() {
  22612. return this._mixer;
  22613. },
  22614. getClip: function() {
  22615. return this._clip;
  22616. },
  22617. getRoot: function() {
  22618. return this._localRoot || this._mixer._root;
  22619. },
  22620. // Interna
  22621. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  22622. // called by the mixer
  22623. var startTime = this._startTime;
  22624. if ( startTime !== null ) {
  22625. // check for scheduled start of action
  22626. var timeRunning = ( time - startTime ) * timeDirection;
  22627. if ( timeRunning < 0 || timeDirection === 0 ) {
  22628. return; // yet to come / don't decide when delta = 0
  22629. }
  22630. // start
  22631. this._startTime = null; // unschedule
  22632. deltaTime = timeDirection * timeRunning;
  22633. }
  22634. // apply time scale and advance time
  22635. deltaTime *= this._updateTimeScale( time );
  22636. var clipTime = this._updateTime( deltaTime );
  22637. // note: _updateTime may disable the action resulting in
  22638. // an effective weight of 0
  22639. var weight = this._updateWeight( time );
  22640. if ( weight > 0 ) {
  22641. var interpolants = this._interpolants;
  22642. var propertyMixers = this._propertyBindings;
  22643. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  22644. interpolants[ j ].evaluate( clipTime );
  22645. propertyMixers[ j ].accumulate( accuIndex, weight );
  22646. }
  22647. }
  22648. },
  22649. _updateWeight: function( time ) {
  22650. var weight = 0;
  22651. if ( this.enabled ) {
  22652. weight = this.weight;
  22653. var interpolant = this._weightInterpolant;
  22654. if ( interpolant !== null ) {
  22655. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22656. weight *= interpolantValue;
  22657. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22658. this.stopFading();
  22659. if ( interpolantValue === 0 ) {
  22660. // faded out, disable
  22661. this.enabled = false;
  22662. }
  22663. }
  22664. }
  22665. }
  22666. this._effectiveWeight = weight;
  22667. return weight;
  22668. },
  22669. _updateTimeScale: function( time ) {
  22670. var timeScale = 0;
  22671. if ( ! this.paused ) {
  22672. timeScale = this.timeScale;
  22673. var interpolant = this._timeScaleInterpolant;
  22674. if ( interpolant !== null ) {
  22675. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  22676. timeScale *= interpolantValue;
  22677. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22678. this.stopWarping();
  22679. if ( timeScale === 0 ) {
  22680. // motion has halted, pause
  22681. this.paused = true;
  22682. } else {
  22683. // warp done - apply final time scale
  22684. this.timeScale = timeScale;
  22685. }
  22686. }
  22687. }
  22688. }
  22689. this._effectiveTimeScale = timeScale;
  22690. return timeScale;
  22691. },
  22692. _updateTime: function( deltaTime ) {
  22693. var time = this.time + deltaTime;
  22694. if ( deltaTime === 0 ) return time;
  22695. var duration = this._clip.duration,
  22696. loop = this.loop,
  22697. loopCount = this._loopCount;
  22698. if ( loop === LoopOnce ) {
  22699. if ( loopCount === -1 ) {
  22700. // just started
  22701. this._loopCount = 0;
  22702. this._setEndings( true, true, false );
  22703. }
  22704. handle_stop: {
  22705. if ( time >= duration ) {
  22706. time = duration;
  22707. } else if ( time < 0 ) {
  22708. time = 0;
  22709. } else break handle_stop;
  22710. if ( this.clampWhenFinished ) this.paused = true;
  22711. else this.enabled = false;
  22712. this._mixer.dispatchEvent( {
  22713. type: 'finished', action: this,
  22714. direction: deltaTime < 0 ? -1 : 1
  22715. } );
  22716. }
  22717. } else { // repetitive Repeat or PingPong
  22718. var pingPong = ( loop === LoopPingPong );
  22719. if ( loopCount === -1 ) {
  22720. // just started
  22721. if ( deltaTime >= 0 ) {
  22722. loopCount = 0;
  22723. this._setEndings(
  22724. true, this.repetitions === 0, pingPong );
  22725. } else {
  22726. // when looping in reverse direction, the initial
  22727. // transition through zero counts as a repetition,
  22728. // so leave loopCount at -1
  22729. this._setEndings(
  22730. this.repetitions === 0, true, pingPong );
  22731. }
  22732. }
  22733. if ( time >= duration || time < 0 ) {
  22734. // wrap around
  22735. var loopDelta = Math.floor( time / duration ); // signed
  22736. time -= duration * loopDelta;
  22737. loopCount += Math.abs( loopDelta );
  22738. var pending = this.repetitions - loopCount;
  22739. if ( pending < 0 ) {
  22740. // have to stop (switch state, clamp time, fire event)
  22741. if ( this.clampWhenFinished ) this.paused = true;
  22742. else this.enabled = false;
  22743. time = deltaTime > 0 ? duration : 0;
  22744. this._mixer.dispatchEvent( {
  22745. type: 'finished', action: this,
  22746. direction: deltaTime > 0 ? 1 : -1
  22747. } );
  22748. } else {
  22749. // keep running
  22750. if ( pending === 0 ) {
  22751. // entering the last round
  22752. var atStart = deltaTime < 0;
  22753. this._setEndings( atStart, ! atStart, pingPong );
  22754. } else {
  22755. this._setEndings( false, false, pingPong );
  22756. }
  22757. this._loopCount = loopCount;
  22758. this._mixer.dispatchEvent( {
  22759. type: 'loop', action: this, loopDelta: loopDelta
  22760. } );
  22761. }
  22762. }
  22763. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22764. // invert time for the "pong round"
  22765. this.time = time;
  22766. return duration - time;
  22767. }
  22768. }
  22769. this.time = time;
  22770. return time;
  22771. },
  22772. _setEndings: function( atStart, atEnd, pingPong ) {
  22773. var settings = this._interpolantSettings;
  22774. if ( pingPong ) {
  22775. settings.endingStart = ZeroSlopeEnding;
  22776. settings.endingEnd = ZeroSlopeEnding;
  22777. } else {
  22778. // assuming for LoopOnce atStart == atEnd == true
  22779. if ( atStart ) {
  22780. settings.endingStart = this.zeroSlopeAtStart ?
  22781. ZeroSlopeEnding : ZeroCurvatureEnding;
  22782. } else {
  22783. settings.endingStart = WrapAroundEnding;
  22784. }
  22785. if ( atEnd ) {
  22786. settings.endingEnd = this.zeroSlopeAtEnd ?
  22787. ZeroSlopeEnding : ZeroCurvatureEnding;
  22788. } else {
  22789. settings.endingEnd = WrapAroundEnding;
  22790. }
  22791. }
  22792. },
  22793. _scheduleFading: function( duration, weightNow, weightThen ) {
  22794. var mixer = this._mixer, now = mixer.time,
  22795. interpolant = this._weightInterpolant;
  22796. if ( interpolant === null ) {
  22797. interpolant = mixer._lendControlInterpolant();
  22798. this._weightInterpolant = interpolant;
  22799. }
  22800. var times = interpolant.parameterPositions,
  22801. values = interpolant.sampleValues;
  22802. times[ 0 ] = now; values[ 0 ] = weightNow;
  22803. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  22804. return this;
  22805. }
  22806. };
  22807. /**
  22808. *
  22809. * Player for AnimationClips.
  22810. *
  22811. *
  22812. * @author Ben Houston / http://clara.io/
  22813. * @author David Sarno / http://lighthaus.us/
  22814. * @author tschw
  22815. */
  22816. function AnimationMixer( root ) {
  22817. this._root = root;
  22818. this._initMemoryManager();
  22819. this._accuIndex = 0;
  22820. this.time = 0;
  22821. this.timeScale = 1.0;
  22822. }
  22823. AnimationMixer.prototype = {
  22824. constructor: AnimationMixer,
  22825. // return an action for a clip optionally using a custom root target
  22826. // object (this method allocates a lot of dynamic memory in case a
  22827. // previously unknown clip/root combination is specified)
  22828. clipAction: function ( clip, optionalRoot ) {
  22829. var root = optionalRoot || this._root,
  22830. rootUuid = root.uuid,
  22831. clipObject = typeof clip === 'string' ?
  22832. AnimationClip.findByName( root, clip ) : clip,
  22833. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  22834. actionsForClip = this._actionsByClip[ clipUuid ],
  22835. prototypeAction = null;
  22836. if ( actionsForClip !== undefined ) {
  22837. var existingAction =
  22838. actionsForClip.actionByRoot[ rootUuid ];
  22839. if ( existingAction !== undefined ) {
  22840. return existingAction;
  22841. }
  22842. // we know the clip, so we don't have to parse all
  22843. // the bindings again but can just copy
  22844. prototypeAction = actionsForClip.knownActions[ 0 ];
  22845. // also, take the clip from the prototype action
  22846. if ( clipObject === null )
  22847. clipObject = prototypeAction._clip;
  22848. }
  22849. // clip must be known when specified via string
  22850. if ( clipObject === null ) return null;
  22851. // allocate all resources required to run it
  22852. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  22853. this._bindAction( newAction, prototypeAction );
  22854. // and make the action known to the memory manager
  22855. this._addInactiveAction( newAction, clipUuid, rootUuid );
  22856. return newAction;
  22857. },
  22858. // get an existing action
  22859. existingAction: function ( clip, optionalRoot ) {
  22860. var root = optionalRoot || this._root,
  22861. rootUuid = root.uuid,
  22862. clipObject = typeof clip === 'string' ?
  22863. AnimationClip.findByName( root, clip ) : clip,
  22864. clipUuid = clipObject ? clipObject.uuid : clip,
  22865. actionsForClip = this._actionsByClip[ clipUuid ];
  22866. if ( actionsForClip !== undefined ) {
  22867. return actionsForClip.actionByRoot[ rootUuid ] || null;
  22868. }
  22869. return null;
  22870. },
  22871. // deactivates all previously scheduled actions
  22872. stopAllAction: function () {
  22873. var actions = this._actions,
  22874. nActions = this._nActiveActions,
  22875. bindings = this._bindings,
  22876. nBindings = this._nActiveBindings;
  22877. this._nActiveActions = 0;
  22878. this._nActiveBindings = 0;
  22879. for ( var i = 0; i !== nActions; ++ i ) {
  22880. actions[ i ].reset();
  22881. }
  22882. for ( var i = 0; i !== nBindings; ++ i ) {
  22883. bindings[ i ].useCount = 0;
  22884. }
  22885. return this;
  22886. },
  22887. // advance the time and update apply the animation
  22888. update: function ( deltaTime ) {
  22889. deltaTime *= this.timeScale;
  22890. var actions = this._actions,
  22891. nActions = this._nActiveActions,
  22892. time = this.time += deltaTime,
  22893. timeDirection = Math.sign( deltaTime ),
  22894. accuIndex = this._accuIndex ^= 1;
  22895. // run active actions
  22896. for ( var i = 0; i !== nActions; ++ i ) {
  22897. var action = actions[ i ];
  22898. if ( action.enabled ) {
  22899. action._update( time, deltaTime, timeDirection, accuIndex );
  22900. }
  22901. }
  22902. // update scene graph
  22903. var bindings = this._bindings,
  22904. nBindings = this._nActiveBindings;
  22905. for ( var i = 0; i !== nBindings; ++ i ) {
  22906. bindings[ i ].apply( accuIndex );
  22907. }
  22908. return this;
  22909. },
  22910. // return this mixer's root target object
  22911. getRoot: function () {
  22912. return this._root;
  22913. },
  22914. // free all resources specific to a particular clip
  22915. uncacheClip: function ( clip ) {
  22916. var actions = this._actions,
  22917. clipUuid = clip.uuid,
  22918. actionsByClip = this._actionsByClip,
  22919. actionsForClip = actionsByClip[ clipUuid ];
  22920. if ( actionsForClip !== undefined ) {
  22921. // note: just calling _removeInactiveAction would mess up the
  22922. // iteration state and also require updating the state we can
  22923. // just throw away
  22924. var actionsToRemove = actionsForClip.knownActions;
  22925. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22926. var action = actionsToRemove[ i ];
  22927. this._deactivateAction( action );
  22928. var cacheIndex = action._cacheIndex,
  22929. lastInactiveAction = actions[ actions.length - 1 ];
  22930. action._cacheIndex = null;
  22931. action._byClipCacheIndex = null;
  22932. lastInactiveAction._cacheIndex = cacheIndex;
  22933. actions[ cacheIndex ] = lastInactiveAction;
  22934. actions.pop();
  22935. this._removeInactiveBindingsForAction( action );
  22936. }
  22937. delete actionsByClip[ clipUuid ];
  22938. }
  22939. },
  22940. // free all resources specific to a particular root target object
  22941. uncacheRoot: function ( root ) {
  22942. var rootUuid = root.uuid,
  22943. actionsByClip = this._actionsByClip;
  22944. for ( var clipUuid in actionsByClip ) {
  22945. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  22946. action = actionByRoot[ rootUuid ];
  22947. if ( action !== undefined ) {
  22948. this._deactivateAction( action );
  22949. this._removeInactiveAction( action );
  22950. }
  22951. }
  22952. var bindingsByRoot = this._bindingsByRootAndName,
  22953. bindingByName = bindingsByRoot[ rootUuid ];
  22954. if ( bindingByName !== undefined ) {
  22955. for ( var trackName in bindingByName ) {
  22956. var binding = bindingByName[ trackName ];
  22957. binding.restoreOriginalState();
  22958. this._removeInactiveBinding( binding );
  22959. }
  22960. }
  22961. },
  22962. // remove a targeted clip from the cache
  22963. uncacheAction: function ( clip, optionalRoot ) {
  22964. var action = this.existingAction( clip, optionalRoot );
  22965. if ( action !== null ) {
  22966. this._deactivateAction( action );
  22967. this._removeInactiveAction( action );
  22968. }
  22969. }
  22970. };
  22971. // Implementation details:
  22972. Object.assign( AnimationMixer.prototype, {
  22973. _bindAction: function ( action, prototypeAction ) {
  22974. var root = action._localRoot || this._root,
  22975. tracks = action._clip.tracks,
  22976. nTracks = tracks.length,
  22977. bindings = action._propertyBindings,
  22978. interpolants = action._interpolants,
  22979. rootUuid = root.uuid,
  22980. bindingsByRoot = this._bindingsByRootAndName,
  22981. bindingsByName = bindingsByRoot[ rootUuid ];
  22982. if ( bindingsByName === undefined ) {
  22983. bindingsByName = {};
  22984. bindingsByRoot[ rootUuid ] = bindingsByName;
  22985. }
  22986. for ( var i = 0; i !== nTracks; ++ i ) {
  22987. var track = tracks[ i ],
  22988. trackName = track.name,
  22989. binding = bindingsByName[ trackName ];
  22990. if ( binding !== undefined ) {
  22991. bindings[ i ] = binding;
  22992. } else {
  22993. binding = bindings[ i ];
  22994. if ( binding !== undefined ) {
  22995. // existing binding, make sure the cache knows
  22996. if ( binding._cacheIndex === null ) {
  22997. ++ binding.referenceCount;
  22998. this._addInactiveBinding( binding, rootUuid, trackName );
  22999. }
  23000. continue;
  23001. }
  23002. var path = prototypeAction && prototypeAction.
  23003. _propertyBindings[ i ].binding.parsedPath;
  23004. binding = new PropertyMixer(
  23005. PropertyBinding.create( root, trackName, path ),
  23006. track.ValueTypeName, track.getValueSize() );
  23007. ++ binding.referenceCount;
  23008. this._addInactiveBinding( binding, rootUuid, trackName );
  23009. bindings[ i ] = binding;
  23010. }
  23011. interpolants[ i ].resultBuffer = binding.buffer;
  23012. }
  23013. },
  23014. _activateAction: function ( action ) {
  23015. if ( ! this._isActiveAction( action ) ) {
  23016. if ( action._cacheIndex === null ) {
  23017. // this action has been forgotten by the cache, but the user
  23018. // appears to be still using it -> rebind
  23019. var rootUuid = ( action._localRoot || this._root ).uuid,
  23020. clipUuid = action._clip.uuid,
  23021. actionsForClip = this._actionsByClip[ clipUuid ];
  23022. this._bindAction( action,
  23023. actionsForClip && actionsForClip.knownActions[ 0 ] );
  23024. this._addInactiveAction( action, clipUuid, rootUuid );
  23025. }
  23026. var bindings = action._propertyBindings;
  23027. // increment reference counts / sort out state
  23028. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23029. var binding = bindings[ i ];
  23030. if ( binding.useCount ++ === 0 ) {
  23031. this._lendBinding( binding );
  23032. binding.saveOriginalState();
  23033. }
  23034. }
  23035. this._lendAction( action );
  23036. }
  23037. },
  23038. _deactivateAction: function ( action ) {
  23039. if ( this._isActiveAction( action ) ) {
  23040. var bindings = action._propertyBindings;
  23041. // decrement reference counts / sort out state
  23042. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23043. var binding = bindings[ i ];
  23044. if ( -- binding.useCount === 0 ) {
  23045. binding.restoreOriginalState();
  23046. this._takeBackBinding( binding );
  23047. }
  23048. }
  23049. this._takeBackAction( action );
  23050. }
  23051. },
  23052. // Memory manager
  23053. _initMemoryManager: function () {
  23054. this._actions = []; // 'nActiveActions' followed by inactive ones
  23055. this._nActiveActions = 0;
  23056. this._actionsByClip = {};
  23057. // inside:
  23058. // {
  23059. // knownActions: Array< AnimationAction > - used as prototypes
  23060. // actionByRoot: AnimationAction - lookup
  23061. // }
  23062. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23063. this._nActiveBindings = 0;
  23064. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23065. this._controlInterpolants = []; // same game as above
  23066. this._nActiveControlInterpolants = 0;
  23067. var scope = this;
  23068. this.stats = {
  23069. actions: {
  23070. get total() { return scope._actions.length; },
  23071. get inUse() { return scope._nActiveActions; }
  23072. },
  23073. bindings: {
  23074. get total() { return scope._bindings.length; },
  23075. get inUse() { return scope._nActiveBindings; }
  23076. },
  23077. controlInterpolants: {
  23078. get total() { return scope._controlInterpolants.length; },
  23079. get inUse() { return scope._nActiveControlInterpolants; }
  23080. }
  23081. };
  23082. },
  23083. // Memory management for AnimationAction objects
  23084. _isActiveAction: function ( action ) {
  23085. var index = action._cacheIndex;
  23086. return index !== null && index < this._nActiveActions;
  23087. },
  23088. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  23089. var actions = this._actions,
  23090. actionsByClip = this._actionsByClip,
  23091. actionsForClip = actionsByClip[ clipUuid ];
  23092. if ( actionsForClip === undefined ) {
  23093. actionsForClip = {
  23094. knownActions: [ action ],
  23095. actionByRoot: {}
  23096. };
  23097. action._byClipCacheIndex = 0;
  23098. actionsByClip[ clipUuid ] = actionsForClip;
  23099. } else {
  23100. var knownActions = actionsForClip.knownActions;
  23101. action._byClipCacheIndex = knownActions.length;
  23102. knownActions.push( action );
  23103. }
  23104. action._cacheIndex = actions.length;
  23105. actions.push( action );
  23106. actionsForClip.actionByRoot[ rootUuid ] = action;
  23107. },
  23108. _removeInactiveAction: function ( action ) {
  23109. var actions = this._actions,
  23110. lastInactiveAction = actions[ actions.length - 1 ],
  23111. cacheIndex = action._cacheIndex;
  23112. lastInactiveAction._cacheIndex = cacheIndex;
  23113. actions[ cacheIndex ] = lastInactiveAction;
  23114. actions.pop();
  23115. action._cacheIndex = null;
  23116. var clipUuid = action._clip.uuid,
  23117. actionsByClip = this._actionsByClip,
  23118. actionsForClip = actionsByClip[ clipUuid ],
  23119. knownActionsForClip = actionsForClip.knownActions,
  23120. lastKnownAction =
  23121. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23122. byClipCacheIndex = action._byClipCacheIndex;
  23123. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23124. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23125. knownActionsForClip.pop();
  23126. action._byClipCacheIndex = null;
  23127. var actionByRoot = actionsForClip.actionByRoot,
  23128. rootUuid = ( actions._localRoot || this._root ).uuid;
  23129. delete actionByRoot[ rootUuid ];
  23130. if ( knownActionsForClip.length === 0 ) {
  23131. delete actionsByClip[ clipUuid ];
  23132. }
  23133. this._removeInactiveBindingsForAction( action );
  23134. },
  23135. _removeInactiveBindingsForAction: function ( action ) {
  23136. var bindings = action._propertyBindings;
  23137. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  23138. var binding = bindings[ i ];
  23139. if ( -- binding.referenceCount === 0 ) {
  23140. this._removeInactiveBinding( binding );
  23141. }
  23142. }
  23143. },
  23144. _lendAction: function ( action ) {
  23145. // [ active actions | inactive actions ]
  23146. // [ active actions >| inactive actions ]
  23147. // s a
  23148. // <-swap->
  23149. // a s
  23150. var actions = this._actions,
  23151. prevIndex = action._cacheIndex,
  23152. lastActiveIndex = this._nActiveActions ++,
  23153. firstInactiveAction = actions[ lastActiveIndex ];
  23154. action._cacheIndex = lastActiveIndex;
  23155. actions[ lastActiveIndex ] = action;
  23156. firstInactiveAction._cacheIndex = prevIndex;
  23157. actions[ prevIndex ] = firstInactiveAction;
  23158. },
  23159. _takeBackAction: function ( action ) {
  23160. // [ active actions | inactive actions ]
  23161. // [ active actions |< inactive actions ]
  23162. // a s
  23163. // <-swap->
  23164. // s a
  23165. var actions = this._actions,
  23166. prevIndex = action._cacheIndex,
  23167. firstInactiveIndex = -- this._nActiveActions,
  23168. lastActiveAction = actions[ firstInactiveIndex ];
  23169. action._cacheIndex = firstInactiveIndex;
  23170. actions[ firstInactiveIndex ] = action;
  23171. lastActiveAction._cacheIndex = prevIndex;
  23172. actions[ prevIndex ] = lastActiveAction;
  23173. },
  23174. // Memory management for PropertyMixer objects
  23175. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  23176. var bindingsByRoot = this._bindingsByRootAndName,
  23177. bindingByName = bindingsByRoot[ rootUuid ],
  23178. bindings = this._bindings;
  23179. if ( bindingByName === undefined ) {
  23180. bindingByName = {};
  23181. bindingsByRoot[ rootUuid ] = bindingByName;
  23182. }
  23183. bindingByName[ trackName ] = binding;
  23184. binding._cacheIndex = bindings.length;
  23185. bindings.push( binding );
  23186. },
  23187. _removeInactiveBinding: function ( binding ) {
  23188. var bindings = this._bindings,
  23189. propBinding = binding.binding,
  23190. rootUuid = propBinding.rootNode.uuid,
  23191. trackName = propBinding.path,
  23192. bindingsByRoot = this._bindingsByRootAndName,
  23193. bindingByName = bindingsByRoot[ rootUuid ],
  23194. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23195. cacheIndex = binding._cacheIndex;
  23196. lastInactiveBinding._cacheIndex = cacheIndex;
  23197. bindings[ cacheIndex ] = lastInactiveBinding;
  23198. bindings.pop();
  23199. delete bindingByName[ trackName ];
  23200. remove_empty_map: {
  23201. for ( var _ in bindingByName ) break remove_empty_map;
  23202. delete bindingsByRoot[ rootUuid ];
  23203. }
  23204. },
  23205. _lendBinding: function ( binding ) {
  23206. var bindings = this._bindings,
  23207. prevIndex = binding._cacheIndex,
  23208. lastActiveIndex = this._nActiveBindings ++,
  23209. firstInactiveBinding = bindings[ lastActiveIndex ];
  23210. binding._cacheIndex = lastActiveIndex;
  23211. bindings[ lastActiveIndex ] = binding;
  23212. firstInactiveBinding._cacheIndex = prevIndex;
  23213. bindings[ prevIndex ] = firstInactiveBinding;
  23214. },
  23215. _takeBackBinding: function ( binding ) {
  23216. var bindings = this._bindings,
  23217. prevIndex = binding._cacheIndex,
  23218. firstInactiveIndex = -- this._nActiveBindings,
  23219. lastActiveBinding = bindings[ firstInactiveIndex ];
  23220. binding._cacheIndex = firstInactiveIndex;
  23221. bindings[ firstInactiveIndex ] = binding;
  23222. lastActiveBinding._cacheIndex = prevIndex;
  23223. bindings[ prevIndex ] = lastActiveBinding;
  23224. },
  23225. // Memory management of Interpolants for weight and time scale
  23226. _lendControlInterpolant: function () {
  23227. var interpolants = this._controlInterpolants,
  23228. lastActiveIndex = this._nActiveControlInterpolants ++,
  23229. interpolant = interpolants[ lastActiveIndex ];
  23230. if ( interpolant === undefined ) {
  23231. interpolant = new LinearInterpolant(
  23232. new Float32Array( 2 ), new Float32Array( 2 ),
  23233. 1, this._controlInterpolantsResultBuffer );
  23234. interpolant.__cacheIndex = lastActiveIndex;
  23235. interpolants[ lastActiveIndex ] = interpolant;
  23236. }
  23237. return interpolant;
  23238. },
  23239. _takeBackControlInterpolant: function ( interpolant ) {
  23240. var interpolants = this._controlInterpolants,
  23241. prevIndex = interpolant.__cacheIndex,
  23242. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23243. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23244. interpolant.__cacheIndex = firstInactiveIndex;
  23245. interpolants[ firstInactiveIndex ] = interpolant;
  23246. lastActiveInterpolant.__cacheIndex = prevIndex;
  23247. interpolants[ prevIndex ] = lastActiveInterpolant;
  23248. },
  23249. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  23250. } );
  23251. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype );
  23252. /**
  23253. * @author mrdoob / http://mrdoob.com/
  23254. */
  23255. function Uniform( value ) {
  23256. if ( typeof value === 'string' ) {
  23257. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  23258. value = arguments[ 1 ];
  23259. }
  23260. this.value = value;
  23261. }
  23262. Uniform.prototype.clone = function () {
  23263. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  23264. };
  23265. /**
  23266. * @author benaadams / https://twitter.com/ben_a_adams
  23267. */
  23268. function InstancedBufferGeometry() {
  23269. BufferGeometry.call( this );
  23270. this.type = 'InstancedBufferGeometry';
  23271. this.maxInstancedCount = undefined;
  23272. }
  23273. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23274. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  23275. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23276. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  23277. this.groups.push( {
  23278. start: start,
  23279. count: count,
  23280. materialIndex: materialIndex
  23281. } );
  23282. };
  23283. InstancedBufferGeometry.prototype.copy = function ( source ) {
  23284. var index = source.index;
  23285. if ( index !== null ) {
  23286. this.setIndex( index.clone() );
  23287. }
  23288. var attributes = source.attributes;
  23289. for ( var name in attributes ) {
  23290. var attribute = attributes[ name ];
  23291. this.addAttribute( name, attribute.clone() );
  23292. }
  23293. var groups = source.groups;
  23294. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  23295. var group = groups[ i ];
  23296. this.addGroup( group.start, group.count, group.materialIndex );
  23297. }
  23298. return this;
  23299. };
  23300. /**
  23301. * @author benaadams / https://twitter.com/ben_a_adams
  23302. */
  23303. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  23304. this.uuid = _Math.generateUUID();
  23305. this.data = interleavedBuffer;
  23306. this.itemSize = itemSize;
  23307. this.offset = offset;
  23308. this.normalized = normalized === true;
  23309. }
  23310. InterleavedBufferAttribute.prototype = {
  23311. constructor: InterleavedBufferAttribute,
  23312. isInterleavedBufferAttribute: true,
  23313. get count() {
  23314. return this.data.count;
  23315. },
  23316. get array() {
  23317. return this.data.array;
  23318. },
  23319. setX: function ( index, x ) {
  23320. this.data.array[ index * this.data.stride + this.offset ] = x;
  23321. return this;
  23322. },
  23323. setY: function ( index, y ) {
  23324. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  23325. return this;
  23326. },
  23327. setZ: function ( index, z ) {
  23328. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  23329. return this;
  23330. },
  23331. setW: function ( index, w ) {
  23332. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  23333. return this;
  23334. },
  23335. getX: function ( index ) {
  23336. return this.data.array[ index * this.data.stride + this.offset ];
  23337. },
  23338. getY: function ( index ) {
  23339. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  23340. },
  23341. getZ: function ( index ) {
  23342. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  23343. },
  23344. getW: function ( index ) {
  23345. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  23346. },
  23347. setXY: function ( index, x, y ) {
  23348. index = index * this.data.stride + this.offset;
  23349. this.data.array[ index + 0 ] = x;
  23350. this.data.array[ index + 1 ] = y;
  23351. return this;
  23352. },
  23353. setXYZ: function ( index, x, y, z ) {
  23354. index = index * this.data.stride + this.offset;
  23355. this.data.array[ index + 0 ] = x;
  23356. this.data.array[ index + 1 ] = y;
  23357. this.data.array[ index + 2 ] = z;
  23358. return this;
  23359. },
  23360. setXYZW: function ( index, x, y, z, w ) {
  23361. index = index * this.data.stride + this.offset;
  23362. this.data.array[ index + 0 ] = x;
  23363. this.data.array[ index + 1 ] = y;
  23364. this.data.array[ index + 2 ] = z;
  23365. this.data.array[ index + 3 ] = w;
  23366. return this;
  23367. }
  23368. };
  23369. /**
  23370. * @author benaadams / https://twitter.com/ben_a_adams
  23371. */
  23372. function InterleavedBuffer( array, stride ) {
  23373. this.uuid = _Math.generateUUID();
  23374. this.array = array;
  23375. this.stride = stride;
  23376. this.count = array !== undefined ? array.length / stride : 0;
  23377. this.dynamic = false;
  23378. this.updateRange = { offset: 0, count: - 1 };
  23379. this.onUploadCallback = function () {};
  23380. this.version = 0;
  23381. }
  23382. InterleavedBuffer.prototype = {
  23383. constructor: InterleavedBuffer,
  23384. isInterleavedBuffer: true,
  23385. set needsUpdate( value ) {
  23386. if ( value === true ) this.version ++;
  23387. },
  23388. setArray: function ( array ) {
  23389. if ( Array.isArray( array ) ) {
  23390. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  23391. }
  23392. this.count = array !== undefined ? array.length / this.stride : 0;
  23393. this.array = array;
  23394. },
  23395. setDynamic: function ( value ) {
  23396. this.dynamic = value;
  23397. return this;
  23398. },
  23399. copy: function ( source ) {
  23400. this.array = new source.array.constructor( source.array );
  23401. this.count = source.count;
  23402. this.stride = source.stride;
  23403. this.dynamic = source.dynamic;
  23404. return this;
  23405. },
  23406. copyAt: function ( index1, attribute, index2 ) {
  23407. index1 *= this.stride;
  23408. index2 *= attribute.stride;
  23409. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  23410. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  23411. }
  23412. return this;
  23413. },
  23414. set: function ( value, offset ) {
  23415. if ( offset === undefined ) offset = 0;
  23416. this.array.set( value, offset );
  23417. return this;
  23418. },
  23419. clone: function () {
  23420. return new this.constructor().copy( this );
  23421. },
  23422. onUpload: function ( callback ) {
  23423. this.onUploadCallback = callback;
  23424. return this;
  23425. }
  23426. };
  23427. /**
  23428. * @author benaadams / https://twitter.com/ben_a_adams
  23429. */
  23430. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  23431. InterleavedBuffer.call( this, array, stride );
  23432. this.meshPerAttribute = meshPerAttribute || 1;
  23433. }
  23434. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  23435. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  23436. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  23437. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  23438. InterleavedBuffer.prototype.copy.call( this, source );
  23439. this.meshPerAttribute = source.meshPerAttribute;
  23440. return this;
  23441. };
  23442. /**
  23443. * @author benaadams / https://twitter.com/ben_a_adams
  23444. */
  23445. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  23446. BufferAttribute.call( this, array, itemSize );
  23447. this.meshPerAttribute = meshPerAttribute || 1;
  23448. }
  23449. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  23450. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  23451. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23452. InstancedBufferAttribute.prototype.copy = function ( source ) {
  23453. BufferAttribute.prototype.copy.call( this, source );
  23454. this.meshPerAttribute = source.meshPerAttribute;
  23455. return this;
  23456. };
  23457. /**
  23458. * @author mrdoob / http://mrdoob.com/
  23459. * @author bhouston / http://clara.io/
  23460. * @author stephomi / http://stephaneginier.com/
  23461. */
  23462. function Raycaster( origin, direction, near, far ) {
  23463. this.ray = new Ray( origin, direction );
  23464. // direction is assumed to be normalized (for accurate distance calculations)
  23465. this.near = near || 0;
  23466. this.far = far || Infinity;
  23467. this.params = {
  23468. Mesh: {},
  23469. Line: {},
  23470. LOD: {},
  23471. Points: { threshold: 1 },
  23472. Sprite: {}
  23473. };
  23474. Object.defineProperties( this.params, {
  23475. PointCloud: {
  23476. get: function () {
  23477. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  23478. return this.Points;
  23479. }
  23480. }
  23481. } );
  23482. }
  23483. function ascSort( a, b ) {
  23484. return a.distance - b.distance;
  23485. }
  23486. function intersectObject( object, raycaster, intersects, recursive ) {
  23487. if ( object.visible === false ) return;
  23488. object.raycast( raycaster, intersects );
  23489. if ( recursive === true ) {
  23490. var children = object.children;
  23491. for ( var i = 0, l = children.length; i < l; i ++ ) {
  23492. intersectObject( children[ i ], raycaster, intersects, true );
  23493. }
  23494. }
  23495. }
  23496. //
  23497. Raycaster.prototype = {
  23498. constructor: Raycaster,
  23499. linePrecision: 1,
  23500. set: function ( origin, direction ) {
  23501. // direction is assumed to be normalized (for accurate distance calculations)
  23502. this.ray.set( origin, direction );
  23503. },
  23504. setFromCamera: function ( coords, camera ) {
  23505. if ( (camera && camera.isPerspectiveCamera) ) {
  23506. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23507. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23508. } else if ( (camera && camera.isOrthographicCamera) ) {
  23509. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23510. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23511. } else {
  23512. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  23513. }
  23514. },
  23515. intersectObject: function ( object, recursive ) {
  23516. var intersects = [];
  23517. intersectObject( object, this, intersects, recursive );
  23518. intersects.sort( ascSort );
  23519. return intersects;
  23520. },
  23521. intersectObjects: function ( objects, recursive ) {
  23522. var intersects = [];
  23523. if ( Array.isArray( objects ) === false ) {
  23524. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  23525. return intersects;
  23526. }
  23527. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  23528. intersectObject( objects[ i ], this, intersects, recursive );
  23529. }
  23530. intersects.sort( ascSort );
  23531. return intersects;
  23532. }
  23533. };
  23534. /**
  23535. * @author alteredq / http://alteredqualia.com/
  23536. */
  23537. function Clock( autoStart ) {
  23538. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  23539. this.startTime = 0;
  23540. this.oldTime = 0;
  23541. this.elapsedTime = 0;
  23542. this.running = false;
  23543. }
  23544. Clock.prototype = {
  23545. constructor: Clock,
  23546. start: function () {
  23547. this.startTime = ( performance || Date ).now();
  23548. this.oldTime = this.startTime;
  23549. this.elapsedTime = 0;
  23550. this.running = true;
  23551. },
  23552. stop: function () {
  23553. this.getElapsedTime();
  23554. this.running = false;
  23555. },
  23556. getElapsedTime: function () {
  23557. this.getDelta();
  23558. return this.elapsedTime;
  23559. },
  23560. getDelta: function () {
  23561. var diff = 0;
  23562. if ( this.autoStart && ! this.running ) {
  23563. this.start();
  23564. }
  23565. if ( this.running ) {
  23566. var newTime = ( performance || Date ).now();
  23567. diff = ( newTime - this.oldTime ) / 1000;
  23568. this.oldTime = newTime;
  23569. this.elapsedTime += diff;
  23570. }
  23571. return diff;
  23572. }
  23573. };
  23574. /**
  23575. * @author bhouston / http://clara.io
  23576. * @author WestLangley / http://github.com/WestLangley
  23577. *
  23578. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23579. *
  23580. * The poles (phi) are at the positive and negative y axis.
  23581. * The equator starts at positive z.
  23582. */
  23583. function Spherical( radius, phi, theta ) {
  23584. this.radius = ( radius !== undefined ) ? radius : 1.0;
  23585. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  23586. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  23587. return this;
  23588. }
  23589. Spherical.prototype = {
  23590. constructor: Spherical,
  23591. set: function ( radius, phi, theta ) {
  23592. this.radius = radius;
  23593. this.phi = phi;
  23594. this.theta = theta;
  23595. return this;
  23596. },
  23597. clone: function () {
  23598. return new this.constructor().copy( this );
  23599. },
  23600. copy: function ( other ) {
  23601. this.radius = other.radius;
  23602. this.phi = other.phi;
  23603. this.theta = other.theta;
  23604. return this;
  23605. },
  23606. // restrict phi to be betwee EPS and PI-EPS
  23607. makeSafe: function() {
  23608. var EPS = 0.000001;
  23609. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23610. return this;
  23611. },
  23612. setFromVector3: function( vec3 ) {
  23613. this.radius = vec3.length();
  23614. if ( this.radius === 0 ) {
  23615. this.theta = 0;
  23616. this.phi = 0;
  23617. } else {
  23618. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  23619. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  23620. }
  23621. return this;
  23622. }
  23623. };
  23624. /**
  23625. * @author Mugen87 / https://github.com/Mugen87
  23626. *
  23627. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  23628. *
  23629. */
  23630. function Cylindrical( radius, theta, y ) {
  23631. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  23632. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  23633. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  23634. return this;
  23635. }
  23636. Cylindrical.prototype = {
  23637. constructor: Cylindrical,
  23638. set: function ( radius, theta, y ) {
  23639. this.radius = radius;
  23640. this.theta = theta;
  23641. this.y = y;
  23642. return this;
  23643. },
  23644. clone: function () {
  23645. return new this.constructor().copy( this );
  23646. },
  23647. copy: function ( other ) {
  23648. this.radius = other.radius;
  23649. this.theta = other.theta;
  23650. this.y = other.y;
  23651. return this;
  23652. },
  23653. setFromVector3: function( vec3 ) {
  23654. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  23655. this.theta = Math.atan2( vec3.x, vec3.z );
  23656. this.y = vec3.y;
  23657. return this;
  23658. }
  23659. };
  23660. /**
  23661. * @author alteredq / http://alteredqualia.com/
  23662. */
  23663. function MorphBlendMesh( geometry, material ) {
  23664. Mesh.call( this, geometry, material );
  23665. this.animationsMap = {};
  23666. this.animationsList = [];
  23667. // prepare default animation
  23668. // (all frames played together in 1 second)
  23669. var numFrames = this.geometry.morphTargets.length;
  23670. var name = "__default";
  23671. var startFrame = 0;
  23672. var endFrame = numFrames - 1;
  23673. var fps = numFrames / 1;
  23674. this.createAnimation( name, startFrame, endFrame, fps );
  23675. this.setAnimationWeight( name, 1 );
  23676. }
  23677. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  23678. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  23679. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23680. var animation = {
  23681. start: start,
  23682. end: end,
  23683. length: end - start + 1,
  23684. fps: fps,
  23685. duration: ( end - start ) / fps,
  23686. lastFrame: 0,
  23687. currentFrame: 0,
  23688. active: false,
  23689. time: 0,
  23690. direction: 1,
  23691. weight: 1,
  23692. directionBackwards: false,
  23693. mirroredLoop: false
  23694. };
  23695. this.animationsMap[ name ] = animation;
  23696. this.animationsList.push( animation );
  23697. };
  23698. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23699. var pattern = /([a-z]+)_?(\d+)/i;
  23700. var firstAnimation, frameRanges = {};
  23701. var geometry = this.geometry;
  23702. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23703. var morph = geometry.morphTargets[ i ];
  23704. var chunks = morph.name.match( pattern );
  23705. if ( chunks && chunks.length > 1 ) {
  23706. var name = chunks[ 1 ];
  23707. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23708. var range = frameRanges[ name ];
  23709. if ( i < range.start ) range.start = i;
  23710. if ( i > range.end ) range.end = i;
  23711. if ( ! firstAnimation ) firstAnimation = name;
  23712. }
  23713. }
  23714. for ( var name in frameRanges ) {
  23715. var range = frameRanges[ name ];
  23716. this.createAnimation( name, range.start, range.end, fps );
  23717. }
  23718. this.firstAnimation = firstAnimation;
  23719. };
  23720. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23721. var animation = this.animationsMap[ name ];
  23722. if ( animation ) {
  23723. animation.direction = 1;
  23724. animation.directionBackwards = false;
  23725. }
  23726. };
  23727. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23728. var animation = this.animationsMap[ name ];
  23729. if ( animation ) {
  23730. animation.direction = - 1;
  23731. animation.directionBackwards = true;
  23732. }
  23733. };
  23734. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23735. var animation = this.animationsMap[ name ];
  23736. if ( animation ) {
  23737. animation.fps = fps;
  23738. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23739. }
  23740. };
  23741. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23742. var animation = this.animationsMap[ name ];
  23743. if ( animation ) {
  23744. animation.duration = duration;
  23745. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23746. }
  23747. };
  23748. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23749. var animation = this.animationsMap[ name ];
  23750. if ( animation ) {
  23751. animation.weight = weight;
  23752. }
  23753. };
  23754. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23755. var animation = this.animationsMap[ name ];
  23756. if ( animation ) {
  23757. animation.time = time;
  23758. }
  23759. };
  23760. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23761. var time = 0;
  23762. var animation = this.animationsMap[ name ];
  23763. if ( animation ) {
  23764. time = animation.time;
  23765. }
  23766. return time;
  23767. };
  23768. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23769. var duration = - 1;
  23770. var animation = this.animationsMap[ name ];
  23771. if ( animation ) {
  23772. duration = animation.duration;
  23773. }
  23774. return duration;
  23775. };
  23776. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23777. var animation = this.animationsMap[ name ];
  23778. if ( animation ) {
  23779. animation.time = 0;
  23780. animation.active = true;
  23781. } else {
  23782. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23783. }
  23784. };
  23785. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23786. var animation = this.animationsMap[ name ];
  23787. if ( animation ) {
  23788. animation.active = false;
  23789. }
  23790. };
  23791. MorphBlendMesh.prototype.update = function ( delta ) {
  23792. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23793. var animation = this.animationsList[ i ];
  23794. if ( ! animation.active ) continue;
  23795. var frameTime = animation.duration / animation.length;
  23796. animation.time += animation.direction * delta;
  23797. if ( animation.mirroredLoop ) {
  23798. if ( animation.time > animation.duration || animation.time < 0 ) {
  23799. animation.direction *= - 1;
  23800. if ( animation.time > animation.duration ) {
  23801. animation.time = animation.duration;
  23802. animation.directionBackwards = true;
  23803. }
  23804. if ( animation.time < 0 ) {
  23805. animation.time = 0;
  23806. animation.directionBackwards = false;
  23807. }
  23808. }
  23809. } else {
  23810. animation.time = animation.time % animation.duration;
  23811. if ( animation.time < 0 ) animation.time += animation.duration;
  23812. }
  23813. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23814. var weight = animation.weight;
  23815. if ( keyframe !== animation.currentFrame ) {
  23816. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23817. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23818. this.morphTargetInfluences[ keyframe ] = 0;
  23819. animation.lastFrame = animation.currentFrame;
  23820. animation.currentFrame = keyframe;
  23821. }
  23822. var mix = ( animation.time % frameTime ) / frameTime;
  23823. if ( animation.directionBackwards ) mix = 1 - mix;
  23824. if ( animation.currentFrame !== animation.lastFrame ) {
  23825. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23826. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23827. } else {
  23828. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23829. }
  23830. }
  23831. };
  23832. /**
  23833. * @author alteredq / http://alteredqualia.com/
  23834. */
  23835. function ImmediateRenderObject( material ) {
  23836. Object3D.call( this );
  23837. this.material = material;
  23838. this.render = function ( renderCallback ) {};
  23839. }
  23840. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  23841. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  23842. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  23843. /**
  23844. * @author mrdoob / http://mrdoob.com/
  23845. * @author WestLangley / http://github.com/WestLangley
  23846. */
  23847. function VertexNormalsHelper( object, size, hex, linewidth ) {
  23848. this.object = object;
  23849. this.size = ( size !== undefined ) ? size : 1;
  23850. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23851. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23852. //
  23853. var nNormals = 0;
  23854. var objGeometry = this.object.geometry;
  23855. if ( objGeometry && objGeometry.isGeometry ) {
  23856. nNormals = objGeometry.faces.length * 3;
  23857. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23858. nNormals = objGeometry.attributes.normal.count;
  23859. }
  23860. //
  23861. var geometry = new BufferGeometry();
  23862. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  23863. geometry.addAttribute( 'position', positions );
  23864. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  23865. //
  23866. this.matrixAutoUpdate = false;
  23867. this.update();
  23868. }
  23869. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  23870. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  23871. VertexNormalsHelper.prototype.update = ( function () {
  23872. var v1 = new Vector3();
  23873. var v2 = new Vector3();
  23874. var normalMatrix = new Matrix3();
  23875. return function update() {
  23876. var keys = [ 'a', 'b', 'c' ];
  23877. this.object.updateMatrixWorld( true );
  23878. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23879. var matrixWorld = this.object.matrixWorld;
  23880. var position = this.geometry.attributes.position;
  23881. //
  23882. var objGeometry = this.object.geometry;
  23883. if ( objGeometry && objGeometry.isGeometry ) {
  23884. var vertices = objGeometry.vertices;
  23885. var faces = objGeometry.faces;
  23886. var idx = 0;
  23887. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23888. var face = faces[ i ];
  23889. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23890. var vertex = vertices[ face[ keys[ j ] ] ];
  23891. var normal = face.vertexNormals[ j ];
  23892. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23893. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23894. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23895. idx = idx + 1;
  23896. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23897. idx = idx + 1;
  23898. }
  23899. }
  23900. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23901. var objPos = objGeometry.attributes.position;
  23902. var objNorm = objGeometry.attributes.normal;
  23903. var idx = 0;
  23904. // for simplicity, ignore index and drawcalls, and render every normal
  23905. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23906. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23907. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23908. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23909. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23910. idx = idx + 1;
  23911. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23912. idx = idx + 1;
  23913. }
  23914. }
  23915. position.needsUpdate = true;
  23916. return this;
  23917. };
  23918. }() );
  23919. /**
  23920. * @author alteredq / http://alteredqualia.com/
  23921. * @author mrdoob / http://mrdoob.com/
  23922. * @author WestLangley / http://github.com/WestLangley
  23923. */
  23924. function SpotLightHelper( light ) {
  23925. Object3D.call( this );
  23926. this.light = light;
  23927. this.light.updateMatrixWorld();
  23928. this.matrix = light.matrixWorld;
  23929. this.matrixAutoUpdate = false;
  23930. var geometry = new BufferGeometry();
  23931. var positions = [
  23932. 0, 0, 0, 0, 0, 1,
  23933. 0, 0, 0, 1, 0, 1,
  23934. 0, 0, 0, - 1, 0, 1,
  23935. 0, 0, 0, 0, 1, 1,
  23936. 0, 0, 0, 0, - 1, 1
  23937. ];
  23938. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  23939. var p1 = ( i / l ) * Math.PI * 2;
  23940. var p2 = ( j / l ) * Math.PI * 2;
  23941. positions.push(
  23942. Math.cos( p1 ), Math.sin( p1 ), 1,
  23943. Math.cos( p2 ), Math.sin( p2 ), 1
  23944. );
  23945. }
  23946. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23947. var material = new LineBasicMaterial( { fog: false } );
  23948. this.cone = new LineSegments( geometry, material );
  23949. this.add( this.cone );
  23950. this.update();
  23951. }
  23952. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  23953. SpotLightHelper.prototype.constructor = SpotLightHelper;
  23954. SpotLightHelper.prototype.dispose = function () {
  23955. this.cone.geometry.dispose();
  23956. this.cone.material.dispose();
  23957. };
  23958. SpotLightHelper.prototype.update = function () {
  23959. var vector = new Vector3();
  23960. var vector2 = new Vector3();
  23961. return function update() {
  23962. var coneLength = this.light.distance ? this.light.distance : 1000;
  23963. var coneWidth = coneLength * Math.tan( this.light.angle );
  23964. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23965. vector.setFromMatrixPosition( this.light.matrixWorld );
  23966. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23967. this.cone.lookAt( vector2.sub( vector ) );
  23968. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23969. };
  23970. }();
  23971. /**
  23972. * @author Sean Griffin / http://twitter.com/sgrif
  23973. * @author Michael Guerrero / http://realitymeltdown.com
  23974. * @author mrdoob / http://mrdoob.com/
  23975. * @author ikerr / http://verold.com
  23976. * @author Mugen87 / https://github.com/Mugen87
  23977. */
  23978. function SkeletonHelper( object ) {
  23979. this.bones = this.getBoneList( object );
  23980. var geometry = new BufferGeometry();
  23981. var vertices = [];
  23982. var colors = [];
  23983. var color1 = new Color( 0, 0, 1 );
  23984. var color2 = new Color( 0, 1, 0 );
  23985. for ( var i = 0; i < this.bones.length; i ++ ) {
  23986. var bone = this.bones[ i ];
  23987. if ( bone.parent && bone.parent.isBone ) {
  23988. vertices.push( 0, 0, 0 );
  23989. vertices.push( 0, 0, 0 );
  23990. colors.push( color1.r, color1.g, color1.b );
  23991. colors.push( color2.r, color2.g, color2.b );
  23992. }
  23993. }
  23994. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23995. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23996. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23997. LineSegments.call( this, geometry, material );
  23998. this.root = object;
  23999. this.matrix = object.matrixWorld;
  24000. this.matrixAutoUpdate = false;
  24001. this.update();
  24002. }
  24003. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  24004. SkeletonHelper.prototype.constructor = SkeletonHelper;
  24005. SkeletonHelper.prototype.getBoneList = function( object ) {
  24006. var boneList = [];
  24007. if ( object && object.isBone ) {
  24008. boneList.push( object );
  24009. }
  24010. for ( var i = 0; i < object.children.length; i ++ ) {
  24011. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24012. }
  24013. return boneList;
  24014. };
  24015. SkeletonHelper.prototype.update = function () {
  24016. var vector = new Vector3();
  24017. var boneMatrix = new Matrix4();
  24018. var matrixWorldInv = new Matrix4();
  24019. return function update() {
  24020. var geometry = this.geometry;
  24021. var position = geometry.getAttribute( 'position' );
  24022. matrixWorldInv.getInverse( this.root.matrixWorld );
  24023. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  24024. var bone = this.bones[ i ];
  24025. if ( bone.parent && bone.parent.isBone ) {
  24026. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24027. vector.setFromMatrixPosition( boneMatrix );
  24028. position.setXYZ( j, vector.x, vector.y, vector.z );
  24029. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24030. vector.setFromMatrixPosition( boneMatrix );
  24031. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  24032. j += 2;
  24033. }
  24034. }
  24035. geometry.getAttribute( 'position' ).needsUpdate = true;
  24036. };
  24037. }();
  24038. /**
  24039. * @author alteredq / http://alteredqualia.com/
  24040. * @author mrdoob / http://mrdoob.com/
  24041. */
  24042. function PointLightHelper( light, sphereSize ) {
  24043. this.light = light;
  24044. this.light.updateMatrixWorld();
  24045. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  24046. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  24047. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24048. Mesh.call( this, geometry, material );
  24049. this.matrix = this.light.matrixWorld;
  24050. this.matrixAutoUpdate = false;
  24051. /*
  24052. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24053. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24054. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24055. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24056. var d = light.distance;
  24057. if ( d === 0.0 ) {
  24058. this.lightDistance.visible = false;
  24059. } else {
  24060. this.lightDistance.scale.set( d, d, d );
  24061. }
  24062. this.add( this.lightDistance );
  24063. */
  24064. }
  24065. PointLightHelper.prototype = Object.create( Mesh.prototype );
  24066. PointLightHelper.prototype.constructor = PointLightHelper;
  24067. PointLightHelper.prototype.dispose = function () {
  24068. this.geometry.dispose();
  24069. this.material.dispose();
  24070. };
  24071. PointLightHelper.prototype.update = function () {
  24072. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24073. /*
  24074. var d = this.light.distance;
  24075. if ( d === 0.0 ) {
  24076. this.lightDistance.visible = false;
  24077. } else {
  24078. this.lightDistance.visible = true;
  24079. this.lightDistance.scale.set( d, d, d );
  24080. }
  24081. */
  24082. };
  24083. /**
  24084. * @author abelnation / http://github.com/abelnation
  24085. * @author Mugen87 / http://github.com/Mugen87
  24086. */
  24087. function RectAreaLightHelper( light ) {
  24088. Object3D.call( this );
  24089. this.light = light;
  24090. this.light.updateMatrixWorld();
  24091. var materialFront = new MeshBasicMaterial( {
  24092. color: light.color,
  24093. fog: false
  24094. } );
  24095. var materialBack = new MeshBasicMaterial( {
  24096. color: light.color,
  24097. fog: false,
  24098. wireframe: true
  24099. } );
  24100. var geometry = new BufferGeometry();
  24101. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  24102. // shows the "front" of the light, e.g. where light comes from
  24103. this.add( new Mesh( geometry, materialFront ) );
  24104. // shows the "back" of the light, which does not emit light
  24105. this.add( new Mesh( geometry, materialBack ) );
  24106. this.update();
  24107. }
  24108. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  24109. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  24110. RectAreaLightHelper.prototype.dispose = function () {
  24111. this.children[ 0 ].geometry.dispose();
  24112. this.children[ 0 ].material.dispose();
  24113. this.children[ 1 ].geometry.dispose();
  24114. this.children[ 1 ].material.dispose();
  24115. };
  24116. RectAreaLightHelper.prototype.update = function () {
  24117. var vector1 = new Vector3();
  24118. var vector2 = new Vector3();
  24119. return function update() {
  24120. var mesh1 = this.children[ 0 ];
  24121. var mesh2 = this.children[ 1 ];
  24122. if ( this.light.target ) {
  24123. vector1.setFromMatrixPosition( this.light.matrixWorld );
  24124. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24125. var lookVec = vector2.clone().sub( vector1 );
  24126. mesh1.lookAt( lookVec );
  24127. mesh2.lookAt( lookVec );
  24128. }
  24129. // update materials
  24130. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24131. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24132. // calculate new dimensions of the helper
  24133. var hx = this.light.width * 0.5;
  24134. var hy = this.light.height * 0.5;
  24135. // because the buffer attribute is shared over both geometries, we only have to update once
  24136. var position = mesh1.geometry.getAttribute( 'position' );
  24137. var array = position.array;
  24138. // first face
  24139. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  24140. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  24141. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  24142. // second face
  24143. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  24144. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  24145. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  24146. position.needsUpdate = true;
  24147. };
  24148. }();
  24149. /**
  24150. * @author alteredq / http://alteredqualia.com/
  24151. * @author mrdoob / http://mrdoob.com/
  24152. * @author Mugen87 / https://github.com/Mugen87
  24153. */
  24154. function HemisphereLightHelper( light, size ) {
  24155. Object3D.call( this );
  24156. this.light = light;
  24157. this.light.updateMatrixWorld();
  24158. this.matrix = light.matrixWorld;
  24159. this.matrixAutoUpdate = false;
  24160. var geometry = new OctahedronBufferGeometry( size );
  24161. geometry.rotateY( Math.PI * 0.5 );
  24162. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  24163. var position = geometry.getAttribute( 'position' );
  24164. var colors = new Float32Array( position.count * 3 );
  24165. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  24166. this.add( new Mesh( geometry, material ) );
  24167. this.update();
  24168. }
  24169. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  24170. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  24171. HemisphereLightHelper.prototype.dispose = function () {
  24172. this.children[ 0 ].geometry.dispose();
  24173. this.children[ 0 ].material.dispose();
  24174. };
  24175. HemisphereLightHelper.prototype.update = function () {
  24176. var vector = new Vector3();
  24177. var color1 = new Color();
  24178. var color2 = new Color();
  24179. return function update() {
  24180. var mesh = this.children[ 0 ];
  24181. var colors = mesh.geometry.getAttribute( 'color' );
  24182. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24183. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24184. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  24185. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  24186. colors.setXYZ( i, color.r, color.g, color.b );
  24187. }
  24188. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24189. colors.needsUpdate = true;
  24190. };
  24191. }();
  24192. /**
  24193. * @author mrdoob / http://mrdoob.com/
  24194. */
  24195. function GridHelper( size, divisions, color1, color2 ) {
  24196. size = size || 10;
  24197. divisions = divisions || 10;
  24198. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24199. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24200. var center = divisions / 2;
  24201. var step = ( size * 2 ) / divisions;
  24202. var vertices = [], colors = [];
  24203. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  24204. vertices.push( - size, 0, k, size, 0, k );
  24205. vertices.push( k, 0, - size, k, 0, size );
  24206. var color = i === center ? color1 : color2;
  24207. color.toArray( colors, j ); j += 3;
  24208. color.toArray( colors, j ); j += 3;
  24209. color.toArray( colors, j ); j += 3;
  24210. color.toArray( colors, j ); j += 3;
  24211. }
  24212. var geometry = new BufferGeometry();
  24213. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24214. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24215. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24216. LineSegments.call( this, geometry, material );
  24217. }
  24218. GridHelper.prototype = Object.create( LineSegments.prototype );
  24219. GridHelper.prototype.constructor = GridHelper;
  24220. /**
  24221. * @author mrdoob / http://mrdoob.com/
  24222. * @author Mugen87 / http://github.com/Mugen87
  24223. * @author Hectate / http://www.github.com/Hectate
  24224. */
  24225. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  24226. radius = radius || 10;
  24227. radials = radials || 16;
  24228. circles = circles || 8;
  24229. divisions = divisions || 64;
  24230. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  24231. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  24232. var vertices = [];
  24233. var colors = [];
  24234. var x, z;
  24235. var v, i, j, r, color;
  24236. // create the radials
  24237. for ( i = 0; i <= radials; i ++ ) {
  24238. v = ( i / radials ) * ( Math.PI * 2 );
  24239. x = Math.sin( v ) * radius;
  24240. z = Math.cos( v ) * radius;
  24241. vertices.push( 0, 0, 0 );
  24242. vertices.push( x, 0, z );
  24243. color = ( i & 1 ) ? color1 : color2;
  24244. colors.push( color.r, color.g, color.b );
  24245. colors.push( color.r, color.g, color.b );
  24246. }
  24247. // create the circles
  24248. for ( i = 0; i <= circles; i ++ ) {
  24249. color = ( i & 1 ) ? color1 : color2;
  24250. r = radius - ( radius / circles * i );
  24251. for ( j = 0; j < divisions; j ++ ) {
  24252. // first vertex
  24253. v = ( j / divisions ) * ( Math.PI * 2 );
  24254. x = Math.sin( v ) * r;
  24255. z = Math.cos( v ) * r;
  24256. vertices.push( x, 0, z );
  24257. colors.push( color.r, color.g, color.b );
  24258. // second vertex
  24259. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  24260. x = Math.sin( v ) * r;
  24261. z = Math.cos( v ) * r;
  24262. vertices.push( x, 0, z );
  24263. colors.push( color.r, color.g, color.b );
  24264. }
  24265. }
  24266. var geometry = new BufferGeometry();
  24267. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24268. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24269. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24270. LineSegments.call( this, geometry, material );
  24271. }
  24272. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  24273. PolarGridHelper.prototype.constructor = PolarGridHelper;
  24274. /**
  24275. * @author mrdoob / http://mrdoob.com/
  24276. * @author WestLangley / http://github.com/WestLangley
  24277. */
  24278. function FaceNormalsHelper( object, size, hex, linewidth ) {
  24279. // FaceNormalsHelper only supports THREE.Geometry
  24280. this.object = object;
  24281. this.size = ( size !== undefined ) ? size : 1;
  24282. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24283. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24284. //
  24285. var nNormals = 0;
  24286. var objGeometry = this.object.geometry;
  24287. if ( objGeometry && objGeometry.isGeometry ) {
  24288. nNormals = objGeometry.faces.length;
  24289. } else {
  24290. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24291. }
  24292. //
  24293. var geometry = new BufferGeometry();
  24294. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  24295. geometry.addAttribute( 'position', positions );
  24296. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  24297. //
  24298. this.matrixAutoUpdate = false;
  24299. this.update();
  24300. }
  24301. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  24302. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  24303. FaceNormalsHelper.prototype.update = ( function () {
  24304. var v1 = new Vector3();
  24305. var v2 = new Vector3();
  24306. var normalMatrix = new Matrix3();
  24307. return function update() {
  24308. this.object.updateMatrixWorld( true );
  24309. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24310. var matrixWorld = this.object.matrixWorld;
  24311. var position = this.geometry.attributes.position;
  24312. //
  24313. var objGeometry = this.object.geometry;
  24314. var vertices = objGeometry.vertices;
  24315. var faces = objGeometry.faces;
  24316. var idx = 0;
  24317. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24318. var face = faces[ i ];
  24319. var normal = face.normal;
  24320. v1.copy( vertices[ face.a ] )
  24321. .add( vertices[ face.b ] )
  24322. .add( vertices[ face.c ] )
  24323. .divideScalar( 3 )
  24324. .applyMatrix4( matrixWorld );
  24325. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24326. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24327. idx = idx + 1;
  24328. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24329. idx = idx + 1;
  24330. }
  24331. position.needsUpdate = true;
  24332. return this;
  24333. };
  24334. }() );
  24335. /**
  24336. * @author alteredq / http://alteredqualia.com/
  24337. * @author mrdoob / http://mrdoob.com/
  24338. * @author WestLangley / http://github.com/WestLangley
  24339. */
  24340. function DirectionalLightHelper( light, size ) {
  24341. Object3D.call( this );
  24342. this.light = light;
  24343. this.light.updateMatrixWorld();
  24344. this.matrix = light.matrixWorld;
  24345. this.matrixAutoUpdate = false;
  24346. if ( size === undefined ) size = 1;
  24347. var geometry = new BufferGeometry();
  24348. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  24349. - size, size, 0,
  24350. size, size, 0,
  24351. size, - size, 0,
  24352. - size, - size, 0,
  24353. - size, size, 0
  24354. ], 3 ) );
  24355. var material = new LineBasicMaterial( { fog: false } );
  24356. this.add( new Line( geometry, material ) );
  24357. geometry = new BufferGeometry();
  24358. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  24359. this.add( new Line( geometry, material ));
  24360. this.update();
  24361. }
  24362. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  24363. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  24364. DirectionalLightHelper.prototype.dispose = function () {
  24365. var lightPlane = this.children[ 0 ];
  24366. var targetLine = this.children[ 1 ];
  24367. lightPlane.geometry.dispose();
  24368. lightPlane.material.dispose();
  24369. targetLine.geometry.dispose();
  24370. targetLine.material.dispose();
  24371. };
  24372. DirectionalLightHelper.prototype.update = function () {
  24373. var v1 = new Vector3();
  24374. var v2 = new Vector3();
  24375. var v3 = new Vector3();
  24376. return function update() {
  24377. v1.setFromMatrixPosition( this.light.matrixWorld );
  24378. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24379. v3.subVectors( v2, v1 );
  24380. var lightPlane = this.children[ 0 ];
  24381. var targetLine = this.children[ 1 ];
  24382. lightPlane.lookAt( v3 );
  24383. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24384. targetLine.lookAt( v3 );
  24385. targetLine.scale.z = v3.length();
  24386. };
  24387. }();
  24388. /**
  24389. * @author alteredq / http://alteredqualia.com/
  24390. * @author Mugen87 / https://github.com/Mugen87
  24391. *
  24392. * - shows frustum, line of sight and up of the camera
  24393. * - suitable for fast updates
  24394. * - based on frustum visualization in lightgl.js shadowmap example
  24395. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24396. */
  24397. function CameraHelper( camera ) {
  24398. var geometry = new BufferGeometry();
  24399. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  24400. var vertices = [];
  24401. var colors = [];
  24402. var pointMap = {};
  24403. // colors
  24404. var colorFrustum = new Color( 0xffaa00 );
  24405. var colorCone = new Color( 0xff0000 );
  24406. var colorUp = new Color( 0x00aaff );
  24407. var colorTarget = new Color( 0xffffff );
  24408. var colorCross = new Color( 0x333333 );
  24409. // near
  24410. addLine( "n1", "n2", colorFrustum );
  24411. addLine( "n2", "n4", colorFrustum );
  24412. addLine( "n4", "n3", colorFrustum );
  24413. addLine( "n3", "n1", colorFrustum );
  24414. // far
  24415. addLine( "f1", "f2", colorFrustum );
  24416. addLine( "f2", "f4", colorFrustum );
  24417. addLine( "f4", "f3", colorFrustum );
  24418. addLine( "f3", "f1", colorFrustum );
  24419. // sides
  24420. addLine( "n1", "f1", colorFrustum );
  24421. addLine( "n2", "f2", colorFrustum );
  24422. addLine( "n3", "f3", colorFrustum );
  24423. addLine( "n4", "f4", colorFrustum );
  24424. // cone
  24425. addLine( "p", "n1", colorCone );
  24426. addLine( "p", "n2", colorCone );
  24427. addLine( "p", "n3", colorCone );
  24428. addLine( "p", "n4", colorCone );
  24429. // up
  24430. addLine( "u1", "u2", colorUp );
  24431. addLine( "u2", "u3", colorUp );
  24432. addLine( "u3", "u1", colorUp );
  24433. // target
  24434. addLine( "c", "t", colorTarget );
  24435. addLine( "p", "c", colorCross );
  24436. // cross
  24437. addLine( "cn1", "cn2", colorCross );
  24438. addLine( "cn3", "cn4", colorCross );
  24439. addLine( "cf1", "cf2", colorCross );
  24440. addLine( "cf3", "cf4", colorCross );
  24441. function addLine( a, b, color ) {
  24442. addPoint( a, color );
  24443. addPoint( b, color );
  24444. }
  24445. function addPoint( id, color ) {
  24446. vertices.push( 0, 0, 0 );
  24447. colors.push( color.r, color.g, color.b );
  24448. if ( pointMap[ id ] === undefined ) {
  24449. pointMap[ id ] = [];
  24450. }
  24451. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  24452. }
  24453. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24454. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24455. LineSegments.call( this, geometry, material );
  24456. this.camera = camera;
  24457. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  24458. this.matrix = camera.matrixWorld;
  24459. this.matrixAutoUpdate = false;
  24460. this.pointMap = pointMap;
  24461. this.update();
  24462. }
  24463. CameraHelper.prototype = Object.create( LineSegments.prototype );
  24464. CameraHelper.prototype.constructor = CameraHelper;
  24465. CameraHelper.prototype.update = function () {
  24466. var geometry, pointMap;
  24467. var vector = new Vector3();
  24468. var camera = new Camera();
  24469. function setPoint( point, x, y, z ) {
  24470. vector.set( x, y, z ).unproject( camera );
  24471. var points = pointMap[ point ];
  24472. if ( points !== undefined ) {
  24473. var position = geometry.getAttribute( 'position' );
  24474. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24475. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  24476. }
  24477. }
  24478. }
  24479. return function update() {
  24480. geometry = this.geometry;
  24481. pointMap = this.pointMap;
  24482. var w = 1, h = 1;
  24483. // we need just camera projection matrix
  24484. // world matrix must be identity
  24485. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24486. // center / target
  24487. setPoint( "c", 0, 0, - 1 );
  24488. setPoint( "t", 0, 0, 1 );
  24489. // near
  24490. setPoint( "n1", - w, - h, - 1 );
  24491. setPoint( "n2", w, - h, - 1 );
  24492. setPoint( "n3", - w, h, - 1 );
  24493. setPoint( "n4", w, h, - 1 );
  24494. // far
  24495. setPoint( "f1", - w, - h, 1 );
  24496. setPoint( "f2", w, - h, 1 );
  24497. setPoint( "f3", - w, h, 1 );
  24498. setPoint( "f4", w, h, 1 );
  24499. // up
  24500. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24501. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24502. setPoint( "u3", 0, h * 2, - 1 );
  24503. // cross
  24504. setPoint( "cf1", - w, 0, 1 );
  24505. setPoint( "cf2", w, 0, 1 );
  24506. setPoint( "cf3", 0, - h, 1 );
  24507. setPoint( "cf4", 0, h, 1 );
  24508. setPoint( "cn1", - w, 0, - 1 );
  24509. setPoint( "cn2", w, 0, - 1 );
  24510. setPoint( "cn3", 0, - h, - 1 );
  24511. setPoint( "cn4", 0, h, - 1 );
  24512. geometry.getAttribute( 'position' ).needsUpdate = true;
  24513. };
  24514. }();
  24515. /**
  24516. * @author mrdoob / http://mrdoob.com/
  24517. */
  24518. function BoxHelper( object, color ) {
  24519. if ( color === undefined ) color = 0xffff00;
  24520. 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 ] );
  24521. var positions = new Float32Array( 8 * 3 );
  24522. var geometry = new BufferGeometry();
  24523. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  24524. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  24525. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  24526. if ( object !== undefined ) {
  24527. this.update( object );
  24528. }
  24529. }
  24530. BoxHelper.prototype = Object.create( LineSegments.prototype );
  24531. BoxHelper.prototype.constructor = BoxHelper;
  24532. BoxHelper.prototype.update = ( function () {
  24533. var box = new Box3();
  24534. return function update( object ) {
  24535. if ( object && object.isBox3 ) {
  24536. box.copy( object );
  24537. } else {
  24538. box.setFromObject( object );
  24539. }
  24540. if ( box.isEmpty() ) return;
  24541. var min = box.min;
  24542. var max = box.max;
  24543. /*
  24544. 5____4
  24545. 1/___0/|
  24546. | 6__|_7
  24547. 2/___3/
  24548. 0: max.x, max.y, max.z
  24549. 1: min.x, max.y, max.z
  24550. 2: min.x, min.y, max.z
  24551. 3: max.x, min.y, max.z
  24552. 4: max.x, max.y, min.z
  24553. 5: min.x, max.y, min.z
  24554. 6: min.x, min.y, min.z
  24555. 7: max.x, min.y, min.z
  24556. */
  24557. var position = this.geometry.attributes.position;
  24558. var array = position.array;
  24559. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24560. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24561. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24562. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24563. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24564. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24565. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24566. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24567. position.needsUpdate = true;
  24568. this.geometry.computeBoundingSphere();
  24569. };
  24570. } )();
  24571. /**
  24572. * @author WestLangley / http://github.com/WestLangley
  24573. * @author zz85 / http://github.com/zz85
  24574. * @author bhouston / http://clara.io
  24575. *
  24576. * Creates an arrow for visualizing directions
  24577. *
  24578. * Parameters:
  24579. * dir - Vector3
  24580. * origin - Vector3
  24581. * length - Number
  24582. * color - color in hex value
  24583. * headLength - Number
  24584. * headWidth - Number
  24585. */
  24586. var lineGeometry = new BufferGeometry();
  24587. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  24588. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  24589. coneGeometry.translate( 0, - 0.5, 0 );
  24590. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24591. // dir is assumed to be normalized
  24592. Object3D.call( this );
  24593. if ( color === undefined ) color = 0xffff00;
  24594. if ( length === undefined ) length = 1;
  24595. if ( headLength === undefined ) headLength = 0.2 * length;
  24596. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24597. this.position.copy( origin );
  24598. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  24599. this.line.matrixAutoUpdate = false;
  24600. this.add( this.line );
  24601. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  24602. this.cone.matrixAutoUpdate = false;
  24603. this.add( this.cone );
  24604. this.setDirection( dir );
  24605. this.setLength( length, headLength, headWidth );
  24606. }
  24607. ArrowHelper.prototype = Object.create( Object3D.prototype );
  24608. ArrowHelper.prototype.constructor = ArrowHelper;
  24609. ArrowHelper.prototype.setDirection = ( function () {
  24610. var axis = new Vector3();
  24611. var radians;
  24612. return function setDirection( dir ) {
  24613. // dir is assumed to be normalized
  24614. if ( dir.y > 0.99999 ) {
  24615. this.quaternion.set( 0, 0, 0, 1 );
  24616. } else if ( dir.y < - 0.99999 ) {
  24617. this.quaternion.set( 1, 0, 0, 0 );
  24618. } else {
  24619. axis.set( dir.z, 0, - dir.x ).normalize();
  24620. radians = Math.acos( dir.y );
  24621. this.quaternion.setFromAxisAngle( axis, radians );
  24622. }
  24623. };
  24624. }() );
  24625. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24626. if ( headLength === undefined ) headLength = 0.2 * length;
  24627. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24628. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24629. this.line.updateMatrix();
  24630. this.cone.scale.set( headWidth, headLength, headWidth );
  24631. this.cone.position.y = length;
  24632. this.cone.updateMatrix();
  24633. };
  24634. ArrowHelper.prototype.setColor = function ( color ) {
  24635. this.line.material.color.copy( color );
  24636. this.cone.material.color.copy( color );
  24637. };
  24638. /**
  24639. * @author sroucheray / http://sroucheray.org/
  24640. * @author mrdoob / http://mrdoob.com/
  24641. */
  24642. function AxisHelper( size ) {
  24643. size = size || 1;
  24644. var vertices = [
  24645. 0, 0, 0, size, 0, 0,
  24646. 0, 0, 0, 0, size, 0,
  24647. 0, 0, 0, 0, 0, size
  24648. ];
  24649. var colors = [
  24650. 1, 0, 0, 1, 0.6, 0,
  24651. 0, 1, 0, 0.6, 1, 0,
  24652. 0, 0, 1, 0, 0.6, 1
  24653. ];
  24654. var geometry = new BufferGeometry();
  24655. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24656. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  24657. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  24658. LineSegments.call( this, geometry, material );
  24659. }
  24660. AxisHelper.prototype = Object.create( LineSegments.prototype );
  24661. AxisHelper.prototype.constructor = AxisHelper;
  24662. /**
  24663. * @author zz85 https://github.com/zz85
  24664. *
  24665. * Centripetal CatmullRom Curve - which is useful for avoiding
  24666. * cusps and self-intersections in non-uniform catmull rom curves.
  24667. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24668. *
  24669. * curve.type accepts centripetal(default), chordal and catmullrom
  24670. * curve.tension is used for catmullrom which defaults to 0.5
  24671. */
  24672. /*
  24673. Based on an optimized c++ solution in
  24674. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24675. - http://ideone.com/NoEbVM
  24676. This CubicPoly class could be used for reusing some variables and calculations,
  24677. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24678. which can be placed in CurveUtils.
  24679. */
  24680. function CubicPoly() {
  24681. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24682. /*
  24683. * Compute coefficients for a cubic polynomial
  24684. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24685. * such that
  24686. * p(0) = x0, p(1) = x1
  24687. * and
  24688. * p'(0) = t0, p'(1) = t1.
  24689. */
  24690. function init( x0, x1, t0, t1 ) {
  24691. c0 = x0;
  24692. c1 = t0;
  24693. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24694. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24695. }
  24696. return {
  24697. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24698. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24699. },
  24700. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24701. // compute tangents when parameterized in [t1,t2]
  24702. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24703. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24704. // rescale tangents for parametrization in [0,1]
  24705. t1 *= dt1;
  24706. t2 *= dt1;
  24707. init( x1, x2, t1, t2 );
  24708. },
  24709. calc: function ( t ) {
  24710. var t2 = t * t;
  24711. var t3 = t2 * t;
  24712. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24713. }
  24714. };
  24715. }
  24716. //
  24717. var tmp = new Vector3();
  24718. var px = new CubicPoly();
  24719. var py = new CubicPoly();
  24720. var pz = new CubicPoly();
  24721. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  24722. this.points = p || [];
  24723. this.closed = false;
  24724. }
  24725. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  24726. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  24727. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  24728. var points = this.points;
  24729. var l = points.length;
  24730. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24731. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24732. var intPoint = Math.floor( point );
  24733. var weight = point - intPoint;
  24734. if ( this.closed ) {
  24735. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24736. } else if ( weight === 0 && intPoint === l - 1 ) {
  24737. intPoint = l - 2;
  24738. weight = 1;
  24739. }
  24740. var p0, p1, p2, p3; // 4 points
  24741. if ( this.closed || intPoint > 0 ) {
  24742. p0 = points[ ( intPoint - 1 ) % l ];
  24743. } else {
  24744. // extrapolate first point
  24745. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24746. p0 = tmp;
  24747. }
  24748. p1 = points[ intPoint % l ];
  24749. p2 = points[ ( intPoint + 1 ) % l ];
  24750. if ( this.closed || intPoint + 2 < l ) {
  24751. p3 = points[ ( intPoint + 2 ) % l ];
  24752. } else {
  24753. // extrapolate last point
  24754. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24755. p3 = tmp;
  24756. }
  24757. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24758. // init Centripetal / Chordal Catmull-Rom
  24759. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24760. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24761. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24762. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24763. // safety check for repeated points
  24764. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24765. if ( dt0 < 1e-4 ) dt0 = dt1;
  24766. if ( dt2 < 1e-4 ) dt2 = dt1;
  24767. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24768. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24769. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24770. } else if ( this.type === 'catmullrom' ) {
  24771. var tension = this.tension !== undefined ? this.tension : 0.5;
  24772. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24773. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24774. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24775. }
  24776. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  24777. };
  24778. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  24779. this.v0 = v0;
  24780. this.v1 = v1;
  24781. this.v2 = v2;
  24782. this.v3 = v3;
  24783. }
  24784. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  24785. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  24786. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  24787. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24788. return new Vector3(
  24789. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24790. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24791. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24792. );
  24793. };
  24794. function QuadraticBezierCurve3( v0, v1, v2 ) {
  24795. this.v0 = v0;
  24796. this.v1 = v1;
  24797. this.v2 = v2;
  24798. }
  24799. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  24800. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  24801. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  24802. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24803. return new Vector3(
  24804. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24805. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24806. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24807. );
  24808. };
  24809. function LineCurve3( v1, v2 ) {
  24810. this.v1 = v1;
  24811. this.v2 = v2;
  24812. }
  24813. LineCurve3.prototype = Object.create( Curve.prototype );
  24814. LineCurve3.prototype.constructor = LineCurve3;
  24815. LineCurve3.prototype.getPoint = function ( t ) {
  24816. if ( t === 1 ) {
  24817. return this.v2.clone();
  24818. }
  24819. var vector = new Vector3();
  24820. vector.subVectors( this.v2, this.v1 ); // diff
  24821. vector.multiplyScalar( t );
  24822. vector.add( this.v1 );
  24823. return vector;
  24824. };
  24825. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24826. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24827. }
  24828. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24829. ArcCurve.prototype.constructor = ArcCurve;
  24830. /**
  24831. * @author alteredq / http://alteredqualia.com/
  24832. */
  24833. var SceneUtils = {
  24834. createMultiMaterialObject: function ( geometry, materials ) {
  24835. var group = new Group();
  24836. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24837. group.add( new Mesh( geometry, materials[ i ] ) );
  24838. }
  24839. return group;
  24840. },
  24841. detach: function ( child, parent, scene ) {
  24842. child.applyMatrix( parent.matrixWorld );
  24843. parent.remove( child );
  24844. scene.add( child );
  24845. },
  24846. attach: function ( child, scene, parent ) {
  24847. var matrixWorldInverse = new Matrix4();
  24848. matrixWorldInverse.getInverse( parent.matrixWorld );
  24849. child.applyMatrix( matrixWorldInverse );
  24850. scene.remove( child );
  24851. parent.add( child );
  24852. }
  24853. };
  24854. /**
  24855. * @author mrdoob / http://mrdoob.com/
  24856. */
  24857. function Face4( a, b, c, d, normal, color, materialIndex ) {
  24858. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  24859. return new Face3( a, b, c, normal, color, materialIndex );
  24860. }
  24861. var LineStrip = 0;
  24862. var LinePieces = 1;
  24863. function MeshFaceMaterial( materials ) {
  24864. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  24865. return new MultiMaterial( materials );
  24866. }
  24867. function PointCloud( geometry, material ) {
  24868. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  24869. return new Points( geometry, material );
  24870. }
  24871. function Particle( material ) {
  24872. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  24873. return new Sprite( material );
  24874. }
  24875. function ParticleSystem( geometry, material ) {
  24876. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  24877. return new Points( geometry, material );
  24878. }
  24879. function PointCloudMaterial( parameters ) {
  24880. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  24881. return new PointsMaterial( parameters );
  24882. }
  24883. function ParticleBasicMaterial( parameters ) {
  24884. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  24885. return new PointsMaterial( parameters );
  24886. }
  24887. function ParticleSystemMaterial( parameters ) {
  24888. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  24889. return new PointsMaterial( parameters );
  24890. }
  24891. function Vertex( x, y, z ) {
  24892. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  24893. return new Vector3( x, y, z );
  24894. }
  24895. //
  24896. function DynamicBufferAttribute( array, itemSize ) {
  24897. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  24898. return new BufferAttribute( array, itemSize ).setDynamic( true );
  24899. }
  24900. function Int8Attribute( array, itemSize ) {
  24901. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  24902. return new Int8BufferAttribute( array, itemSize );
  24903. }
  24904. function Uint8Attribute( array, itemSize ) {
  24905. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  24906. return new Uint8BufferAttribute( array, itemSize );
  24907. }
  24908. function Uint8ClampedAttribute( array, itemSize ) {
  24909. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  24910. return new Uint8ClampedBufferAttribute( array, itemSize );
  24911. }
  24912. function Int16Attribute( array, itemSize ) {
  24913. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  24914. return new Int16BufferAttribute( array, itemSize );
  24915. }
  24916. function Uint16Attribute( array, itemSize ) {
  24917. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  24918. return new Uint16BufferAttribute( array, itemSize );
  24919. }
  24920. function Int32Attribute( array, itemSize ) {
  24921. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  24922. return new Int32BufferAttribute( array, itemSize );
  24923. }
  24924. function Uint32Attribute( array, itemSize ) {
  24925. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  24926. return new Uint32BufferAttribute( array, itemSize );
  24927. }
  24928. function Float32Attribute( array, itemSize ) {
  24929. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  24930. return new Float32BufferAttribute( array, itemSize );
  24931. }
  24932. function Float64Attribute( array, itemSize ) {
  24933. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  24934. return new Float64BufferAttribute( array, itemSize );
  24935. }
  24936. //
  24937. Curve.create = function ( construct, getPoint ) {
  24938. console.log( 'THREE.Curve.create() has been deprecated' );
  24939. construct.prototype = Object.create( Curve.prototype );
  24940. construct.prototype.constructor = construct;
  24941. construct.prototype.getPoint = getPoint;
  24942. return construct;
  24943. };
  24944. //
  24945. function ClosedSplineCurve3( points ) {
  24946. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  24947. CatmullRomCurve3.call( this, points );
  24948. this.type = 'catmullrom';
  24949. this.closed = true;
  24950. }
  24951. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  24952. //
  24953. function SplineCurve3( points ) {
  24954. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  24955. CatmullRomCurve3.call( this, points );
  24956. this.type = 'catmullrom';
  24957. }
  24958. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  24959. //
  24960. function Spline( points ) {
  24961. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  24962. CatmullRomCurve3.call( this, points );
  24963. this.type = 'catmullrom';
  24964. }
  24965. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  24966. Object.assign( Spline.prototype, {
  24967. initFromArray: function ( a ) {
  24968. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  24969. },
  24970. getControlPointsArray: function ( optionalTarget ) {
  24971. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  24972. },
  24973. reparametrizeByArcLength: function ( samplingCoef ) {
  24974. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  24975. }
  24976. } );
  24977. //
  24978. function BoundingBoxHelper( object, color ) {
  24979. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  24980. return new BoxHelper( object, color );
  24981. }
  24982. function EdgesHelper( object, hex ) {
  24983. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  24984. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  24985. }
  24986. GridHelper.prototype.setColors = function () {
  24987. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  24988. };
  24989. function WireframeHelper( object, hex ) {
  24990. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  24991. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  24992. }
  24993. //
  24994. function XHRLoader( manager ) {
  24995. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  24996. return new FileLoader( manager );
  24997. }
  24998. function BinaryTextureLoader( manager ) {
  24999. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  25000. return new DataTextureLoader( manager );
  25001. }
  25002. //
  25003. Object.assign( Box2.prototype, {
  25004. center: function ( optionalTarget ) {
  25005. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  25006. return this.getCenter( optionalTarget );
  25007. },
  25008. empty: function () {
  25009. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  25010. return this.isEmpty();
  25011. },
  25012. isIntersectionBox: function ( box ) {
  25013. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25014. return this.intersectsBox( box );
  25015. },
  25016. size: function ( optionalTarget ) {
  25017. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  25018. return this.getSize( optionalTarget );
  25019. }
  25020. } );
  25021. Object.assign( Box3.prototype, {
  25022. center: function ( optionalTarget ) {
  25023. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  25024. return this.getCenter( optionalTarget );
  25025. },
  25026. empty: function () {
  25027. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  25028. return this.isEmpty();
  25029. },
  25030. isIntersectionBox: function ( box ) {
  25031. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25032. return this.intersectsBox( box );
  25033. },
  25034. isIntersectionSphere: function ( sphere ) {
  25035. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25036. return this.intersectsSphere( sphere );
  25037. },
  25038. size: function ( optionalTarget ) {
  25039. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  25040. return this.getSize( optionalTarget );
  25041. }
  25042. } );
  25043. Line3.prototype.center = function ( optionalTarget ) {
  25044. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  25045. return this.getCenter( optionalTarget );
  25046. };
  25047. _Math.random16 = function () {
  25048. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  25049. return Math.random();
  25050. };
  25051. Object.assign( Matrix3.prototype, {
  25052. flattenToArrayOffset: function ( array, offset ) {
  25053. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25054. return this.toArray( array, offset );
  25055. },
  25056. multiplyVector3: function ( vector ) {
  25057. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  25058. return vector.applyMatrix3( this );
  25059. },
  25060. multiplyVector3Array: function ( a ) {
  25061. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25062. return this.applyToVector3Array( a );
  25063. },
  25064. applyToBuffer: function( buffer, offset, length ) {
  25065. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25066. return this.applyToBufferAttribute( buffer );
  25067. },
  25068. applyToVector3Array: function( array, offset, length ) {
  25069. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  25070. }
  25071. } );
  25072. Object.assign( Matrix4.prototype, {
  25073. extractPosition: function ( m ) {
  25074. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  25075. return this.copyPosition( m );
  25076. },
  25077. flattenToArrayOffset: function ( array, offset ) {
  25078. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  25079. return this.toArray( array, offset );
  25080. },
  25081. getPosition: function () {
  25082. var v1;
  25083. return function getPosition() {
  25084. if ( v1 === undefined ) v1 = new Vector3();
  25085. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  25086. return v1.setFromMatrixColumn( this, 3 );
  25087. };
  25088. }(),
  25089. setRotationFromQuaternion: function ( q ) {
  25090. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  25091. return this.makeRotationFromQuaternion( q );
  25092. },
  25093. multiplyVector3: function ( vector ) {
  25094. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25095. return vector.applyMatrix4( this );
  25096. },
  25097. multiplyVector4: function ( vector ) {
  25098. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25099. return vector.applyMatrix4( this );
  25100. },
  25101. multiplyVector3Array: function ( a ) {
  25102. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  25103. return this.applyToVector3Array( a );
  25104. },
  25105. rotateAxis: function ( v ) {
  25106. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  25107. v.transformDirection( this );
  25108. },
  25109. crossVector: function ( vector ) {
  25110. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  25111. return vector.applyMatrix4( this );
  25112. },
  25113. translate: function () {
  25114. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  25115. },
  25116. rotateX: function () {
  25117. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  25118. },
  25119. rotateY: function () {
  25120. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  25121. },
  25122. rotateZ: function () {
  25123. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  25124. },
  25125. rotateByAxis: function () {
  25126. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  25127. },
  25128. applyToBuffer: function( buffer, offset, length ) {
  25129. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  25130. return this.applyToBufferAttribute( buffer );
  25131. },
  25132. applyToVector3Array: function( array, offset, length ) {
  25133. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  25134. },
  25135. makeFrustum: function( left, right, bottom, top, near, far ) {
  25136. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  25137. return this.makePerspective( left, right, top, bottom, near, far );
  25138. }
  25139. } );
  25140. Plane.prototype.isIntersectionLine = function ( line ) {
  25141. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  25142. return this.intersectsLine( line );
  25143. };
  25144. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  25145. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  25146. return vector.applyQuaternion( this );
  25147. };
  25148. Object.assign( Ray.prototype, {
  25149. isIntersectionBox: function ( box ) {
  25150. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  25151. return this.intersectsBox( box );
  25152. },
  25153. isIntersectionPlane: function ( plane ) {
  25154. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  25155. return this.intersectsPlane( plane );
  25156. },
  25157. isIntersectionSphere: function ( sphere ) {
  25158. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  25159. return this.intersectsSphere( sphere );
  25160. }
  25161. } );
  25162. Object.assign( Shape.prototype, {
  25163. extrude: function ( options ) {
  25164. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  25165. return new ExtrudeGeometry( this, options );
  25166. },
  25167. makeGeometry: function ( options ) {
  25168. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  25169. return new ShapeGeometry( this, options );
  25170. }
  25171. } );
  25172. Object.assign( Vector2.prototype, {
  25173. fromAttribute: function ( attribute, index, offset ) {
  25174. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25175. return this.fromBufferAttribute( attribute, index, offset );
  25176. }
  25177. } );
  25178. Object.assign( Vector3.prototype, {
  25179. setEulerFromRotationMatrix: function () {
  25180. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  25181. },
  25182. setEulerFromQuaternion: function () {
  25183. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  25184. },
  25185. getPositionFromMatrix: function ( m ) {
  25186. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  25187. return this.setFromMatrixPosition( m );
  25188. },
  25189. getScaleFromMatrix: function ( m ) {
  25190. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  25191. return this.setFromMatrixScale( m );
  25192. },
  25193. getColumnFromMatrix: function ( index, matrix ) {
  25194. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  25195. return this.setFromMatrixColumn( matrix, index );
  25196. },
  25197. applyProjection: function ( m ) {
  25198. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  25199. return this.applyMatrix4( m );
  25200. },
  25201. fromAttribute: function ( attribute, index, offset ) {
  25202. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25203. return this.fromBufferAttribute( attribute, index, offset );
  25204. }
  25205. } );
  25206. Object.assign( Vector4.prototype, {
  25207. fromAttribute: function ( attribute, index, offset ) {
  25208. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  25209. return this.fromBufferAttribute( attribute, index, offset );
  25210. }
  25211. } );
  25212. //
  25213. Geometry.prototype.computeTangents = function () {
  25214. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  25215. };
  25216. Object.assign( Object3D.prototype, {
  25217. getChildByName: function ( name ) {
  25218. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  25219. return this.getObjectByName( name );
  25220. },
  25221. renderDepth: function () {
  25222. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  25223. },
  25224. translate: function ( distance, axis ) {
  25225. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  25226. return this.translateOnAxis( axis, distance );
  25227. }
  25228. } );
  25229. Object.defineProperties( Object3D.prototype, {
  25230. eulerOrder: {
  25231. get: function () {
  25232. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25233. return this.rotation.order;
  25234. },
  25235. set: function ( value ) {
  25236. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  25237. this.rotation.order = value;
  25238. }
  25239. },
  25240. useQuaternion: {
  25241. get: function () {
  25242. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25243. },
  25244. set: function () {
  25245. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  25246. }
  25247. }
  25248. } );
  25249. Object.defineProperties( LOD.prototype, {
  25250. objects: {
  25251. get: function () {
  25252. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  25253. return this.levels;
  25254. }
  25255. }
  25256. } );
  25257. //
  25258. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  25259. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  25260. "Use .setFocalLength and .filmGauge for a photographic setup." );
  25261. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  25262. this.setFocalLength( focalLength );
  25263. };
  25264. //
  25265. Object.defineProperties( Light.prototype, {
  25266. onlyShadow: {
  25267. set: function () {
  25268. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  25269. }
  25270. },
  25271. shadowCameraFov: {
  25272. set: function ( value ) {
  25273. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  25274. this.shadow.camera.fov = value;
  25275. }
  25276. },
  25277. shadowCameraLeft: {
  25278. set: function ( value ) {
  25279. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  25280. this.shadow.camera.left = value;
  25281. }
  25282. },
  25283. shadowCameraRight: {
  25284. set: function ( value ) {
  25285. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  25286. this.shadow.camera.right = value;
  25287. }
  25288. },
  25289. shadowCameraTop: {
  25290. set: function ( value ) {
  25291. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  25292. this.shadow.camera.top = value;
  25293. }
  25294. },
  25295. shadowCameraBottom: {
  25296. set: function ( value ) {
  25297. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  25298. this.shadow.camera.bottom = value;
  25299. }
  25300. },
  25301. shadowCameraNear: {
  25302. set: function ( value ) {
  25303. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  25304. this.shadow.camera.near = value;
  25305. }
  25306. },
  25307. shadowCameraFar: {
  25308. set: function ( value ) {
  25309. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  25310. this.shadow.camera.far = value;
  25311. }
  25312. },
  25313. shadowCameraVisible: {
  25314. set: function () {
  25315. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  25316. }
  25317. },
  25318. shadowBias: {
  25319. set: function ( value ) {
  25320. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  25321. this.shadow.bias = value;
  25322. }
  25323. },
  25324. shadowDarkness: {
  25325. set: function () {
  25326. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  25327. }
  25328. },
  25329. shadowMapWidth: {
  25330. set: function ( value ) {
  25331. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  25332. this.shadow.mapSize.width = value;
  25333. }
  25334. },
  25335. shadowMapHeight: {
  25336. set: function ( value ) {
  25337. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  25338. this.shadow.mapSize.height = value;
  25339. }
  25340. }
  25341. } );
  25342. //
  25343. Object.defineProperties( BufferAttribute.prototype, {
  25344. length: {
  25345. get: function () {
  25346. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  25347. return this.array.length;
  25348. }
  25349. }
  25350. } );
  25351. Object.assign( BufferGeometry.prototype, {
  25352. addIndex: function ( index ) {
  25353. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  25354. this.setIndex( index );
  25355. },
  25356. addDrawCall: function ( start, count, indexOffset ) {
  25357. if ( indexOffset !== undefined ) {
  25358. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  25359. }
  25360. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  25361. this.addGroup( start, count );
  25362. },
  25363. clearDrawCalls: function () {
  25364. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  25365. this.clearGroups();
  25366. },
  25367. computeTangents: function () {
  25368. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  25369. },
  25370. computeOffsets: function () {
  25371. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  25372. }
  25373. } );
  25374. Object.defineProperties( BufferGeometry.prototype, {
  25375. drawcalls: {
  25376. get: function () {
  25377. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  25378. return this.groups;
  25379. }
  25380. },
  25381. offsets: {
  25382. get: function () {
  25383. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  25384. return this.groups;
  25385. }
  25386. }
  25387. } );
  25388. //
  25389. Object.defineProperties( Uniform.prototype, {
  25390. dynamic: {
  25391. set: function () {
  25392. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  25393. }
  25394. },
  25395. onUpdate: {
  25396. value: function () {
  25397. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  25398. return this;
  25399. }
  25400. }
  25401. } );
  25402. //
  25403. Object.defineProperties( Material.prototype, {
  25404. wrapAround: {
  25405. get: function () {
  25406. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25407. },
  25408. set: function () {
  25409. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  25410. }
  25411. },
  25412. wrapRGB: {
  25413. get: function () {
  25414. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  25415. return new Color();
  25416. }
  25417. }
  25418. } );
  25419. Object.defineProperties( MeshPhongMaterial.prototype, {
  25420. metal: {
  25421. get: function () {
  25422. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  25423. return false;
  25424. },
  25425. set: function () {
  25426. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  25427. }
  25428. }
  25429. } );
  25430. Object.defineProperties( ShaderMaterial.prototype, {
  25431. derivatives: {
  25432. get: function () {
  25433. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25434. return this.extensions.derivatives;
  25435. },
  25436. set: function ( value ) {
  25437. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  25438. this.extensions.derivatives = value;
  25439. }
  25440. }
  25441. } );
  25442. //
  25443. Object.assign( WebGLRenderer.prototype, {
  25444. supportsFloatTextures: function () {
  25445. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  25446. return this.extensions.get( 'OES_texture_float' );
  25447. },
  25448. supportsHalfFloatTextures: function () {
  25449. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  25450. return this.extensions.get( 'OES_texture_half_float' );
  25451. },
  25452. supportsStandardDerivatives: function () {
  25453. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  25454. return this.extensions.get( 'OES_standard_derivatives' );
  25455. },
  25456. supportsCompressedTextureS3TC: function () {
  25457. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  25458. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25459. },
  25460. supportsCompressedTexturePVRTC: function () {
  25461. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  25462. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25463. },
  25464. supportsBlendMinMax: function () {
  25465. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25466. return this.extensions.get( 'EXT_blend_minmax' );
  25467. },
  25468. supportsVertexTextures: function () {
  25469. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  25470. return this.capabilities.vertexTextures;
  25471. },
  25472. supportsInstancedArrays: function () {
  25473. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25474. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25475. },
  25476. enableScissorTest: function ( boolean ) {
  25477. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25478. this.setScissorTest( boolean );
  25479. },
  25480. initMaterial: function () {
  25481. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25482. },
  25483. addPrePlugin: function () {
  25484. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25485. },
  25486. addPostPlugin: function () {
  25487. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25488. },
  25489. updateShadowMap: function () {
  25490. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25491. }
  25492. } );
  25493. Object.defineProperties( WebGLRenderer.prototype, {
  25494. shadowMapEnabled: {
  25495. get: function () {
  25496. return this.shadowMap.enabled;
  25497. },
  25498. set: function ( value ) {
  25499. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25500. this.shadowMap.enabled = value;
  25501. }
  25502. },
  25503. shadowMapType: {
  25504. get: function () {
  25505. return this.shadowMap.type;
  25506. },
  25507. set: function ( value ) {
  25508. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25509. this.shadowMap.type = value;
  25510. }
  25511. },
  25512. shadowMapCullFace: {
  25513. get: function () {
  25514. return this.shadowMap.cullFace;
  25515. },
  25516. set: function ( value ) {
  25517. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25518. this.shadowMap.cullFace = value;
  25519. }
  25520. }
  25521. } );
  25522. Object.defineProperties( WebGLShadowMap.prototype, {
  25523. cullFace: {
  25524. get: function () {
  25525. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  25526. },
  25527. set: function ( cullFace ) {
  25528. var value = ( cullFace !== CullFaceBack );
  25529. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25530. this.renderReverseSided = value;
  25531. }
  25532. }
  25533. } );
  25534. //
  25535. Object.defineProperties( WebGLRenderTarget.prototype, {
  25536. wrapS: {
  25537. get: function () {
  25538. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25539. return this.texture.wrapS;
  25540. },
  25541. set: function ( value ) {
  25542. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25543. this.texture.wrapS = value;
  25544. }
  25545. },
  25546. wrapT: {
  25547. get: function () {
  25548. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25549. return this.texture.wrapT;
  25550. },
  25551. set: function ( value ) {
  25552. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25553. this.texture.wrapT = value;
  25554. }
  25555. },
  25556. magFilter: {
  25557. get: function () {
  25558. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25559. return this.texture.magFilter;
  25560. },
  25561. set: function ( value ) {
  25562. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25563. this.texture.magFilter = value;
  25564. }
  25565. },
  25566. minFilter: {
  25567. get: function () {
  25568. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25569. return this.texture.minFilter;
  25570. },
  25571. set: function ( value ) {
  25572. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25573. this.texture.minFilter = value;
  25574. }
  25575. },
  25576. anisotropy: {
  25577. get: function () {
  25578. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25579. return this.texture.anisotropy;
  25580. },
  25581. set: function ( value ) {
  25582. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25583. this.texture.anisotropy = value;
  25584. }
  25585. },
  25586. offset: {
  25587. get: function () {
  25588. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25589. return this.texture.offset;
  25590. },
  25591. set: function ( value ) {
  25592. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25593. this.texture.offset = value;
  25594. }
  25595. },
  25596. repeat: {
  25597. get: function () {
  25598. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25599. return this.texture.repeat;
  25600. },
  25601. set: function ( value ) {
  25602. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25603. this.texture.repeat = value;
  25604. }
  25605. },
  25606. format: {
  25607. get: function () {
  25608. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25609. return this.texture.format;
  25610. },
  25611. set: function ( value ) {
  25612. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25613. this.texture.format = value;
  25614. }
  25615. },
  25616. type: {
  25617. get: function () {
  25618. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25619. return this.texture.type;
  25620. },
  25621. set: function ( value ) {
  25622. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25623. this.texture.type = value;
  25624. }
  25625. },
  25626. generateMipmaps: {
  25627. get: function () {
  25628. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25629. return this.texture.generateMipmaps;
  25630. },
  25631. set: function ( value ) {
  25632. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25633. this.texture.generateMipmaps = value;
  25634. }
  25635. }
  25636. } );
  25637. //
  25638. Audio.prototype.load = function ( file ) {
  25639. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  25640. var scope = this;
  25641. var audioLoader = new AudioLoader();
  25642. audioLoader.load( file, function ( buffer ) {
  25643. scope.setBuffer( buffer );
  25644. } );
  25645. return this;
  25646. };
  25647. AudioAnalyser.prototype.getData = function () {
  25648. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25649. return this.getFrequencyData();
  25650. };
  25651. //
  25652. var GeometryUtils = {
  25653. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25654. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25655. var matrix;
  25656. if ( geometry2.isMesh ) {
  25657. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25658. matrix = geometry2.matrix;
  25659. geometry2 = geometry2.geometry;
  25660. }
  25661. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25662. },
  25663. center: function ( geometry ) {
  25664. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25665. return geometry.center();
  25666. }
  25667. };
  25668. var ImageUtils = {
  25669. crossOrigin: undefined,
  25670. loadTexture: function ( url, mapping, onLoad, onError ) {
  25671. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25672. var loader = new TextureLoader();
  25673. loader.setCrossOrigin( this.crossOrigin );
  25674. var texture = loader.load( url, onLoad, undefined, onError );
  25675. if ( mapping ) texture.mapping = mapping;
  25676. return texture;
  25677. },
  25678. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25679. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25680. var loader = new CubeTextureLoader();
  25681. loader.setCrossOrigin( this.crossOrigin );
  25682. var texture = loader.load( urls, onLoad, undefined, onError );
  25683. if ( mapping ) texture.mapping = mapping;
  25684. return texture;
  25685. },
  25686. loadCompressedTexture: function () {
  25687. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25688. },
  25689. loadCompressedTextureCube: function () {
  25690. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25691. }
  25692. };
  25693. //
  25694. function Projector() {
  25695. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25696. this.projectVector = function ( vector, camera ) {
  25697. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25698. vector.project( camera );
  25699. };
  25700. this.unprojectVector = function ( vector, camera ) {
  25701. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25702. vector.unproject( camera );
  25703. };
  25704. this.pickingRay = function () {
  25705. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25706. };
  25707. }
  25708. //
  25709. function CanvasRenderer() {
  25710. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25711. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25712. this.clear = function () {};
  25713. this.render = function () {};
  25714. this.setClearColor = function () {};
  25715. this.setSize = function () {};
  25716. }
  25717. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  25718. exports.WebGLRenderTarget = WebGLRenderTarget;
  25719. exports.WebGLRenderer = WebGLRenderer;
  25720. exports.ShaderLib = ShaderLib;
  25721. exports.UniformsLib = UniformsLib;
  25722. exports.UniformsUtils = UniformsUtils;
  25723. exports.ShaderChunk = ShaderChunk;
  25724. exports.FogExp2 = FogExp2;
  25725. exports.Fog = Fog;
  25726. exports.Scene = Scene;
  25727. exports.LensFlare = LensFlare;
  25728. exports.Sprite = Sprite;
  25729. exports.LOD = LOD;
  25730. exports.SkinnedMesh = SkinnedMesh;
  25731. exports.Skeleton = Skeleton;
  25732. exports.Bone = Bone;
  25733. exports.Mesh = Mesh;
  25734. exports.LineSegments = LineSegments;
  25735. exports.Line = Line;
  25736. exports.Points = Points;
  25737. exports.Group = Group;
  25738. exports.VideoTexture = VideoTexture;
  25739. exports.DataTexture = DataTexture;
  25740. exports.CompressedTexture = CompressedTexture;
  25741. exports.CubeTexture = CubeTexture;
  25742. exports.CanvasTexture = CanvasTexture;
  25743. exports.DepthTexture = DepthTexture;
  25744. exports.Texture = Texture;
  25745. exports.CompressedTextureLoader = CompressedTextureLoader;
  25746. exports.DataTextureLoader = DataTextureLoader;
  25747. exports.CubeTextureLoader = CubeTextureLoader;
  25748. exports.TextureLoader = TextureLoader;
  25749. exports.ObjectLoader = ObjectLoader;
  25750. exports.MaterialLoader = MaterialLoader;
  25751. exports.BufferGeometryLoader = BufferGeometryLoader;
  25752. exports.DefaultLoadingManager = DefaultLoadingManager;
  25753. exports.LoadingManager = LoadingManager;
  25754. exports.JSONLoader = JSONLoader;
  25755. exports.ImageLoader = ImageLoader;
  25756. exports.FontLoader = FontLoader;
  25757. exports.FileLoader = FileLoader;
  25758. exports.Loader = Loader;
  25759. exports.Cache = Cache;
  25760. exports.AudioLoader = AudioLoader;
  25761. exports.SpotLightShadow = SpotLightShadow;
  25762. exports.SpotLight = SpotLight;
  25763. exports.PointLight = PointLight;
  25764. exports.RectAreaLight = RectAreaLight;
  25765. exports.HemisphereLight = HemisphereLight;
  25766. exports.DirectionalLightShadow = DirectionalLightShadow;
  25767. exports.DirectionalLight = DirectionalLight;
  25768. exports.AmbientLight = AmbientLight;
  25769. exports.LightShadow = LightShadow;
  25770. exports.Light = Light;
  25771. exports.StereoCamera = StereoCamera;
  25772. exports.PerspectiveCamera = PerspectiveCamera;
  25773. exports.OrthographicCamera = OrthographicCamera;
  25774. exports.CubeCamera = CubeCamera;
  25775. exports.Camera = Camera;
  25776. exports.AudioListener = AudioListener;
  25777. exports.PositionalAudio = PositionalAudio;
  25778. exports.AudioContext = AudioContext;
  25779. exports.AudioAnalyser = AudioAnalyser;
  25780. exports.Audio = Audio;
  25781. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  25782. exports.StringKeyframeTrack = StringKeyframeTrack;
  25783. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  25784. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  25785. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  25786. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  25787. exports.PropertyMixer = PropertyMixer;
  25788. exports.PropertyBinding = PropertyBinding;
  25789. exports.KeyframeTrack = KeyframeTrack;
  25790. exports.AnimationUtils = AnimationUtils;
  25791. exports.AnimationObjectGroup = AnimationObjectGroup;
  25792. exports.AnimationMixer = AnimationMixer;
  25793. exports.AnimationClip = AnimationClip;
  25794. exports.Uniform = Uniform;
  25795. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  25796. exports.BufferGeometry = BufferGeometry;
  25797. exports.GeometryIdCount = GeometryIdCount;
  25798. exports.Geometry = Geometry;
  25799. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  25800. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  25801. exports.InterleavedBuffer = InterleavedBuffer;
  25802. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  25803. exports.Face3 = Face3;
  25804. exports.Object3D = Object3D;
  25805. exports.Raycaster = Raycaster;
  25806. exports.Layers = Layers;
  25807. exports.EventDispatcher = EventDispatcher;
  25808. exports.Clock = Clock;
  25809. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  25810. exports.LinearInterpolant = LinearInterpolant;
  25811. exports.DiscreteInterpolant = DiscreteInterpolant;
  25812. exports.CubicInterpolant = CubicInterpolant;
  25813. exports.Interpolant = Interpolant;
  25814. exports.Triangle = Triangle;
  25815. exports.Math = _Math;
  25816. exports.Spherical = Spherical;
  25817. exports.Cylindrical = Cylindrical;
  25818. exports.Plane = Plane;
  25819. exports.Frustum = Frustum;
  25820. exports.Sphere = Sphere;
  25821. exports.Ray = Ray;
  25822. exports.Matrix4 = Matrix4;
  25823. exports.Matrix3 = Matrix3;
  25824. exports.Box3 = Box3;
  25825. exports.Box2 = Box2;
  25826. exports.Line3 = Line3;
  25827. exports.Euler = Euler;
  25828. exports.Vector4 = Vector4;
  25829. exports.Vector3 = Vector3;
  25830. exports.Vector2 = Vector2;
  25831. exports.Quaternion = Quaternion;
  25832. exports.Color = Color;
  25833. exports.MorphBlendMesh = MorphBlendMesh;
  25834. exports.ImmediateRenderObject = ImmediateRenderObject;
  25835. exports.VertexNormalsHelper = VertexNormalsHelper;
  25836. exports.SpotLightHelper = SpotLightHelper;
  25837. exports.SkeletonHelper = SkeletonHelper;
  25838. exports.PointLightHelper = PointLightHelper;
  25839. exports.RectAreaLightHelper = RectAreaLightHelper;
  25840. exports.HemisphereLightHelper = HemisphereLightHelper;
  25841. exports.GridHelper = GridHelper;
  25842. exports.PolarGridHelper = PolarGridHelper;
  25843. exports.FaceNormalsHelper = FaceNormalsHelper;
  25844. exports.DirectionalLightHelper = DirectionalLightHelper;
  25845. exports.CameraHelper = CameraHelper;
  25846. exports.BoxHelper = BoxHelper;
  25847. exports.ArrowHelper = ArrowHelper;
  25848. exports.AxisHelper = AxisHelper;
  25849. exports.CatmullRomCurve3 = CatmullRomCurve3;
  25850. exports.CubicBezierCurve3 = CubicBezierCurve3;
  25851. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  25852. exports.LineCurve3 = LineCurve3;
  25853. exports.ArcCurve = ArcCurve;
  25854. exports.EllipseCurve = EllipseCurve;
  25855. exports.SplineCurve = SplineCurve;
  25856. exports.CubicBezierCurve = CubicBezierCurve;
  25857. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  25858. exports.LineCurve = LineCurve;
  25859. exports.Shape = Shape;
  25860. exports.Path = Path;
  25861. exports.ShapePath = ShapePath;
  25862. exports.Font = Font;
  25863. exports.CurvePath = CurvePath;
  25864. exports.Curve = Curve;
  25865. exports.ShapeUtils = ShapeUtils;
  25866. exports.SceneUtils = SceneUtils;
  25867. exports.WireframeGeometry = WireframeGeometry;
  25868. exports.ParametricGeometry = ParametricGeometry;
  25869. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  25870. exports.TetrahedronGeometry = TetrahedronGeometry;
  25871. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  25872. exports.OctahedronGeometry = OctahedronGeometry;
  25873. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  25874. exports.IcosahedronGeometry = IcosahedronGeometry;
  25875. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  25876. exports.DodecahedronGeometry = DodecahedronGeometry;
  25877. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  25878. exports.PolyhedronGeometry = PolyhedronGeometry;
  25879. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  25880. exports.TubeGeometry = TubeGeometry;
  25881. exports.TubeBufferGeometry = TubeBufferGeometry;
  25882. exports.TorusKnotGeometry = TorusKnotGeometry;
  25883. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  25884. exports.TorusGeometry = TorusGeometry;
  25885. exports.TorusBufferGeometry = TorusBufferGeometry;
  25886. exports.TextGeometry = TextGeometry;
  25887. exports.SphereBufferGeometry = SphereBufferGeometry;
  25888. exports.SphereGeometry = SphereGeometry;
  25889. exports.RingGeometry = RingGeometry;
  25890. exports.RingBufferGeometry = RingBufferGeometry;
  25891. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  25892. exports.PlaneGeometry = PlaneGeometry;
  25893. exports.LatheGeometry = LatheGeometry;
  25894. exports.LatheBufferGeometry = LatheBufferGeometry;
  25895. exports.ShapeGeometry = ShapeGeometry;
  25896. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  25897. exports.ExtrudeGeometry = ExtrudeGeometry;
  25898. exports.EdgesGeometry = EdgesGeometry;
  25899. exports.ConeGeometry = ConeGeometry;
  25900. exports.ConeBufferGeometry = ConeBufferGeometry;
  25901. exports.CylinderGeometry = CylinderGeometry;
  25902. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  25903. exports.CircleBufferGeometry = CircleBufferGeometry;
  25904. exports.CircleGeometry = CircleGeometry;
  25905. exports.BoxBufferGeometry = BoxBufferGeometry;
  25906. exports.BoxGeometry = BoxGeometry;
  25907. exports.ShadowMaterial = ShadowMaterial;
  25908. exports.SpriteMaterial = SpriteMaterial;
  25909. exports.RawShaderMaterial = RawShaderMaterial;
  25910. exports.ShaderMaterial = ShaderMaterial;
  25911. exports.PointsMaterial = PointsMaterial;
  25912. exports.MultiMaterial = MultiMaterial;
  25913. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  25914. exports.MeshStandardMaterial = MeshStandardMaterial;
  25915. exports.MeshPhongMaterial = MeshPhongMaterial;
  25916. exports.MeshToonMaterial = MeshToonMaterial;
  25917. exports.MeshNormalMaterial = MeshNormalMaterial;
  25918. exports.MeshLambertMaterial = MeshLambertMaterial;
  25919. exports.MeshDepthMaterial = MeshDepthMaterial;
  25920. exports.MeshBasicMaterial = MeshBasicMaterial;
  25921. exports.LineDashedMaterial = LineDashedMaterial;
  25922. exports.LineBasicMaterial = LineBasicMaterial;
  25923. exports.Material = Material;
  25924. exports.Float64BufferAttribute = Float64BufferAttribute;
  25925. exports.Float32BufferAttribute = Float32BufferAttribute;
  25926. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  25927. exports.Int32BufferAttribute = Int32BufferAttribute;
  25928. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  25929. exports.Int16BufferAttribute = Int16BufferAttribute;
  25930. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  25931. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  25932. exports.Int8BufferAttribute = Int8BufferAttribute;
  25933. exports.BufferAttribute = BufferAttribute;
  25934. exports.REVISION = REVISION;
  25935. exports.MOUSE = MOUSE;
  25936. exports.CullFaceNone = CullFaceNone;
  25937. exports.CullFaceBack = CullFaceBack;
  25938. exports.CullFaceFront = CullFaceFront;
  25939. exports.CullFaceFrontBack = CullFaceFrontBack;
  25940. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  25941. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  25942. exports.BasicShadowMap = BasicShadowMap;
  25943. exports.PCFShadowMap = PCFShadowMap;
  25944. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  25945. exports.FrontSide = FrontSide;
  25946. exports.BackSide = BackSide;
  25947. exports.DoubleSide = DoubleSide;
  25948. exports.FlatShading = FlatShading;
  25949. exports.SmoothShading = SmoothShading;
  25950. exports.NoColors = NoColors;
  25951. exports.FaceColors = FaceColors;
  25952. exports.VertexColors = VertexColors;
  25953. exports.NoBlending = NoBlending;
  25954. exports.NormalBlending = NormalBlending;
  25955. exports.AdditiveBlending = AdditiveBlending;
  25956. exports.SubtractiveBlending = SubtractiveBlending;
  25957. exports.MultiplyBlending = MultiplyBlending;
  25958. exports.CustomBlending = CustomBlending;
  25959. exports.AddEquation = AddEquation;
  25960. exports.SubtractEquation = SubtractEquation;
  25961. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  25962. exports.MinEquation = MinEquation;
  25963. exports.MaxEquation = MaxEquation;
  25964. exports.ZeroFactor = ZeroFactor;
  25965. exports.OneFactor = OneFactor;
  25966. exports.SrcColorFactor = SrcColorFactor;
  25967. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  25968. exports.SrcAlphaFactor = SrcAlphaFactor;
  25969. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  25970. exports.DstAlphaFactor = DstAlphaFactor;
  25971. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  25972. exports.DstColorFactor = DstColorFactor;
  25973. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  25974. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  25975. exports.NeverDepth = NeverDepth;
  25976. exports.AlwaysDepth = AlwaysDepth;
  25977. exports.LessDepth = LessDepth;
  25978. exports.LessEqualDepth = LessEqualDepth;
  25979. exports.EqualDepth = EqualDepth;
  25980. exports.GreaterEqualDepth = GreaterEqualDepth;
  25981. exports.GreaterDepth = GreaterDepth;
  25982. exports.NotEqualDepth = NotEqualDepth;
  25983. exports.MultiplyOperation = MultiplyOperation;
  25984. exports.MixOperation = MixOperation;
  25985. exports.AddOperation = AddOperation;
  25986. exports.NoToneMapping = NoToneMapping;
  25987. exports.LinearToneMapping = LinearToneMapping;
  25988. exports.ReinhardToneMapping = ReinhardToneMapping;
  25989. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  25990. exports.CineonToneMapping = CineonToneMapping;
  25991. exports.UVMapping = UVMapping;
  25992. exports.CubeReflectionMapping = CubeReflectionMapping;
  25993. exports.CubeRefractionMapping = CubeRefractionMapping;
  25994. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  25995. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  25996. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  25997. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  25998. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  25999. exports.RepeatWrapping = RepeatWrapping;
  26000. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  26001. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  26002. exports.NearestFilter = NearestFilter;
  26003. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  26004. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  26005. exports.LinearFilter = LinearFilter;
  26006. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  26007. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  26008. exports.UnsignedByteType = UnsignedByteType;
  26009. exports.ByteType = ByteType;
  26010. exports.ShortType = ShortType;
  26011. exports.UnsignedShortType = UnsignedShortType;
  26012. exports.IntType = IntType;
  26013. exports.UnsignedIntType = UnsignedIntType;
  26014. exports.FloatType = FloatType;
  26015. exports.HalfFloatType = HalfFloatType;
  26016. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  26017. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  26018. exports.UnsignedShort565Type = UnsignedShort565Type;
  26019. exports.UnsignedInt248Type = UnsignedInt248Type;
  26020. exports.AlphaFormat = AlphaFormat;
  26021. exports.RGBFormat = RGBFormat;
  26022. exports.RGBAFormat = RGBAFormat;
  26023. exports.LuminanceFormat = LuminanceFormat;
  26024. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  26025. exports.RGBEFormat = RGBEFormat;
  26026. exports.DepthFormat = DepthFormat;
  26027. exports.DepthStencilFormat = DepthStencilFormat;
  26028. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  26029. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  26030. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  26031. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  26032. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  26033. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  26034. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  26035. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  26036. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  26037. exports.LoopOnce = LoopOnce;
  26038. exports.LoopRepeat = LoopRepeat;
  26039. exports.LoopPingPong = LoopPingPong;
  26040. exports.InterpolateDiscrete = InterpolateDiscrete;
  26041. exports.InterpolateLinear = InterpolateLinear;
  26042. exports.InterpolateSmooth = InterpolateSmooth;
  26043. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  26044. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  26045. exports.WrapAroundEnding = WrapAroundEnding;
  26046. exports.TrianglesDrawMode = TrianglesDrawMode;
  26047. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  26048. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  26049. exports.LinearEncoding = LinearEncoding;
  26050. exports.sRGBEncoding = sRGBEncoding;
  26051. exports.GammaEncoding = GammaEncoding;
  26052. exports.RGBEEncoding = RGBEEncoding;
  26053. exports.LogLuvEncoding = LogLuvEncoding;
  26054. exports.RGBM7Encoding = RGBM7Encoding;
  26055. exports.RGBM16Encoding = RGBM16Encoding;
  26056. exports.RGBDEncoding = RGBDEncoding;
  26057. exports.BasicDepthPacking = BasicDepthPacking;
  26058. exports.RGBADepthPacking = RGBADepthPacking;
  26059. exports.CubeGeometry = BoxGeometry;
  26060. exports.Face4 = Face4;
  26061. exports.LineStrip = LineStrip;
  26062. exports.LinePieces = LinePieces;
  26063. exports.MeshFaceMaterial = MeshFaceMaterial;
  26064. exports.PointCloud = PointCloud;
  26065. exports.Particle = Particle;
  26066. exports.ParticleSystem = ParticleSystem;
  26067. exports.PointCloudMaterial = PointCloudMaterial;
  26068. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  26069. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  26070. exports.Vertex = Vertex;
  26071. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  26072. exports.Int8Attribute = Int8Attribute;
  26073. exports.Uint8Attribute = Uint8Attribute;
  26074. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  26075. exports.Int16Attribute = Int16Attribute;
  26076. exports.Uint16Attribute = Uint16Attribute;
  26077. exports.Int32Attribute = Int32Attribute;
  26078. exports.Uint32Attribute = Uint32Attribute;
  26079. exports.Float32Attribute = Float32Attribute;
  26080. exports.Float64Attribute = Float64Attribute;
  26081. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  26082. exports.SplineCurve3 = SplineCurve3;
  26083. exports.Spline = Spline;
  26084. exports.BoundingBoxHelper = BoundingBoxHelper;
  26085. exports.EdgesHelper = EdgesHelper;
  26086. exports.WireframeHelper = WireframeHelper;
  26087. exports.XHRLoader = XHRLoader;
  26088. exports.BinaryTextureLoader = BinaryTextureLoader;
  26089. exports.GeometryUtils = GeometryUtils;
  26090. exports.ImageUtils = ImageUtils;
  26091. exports.Projector = Projector;
  26092. exports.CanvasRenderer = CanvasRenderer;
  26093. Object.defineProperty(exports, '__esModule', { value: true });
  26094. })));